Fix PR12526: -location watchpoints for bitfield arguments
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "exceptions.h"
55 #include "memattr.h"
56 #include "ada-lang.h"
57 #include "top.h"
58 #include "valprint.h"
59 #include "jit.h"
60 #include "xml-syscall.h"
61 #include "parser-defs.h"
62 #include "gdb_regex.h"
63 #include "probe.h"
64 #include "cli/cli-utils.h"
65 #include "continuations.h"
66 #include "stack.h"
67 #include "skip.h"
68 #include "ax-gdb.h"
69 #include "dummy-frame.h"
70
71 #include "format.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82
83 /* Enums for exception-handling support.  */
84 enum exception_event_kind
85 {
86   EX_EVENT_THROW,
87   EX_EVENT_RETHROW,
88   EX_EVENT_CATCH
89 };
90
91 /* Prototypes for local functions.  */
92
93 static void enable_delete_command (char *, int);
94
95 static void enable_once_command (char *, int);
96
97 static void enable_count_command (char *, int);
98
99 static void disable_command (char *, int);
100
101 static void enable_command (char *, int);
102
103 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
104                                                       void *),
105                                     void *);
106
107 static void ignore_command (char *, int);
108
109 static int breakpoint_re_set_one (void *);
110
111 static void breakpoint_re_set_default (struct breakpoint *);
112
113 static void create_sals_from_address_default (char **,
114                                               struct linespec_result *,
115                                               enum bptype, char *,
116                                               char **);
117
118 static void create_breakpoints_sal_default (struct gdbarch *,
119                                             struct linespec_result *,
120                                             char *, char *, enum bptype,
121                                             enum bpdisp, int, int,
122                                             int,
123                                             const struct breakpoint_ops *,
124                                             int, int, int, unsigned);
125
126 static void decode_linespec_default (struct breakpoint *, char **,
127                                      struct symtabs_and_lines *);
128
129 static void clear_command (char *, int);
130
131 static void catch_command (char *, int);
132
133 static int can_use_hardware_watchpoint (struct value *);
134
135 static void break_command_1 (char *, int, int);
136
137 static void mention (struct breakpoint *);
138
139 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
140                                                                enum bptype,
141                                                                const struct breakpoint_ops *);
142 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
143                                                        const struct symtab_and_line *);
144
145 /* This function is used in gdbtk sources and thus can not be made
146    static.  */
147 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
148                                        struct symtab_and_line,
149                                        enum bptype,
150                                        const struct breakpoint_ops *);
151
152 static struct breakpoint *
153   momentary_breakpoint_from_master (struct breakpoint *orig,
154                                     enum bptype type,
155                                     const struct breakpoint_ops *ops,
156                                     int loc_enabled);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int watchpoint_locations_match (struct bp_location *loc1,
169                                        struct bp_location *loc2);
170
171 static int breakpoint_location_address_match (struct bp_location *bl,
172                                               struct address_space *aspace,
173                                               CORE_ADDR addr);
174
175 static void breakpoints_info (char *, int);
176
177 static void watchpoints_info (char *, int);
178
179 static int breakpoint_1 (char *, int, 
180                          int (*) (const struct breakpoint *));
181
182 static int breakpoint_cond_eval (void *);
183
184 static void cleanup_executing_breakpoints (void *);
185
186 static void commands_command (char *, int);
187
188 static void condition_command (char *, int);
189
190 typedef enum
191   {
192     mark_inserted,
193     mark_uninserted
194   }
195 insertion_state_t;
196
197 static int remove_breakpoint (struct bp_location *, insertion_state_t);
198 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
199
200 static enum print_stop_action print_bp_stop_message (bpstat bs);
201
202 static int watchpoint_check (void *);
203
204 static void maintenance_info_breakpoints (char *, int);
205
206 static int hw_breakpoint_used_count (void);
207
208 static int hw_watchpoint_use_count (struct breakpoint *);
209
210 static int hw_watchpoint_used_count_others (struct breakpoint *except,
211                                             enum bptype type,
212                                             int *other_type_used);
213
214 static void hbreak_command (char *, int);
215
216 static void thbreak_command (char *, int);
217
218 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
219                                     int count);
220
221 static void stop_command (char *arg, int from_tty);
222
223 static void stopin_command (char *arg, int from_tty);
224
225 static void stopat_command (char *arg, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int find_single_step_breakpoint (struct address_space *aspace,
232                                         CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 static void update_global_location_list (int);
241
242 static void update_global_location_list_nothrow (int);
243
244 static int is_hardware_watchpoint (const struct breakpoint *bpt);
245
246 static void insert_breakpoint_locations (void);
247
248 static int syscall_catchpoint_p (struct breakpoint *b);
249
250 static void tracepoints_info (char *, int);
251
252 static void delete_trace_command (char *, int);
253
254 static void enable_trace_command (char *, int);
255
256 static void disable_trace_command (char *, int);
257
258 static void trace_pass_command (char *, int);
259
260 static void set_tracepoint_count (int num);
261
262 static int is_masked_watchpoint (const struct breakpoint *b);
263
264 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
265
266 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
267    otherwise.  */
268
269 static int strace_marker_p (struct breakpoint *b);
270
271 /* The abstract base class all breakpoint_ops structures inherit
272    from.  */
273 struct breakpoint_ops base_breakpoint_ops;
274
275 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
276    that are implemented on top of software or hardware breakpoints
277    (user breakpoints, internal and momentary breakpoints, etc.).  */
278 static struct breakpoint_ops bkpt_base_breakpoint_ops;
279
280 /* Internal breakpoints class type.  */
281 static struct breakpoint_ops internal_breakpoint_ops;
282
283 /* Momentary breakpoints class type.  */
284 static struct breakpoint_ops momentary_breakpoint_ops;
285
286 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
287 static struct breakpoint_ops longjmp_breakpoint_ops;
288
289 /* The breakpoint_ops structure to be used in regular user created
290    breakpoints.  */
291 struct breakpoint_ops bkpt_breakpoint_ops;
292
293 /* Breakpoints set on probes.  */
294 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
295
296 /* Dynamic printf class type.  */
297 struct breakpoint_ops dprintf_breakpoint_ops;
298
299 /* One (or perhaps two) breakpoints used for software single
300    stepping.  */
301
302 static void *single_step_breakpoints[2];
303 static struct gdbarch *single_step_gdbarch[2];
304
305 /* The style in which to perform a dynamic printf.  This is a user
306    option because different output options have different tradeoffs;
307    if GDB does the printing, there is better error handling if there
308    is a problem with any of the arguments, but using an inferior
309    function lets you have special-purpose printers and sending of
310    output to the same place as compiled-in print functions.  */
311
312 static const char dprintf_style_gdb[] = "gdb";
313 static const char dprintf_style_call[] = "call";
314 static const char dprintf_style_agent[] = "agent";
315 static const char *const dprintf_style_enums[] = {
316   dprintf_style_gdb,
317   dprintf_style_call,
318   dprintf_style_agent,
319   NULL
320 };
321 static const char *dprintf_style = dprintf_style_gdb;
322
323 /* The function to use for dynamic printf if the preferred style is to
324    call into the inferior.  The value is simply a string that is
325    copied into the command, so it can be anything that GDB can
326    evaluate to a callable address, not necessarily a function name.  */
327
328 static char *dprintf_function = "";
329
330 /* The channel to use for dynamic printf if the preferred style is to
331    call into the inferior; if a nonempty string, it will be passed to
332    the call as the first argument, with the format string as the
333    second.  As with the dprintf function, this can be anything that
334    GDB knows how to evaluate, so in addition to common choices like
335    "stderr", this could be an app-specific expression like
336    "mystreams[curlogger]".  */
337
338 static char *dprintf_channel = "";
339
340 /* True if dprintf commands should continue to operate even if GDB
341    has disconnected.  */
342 static int disconnected_dprintf = 1;
343
344 /* A reference-counted struct command_line.  This lets multiple
345    breakpoints share a single command list.  */
346 struct counted_command_line
347 {
348   /* The reference count.  */
349   int refc;
350
351   /* The command list.  */
352   struct command_line *commands;
353 };
354
355 struct command_line *
356 breakpoint_commands (struct breakpoint *b)
357 {
358   return b->commands ? b->commands->commands : NULL;
359 }
360
361 /* Flag indicating that a command has proceeded the inferior past the
362    current breakpoint.  */
363
364 static int breakpoint_proceeded;
365
366 const char *
367 bpdisp_text (enum bpdisp disp)
368 {
369   /* NOTE: the following values are a part of MI protocol and
370      represent values of 'disp' field returned when inferior stops at
371      a breakpoint.  */
372   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
373
374   return bpdisps[(int) disp];
375 }
376
377 /* Prototypes for exported functions.  */
378 /* If FALSE, gdb will not use hardware support for watchpoints, even
379    if such is available.  */
380 static int can_use_hw_watchpoints;
381
382 static void
383 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
384                              struct cmd_list_element *c,
385                              const char *value)
386 {
387   fprintf_filtered (file,
388                     _("Debugger's willingness to use "
389                       "watchpoint hardware is %s.\n"),
390                     value);
391 }
392
393 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
394    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
395    for unrecognized breakpoint locations.
396    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
397 static enum auto_boolean pending_break_support;
398 static void
399 show_pending_break_support (struct ui_file *file, int from_tty,
400                             struct cmd_list_element *c,
401                             const char *value)
402 {
403   fprintf_filtered (file,
404                     _("Debugger's behavior regarding "
405                       "pending breakpoints is %s.\n"),
406                     value);
407 }
408
409 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
410    set with "break" but falling in read-only memory.
411    If 0, gdb will warn about such breakpoints, but won't automatically
412    use hardware breakpoints.  */
413 static int automatic_hardware_breakpoints;
414 static void
415 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
416                                      struct cmd_list_element *c,
417                                      const char *value)
418 {
419   fprintf_filtered (file,
420                     _("Automatic usage of hardware breakpoints is %s.\n"),
421                     value);
422 }
423
424 /* If on, gdb will keep breakpoints inserted even as inferior is
425    stopped, and immediately insert any new breakpoints.  If off, gdb
426    will insert breakpoints into inferior only when resuming it, and
427    will remove breakpoints upon stop.  If auto, GDB will behave as ON
428    if in non-stop mode, and as OFF if all-stop mode.*/
429
430 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
431
432 static void
433 show_always_inserted_mode (struct ui_file *file, int from_tty,
434                      struct cmd_list_element *c, const char *value)
435 {
436   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
437     fprintf_filtered (file,
438                       _("Always inserted breakpoint "
439                         "mode is %s (currently %s).\n"),
440                       value,
441                       breakpoints_always_inserted_mode () ? "on" : "off");
442   else
443     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
444                       value);
445 }
446
447 int
448 breakpoints_always_inserted_mode (void)
449 {
450   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
451           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
452 }
453
454 static const char condition_evaluation_both[] = "host or target";
455
456 /* Modes for breakpoint condition evaluation.  */
457 static const char condition_evaluation_auto[] = "auto";
458 static const char condition_evaluation_host[] = "host";
459 static const char condition_evaluation_target[] = "target";
460 static const char *const condition_evaluation_enums[] = {
461   condition_evaluation_auto,
462   condition_evaluation_host,
463   condition_evaluation_target,
464   NULL
465 };
466
467 /* Global that holds the current mode for breakpoint condition evaluation.  */
468 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
469
470 /* Global that we use to display information to the user (gets its value from
471    condition_evaluation_mode_1.  */
472 static const char *condition_evaluation_mode = condition_evaluation_auto;
473
474 /* Translate a condition evaluation mode MODE into either "host"
475    or "target".  This is used mostly to translate from "auto" to the
476    real setting that is being used.  It returns the translated
477    evaluation mode.  */
478
479 static const char *
480 translate_condition_evaluation_mode (const char *mode)
481 {
482   if (mode == condition_evaluation_auto)
483     {
484       if (target_supports_evaluation_of_breakpoint_conditions ())
485         return condition_evaluation_target;
486       else
487         return condition_evaluation_host;
488     }
489   else
490     return mode;
491 }
492
493 /* Discovers what condition_evaluation_auto translates to.  */
494
495 static const char *
496 breakpoint_condition_evaluation_mode (void)
497 {
498   return translate_condition_evaluation_mode (condition_evaluation_mode);
499 }
500
501 /* Return true if GDB should evaluate breakpoint conditions or false
502    otherwise.  */
503
504 static int
505 gdb_evaluates_breakpoint_condition_p (void)
506 {
507   const char *mode = breakpoint_condition_evaluation_mode ();
508
509   return (mode == condition_evaluation_host);
510 }
511
512 void _initialize_breakpoint (void);
513
514 /* Are we executing breakpoint commands?  */
515 static int executing_breakpoint_commands;
516
517 /* Are overlay event breakpoints enabled? */
518 static int overlay_events_enabled;
519
520 /* See description in breakpoint.h. */
521 int target_exact_watchpoints = 0;
522
523 /* Walk the following statement or block through all breakpoints.
524    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
525    current breakpoint.  */
526
527 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
528
529 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
530         for (B = breakpoint_chain;      \
531              B ? (TMP=B->next, 1): 0;   \
532              B = TMP)
533
534 /* Similar iterator for the low-level breakpoints.  SAFE variant is
535    not provided so update_global_location_list must not be called
536    while executing the block of ALL_BP_LOCATIONS.  */
537
538 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
539         for (BP_TMP = bp_location;                                      \
540              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
541              BP_TMP++)
542
543 /* Iterates through locations with address ADDRESS for the currently selected
544    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
545    to where the loop should start from.
546    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
547    appropriate location to start with.  */
548
549 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
550         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
551              BP_LOCP_TMP = BP_LOCP_START;                               \
552              BP_LOCP_START                                              \
553              && (BP_LOCP_TMP < bp_location + bp_location_count          \
554              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
555              BP_LOCP_TMP++)
556
557 /* Iterator for tracepoints only.  */
558
559 #define ALL_TRACEPOINTS(B)  \
560   for (B = breakpoint_chain; B; B = B->next)  \
561     if (is_tracepoint (B))
562
563 /* Chains of all breakpoints defined.  */
564
565 struct breakpoint *breakpoint_chain;
566
567 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
568
569 static struct bp_location **bp_location;
570
571 /* Number of elements of BP_LOCATION.  */
572
573 static unsigned bp_location_count;
574
575 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
576    ADDRESS for the current elements of BP_LOCATION which get a valid
577    result from bp_location_has_shadow.  You can use it for roughly
578    limiting the subrange of BP_LOCATION to scan for shadow bytes for
579    an address you need to read.  */
580
581 static CORE_ADDR bp_location_placed_address_before_address_max;
582
583 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
584    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
585    BP_LOCATION which get a valid result from bp_location_has_shadow.
586    You can use it for roughly limiting the subrange of BP_LOCATION to
587    scan for shadow bytes for an address you need to read.  */
588
589 static CORE_ADDR bp_location_shadow_len_after_address_max;
590
591 /* The locations that no longer correspond to any breakpoint, unlinked
592    from bp_location array, but for which a hit may still be reported
593    by a target.  */
594 VEC(bp_location_p) *moribund_locations = NULL;
595
596 /* Number of last breakpoint made.  */
597
598 static int breakpoint_count;
599
600 /* The value of `breakpoint_count' before the last command that
601    created breakpoints.  If the last (break-like) command created more
602    than one breakpoint, then the difference between BREAKPOINT_COUNT
603    and PREV_BREAKPOINT_COUNT is more than one.  */
604 static int prev_breakpoint_count;
605
606 /* Number of last tracepoint made.  */
607
608 static int tracepoint_count;
609
610 static struct cmd_list_element *breakpoint_set_cmdlist;
611 static struct cmd_list_element *breakpoint_show_cmdlist;
612 struct cmd_list_element *save_cmdlist;
613
614 /* Return whether a breakpoint is an active enabled breakpoint.  */
615 static int
616 breakpoint_enabled (struct breakpoint *b)
617 {
618   return (b->enable_state == bp_enabled);
619 }
620
621 /* Set breakpoint count to NUM.  */
622
623 static void
624 set_breakpoint_count (int num)
625 {
626   prev_breakpoint_count = breakpoint_count;
627   breakpoint_count = num;
628   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
629 }
630
631 /* Used by `start_rbreak_breakpoints' below, to record the current
632    breakpoint count before "rbreak" creates any breakpoint.  */
633 static int rbreak_start_breakpoint_count;
634
635 /* Called at the start an "rbreak" command to record the first
636    breakpoint made.  */
637
638 void
639 start_rbreak_breakpoints (void)
640 {
641   rbreak_start_breakpoint_count = breakpoint_count;
642 }
643
644 /* Called at the end of an "rbreak" command to record the last
645    breakpoint made.  */
646
647 void
648 end_rbreak_breakpoints (void)
649 {
650   prev_breakpoint_count = rbreak_start_breakpoint_count;
651 }
652
653 /* Used in run_command to zero the hit count when a new run starts.  */
654
655 void
656 clear_breakpoint_hit_counts (void)
657 {
658   struct breakpoint *b;
659
660   ALL_BREAKPOINTS (b)
661     b->hit_count = 0;
662 }
663
664 /* Allocate a new counted_command_line with reference count of 1.
665    The new structure owns COMMANDS.  */
666
667 static struct counted_command_line *
668 alloc_counted_command_line (struct command_line *commands)
669 {
670   struct counted_command_line *result
671     = xmalloc (sizeof (struct counted_command_line));
672
673   result->refc = 1;
674   result->commands = commands;
675   return result;
676 }
677
678 /* Increment reference count.  This does nothing if CMD is NULL.  */
679
680 static void
681 incref_counted_command_line (struct counted_command_line *cmd)
682 {
683   if (cmd)
684     ++cmd->refc;
685 }
686
687 /* Decrement reference count.  If the reference count reaches 0,
688    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
689    nothing if *CMDP is NULL.  */
690
691 static void
692 decref_counted_command_line (struct counted_command_line **cmdp)
693 {
694   if (*cmdp)
695     {
696       if (--(*cmdp)->refc == 0)
697         {
698           free_command_lines (&(*cmdp)->commands);
699           xfree (*cmdp);
700         }
701       *cmdp = NULL;
702     }
703 }
704
705 /* A cleanup function that calls decref_counted_command_line.  */
706
707 static void
708 do_cleanup_counted_command_line (void *arg)
709 {
710   decref_counted_command_line (arg);
711 }
712
713 /* Create a cleanup that calls decref_counted_command_line on the
714    argument.  */
715
716 static struct cleanup *
717 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
718 {
719   return make_cleanup (do_cleanup_counted_command_line, cmdp);
720 }
721
722 \f
723 /* Return the breakpoint with the specified number, or NULL
724    if the number does not refer to an existing breakpoint.  */
725
726 struct breakpoint *
727 get_breakpoint (int num)
728 {
729   struct breakpoint *b;
730
731   ALL_BREAKPOINTS (b)
732     if (b->number == num)
733       return b;
734   
735   return NULL;
736 }
737
738 \f
739
740 /* Mark locations as "conditions have changed" in case the target supports
741    evaluating conditions on its side.  */
742
743 static void
744 mark_breakpoint_modified (struct breakpoint *b)
745 {
746   struct bp_location *loc;
747
748   /* This is only meaningful if the target is
749      evaluating conditions and if the user has
750      opted for condition evaluation on the target's
751      side.  */
752   if (gdb_evaluates_breakpoint_condition_p ()
753       || !target_supports_evaluation_of_breakpoint_conditions ())
754     return;
755
756   if (!is_breakpoint (b))
757     return;
758
759   for (loc = b->loc; loc; loc = loc->next)
760     loc->condition_changed = condition_modified;
761 }
762
763 /* Mark location as "conditions have changed" in case the target supports
764    evaluating conditions on its side.  */
765
766 static void
767 mark_breakpoint_location_modified (struct bp_location *loc)
768 {
769   /* This is only meaningful if the target is
770      evaluating conditions and if the user has
771      opted for condition evaluation on the target's
772      side.  */
773   if (gdb_evaluates_breakpoint_condition_p ()
774       || !target_supports_evaluation_of_breakpoint_conditions ())
775
776     return;
777
778   if (!is_breakpoint (loc->owner))
779     return;
780
781   loc->condition_changed = condition_modified;
782 }
783
784 /* Sets the condition-evaluation mode using the static global
785    condition_evaluation_mode.  */
786
787 static void
788 set_condition_evaluation_mode (char *args, int from_tty,
789                                struct cmd_list_element *c)
790 {
791   const char *old_mode, *new_mode;
792
793   if ((condition_evaluation_mode_1 == condition_evaluation_target)
794       && !target_supports_evaluation_of_breakpoint_conditions ())
795     {
796       condition_evaluation_mode_1 = condition_evaluation_mode;
797       warning (_("Target does not support breakpoint condition evaluation.\n"
798                  "Using host evaluation mode instead."));
799       return;
800     }
801
802   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
803   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
804
805   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
806      settings was "auto".  */
807   condition_evaluation_mode = condition_evaluation_mode_1;
808
809   /* Only update the mode if the user picked a different one.  */
810   if (new_mode != old_mode)
811     {
812       struct bp_location *loc, **loc_tmp;
813       /* If the user switched to a different evaluation mode, we
814          need to synch the changes with the target as follows:
815
816          "host" -> "target": Send all (valid) conditions to the target.
817          "target" -> "host": Remove all the conditions from the target.
818       */
819
820       if (new_mode == condition_evaluation_target)
821         {
822           /* Mark everything modified and synch conditions with the
823              target.  */
824           ALL_BP_LOCATIONS (loc, loc_tmp)
825             mark_breakpoint_location_modified (loc);
826         }
827       else
828         {
829           /* Manually mark non-duplicate locations to synch conditions
830              with the target.  We do this to remove all the conditions the
831              target knows about.  */
832           ALL_BP_LOCATIONS (loc, loc_tmp)
833             if (is_breakpoint (loc->owner) && loc->inserted)
834               loc->needs_update = 1;
835         }
836
837       /* Do the update.  */
838       update_global_location_list (1);
839     }
840
841   return;
842 }
843
844 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
845    what "auto" is translating to.  */
846
847 static void
848 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
849                                 struct cmd_list_element *c, const char *value)
850 {
851   if (condition_evaluation_mode == condition_evaluation_auto)
852     fprintf_filtered (file,
853                       _("Breakpoint condition evaluation "
854                         "mode is %s (currently %s).\n"),
855                       value,
856                       breakpoint_condition_evaluation_mode ());
857   else
858     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
859                       value);
860 }
861
862 /* A comparison function for bp_location AP and BP that is used by
863    bsearch.  This comparison function only cares about addresses, unlike
864    the more general bp_location_compare function.  */
865
866 static int
867 bp_location_compare_addrs (const void *ap, const void *bp)
868 {
869   struct bp_location *a = *(void **) ap;
870   struct bp_location *b = *(void **) bp;
871
872   if (a->address == b->address)
873     return 0;
874   else
875     return ((a->address > b->address) - (a->address < b->address));
876 }
877
878 /* Helper function to skip all bp_locations with addresses
879    less than ADDRESS.  It returns the first bp_location that
880    is greater than or equal to ADDRESS.  If none is found, just
881    return NULL.  */
882
883 static struct bp_location **
884 get_first_locp_gte_addr (CORE_ADDR address)
885 {
886   struct bp_location dummy_loc;
887   struct bp_location *dummy_locp = &dummy_loc;
888   struct bp_location **locp_found = NULL;
889
890   /* Initialize the dummy location's address field.  */
891   memset (&dummy_loc, 0, sizeof (struct bp_location));
892   dummy_loc.address = address;
893
894   /* Find a close match to the first location at ADDRESS.  */
895   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
896                         sizeof (struct bp_location **),
897                         bp_location_compare_addrs);
898
899   /* Nothing was found, nothing left to do.  */
900   if (locp_found == NULL)
901     return NULL;
902
903   /* We may have found a location that is at ADDRESS but is not the first in the
904      location's list.  Go backwards (if possible) and locate the first one.  */
905   while ((locp_found - 1) >= bp_location
906          && (*(locp_found - 1))->address == address)
907     locp_found--;
908
909   return locp_found;
910 }
911
912 void
913 set_breakpoint_condition (struct breakpoint *b, char *exp,
914                           int from_tty)
915 {
916   xfree (b->cond_string);
917   b->cond_string = NULL;
918
919   if (is_watchpoint (b))
920     {
921       struct watchpoint *w = (struct watchpoint *) b;
922
923       xfree (w->cond_exp);
924       w->cond_exp = NULL;
925     }
926   else
927     {
928       struct bp_location *loc;
929
930       for (loc = b->loc; loc; loc = loc->next)
931         {
932           xfree (loc->cond);
933           loc->cond = NULL;
934
935           /* No need to free the condition agent expression
936              bytecode (if we have one).  We will handle this
937              when we go through update_global_location_list.  */
938         }
939     }
940
941   if (*exp == 0)
942     {
943       if (from_tty)
944         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
945     }
946   else
947     {
948       const char *arg = exp;
949
950       /* I don't know if it matters whether this is the string the user
951          typed in or the decompiled expression.  */
952       b->cond_string = xstrdup (arg);
953       b->condition_not_parsed = 0;
954
955       if (is_watchpoint (b))
956         {
957           struct watchpoint *w = (struct watchpoint *) b;
958
959           innermost_block = NULL;
960           arg = exp;
961           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
962           if (*arg)
963             error (_("Junk at end of expression"));
964           w->cond_exp_valid_block = innermost_block;
965         }
966       else
967         {
968           struct bp_location *loc;
969
970           for (loc = b->loc; loc; loc = loc->next)
971             {
972               arg = exp;
973               loc->cond =
974                 parse_exp_1 (&arg, loc->address,
975                              block_for_pc (loc->address), 0);
976               if (*arg)
977                 error (_("Junk at end of expression"));
978             }
979         }
980     }
981   mark_breakpoint_modified (b);
982
983   observer_notify_breakpoint_modified (b);
984 }
985
986 /* Completion for the "condition" command.  */
987
988 static VEC (char_ptr) *
989 condition_completer (struct cmd_list_element *cmd,
990                      const char *text, const char *word)
991 {
992   const char *space;
993
994   text = skip_spaces_const (text);
995   space = skip_to_space_const (text);
996   if (*space == '\0')
997     {
998       int len;
999       struct breakpoint *b;
1000       VEC (char_ptr) *result = NULL;
1001
1002       if (text[0] == '$')
1003         {
1004           /* We don't support completion of history indices.  */
1005           if (isdigit (text[1]))
1006             return NULL;
1007           return complete_internalvar (&text[1]);
1008         }
1009
1010       /* We're completing the breakpoint number.  */
1011       len = strlen (text);
1012
1013       ALL_BREAKPOINTS (b)
1014         {
1015           char number[50];
1016
1017           xsnprintf (number, sizeof (number), "%d", b->number);
1018
1019           if (strncmp (number, text, len) == 0)
1020             VEC_safe_push (char_ptr, result, xstrdup (number));
1021         }
1022
1023       return result;
1024     }
1025
1026   /* We're completing the expression part.  */
1027   text = skip_spaces_const (space);
1028   return expression_completer (cmd, text, word);
1029 }
1030
1031 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1032
1033 static void
1034 condition_command (char *arg, int from_tty)
1035 {
1036   struct breakpoint *b;
1037   char *p;
1038   int bnum;
1039
1040   if (arg == 0)
1041     error_no_arg (_("breakpoint number"));
1042
1043   p = arg;
1044   bnum = get_number (&p);
1045   if (bnum == 0)
1046     error (_("Bad breakpoint argument: '%s'"), arg);
1047
1048   ALL_BREAKPOINTS (b)
1049     if (b->number == bnum)
1050       {
1051         /* Check if this breakpoint has a "stop" method implemented in an
1052            extension language.  This method and conditions entered into GDB
1053            from the CLI are mutually exclusive.  */
1054         const struct extension_language_defn *extlang
1055           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1056
1057         if (extlang != NULL)
1058           {
1059             error (_("Only one stop condition allowed.  There is currently"
1060                      " a %s stop condition defined for this breakpoint."),
1061                    ext_lang_capitalized_name (extlang));
1062           }
1063         set_breakpoint_condition (b, p, from_tty);
1064
1065         if (is_breakpoint (b))
1066           update_global_location_list (1);
1067
1068         return;
1069       }
1070
1071   error (_("No breakpoint number %d."), bnum);
1072 }
1073
1074 /* Check that COMMAND do not contain commands that are suitable
1075    only for tracepoints and not suitable for ordinary breakpoints.
1076    Throw if any such commands is found.  */
1077
1078 static void
1079 check_no_tracepoint_commands (struct command_line *commands)
1080 {
1081   struct command_line *c;
1082
1083   for (c = commands; c; c = c->next)
1084     {
1085       int i;
1086
1087       if (c->control_type == while_stepping_control)
1088         error (_("The 'while-stepping' command can "
1089                  "only be used for tracepoints"));
1090
1091       for (i = 0; i < c->body_count; ++i)
1092         check_no_tracepoint_commands ((c->body_list)[i]);
1093
1094       /* Not that command parsing removes leading whitespace and comment
1095          lines and also empty lines.  So, we only need to check for
1096          command directly.  */
1097       if (strstr (c->line, "collect ") == c->line)
1098         error (_("The 'collect' command can only be used for tracepoints"));
1099
1100       if (strstr (c->line, "teval ") == c->line)
1101         error (_("The 'teval' command can only be used for tracepoints"));
1102     }
1103 }
1104
1105 /* Encapsulate tests for different types of tracepoints.  */
1106
1107 static int
1108 is_tracepoint_type (enum bptype type)
1109 {
1110   return (type == bp_tracepoint
1111           || type == bp_fast_tracepoint
1112           || type == bp_static_tracepoint);
1113 }
1114
1115 int
1116 is_tracepoint (const struct breakpoint *b)
1117 {
1118   return is_tracepoint_type (b->type);
1119 }
1120
1121 /* A helper function that validates that COMMANDS are valid for a
1122    breakpoint.  This function will throw an exception if a problem is
1123    found.  */
1124
1125 static void
1126 validate_commands_for_breakpoint (struct breakpoint *b,
1127                                   struct command_line *commands)
1128 {
1129   if (is_tracepoint (b))
1130     {
1131       struct tracepoint *t = (struct tracepoint *) b;
1132       struct command_line *c;
1133       struct command_line *while_stepping = 0;
1134
1135       /* Reset the while-stepping step count.  The previous commands
1136          might have included a while-stepping action, while the new
1137          ones might not.  */
1138       t->step_count = 0;
1139
1140       /* We need to verify that each top-level element of commands is
1141          valid for tracepoints, that there's at most one
1142          while-stepping element, and that the while-stepping's body
1143          has valid tracing commands excluding nested while-stepping.
1144          We also need to validate the tracepoint action line in the
1145          context of the tracepoint --- validate_actionline actually
1146          has side effects, like setting the tracepoint's
1147          while-stepping STEP_COUNT, in addition to checking if the
1148          collect/teval actions parse and make sense in the
1149          tracepoint's context.  */
1150       for (c = commands; c; c = c->next)
1151         {
1152           if (c->control_type == while_stepping_control)
1153             {
1154               if (b->type == bp_fast_tracepoint)
1155                 error (_("The 'while-stepping' command "
1156                          "cannot be used for fast tracepoint"));
1157               else if (b->type == bp_static_tracepoint)
1158                 error (_("The 'while-stepping' command "
1159                          "cannot be used for static tracepoint"));
1160
1161               if (while_stepping)
1162                 error (_("The 'while-stepping' command "
1163                          "can be used only once"));
1164               else
1165                 while_stepping = c;
1166             }
1167
1168           validate_actionline (c->line, b);
1169         }
1170       if (while_stepping)
1171         {
1172           struct command_line *c2;
1173
1174           gdb_assert (while_stepping->body_count == 1);
1175           c2 = while_stepping->body_list[0];
1176           for (; c2; c2 = c2->next)
1177             {
1178               if (c2->control_type == while_stepping_control)
1179                 error (_("The 'while-stepping' command cannot be nested"));
1180             }
1181         }
1182     }
1183   else
1184     {
1185       check_no_tracepoint_commands (commands);
1186     }
1187 }
1188
1189 /* Return a vector of all the static tracepoints set at ADDR.  The
1190    caller is responsible for releasing the vector.  */
1191
1192 VEC(breakpoint_p) *
1193 static_tracepoints_here (CORE_ADDR addr)
1194 {
1195   struct breakpoint *b;
1196   VEC(breakpoint_p) *found = 0;
1197   struct bp_location *loc;
1198
1199   ALL_BREAKPOINTS (b)
1200     if (b->type == bp_static_tracepoint)
1201       {
1202         for (loc = b->loc; loc; loc = loc->next)
1203           if (loc->address == addr)
1204             VEC_safe_push(breakpoint_p, found, b);
1205       }
1206
1207   return found;
1208 }
1209
1210 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1211    validate that only allowed commands are included.  */
1212
1213 void
1214 breakpoint_set_commands (struct breakpoint *b, 
1215                          struct command_line *commands)
1216 {
1217   validate_commands_for_breakpoint (b, commands);
1218
1219   decref_counted_command_line (&b->commands);
1220   b->commands = alloc_counted_command_line (commands);
1221   observer_notify_breakpoint_modified (b);
1222 }
1223
1224 /* Set the internal `silent' flag on the breakpoint.  Note that this
1225    is not the same as the "silent" that may appear in the breakpoint's
1226    commands.  */
1227
1228 void
1229 breakpoint_set_silent (struct breakpoint *b, int silent)
1230 {
1231   int old_silent = b->silent;
1232
1233   b->silent = silent;
1234   if (old_silent != silent)
1235     observer_notify_breakpoint_modified (b);
1236 }
1237
1238 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1239    breakpoint work for any thread.  */
1240
1241 void
1242 breakpoint_set_thread (struct breakpoint *b, int thread)
1243 {
1244   int old_thread = b->thread;
1245
1246   b->thread = thread;
1247   if (old_thread != thread)
1248     observer_notify_breakpoint_modified (b);
1249 }
1250
1251 /* Set the task for this breakpoint.  If TASK is 0, make the
1252    breakpoint work for any task.  */
1253
1254 void
1255 breakpoint_set_task (struct breakpoint *b, int task)
1256 {
1257   int old_task = b->task;
1258
1259   b->task = task;
1260   if (old_task != task)
1261     observer_notify_breakpoint_modified (b);
1262 }
1263
1264 void
1265 check_tracepoint_command (char *line, void *closure)
1266 {
1267   struct breakpoint *b = closure;
1268
1269   validate_actionline (line, b);
1270 }
1271
1272 /* A structure used to pass information through
1273    map_breakpoint_numbers.  */
1274
1275 struct commands_info
1276 {
1277   /* True if the command was typed at a tty.  */
1278   int from_tty;
1279
1280   /* The breakpoint range spec.  */
1281   char *arg;
1282
1283   /* Non-NULL if the body of the commands are being read from this
1284      already-parsed command.  */
1285   struct command_line *control;
1286
1287   /* The command lines read from the user, or NULL if they have not
1288      yet been read.  */
1289   struct counted_command_line *cmd;
1290 };
1291
1292 /* A callback for map_breakpoint_numbers that sets the commands for
1293    commands_command.  */
1294
1295 static void
1296 do_map_commands_command (struct breakpoint *b, void *data)
1297 {
1298   struct commands_info *info = data;
1299
1300   if (info->cmd == NULL)
1301     {
1302       struct command_line *l;
1303
1304       if (info->control != NULL)
1305         l = copy_command_lines (info->control->body_list[0]);
1306       else
1307         {
1308           struct cleanup *old_chain;
1309           char *str;
1310
1311           str = xstrprintf (_("Type commands for breakpoint(s) "
1312                               "%s, one per line."),
1313                             info->arg);
1314
1315           old_chain = make_cleanup (xfree, str);
1316
1317           l = read_command_lines (str,
1318                                   info->from_tty, 1,
1319                                   (is_tracepoint (b)
1320                                    ? check_tracepoint_command : 0),
1321                                   b);
1322
1323           do_cleanups (old_chain);
1324         }
1325
1326       info->cmd = alloc_counted_command_line (l);
1327     }
1328
1329   /* If a breakpoint was on the list more than once, we don't need to
1330      do anything.  */
1331   if (b->commands != info->cmd)
1332     {
1333       validate_commands_for_breakpoint (b, info->cmd->commands);
1334       incref_counted_command_line (info->cmd);
1335       decref_counted_command_line (&b->commands);
1336       b->commands = info->cmd;
1337       observer_notify_breakpoint_modified (b);
1338     }
1339 }
1340
1341 static void
1342 commands_command_1 (char *arg, int from_tty, 
1343                     struct command_line *control)
1344 {
1345   struct cleanup *cleanups;
1346   struct commands_info info;
1347
1348   info.from_tty = from_tty;
1349   info.control = control;
1350   info.cmd = NULL;
1351   /* If we read command lines from the user, then `info' will hold an
1352      extra reference to the commands that we must clean up.  */
1353   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1354
1355   if (arg == NULL || !*arg)
1356     {
1357       if (breakpoint_count - prev_breakpoint_count > 1)
1358         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1359                           breakpoint_count);
1360       else if (breakpoint_count > 0)
1361         arg = xstrprintf ("%d", breakpoint_count);
1362       else
1363         {
1364           /* So that we don't try to free the incoming non-NULL
1365              argument in the cleanup below.  Mapping breakpoint
1366              numbers will fail in this case.  */
1367           arg = NULL;
1368         }
1369     }
1370   else
1371     /* The command loop has some static state, so we need to preserve
1372        our argument.  */
1373     arg = xstrdup (arg);
1374
1375   if (arg != NULL)
1376     make_cleanup (xfree, arg);
1377
1378   info.arg = arg;
1379
1380   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1381
1382   if (info.cmd == NULL)
1383     error (_("No breakpoints specified."));
1384
1385   do_cleanups (cleanups);
1386 }
1387
1388 static void
1389 commands_command (char *arg, int from_tty)
1390 {
1391   commands_command_1 (arg, from_tty, NULL);
1392 }
1393
1394 /* Like commands_command, but instead of reading the commands from
1395    input stream, takes them from an already parsed command structure.
1396
1397    This is used by cli-script.c to DTRT with breakpoint commands
1398    that are part of if and while bodies.  */
1399 enum command_control_type
1400 commands_from_control_command (char *arg, struct command_line *cmd)
1401 {
1402   commands_command_1 (arg, 0, cmd);
1403   return simple_control;
1404 }
1405
1406 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1407
1408 static int
1409 bp_location_has_shadow (struct bp_location *bl)
1410 {
1411   if (bl->loc_type != bp_loc_software_breakpoint)
1412     return 0;
1413   if (!bl->inserted)
1414     return 0;
1415   if (bl->target_info.shadow_len == 0)
1416     /* BL isn't valid, or doesn't shadow memory.  */
1417     return 0;
1418   return 1;
1419 }
1420
1421 /* Update BUF, which is LEN bytes read from the target address
1422    MEMADDR, by replacing a memory breakpoint with its shadowed
1423    contents.
1424
1425    If READBUF is not NULL, this buffer must not overlap with the of
1426    the breakpoint location's shadow_contents buffer.  Otherwise, a
1427    failed assertion internal error will be raised.  */
1428
1429 static void
1430 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1431                             const gdb_byte *writebuf_org,
1432                             ULONGEST memaddr, LONGEST len,
1433                             struct bp_target_info *target_info,
1434                             struct gdbarch *gdbarch)
1435 {
1436   /* Now do full processing of the found relevant range of elements.  */
1437   CORE_ADDR bp_addr = 0;
1438   int bp_size = 0;
1439   int bptoffset = 0;
1440
1441   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1442                                  current_program_space->aspace, 0))
1443     {
1444       /* The breakpoint is inserted in a different address space.  */
1445       return;
1446     }
1447
1448   /* Addresses and length of the part of the breakpoint that
1449      we need to copy.  */
1450   bp_addr = target_info->placed_address;
1451   bp_size = target_info->shadow_len;
1452
1453   if (bp_addr + bp_size <= memaddr)
1454     {
1455       /* The breakpoint is entirely before the chunk of memory we are
1456          reading.  */
1457       return;
1458     }
1459
1460   if (bp_addr >= memaddr + len)
1461     {
1462       /* The breakpoint is entirely after the chunk of memory we are
1463          reading.  */
1464       return;
1465     }
1466
1467   /* Offset within shadow_contents.  */
1468   if (bp_addr < memaddr)
1469     {
1470       /* Only copy the second part of the breakpoint.  */
1471       bp_size -= memaddr - bp_addr;
1472       bptoffset = memaddr - bp_addr;
1473       bp_addr = memaddr;
1474     }
1475
1476   if (bp_addr + bp_size > memaddr + len)
1477     {
1478       /* Only copy the first part of the breakpoint.  */
1479       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1480     }
1481
1482   if (readbuf != NULL)
1483     {
1484       /* Verify that the readbuf buffer does not overlap with the
1485          shadow_contents buffer.  */
1486       gdb_assert (target_info->shadow_contents >= readbuf + len
1487                   || readbuf >= (target_info->shadow_contents
1488                                  + target_info->shadow_len));
1489
1490       /* Update the read buffer with this inserted breakpoint's
1491          shadow.  */
1492       memcpy (readbuf + bp_addr - memaddr,
1493               target_info->shadow_contents + bptoffset, bp_size);
1494     }
1495   else
1496     {
1497       const unsigned char *bp;
1498       CORE_ADDR placed_address = target_info->placed_address;
1499       int placed_size = target_info->placed_size;
1500
1501       /* Update the shadow with what we want to write to memory.  */
1502       memcpy (target_info->shadow_contents + bptoffset,
1503               writebuf_org + bp_addr - memaddr, bp_size);
1504
1505       /* Determine appropriate breakpoint contents and size for this
1506          address.  */
1507       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1508
1509       /* Update the final write buffer with this inserted
1510          breakpoint's INSN.  */
1511       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1512     }
1513 }
1514
1515 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1516    by replacing any memory breakpoints with their shadowed contents.
1517
1518    If READBUF is not NULL, this buffer must not overlap with any of
1519    the breakpoint location's shadow_contents buffers.  Otherwise,
1520    a failed assertion internal error will be raised.
1521
1522    The range of shadowed area by each bp_location is:
1523      bl->address - bp_location_placed_address_before_address_max
1524      up to bl->address + bp_location_shadow_len_after_address_max
1525    The range we were requested to resolve shadows for is:
1526      memaddr ... memaddr + len
1527    Thus the safe cutoff boundaries for performance optimization are
1528      memaddr + len <= (bl->address
1529                        - bp_location_placed_address_before_address_max)
1530    and:
1531      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1532
1533 void
1534 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1535                         const gdb_byte *writebuf_org,
1536                         ULONGEST memaddr, LONGEST len)
1537 {
1538   /* Left boundary, right boundary and median element of our binary
1539      search.  */
1540   unsigned bc_l, bc_r, bc;
1541   size_t i;
1542
1543   /* Find BC_L which is a leftmost element which may affect BUF
1544      content.  It is safe to report lower value but a failure to
1545      report higher one.  */
1546
1547   bc_l = 0;
1548   bc_r = bp_location_count;
1549   while (bc_l + 1 < bc_r)
1550     {
1551       struct bp_location *bl;
1552
1553       bc = (bc_l + bc_r) / 2;
1554       bl = bp_location[bc];
1555
1556       /* Check first BL->ADDRESS will not overflow due to the added
1557          constant.  Then advance the left boundary only if we are sure
1558          the BC element can in no way affect the BUF content (MEMADDR
1559          to MEMADDR + LEN range).
1560
1561          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1562          offset so that we cannot miss a breakpoint with its shadow
1563          range tail still reaching MEMADDR.  */
1564
1565       if ((bl->address + bp_location_shadow_len_after_address_max
1566            >= bl->address)
1567           && (bl->address + bp_location_shadow_len_after_address_max
1568               <= memaddr))
1569         bc_l = bc;
1570       else
1571         bc_r = bc;
1572     }
1573
1574   /* Due to the binary search above, we need to make sure we pick the
1575      first location that's at BC_L's address.  E.g., if there are
1576      multiple locations at the same address, BC_L may end up pointing
1577      at a duplicate location, and miss the "master"/"inserted"
1578      location.  Say, given locations L1, L2 and L3 at addresses A and
1579      B:
1580
1581       L1@A, L2@A, L3@B, ...
1582
1583      BC_L could end up pointing at location L2, while the "master"
1584      location could be L1.  Since the `loc->inserted' flag is only set
1585      on "master" locations, we'd forget to restore the shadow of L1
1586      and L2.  */
1587   while (bc_l > 0
1588          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1589     bc_l--;
1590
1591   /* Now do full processing of the found relevant range of elements.  */
1592
1593   for (bc = bc_l; bc < bp_location_count; bc++)
1594   {
1595     struct bp_location *bl = bp_location[bc];
1596     CORE_ADDR bp_addr = 0;
1597     int bp_size = 0;
1598     int bptoffset = 0;
1599
1600     /* bp_location array has BL->OWNER always non-NULL.  */
1601     if (bl->owner->type == bp_none)
1602       warning (_("reading through apparently deleted breakpoint #%d?"),
1603                bl->owner->number);
1604
1605     /* Performance optimization: any further element can no longer affect BUF
1606        content.  */
1607
1608     if (bl->address >= bp_location_placed_address_before_address_max
1609         && memaddr + len <= (bl->address
1610                              - bp_location_placed_address_before_address_max))
1611       break;
1612
1613     if (!bp_location_has_shadow (bl))
1614       continue;
1615
1616     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1617                                 memaddr, len, &bl->target_info, bl->gdbarch);
1618   }
1619
1620   /* Now process single-step breakpoints.  These are not found in the
1621      bp_location array.  */
1622   for (i = 0; i < 2; i++)
1623     {
1624       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1625
1626       if (bp_tgt != NULL)
1627         {
1628           struct gdbarch *gdbarch = single_step_gdbarch[i];
1629
1630           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1631                                       memaddr, len, bp_tgt, gdbarch);
1632         }
1633     }
1634 }
1635
1636 \f
1637
1638 /* Return true if BPT is either a software breakpoint or a hardware
1639    breakpoint.  */
1640
1641 int
1642 is_breakpoint (const struct breakpoint *bpt)
1643 {
1644   return (bpt->type == bp_breakpoint
1645           || bpt->type == bp_hardware_breakpoint
1646           || bpt->type == bp_dprintf);
1647 }
1648
1649 /* Return true if BPT is of any hardware watchpoint kind.  */
1650
1651 static int
1652 is_hardware_watchpoint (const struct breakpoint *bpt)
1653 {
1654   return (bpt->type == bp_hardware_watchpoint
1655           || bpt->type == bp_read_watchpoint
1656           || bpt->type == bp_access_watchpoint);
1657 }
1658
1659 /* Return true if BPT is of any watchpoint kind, hardware or
1660    software.  */
1661
1662 int
1663 is_watchpoint (const struct breakpoint *bpt)
1664 {
1665   return (is_hardware_watchpoint (bpt)
1666           || bpt->type == bp_watchpoint);
1667 }
1668
1669 /* Returns true if the current thread and its running state are safe
1670    to evaluate or update watchpoint B.  Watchpoints on local
1671    expressions need to be evaluated in the context of the thread that
1672    was current when the watchpoint was created, and, that thread needs
1673    to be stopped to be able to select the correct frame context.
1674    Watchpoints on global expressions can be evaluated on any thread,
1675    and in any state.  It is presently left to the target allowing
1676    memory accesses when threads are running.  */
1677
1678 static int
1679 watchpoint_in_thread_scope (struct watchpoint *b)
1680 {
1681   return (b->base.pspace == current_program_space
1682           && (ptid_equal (b->watchpoint_thread, null_ptid)
1683               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1684                   && !is_executing (inferior_ptid))));
1685 }
1686
1687 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1688    associated bp_watchpoint_scope breakpoint.  */
1689
1690 static void
1691 watchpoint_del_at_next_stop (struct watchpoint *w)
1692 {
1693   struct breakpoint *b = &w->base;
1694
1695   if (b->related_breakpoint != b)
1696     {
1697       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1698       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1699       b->related_breakpoint->disposition = disp_del_at_next_stop;
1700       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1701       b->related_breakpoint = b;
1702     }
1703   b->disposition = disp_del_at_next_stop;
1704 }
1705
1706 /* Extract a bitfield value from value VAL using the bit parameters contained in
1707    watchpoint W.  */
1708
1709 static struct value *
1710 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1711 {
1712   struct value *bit_val;
1713
1714   if (val == NULL)
1715     return NULL;
1716
1717   bit_val = allocate_value (value_type (val));
1718
1719   unpack_value_bitfield (bit_val,
1720                          w->val_bitpos,
1721                          w->val_bitsize,
1722                          value_contents_for_printing (val),
1723                          value_offset (val),
1724                          val);
1725
1726   return bit_val;
1727 }
1728
1729 /* Assuming that B is a watchpoint:
1730    - Reparse watchpoint expression, if REPARSE is non-zero
1731    - Evaluate expression and store the result in B->val
1732    - Evaluate the condition if there is one, and store the result
1733      in b->loc->cond.
1734    - Update the list of values that must be watched in B->loc.
1735
1736    If the watchpoint disposition is disp_del_at_next_stop, then do
1737    nothing.  If this is local watchpoint that is out of scope, delete
1738    it.
1739
1740    Even with `set breakpoint always-inserted on' the watchpoints are
1741    removed + inserted on each stop here.  Normal breakpoints must
1742    never be removed because they might be missed by a running thread
1743    when debugging in non-stop mode.  On the other hand, hardware
1744    watchpoints (is_hardware_watchpoint; processed here) are specific
1745    to each LWP since they are stored in each LWP's hardware debug
1746    registers.  Therefore, such LWP must be stopped first in order to
1747    be able to modify its hardware watchpoints.
1748
1749    Hardware watchpoints must be reset exactly once after being
1750    presented to the user.  It cannot be done sooner, because it would
1751    reset the data used to present the watchpoint hit to the user.  And
1752    it must not be done later because it could display the same single
1753    watchpoint hit during multiple GDB stops.  Note that the latter is
1754    relevant only to the hardware watchpoint types bp_read_watchpoint
1755    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1756    not user-visible - its hit is suppressed if the memory content has
1757    not changed.
1758
1759    The following constraints influence the location where we can reset
1760    hardware watchpoints:
1761
1762    * target_stopped_by_watchpoint and target_stopped_data_address are
1763      called several times when GDB stops.
1764
1765    [linux] 
1766    * Multiple hardware watchpoints can be hit at the same time,
1767      causing GDB to stop.  GDB only presents one hardware watchpoint
1768      hit at a time as the reason for stopping, and all the other hits
1769      are presented later, one after the other, each time the user
1770      requests the execution to be resumed.  Execution is not resumed
1771      for the threads still having pending hit event stored in
1772      LWP_INFO->STATUS.  While the watchpoint is already removed from
1773      the inferior on the first stop the thread hit event is kept being
1774      reported from its cached value by linux_nat_stopped_data_address
1775      until the real thread resume happens after the watchpoint gets
1776      presented and thus its LWP_INFO->STATUS gets reset.
1777
1778    Therefore the hardware watchpoint hit can get safely reset on the
1779    watchpoint removal from inferior.  */
1780
1781 static void
1782 update_watchpoint (struct watchpoint *b, int reparse)
1783 {
1784   int within_current_scope;
1785   struct frame_id saved_frame_id;
1786   int frame_saved;
1787
1788   /* If this is a local watchpoint, we only want to check if the
1789      watchpoint frame is in scope if the current thread is the thread
1790      that was used to create the watchpoint.  */
1791   if (!watchpoint_in_thread_scope (b))
1792     return;
1793
1794   if (b->base.disposition == disp_del_at_next_stop)
1795     return;
1796  
1797   frame_saved = 0;
1798
1799   /* Determine if the watchpoint is within scope.  */
1800   if (b->exp_valid_block == NULL)
1801     within_current_scope = 1;
1802   else
1803     {
1804       struct frame_info *fi = get_current_frame ();
1805       struct gdbarch *frame_arch = get_frame_arch (fi);
1806       CORE_ADDR frame_pc = get_frame_pc (fi);
1807
1808       /* If we're in a function epilogue, unwinding may not work
1809          properly, so do not attempt to recreate locations at this
1810          point.  See similar comments in watchpoint_check.  */
1811       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1812         return;
1813
1814       /* Save the current frame's ID so we can restore it after
1815          evaluating the watchpoint expression on its own frame.  */
1816       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1817          took a frame parameter, so that we didn't have to change the
1818          selected frame.  */
1819       frame_saved = 1;
1820       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1821
1822       fi = frame_find_by_id (b->watchpoint_frame);
1823       within_current_scope = (fi != NULL);
1824       if (within_current_scope)
1825         select_frame (fi);
1826     }
1827
1828   /* We don't free locations.  They are stored in the bp_location array
1829      and update_global_location_list will eventually delete them and
1830      remove breakpoints if needed.  */
1831   b->base.loc = NULL;
1832
1833   if (within_current_scope && reparse)
1834     {
1835       const char *s;
1836
1837       if (b->exp)
1838         {
1839           xfree (b->exp);
1840           b->exp = NULL;
1841         }
1842       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1843       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1844       /* If the meaning of expression itself changed, the old value is
1845          no longer relevant.  We don't want to report a watchpoint hit
1846          to the user when the old value and the new value may actually
1847          be completely different objects.  */
1848       value_free (b->val);
1849       b->val = NULL;
1850       b->val_valid = 0;
1851
1852       /* Note that unlike with breakpoints, the watchpoint's condition
1853          expression is stored in the breakpoint object, not in the
1854          locations (re)created below.  */
1855       if (b->base.cond_string != NULL)
1856         {
1857           if (b->cond_exp != NULL)
1858             {
1859               xfree (b->cond_exp);
1860               b->cond_exp = NULL;
1861             }
1862
1863           s = b->base.cond_string;
1864           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1865         }
1866     }
1867
1868   /* If we failed to parse the expression, for example because
1869      it refers to a global variable in a not-yet-loaded shared library,
1870      don't try to insert watchpoint.  We don't automatically delete
1871      such watchpoint, though, since failure to parse expression
1872      is different from out-of-scope watchpoint.  */
1873   if (!target_has_execution)
1874     {
1875       /* Without execution, memory can't change.  No use to try and
1876          set watchpoint locations.  The watchpoint will be reset when
1877          the target gains execution, through breakpoint_re_set.  */
1878       if (!can_use_hw_watchpoints)
1879         {
1880           if (b->base.ops->works_in_software_mode (&b->base))
1881             b->base.type = bp_watchpoint;
1882           else
1883             error (_("Can't set read/access watchpoint when "
1884                      "hardware watchpoints are disabled."));
1885         }
1886     }
1887   else if (within_current_scope && b->exp)
1888     {
1889       int pc = 0;
1890       struct value *val_chain, *v, *result, *next;
1891       struct program_space *frame_pspace;
1892
1893       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1894
1895       /* Avoid setting b->val if it's already set.  The meaning of
1896          b->val is 'the last value' user saw, and we should update
1897          it only if we reported that last value to user.  As it
1898          happens, the code that reports it updates b->val directly.
1899          We don't keep track of the memory value for masked
1900          watchpoints.  */
1901       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1902         {
1903           if (b->val_bitsize != 0)
1904             {
1905               v = extract_bitfield_from_watchpoint_value (b, v);
1906               if (v != NULL)
1907                 release_value (v);
1908             }
1909           b->val = v;
1910           b->val_valid = 1;
1911         }
1912
1913       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1914
1915       /* Look at each value on the value chain.  */
1916       for (v = val_chain; v; v = value_next (v))
1917         {
1918           /* If it's a memory location, and GDB actually needed
1919              its contents to evaluate the expression, then we
1920              must watch it.  If the first value returned is
1921              still lazy, that means an error occurred reading it;
1922              watch it anyway in case it becomes readable.  */
1923           if (VALUE_LVAL (v) == lval_memory
1924               && (v == val_chain || ! value_lazy (v)))
1925             {
1926               struct type *vtype = check_typedef (value_type (v));
1927
1928               /* We only watch structs and arrays if user asked
1929                  for it explicitly, never if they just happen to
1930                  appear in the middle of some value chain.  */
1931               if (v == result
1932                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1933                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1934                 {
1935                   CORE_ADDR addr;
1936                   int type;
1937                   struct bp_location *loc, **tmp;
1938                   int bitpos = 0, bitsize = 0;
1939
1940                   if (value_bitsize (v) != 0)
1941                     {
1942                       /* Extract the bit parameters out from the bitfield
1943                          sub-expression.  */
1944                       bitpos = value_bitpos (v);
1945                       bitsize = value_bitsize (v);
1946                     }
1947                   else if (v == result && b->val_bitsize != 0)
1948                     {
1949                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1950                         lvalue whose bit parameters are saved in the fields
1951                         VAL_BITPOS and VAL_BITSIZE.  */
1952                       bitpos = b->val_bitpos;
1953                       bitsize = b->val_bitsize;
1954                     }
1955
1956                   addr = value_address (v);
1957                   if (bitsize != 0)
1958                     {
1959                       /* Skip the bytes that don't contain the bitfield.  */
1960                       addr += bitpos / 8;
1961                     }
1962
1963                   type = hw_write;
1964                   if (b->base.type == bp_read_watchpoint)
1965                     type = hw_read;
1966                   else if (b->base.type == bp_access_watchpoint)
1967                     type = hw_access;
1968
1969                   loc = allocate_bp_location (&b->base);
1970                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1971                     ;
1972                   *tmp = loc;
1973                   loc->gdbarch = get_type_arch (value_type (v));
1974
1975                   loc->pspace = frame_pspace;
1976                   loc->address = addr;
1977
1978                   if (bitsize != 0)
1979                     {
1980                       /* Just cover the bytes that make up the bitfield.  */
1981                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1982                     }
1983                   else
1984                     loc->length = TYPE_LENGTH (value_type (v));
1985
1986                   loc->watchpoint_type = type;
1987                 }
1988             }
1989         }
1990
1991       /* Change the type of breakpoint between hardware assisted or
1992          an ordinary watchpoint depending on the hardware support
1993          and free hardware slots.  REPARSE is set when the inferior
1994          is started.  */
1995       if (reparse)
1996         {
1997           int reg_cnt;
1998           enum bp_loc_type loc_type;
1999           struct bp_location *bl;
2000
2001           reg_cnt = can_use_hardware_watchpoint (val_chain);
2002
2003           if (reg_cnt)
2004             {
2005               int i, target_resources_ok, other_type_used;
2006               enum bptype type;
2007
2008               /* Use an exact watchpoint when there's only one memory region to be
2009                  watched, and only one debug register is needed to watch it.  */
2010               b->exact = target_exact_watchpoints && reg_cnt == 1;
2011
2012               /* We need to determine how many resources are already
2013                  used for all other hardware watchpoints plus this one
2014                  to see if we still have enough resources to also fit
2015                  this watchpoint in as well.  */
2016
2017               /* If this is a software watchpoint, we try to turn it
2018                  to a hardware one -- count resources as if B was of
2019                  hardware watchpoint type.  */
2020               type = b->base.type;
2021               if (type == bp_watchpoint)
2022                 type = bp_hardware_watchpoint;
2023
2024               /* This watchpoint may or may not have been placed on
2025                  the list yet at this point (it won't be in the list
2026                  if we're trying to create it for the first time,
2027                  through watch_command), so always account for it
2028                  manually.  */
2029
2030               /* Count resources used by all watchpoints except B.  */
2031               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2032
2033               /* Add in the resources needed for B.  */
2034               i += hw_watchpoint_use_count (&b->base);
2035
2036               target_resources_ok
2037                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2038               if (target_resources_ok <= 0)
2039                 {
2040                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2041
2042                   if (target_resources_ok == 0 && !sw_mode)
2043                     error (_("Target does not support this type of "
2044                              "hardware watchpoint."));
2045                   else if (target_resources_ok < 0 && !sw_mode)
2046                     error (_("There are not enough available hardware "
2047                              "resources for this watchpoint."));
2048
2049                   /* Downgrade to software watchpoint.  */
2050                   b->base.type = bp_watchpoint;
2051                 }
2052               else
2053                 {
2054                   /* If this was a software watchpoint, we've just
2055                      found we have enough resources to turn it to a
2056                      hardware watchpoint.  Otherwise, this is a
2057                      nop.  */
2058                   b->base.type = type;
2059                 }
2060             }
2061           else if (!b->base.ops->works_in_software_mode (&b->base))
2062             {
2063               if (!can_use_hw_watchpoints)
2064                 error (_("Can't set read/access watchpoint when "
2065                          "hardware watchpoints are disabled."));
2066               else
2067                 error (_("Expression cannot be implemented with "
2068                          "read/access watchpoint."));
2069             }
2070           else
2071             b->base.type = bp_watchpoint;
2072
2073           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2074                       : bp_loc_hardware_watchpoint);
2075           for (bl = b->base.loc; bl; bl = bl->next)
2076             bl->loc_type = loc_type;
2077         }
2078
2079       for (v = val_chain; v; v = next)
2080         {
2081           next = value_next (v);
2082           if (v != b->val)
2083             value_free (v);
2084         }
2085
2086       /* If a software watchpoint is not watching any memory, then the
2087          above left it without any location set up.  But,
2088          bpstat_stop_status requires a location to be able to report
2089          stops, so make sure there's at least a dummy one.  */
2090       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2091         {
2092           struct breakpoint *base = &b->base;
2093           base->loc = allocate_bp_location (base);
2094           base->loc->pspace = frame_pspace;
2095           base->loc->address = -1;
2096           base->loc->length = -1;
2097           base->loc->watchpoint_type = -1;
2098         }
2099     }
2100   else if (!within_current_scope)
2101     {
2102       printf_filtered (_("\
2103 Watchpoint %d deleted because the program has left the block\n\
2104 in which its expression is valid.\n"),
2105                        b->base.number);
2106       watchpoint_del_at_next_stop (b);
2107     }
2108
2109   /* Restore the selected frame.  */
2110   if (frame_saved)
2111     select_frame (frame_find_by_id (saved_frame_id));
2112 }
2113
2114
2115 /* Returns 1 iff breakpoint location should be
2116    inserted in the inferior.  We don't differentiate the type of BL's owner
2117    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2118    breakpoint_ops is not defined, because in insert_bp_location,
2119    tracepoint's insert_location will not be called.  */
2120 static int
2121 should_be_inserted (struct bp_location *bl)
2122 {
2123   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2124     return 0;
2125
2126   if (bl->owner->disposition == disp_del_at_next_stop)
2127     return 0;
2128
2129   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2130     return 0;
2131
2132   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2133     return 0;
2134
2135   /* This is set for example, when we're attached to the parent of a
2136      vfork, and have detached from the child.  The child is running
2137      free, and we expect it to do an exec or exit, at which point the
2138      OS makes the parent schedulable again (and the target reports
2139      that the vfork is done).  Until the child is done with the shared
2140      memory region, do not insert breakpoints in the parent, otherwise
2141      the child could still trip on the parent's breakpoints.  Since
2142      the parent is blocked anyway, it won't miss any breakpoint.  */
2143   if (bl->pspace->breakpoints_not_allowed)
2144     return 0;
2145
2146   /* Don't insert a breakpoint if we're trying to step past its
2147      location.  */
2148   if ((bl->loc_type == bp_loc_software_breakpoint
2149        || bl->loc_type == bp_loc_hardware_breakpoint)
2150       && stepping_past_instruction_at (bl->pspace->aspace,
2151                                        bl->address))
2152     return 0;
2153
2154   return 1;
2155 }
2156
2157 /* Same as should_be_inserted but does the check assuming
2158    that the location is not duplicated.  */
2159
2160 static int
2161 unduplicated_should_be_inserted (struct bp_location *bl)
2162 {
2163   int result;
2164   const int save_duplicate = bl->duplicate;
2165
2166   bl->duplicate = 0;
2167   result = should_be_inserted (bl);
2168   bl->duplicate = save_duplicate;
2169   return result;
2170 }
2171
2172 /* Parses a conditional described by an expression COND into an
2173    agent expression bytecode suitable for evaluation
2174    by the bytecode interpreter.  Return NULL if there was
2175    any error during parsing.  */
2176
2177 static struct agent_expr *
2178 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2179 {
2180   struct agent_expr *aexpr = NULL;
2181   volatile struct gdb_exception ex;
2182
2183   if (!cond)
2184     return NULL;
2185
2186   /* We don't want to stop processing, so catch any errors
2187      that may show up.  */
2188   TRY_CATCH (ex, RETURN_MASK_ERROR)
2189     {
2190       aexpr = gen_eval_for_expr (scope, cond);
2191     }
2192
2193   if (ex.reason < 0)
2194     {
2195       /* If we got here, it means the condition could not be parsed to a valid
2196          bytecode expression and thus can't be evaluated on the target's side.
2197          It's no use iterating through the conditions.  */
2198       return NULL;
2199     }
2200
2201   /* We have a valid agent expression.  */
2202   return aexpr;
2203 }
2204
2205 /* Based on location BL, create a list of breakpoint conditions to be
2206    passed on to the target.  If we have duplicated locations with different
2207    conditions, we will add such conditions to the list.  The idea is that the
2208    target will evaluate the list of conditions and will only notify GDB when
2209    one of them is true.  */
2210
2211 static void
2212 build_target_condition_list (struct bp_location *bl)
2213 {
2214   struct bp_location **locp = NULL, **loc2p;
2215   int null_condition_or_parse_error = 0;
2216   int modified = bl->needs_update;
2217   struct bp_location *loc;
2218
2219   /* Release conditions left over from a previous insert.  */
2220   VEC_free (agent_expr_p, bl->target_info.conditions);
2221
2222   /* This is only meaningful if the target is
2223      evaluating conditions and if the user has
2224      opted for condition evaluation on the target's
2225      side.  */
2226   if (gdb_evaluates_breakpoint_condition_p ()
2227       || !target_supports_evaluation_of_breakpoint_conditions ())
2228     return;
2229
2230   /* Do a first pass to check for locations with no assigned
2231      conditions or conditions that fail to parse to a valid agent expression
2232      bytecode.  If any of these happen, then it's no use to send conditions
2233      to the target since this location will always trigger and generate a
2234      response back to GDB.  */
2235   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2236     {
2237       loc = (*loc2p);
2238       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2239         {
2240           if (modified)
2241             {
2242               struct agent_expr *aexpr;
2243
2244               /* Re-parse the conditions since something changed.  In that
2245                  case we already freed the condition bytecodes (see
2246                  force_breakpoint_reinsertion).  We just
2247                  need to parse the condition to bytecodes again.  */
2248               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2249               loc->cond_bytecode = aexpr;
2250
2251               /* Check if we managed to parse the conditional expression
2252                  correctly.  If not, we will not send this condition
2253                  to the target.  */
2254               if (aexpr)
2255                 continue;
2256             }
2257
2258           /* If we have a NULL bytecode expression, it means something
2259              went wrong or we have a null condition expression.  */
2260           if (!loc->cond_bytecode)
2261             {
2262               null_condition_or_parse_error = 1;
2263               break;
2264             }
2265         }
2266     }
2267
2268   /* If any of these happened, it means we will have to evaluate the conditions
2269      for the location's address on gdb's side.  It is no use keeping bytecodes
2270      for all the other duplicate locations, thus we free all of them here.
2271
2272      This is so we have a finer control over which locations' conditions are
2273      being evaluated by GDB or the remote stub.  */
2274   if (null_condition_or_parse_error)
2275     {
2276       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2277         {
2278           loc = (*loc2p);
2279           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2280             {
2281               /* Only go as far as the first NULL bytecode is
2282                  located.  */
2283               if (!loc->cond_bytecode)
2284                 return;
2285
2286               free_agent_expr (loc->cond_bytecode);
2287               loc->cond_bytecode = NULL;
2288             }
2289         }
2290     }
2291
2292   /* No NULL conditions or failed bytecode generation.  Build a condition list
2293      for this location's address.  */
2294   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2295     {
2296       loc = (*loc2p);
2297       if (loc->cond
2298           && is_breakpoint (loc->owner)
2299           && loc->pspace->num == bl->pspace->num
2300           && loc->owner->enable_state == bp_enabled
2301           && loc->enabled)
2302         /* Add the condition to the vector.  This will be used later to send the
2303            conditions to the target.  */
2304         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2305                        loc->cond_bytecode);
2306     }
2307
2308   return;
2309 }
2310
2311 /* Parses a command described by string CMD into an agent expression
2312    bytecode suitable for evaluation by the bytecode interpreter.
2313    Return NULL if there was any error during parsing.  */
2314
2315 static struct agent_expr *
2316 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2317 {
2318   struct cleanup *old_cleanups = 0;
2319   struct expression *expr, **argvec;
2320   struct agent_expr *aexpr = NULL;
2321   volatile struct gdb_exception ex;
2322   const char *cmdrest;
2323   const char *format_start, *format_end;
2324   struct format_piece *fpieces;
2325   int nargs;
2326   struct gdbarch *gdbarch = get_current_arch ();
2327
2328   if (!cmd)
2329     return NULL;
2330
2331   cmdrest = cmd;
2332
2333   if (*cmdrest == ',')
2334     ++cmdrest;
2335   cmdrest = skip_spaces_const (cmdrest);
2336
2337   if (*cmdrest++ != '"')
2338     error (_("No format string following the location"));
2339
2340   format_start = cmdrest;
2341
2342   fpieces = parse_format_string (&cmdrest);
2343
2344   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2345
2346   format_end = cmdrest;
2347
2348   if (*cmdrest++ != '"')
2349     error (_("Bad format string, non-terminated '\"'."));
2350   
2351   cmdrest = skip_spaces_const (cmdrest);
2352
2353   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2354     error (_("Invalid argument syntax"));
2355
2356   if (*cmdrest == ',')
2357     cmdrest++;
2358   cmdrest = skip_spaces_const (cmdrest);
2359
2360   /* For each argument, make an expression.  */
2361
2362   argvec = (struct expression **) alloca (strlen (cmd)
2363                                          * sizeof (struct expression *));
2364
2365   nargs = 0;
2366   while (*cmdrest != '\0')
2367     {
2368       const char *cmd1;
2369
2370       cmd1 = cmdrest;
2371       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2372       argvec[nargs++] = expr;
2373       cmdrest = cmd1;
2374       if (*cmdrest == ',')
2375         ++cmdrest;
2376     }
2377
2378   /* We don't want to stop processing, so catch any errors
2379      that may show up.  */
2380   TRY_CATCH (ex, RETURN_MASK_ERROR)
2381     {
2382       aexpr = gen_printf (scope, gdbarch, 0, 0,
2383                           format_start, format_end - format_start,
2384                           fpieces, nargs, argvec);
2385     }
2386
2387   do_cleanups (old_cleanups);
2388
2389   if (ex.reason < 0)
2390     {
2391       /* If we got here, it means the command could not be parsed to a valid
2392          bytecode expression and thus can't be evaluated on the target's side.
2393          It's no use iterating through the other commands.  */
2394       return NULL;
2395     }
2396
2397   /* We have a valid agent expression, return it.  */
2398   return aexpr;
2399 }
2400
2401 /* Based on location BL, create a list of breakpoint commands to be
2402    passed on to the target.  If we have duplicated locations with
2403    different commands, we will add any such to the list.  */
2404
2405 static void
2406 build_target_command_list (struct bp_location *bl)
2407 {
2408   struct bp_location **locp = NULL, **loc2p;
2409   int null_command_or_parse_error = 0;
2410   int modified = bl->needs_update;
2411   struct bp_location *loc;
2412
2413   /* Release commands left over from a previous insert.  */
2414   VEC_free (agent_expr_p, bl->target_info.tcommands);
2415
2416   if (!target_can_run_breakpoint_commands ())
2417     return;
2418
2419   /* For now, limit to agent-style dprintf breakpoints.  */
2420   if (dprintf_style != dprintf_style_agent)
2421     return;
2422
2423   /* For now, if we have any duplicate location that isn't a dprintf,
2424      don't install the target-side commands, as that would make the
2425      breakpoint not be reported to the core, and we'd lose
2426      control.  */
2427   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2428     {
2429       loc = (*loc2p);
2430       if (is_breakpoint (loc->owner)
2431           && loc->pspace->num == bl->pspace->num
2432           && loc->owner->type != bp_dprintf)
2433         return;
2434     }
2435
2436   /* Do a first pass to check for locations with no assigned
2437      conditions or conditions that fail to parse to a valid agent expression
2438      bytecode.  If any of these happen, then it's no use to send conditions
2439      to the target since this location will always trigger and generate a
2440      response back to GDB.  */
2441   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2442     {
2443       loc = (*loc2p);
2444       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2445         {
2446           if (modified)
2447             {
2448               struct agent_expr *aexpr;
2449
2450               /* Re-parse the commands since something changed.  In that
2451                  case we already freed the command bytecodes (see
2452                  force_breakpoint_reinsertion).  We just
2453                  need to parse the command to bytecodes again.  */
2454               aexpr = parse_cmd_to_aexpr (bl->address,
2455                                           loc->owner->extra_string);
2456               loc->cmd_bytecode = aexpr;
2457
2458               if (!aexpr)
2459                 continue;
2460             }
2461
2462           /* If we have a NULL bytecode expression, it means something
2463              went wrong or we have a null command expression.  */
2464           if (!loc->cmd_bytecode)
2465             {
2466               null_command_or_parse_error = 1;
2467               break;
2468             }
2469         }
2470     }
2471
2472   /* If anything failed, then we're not doing target-side commands,
2473      and so clean up.  */
2474   if (null_command_or_parse_error)
2475     {
2476       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2477         {
2478           loc = (*loc2p);
2479           if (is_breakpoint (loc->owner)
2480               && loc->pspace->num == bl->pspace->num)
2481             {
2482               /* Only go as far as the first NULL bytecode is
2483                  located.  */
2484               if (loc->cmd_bytecode == NULL)
2485                 return;
2486
2487               free_agent_expr (loc->cmd_bytecode);
2488               loc->cmd_bytecode = NULL;
2489             }
2490         }
2491     }
2492
2493   /* No NULL commands or failed bytecode generation.  Build a command list
2494      for this location's address.  */
2495   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2496     {
2497       loc = (*loc2p);
2498       if (loc->owner->extra_string
2499           && is_breakpoint (loc->owner)
2500           && loc->pspace->num == bl->pspace->num
2501           && loc->owner->enable_state == bp_enabled
2502           && loc->enabled)
2503         /* Add the command to the vector.  This will be used later
2504            to send the commands to the target.  */
2505         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2506                        loc->cmd_bytecode);
2507     }
2508
2509   bl->target_info.persist = 0;
2510   /* Maybe flag this location as persistent.  */
2511   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2512     bl->target_info.persist = 1;
2513 }
2514
2515 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2516    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2517    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2518    Returns 0 for success, 1 if the bp_location type is not supported or
2519    -1 for failure.
2520
2521    NOTE drow/2003-09-09: This routine could be broken down to an
2522    object-style method for each breakpoint or catchpoint type.  */
2523 static int
2524 insert_bp_location (struct bp_location *bl,
2525                     struct ui_file *tmp_error_stream,
2526                     int *disabled_breaks,
2527                     int *hw_breakpoint_error,
2528                     int *hw_bp_error_explained_already)
2529 {
2530   enum errors bp_err = GDB_NO_ERROR;
2531   const char *bp_err_message = NULL;
2532   volatile struct gdb_exception e;
2533
2534   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2535     return 0;
2536
2537   /* Note we don't initialize bl->target_info, as that wipes out
2538      the breakpoint location's shadow_contents if the breakpoint
2539      is still inserted at that location.  This in turn breaks
2540      target_read_memory which depends on these buffers when
2541      a memory read is requested at the breakpoint location:
2542      Once the target_info has been wiped, we fail to see that
2543      we have a breakpoint inserted at that address and thus
2544      read the breakpoint instead of returning the data saved in
2545      the breakpoint location's shadow contents.  */
2546   bl->target_info.placed_address = bl->address;
2547   bl->target_info.placed_address_space = bl->pspace->aspace;
2548   bl->target_info.length = bl->length;
2549
2550   /* When working with target-side conditions, we must pass all the conditions
2551      for the same breakpoint address down to the target since GDB will not
2552      insert those locations.  With a list of breakpoint conditions, the target
2553      can decide when to stop and notify GDB.  */
2554
2555   if (is_breakpoint (bl->owner))
2556     {
2557       build_target_condition_list (bl);
2558       build_target_command_list (bl);
2559       /* Reset the modification marker.  */
2560       bl->needs_update = 0;
2561     }
2562
2563   if (bl->loc_type == bp_loc_software_breakpoint
2564       || bl->loc_type == bp_loc_hardware_breakpoint)
2565     {
2566       if (bl->owner->type != bp_hardware_breakpoint)
2567         {
2568           /* If the explicitly specified breakpoint type
2569              is not hardware breakpoint, check the memory map to see
2570              if the breakpoint address is in read only memory or not.
2571
2572              Two important cases are:
2573              - location type is not hardware breakpoint, memory
2574              is readonly.  We change the type of the location to
2575              hardware breakpoint.
2576              - location type is hardware breakpoint, memory is
2577              read-write.  This means we've previously made the
2578              location hardware one, but then the memory map changed,
2579              so we undo.
2580              
2581              When breakpoints are removed, remove_breakpoints will use
2582              location types we've just set here, the only possible
2583              problem is that memory map has changed during running
2584              program, but it's not going to work anyway with current
2585              gdb.  */
2586           struct mem_region *mr 
2587             = lookup_mem_region (bl->target_info.placed_address);
2588           
2589           if (mr)
2590             {
2591               if (automatic_hardware_breakpoints)
2592                 {
2593                   enum bp_loc_type new_type;
2594                   
2595                   if (mr->attrib.mode != MEM_RW)
2596                     new_type = bp_loc_hardware_breakpoint;
2597                   else 
2598                     new_type = bp_loc_software_breakpoint;
2599                   
2600                   if (new_type != bl->loc_type)
2601                     {
2602                       static int said = 0;
2603
2604                       bl->loc_type = new_type;
2605                       if (!said)
2606                         {
2607                           fprintf_filtered (gdb_stdout,
2608                                             _("Note: automatically using "
2609                                               "hardware breakpoints for "
2610                                               "read-only addresses.\n"));
2611                           said = 1;
2612                         }
2613                     }
2614                 }
2615               else if (bl->loc_type == bp_loc_software_breakpoint
2616                        && mr->attrib.mode != MEM_RW)        
2617                 warning (_("cannot set software breakpoint "
2618                            "at readonly address %s"),
2619                          paddress (bl->gdbarch, bl->address));
2620             }
2621         }
2622         
2623       /* First check to see if we have to handle an overlay.  */
2624       if (overlay_debugging == ovly_off
2625           || bl->section == NULL
2626           || !(section_is_overlay (bl->section)))
2627         {
2628           /* No overlay handling: just set the breakpoint.  */
2629           TRY_CATCH (e, RETURN_MASK_ALL)
2630             {
2631               int val;
2632
2633               val = bl->owner->ops->insert_location (bl);
2634               if (val)
2635                 bp_err = GENERIC_ERROR;
2636             }
2637           if (e.reason < 0)
2638             {
2639               bp_err = e.error;
2640               bp_err_message = e.message;
2641             }
2642         }
2643       else
2644         {
2645           /* This breakpoint is in an overlay section.
2646              Shall we set a breakpoint at the LMA?  */
2647           if (!overlay_events_enabled)
2648             {
2649               /* Yes -- overlay event support is not active, 
2650                  so we must try to set a breakpoint at the LMA.
2651                  This will not work for a hardware breakpoint.  */
2652               if (bl->loc_type == bp_loc_hardware_breakpoint)
2653                 warning (_("hardware breakpoint %d not supported in overlay!"),
2654                          bl->owner->number);
2655               else
2656                 {
2657                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2658                                                              bl->section);
2659                   /* Set a software (trap) breakpoint at the LMA.  */
2660                   bl->overlay_target_info = bl->target_info;
2661                   bl->overlay_target_info.placed_address = addr;
2662
2663                   /* No overlay handling: just set the breakpoint.  */
2664                   TRY_CATCH (e, RETURN_MASK_ALL)
2665                     {
2666                       int val;
2667
2668                       val = target_insert_breakpoint (bl->gdbarch,
2669                                                       &bl->overlay_target_info);
2670                       if (val)
2671                         bp_err = GENERIC_ERROR;
2672                     }
2673                   if (e.reason < 0)
2674                     {
2675                       bp_err = e.error;
2676                       bp_err_message = e.message;
2677                     }
2678
2679                   if (bp_err != GDB_NO_ERROR)
2680                     fprintf_unfiltered (tmp_error_stream,
2681                                         "Overlay breakpoint %d "
2682                                         "failed: in ROM?\n",
2683                                         bl->owner->number);
2684                 }
2685             }
2686           /* Shall we set a breakpoint at the VMA? */
2687           if (section_is_mapped (bl->section))
2688             {
2689               /* Yes.  This overlay section is mapped into memory.  */
2690               TRY_CATCH (e, RETURN_MASK_ALL)
2691                 {
2692                   int val;
2693
2694                   val = bl->owner->ops->insert_location (bl);
2695                   if (val)
2696                     bp_err = GENERIC_ERROR;
2697                 }
2698               if (e.reason < 0)
2699                 {
2700                   bp_err = e.error;
2701                   bp_err_message = e.message;
2702                 }
2703             }
2704           else
2705             {
2706               /* No.  This breakpoint will not be inserted.  
2707                  No error, but do not mark the bp as 'inserted'.  */
2708               return 0;
2709             }
2710         }
2711
2712       if (bp_err != GDB_NO_ERROR)
2713         {
2714           /* Can't set the breakpoint.  */
2715
2716           /* In some cases, we might not be able to insert a
2717              breakpoint in a shared library that has already been
2718              removed, but we have not yet processed the shlib unload
2719              event.  Unfortunately, some targets that implement
2720              breakpoint insertion themselves can't tell why the
2721              breakpoint insertion failed (e.g., the remote target
2722              doesn't define error codes), so we must treat generic
2723              errors as memory errors.  */
2724           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2725               && bl->loc_type == bp_loc_software_breakpoint
2726               && (solib_name_from_address (bl->pspace, bl->address)
2727                   || shared_objfile_contains_address_p (bl->pspace,
2728                                                         bl->address)))
2729             {
2730               /* See also: disable_breakpoints_in_shlibs.  */
2731               bl->shlib_disabled = 1;
2732               observer_notify_breakpoint_modified (bl->owner);
2733               if (!*disabled_breaks)
2734                 {
2735                   fprintf_unfiltered (tmp_error_stream, 
2736                                       "Cannot insert breakpoint %d.\n", 
2737                                       bl->owner->number);
2738                   fprintf_unfiltered (tmp_error_stream, 
2739                                       "Temporarily disabling shared "
2740                                       "library breakpoints:\n");
2741                 }
2742               *disabled_breaks = 1;
2743               fprintf_unfiltered (tmp_error_stream,
2744                                   "breakpoint #%d\n", bl->owner->number);
2745               return 0;
2746             }
2747           else
2748             {
2749               if (bl->loc_type == bp_loc_hardware_breakpoint)
2750                 {
2751                   *hw_breakpoint_error = 1;
2752                   *hw_bp_error_explained_already = bp_err_message != NULL;
2753                   fprintf_unfiltered (tmp_error_stream,
2754                                       "Cannot insert hardware breakpoint %d%s",
2755                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2756                   if (bp_err_message != NULL)
2757                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2758                 }
2759               else
2760                 {
2761                   if (bp_err_message == NULL)
2762                     {
2763                       char *message
2764                         = memory_error_message (TARGET_XFER_E_IO,
2765                                                 bl->gdbarch, bl->address);
2766                       struct cleanup *old_chain = make_cleanup (xfree, message);
2767
2768                       fprintf_unfiltered (tmp_error_stream,
2769                                           "Cannot insert breakpoint %d.\n"
2770                                           "%s\n",
2771                                           bl->owner->number, message);
2772                       do_cleanups (old_chain);
2773                     }
2774                   else
2775                     {
2776                       fprintf_unfiltered (tmp_error_stream,
2777                                           "Cannot insert breakpoint %d: %s\n",
2778                                           bl->owner->number,
2779                                           bp_err_message);
2780                     }
2781                 }
2782               return 1;
2783
2784             }
2785         }
2786       else
2787         bl->inserted = 1;
2788
2789       return 0;
2790     }
2791
2792   else if (bl->loc_type == bp_loc_hardware_watchpoint
2793            /* NOTE drow/2003-09-08: This state only exists for removing
2794               watchpoints.  It's not clear that it's necessary...  */
2795            && bl->owner->disposition != disp_del_at_next_stop)
2796     {
2797       int val;
2798
2799       gdb_assert (bl->owner->ops != NULL
2800                   && bl->owner->ops->insert_location != NULL);
2801
2802       val = bl->owner->ops->insert_location (bl);
2803
2804       /* If trying to set a read-watchpoint, and it turns out it's not
2805          supported, try emulating one with an access watchpoint.  */
2806       if (val == 1 && bl->watchpoint_type == hw_read)
2807         {
2808           struct bp_location *loc, **loc_temp;
2809
2810           /* But don't try to insert it, if there's already another
2811              hw_access location that would be considered a duplicate
2812              of this one.  */
2813           ALL_BP_LOCATIONS (loc, loc_temp)
2814             if (loc != bl
2815                 && loc->watchpoint_type == hw_access
2816                 && watchpoint_locations_match (bl, loc))
2817               {
2818                 bl->duplicate = 1;
2819                 bl->inserted = 1;
2820                 bl->target_info = loc->target_info;
2821                 bl->watchpoint_type = hw_access;
2822                 val = 0;
2823                 break;
2824               }
2825
2826           if (val == 1)
2827             {
2828               bl->watchpoint_type = hw_access;
2829               val = bl->owner->ops->insert_location (bl);
2830
2831               if (val)
2832                 /* Back to the original value.  */
2833                 bl->watchpoint_type = hw_read;
2834             }
2835         }
2836
2837       bl->inserted = (val == 0);
2838     }
2839
2840   else if (bl->owner->type == bp_catchpoint)
2841     {
2842       int val;
2843
2844       gdb_assert (bl->owner->ops != NULL
2845                   && bl->owner->ops->insert_location != NULL);
2846
2847       val = bl->owner->ops->insert_location (bl);
2848       if (val)
2849         {
2850           bl->owner->enable_state = bp_disabled;
2851
2852           if (val == 1)
2853             warning (_("\
2854 Error inserting catchpoint %d: Your system does not support this type\n\
2855 of catchpoint."), bl->owner->number);
2856           else
2857             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2858         }
2859
2860       bl->inserted = (val == 0);
2861
2862       /* We've already printed an error message if there was a problem
2863          inserting this catchpoint, and we've disabled the catchpoint,
2864          so just return success.  */
2865       return 0;
2866     }
2867
2868   return 0;
2869 }
2870
2871 /* This function is called when program space PSPACE is about to be
2872    deleted.  It takes care of updating breakpoints to not reference
2873    PSPACE anymore.  */
2874
2875 void
2876 breakpoint_program_space_exit (struct program_space *pspace)
2877 {
2878   struct breakpoint *b, *b_temp;
2879   struct bp_location *loc, **loc_temp;
2880
2881   /* Remove any breakpoint that was set through this program space.  */
2882   ALL_BREAKPOINTS_SAFE (b, b_temp)
2883     {
2884       if (b->pspace == pspace)
2885         delete_breakpoint (b);
2886     }
2887
2888   /* Breakpoints set through other program spaces could have locations
2889      bound to PSPACE as well.  Remove those.  */
2890   ALL_BP_LOCATIONS (loc, loc_temp)
2891     {
2892       struct bp_location *tmp;
2893
2894       if (loc->pspace == pspace)
2895         {
2896           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2897           if (loc->owner->loc == loc)
2898             loc->owner->loc = loc->next;
2899           else
2900             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2901               if (tmp->next == loc)
2902                 {
2903                   tmp->next = loc->next;
2904                   break;
2905                 }
2906         }
2907     }
2908
2909   /* Now update the global location list to permanently delete the
2910      removed locations above.  */
2911   update_global_location_list (0);
2912 }
2913
2914 /* Make sure all breakpoints are inserted in inferior.
2915    Throws exception on any error.
2916    A breakpoint that is already inserted won't be inserted
2917    again, so calling this function twice is safe.  */
2918 void
2919 insert_breakpoints (void)
2920 {
2921   struct breakpoint *bpt;
2922
2923   ALL_BREAKPOINTS (bpt)
2924     if (is_hardware_watchpoint (bpt))
2925       {
2926         struct watchpoint *w = (struct watchpoint *) bpt;
2927
2928         update_watchpoint (w, 0 /* don't reparse.  */);
2929       }
2930
2931   update_global_location_list (1);
2932
2933   /* update_global_location_list does not insert breakpoints when
2934      always_inserted_mode is not enabled.  Explicitly insert them
2935      now.  */
2936   if (!breakpoints_always_inserted_mode ())
2937     insert_breakpoint_locations ();
2938 }
2939
2940 /* Invoke CALLBACK for each of bp_location.  */
2941
2942 void
2943 iterate_over_bp_locations (walk_bp_location_callback callback)
2944 {
2945   struct bp_location *loc, **loc_tmp;
2946
2947   ALL_BP_LOCATIONS (loc, loc_tmp)
2948     {
2949       callback (loc, NULL);
2950     }
2951 }
2952
2953 /* This is used when we need to synch breakpoint conditions between GDB and the
2954    target.  It is the case with deleting and disabling of breakpoints when using
2955    always-inserted mode.  */
2956
2957 static void
2958 update_inserted_breakpoint_locations (void)
2959 {
2960   struct bp_location *bl, **blp_tmp;
2961   int error_flag = 0;
2962   int val = 0;
2963   int disabled_breaks = 0;
2964   int hw_breakpoint_error = 0;
2965   int hw_bp_details_reported = 0;
2966
2967   struct ui_file *tmp_error_stream = mem_fileopen ();
2968   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2969
2970   /* Explicitly mark the warning -- this will only be printed if
2971      there was an error.  */
2972   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2973
2974   save_current_space_and_thread ();
2975
2976   ALL_BP_LOCATIONS (bl, blp_tmp)
2977     {
2978       /* We only want to update software breakpoints and hardware
2979          breakpoints.  */
2980       if (!is_breakpoint (bl->owner))
2981         continue;
2982
2983       /* We only want to update locations that are already inserted
2984          and need updating.  This is to avoid unwanted insertion during
2985          deletion of breakpoints.  */
2986       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2987         continue;
2988
2989       switch_to_program_space_and_thread (bl->pspace);
2990
2991       /* For targets that support global breakpoints, there's no need
2992          to select an inferior to insert breakpoint to.  In fact, even
2993          if we aren't attached to any process yet, we should still
2994          insert breakpoints.  */
2995       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2996           && ptid_equal (inferior_ptid, null_ptid))
2997         continue;
2998
2999       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3000                                     &hw_breakpoint_error, &hw_bp_details_reported);
3001       if (val)
3002         error_flag = val;
3003     }
3004
3005   if (error_flag)
3006     {
3007       target_terminal_ours_for_output ();
3008       error_stream (tmp_error_stream);
3009     }
3010
3011   do_cleanups (cleanups);
3012 }
3013
3014 /* Used when starting or continuing the program.  */
3015
3016 static void
3017 insert_breakpoint_locations (void)
3018 {
3019   struct breakpoint *bpt;
3020   struct bp_location *bl, **blp_tmp;
3021   int error_flag = 0;
3022   int val = 0;
3023   int disabled_breaks = 0;
3024   int hw_breakpoint_error = 0;
3025   int hw_bp_error_explained_already = 0;
3026
3027   struct ui_file *tmp_error_stream = mem_fileopen ();
3028   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3029   
3030   /* Explicitly mark the warning -- this will only be printed if
3031      there was an error.  */
3032   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3033
3034   save_current_space_and_thread ();
3035
3036   ALL_BP_LOCATIONS (bl, blp_tmp)
3037     {
3038       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3039         continue;
3040
3041       /* There is no point inserting thread-specific breakpoints if
3042          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3043          has BL->OWNER always non-NULL.  */
3044       if (bl->owner->thread != -1
3045           && !valid_thread_id (bl->owner->thread))
3046         continue;
3047
3048       switch_to_program_space_and_thread (bl->pspace);
3049
3050       /* For targets that support global breakpoints, there's no need
3051          to select an inferior to insert breakpoint to.  In fact, even
3052          if we aren't attached to any process yet, we should still
3053          insert breakpoints.  */
3054       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3055           && ptid_equal (inferior_ptid, null_ptid))
3056         continue;
3057
3058       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3059                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3060       if (val)
3061         error_flag = val;
3062     }
3063
3064   /* If we failed to insert all locations of a watchpoint, remove
3065      them, as half-inserted watchpoint is of limited use.  */
3066   ALL_BREAKPOINTS (bpt)  
3067     {
3068       int some_failed = 0;
3069       struct bp_location *loc;
3070
3071       if (!is_hardware_watchpoint (bpt))
3072         continue;
3073
3074       if (!breakpoint_enabled (bpt))
3075         continue;
3076
3077       if (bpt->disposition == disp_del_at_next_stop)
3078         continue;
3079       
3080       for (loc = bpt->loc; loc; loc = loc->next)
3081         if (!loc->inserted && should_be_inserted (loc))
3082           {
3083             some_failed = 1;
3084             break;
3085           }
3086       if (some_failed)
3087         {
3088           for (loc = bpt->loc; loc; loc = loc->next)
3089             if (loc->inserted)
3090               remove_breakpoint (loc, mark_uninserted);
3091
3092           hw_breakpoint_error = 1;
3093           fprintf_unfiltered (tmp_error_stream,
3094                               "Could not insert hardware watchpoint %d.\n", 
3095                               bpt->number);
3096           error_flag = -1;
3097         }
3098     }
3099
3100   if (error_flag)
3101     {
3102       /* If a hardware breakpoint or watchpoint was inserted, add a
3103          message about possibly exhausted resources.  */
3104       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3105         {
3106           fprintf_unfiltered (tmp_error_stream, 
3107                               "Could not insert hardware breakpoints:\n\
3108 You may have requested too many hardware breakpoints/watchpoints.\n");
3109         }
3110       target_terminal_ours_for_output ();
3111       error_stream (tmp_error_stream);
3112     }
3113
3114   do_cleanups (cleanups);
3115 }
3116
3117 /* Used when the program stops.
3118    Returns zero if successful, or non-zero if there was a problem
3119    removing a breakpoint location.  */
3120
3121 int
3122 remove_breakpoints (void)
3123 {
3124   struct bp_location *bl, **blp_tmp;
3125   int val = 0;
3126
3127   ALL_BP_LOCATIONS (bl, blp_tmp)
3128   {
3129     if (bl->inserted && !is_tracepoint (bl->owner))
3130       val |= remove_breakpoint (bl, mark_uninserted);
3131   }
3132   return val;
3133 }
3134
3135 /* When a thread exits, remove breakpoints that are related to
3136    that thread.  */
3137
3138 static void
3139 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3140 {
3141   struct breakpoint *b, *b_tmp;
3142
3143   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3144     {
3145       if (b->thread == tp->num && user_breakpoint_p (b))
3146         {
3147           b->disposition = disp_del_at_next_stop;
3148
3149           printf_filtered (_("\
3150 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3151                           b->number, tp->num);
3152
3153           /* Hide it from the user.  */
3154           b->number = 0;
3155        }
3156     }
3157 }
3158
3159 /* Remove breakpoints of process PID.  */
3160
3161 int
3162 remove_breakpoints_pid (int pid)
3163 {
3164   struct bp_location *bl, **blp_tmp;
3165   int val;
3166   struct inferior *inf = find_inferior_pid (pid);
3167
3168   ALL_BP_LOCATIONS (bl, blp_tmp)
3169   {
3170     if (bl->pspace != inf->pspace)
3171       continue;
3172
3173     if (bl->owner->type == bp_dprintf)
3174       continue;
3175
3176     if (bl->inserted)
3177       {
3178         val = remove_breakpoint (bl, mark_uninserted);
3179         if (val != 0)
3180           return val;
3181       }
3182   }
3183   return 0;
3184 }
3185
3186 int
3187 reattach_breakpoints (int pid)
3188 {
3189   struct cleanup *old_chain;
3190   struct bp_location *bl, **blp_tmp;
3191   int val;
3192   struct ui_file *tmp_error_stream;
3193   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3194   struct inferior *inf;
3195   struct thread_info *tp;
3196
3197   tp = any_live_thread_of_process (pid);
3198   if (tp == NULL)
3199     return 1;
3200
3201   inf = find_inferior_pid (pid);
3202   old_chain = save_inferior_ptid ();
3203
3204   inferior_ptid = tp->ptid;
3205
3206   tmp_error_stream = mem_fileopen ();
3207   make_cleanup_ui_file_delete (tmp_error_stream);
3208
3209   ALL_BP_LOCATIONS (bl, blp_tmp)
3210   {
3211     if (bl->pspace != inf->pspace)
3212       continue;
3213
3214     if (bl->inserted)
3215       {
3216         bl->inserted = 0;
3217         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3218         if (val != 0)
3219           {
3220             do_cleanups (old_chain);
3221             return val;
3222           }
3223       }
3224   }
3225   do_cleanups (old_chain);
3226   return 0;
3227 }
3228
3229 static int internal_breakpoint_number = -1;
3230
3231 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3232    If INTERNAL is non-zero, the breakpoint number will be populated
3233    from internal_breakpoint_number and that variable decremented.
3234    Otherwise the breakpoint number will be populated from
3235    breakpoint_count and that value incremented.  Internal breakpoints
3236    do not set the internal var bpnum.  */
3237 static void
3238 set_breakpoint_number (int internal, struct breakpoint *b)
3239 {
3240   if (internal)
3241     b->number = internal_breakpoint_number--;
3242   else
3243     {
3244       set_breakpoint_count (breakpoint_count + 1);
3245       b->number = breakpoint_count;
3246     }
3247 }
3248
3249 static struct breakpoint *
3250 create_internal_breakpoint (struct gdbarch *gdbarch,
3251                             CORE_ADDR address, enum bptype type,
3252                             const struct breakpoint_ops *ops)
3253 {
3254   struct symtab_and_line sal;
3255   struct breakpoint *b;
3256
3257   init_sal (&sal);              /* Initialize to zeroes.  */
3258
3259   sal.pc = address;
3260   sal.section = find_pc_overlay (sal.pc);
3261   sal.pspace = current_program_space;
3262
3263   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3264   b->number = internal_breakpoint_number--;
3265   b->disposition = disp_donttouch;
3266
3267   return b;
3268 }
3269
3270 static const char *const longjmp_names[] =
3271   {
3272     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3273   };
3274 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3275
3276 /* Per-objfile data private to breakpoint.c.  */
3277 struct breakpoint_objfile_data
3278 {
3279   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3280   struct bound_minimal_symbol overlay_msym;
3281
3282   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3283   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3284
3285   /* True if we have looked for longjmp probes.  */
3286   int longjmp_searched;
3287
3288   /* SystemTap probe points for longjmp (if any).  */
3289   VEC (probe_p) *longjmp_probes;
3290
3291   /* Minimal symbol for "std::terminate()" (if any).  */
3292   struct bound_minimal_symbol terminate_msym;
3293
3294   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3295   struct bound_minimal_symbol exception_msym;
3296
3297   /* True if we have looked for exception probes.  */
3298   int exception_searched;
3299
3300   /* SystemTap probe points for unwinding (if any).  */
3301   VEC (probe_p) *exception_probes;
3302 };
3303
3304 static const struct objfile_data *breakpoint_objfile_key;
3305
3306 /* Minimal symbol not found sentinel.  */
3307 static struct minimal_symbol msym_not_found;
3308
3309 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3310
3311 static int
3312 msym_not_found_p (const struct minimal_symbol *msym)
3313 {
3314   return msym == &msym_not_found;
3315 }
3316
3317 /* Return per-objfile data needed by breakpoint.c.
3318    Allocate the data if necessary.  */
3319
3320 static struct breakpoint_objfile_data *
3321 get_breakpoint_objfile_data (struct objfile *objfile)
3322 {
3323   struct breakpoint_objfile_data *bp_objfile_data;
3324
3325   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3326   if (bp_objfile_data == NULL)
3327     {
3328       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3329                                        sizeof (*bp_objfile_data));
3330
3331       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3332       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3333     }
3334   return bp_objfile_data;
3335 }
3336
3337 static void
3338 free_breakpoint_probes (struct objfile *obj, void *data)
3339 {
3340   struct breakpoint_objfile_data *bp_objfile_data = data;
3341
3342   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3343   VEC_free (probe_p, bp_objfile_data->exception_probes);
3344 }
3345
3346 static void
3347 create_overlay_event_breakpoint (void)
3348 {
3349   struct objfile *objfile;
3350   const char *const func_name = "_ovly_debug_event";
3351
3352   ALL_OBJFILES (objfile)
3353     {
3354       struct breakpoint *b;
3355       struct breakpoint_objfile_data *bp_objfile_data;
3356       CORE_ADDR addr;
3357
3358       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3359
3360       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3361         continue;
3362
3363       if (bp_objfile_data->overlay_msym.minsym == NULL)
3364         {
3365           struct bound_minimal_symbol m;
3366
3367           m = lookup_minimal_symbol_text (func_name, objfile);
3368           if (m.minsym == NULL)
3369             {
3370               /* Avoid future lookups in this objfile.  */
3371               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3372               continue;
3373             }
3374           bp_objfile_data->overlay_msym = m;
3375         }
3376
3377       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3378       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3379                                       bp_overlay_event,
3380                                       &internal_breakpoint_ops);
3381       b->addr_string = xstrdup (func_name);
3382
3383       if (overlay_debugging == ovly_auto)
3384         {
3385           b->enable_state = bp_enabled;
3386           overlay_events_enabled = 1;
3387         }
3388       else
3389        {
3390          b->enable_state = bp_disabled;
3391          overlay_events_enabled = 0;
3392        }
3393     }
3394   update_global_location_list (1);
3395 }
3396
3397 static void
3398 create_longjmp_master_breakpoint (void)
3399 {
3400   struct program_space *pspace;
3401   struct cleanup *old_chain;
3402
3403   old_chain = save_current_program_space ();
3404
3405   ALL_PSPACES (pspace)
3406   {
3407     struct objfile *objfile;
3408
3409     set_current_program_space (pspace);
3410
3411     ALL_OBJFILES (objfile)
3412     {
3413       int i;
3414       struct gdbarch *gdbarch;
3415       struct breakpoint_objfile_data *bp_objfile_data;
3416
3417       gdbarch = get_objfile_arch (objfile);
3418
3419       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3420
3421       if (!bp_objfile_data->longjmp_searched)
3422         {
3423           VEC (probe_p) *ret;
3424
3425           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3426           if (ret != NULL)
3427             {
3428               /* We are only interested in checking one element.  */
3429               struct probe *p = VEC_index (probe_p, ret, 0);
3430
3431               if (!can_evaluate_probe_arguments (p))
3432                 {
3433                   /* We cannot use the probe interface here, because it does
3434                      not know how to evaluate arguments.  */
3435                   VEC_free (probe_p, ret);
3436                   ret = NULL;
3437                 }
3438             }
3439           bp_objfile_data->longjmp_probes = ret;
3440           bp_objfile_data->longjmp_searched = 1;
3441         }
3442
3443       if (bp_objfile_data->longjmp_probes != NULL)
3444         {
3445           int i;
3446           struct probe *probe;
3447           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3448
3449           for (i = 0;
3450                VEC_iterate (probe_p,
3451                             bp_objfile_data->longjmp_probes,
3452                             i, probe);
3453                ++i)
3454             {
3455               struct breakpoint *b;
3456
3457               b = create_internal_breakpoint (gdbarch,
3458                                               get_probe_address (probe,
3459                                                                  objfile),
3460                                               bp_longjmp_master,
3461                                               &internal_breakpoint_ops);
3462               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3463               b->enable_state = bp_disabled;
3464             }
3465
3466           continue;
3467         }
3468
3469       if (!gdbarch_get_longjmp_target_p (gdbarch))
3470         continue;
3471
3472       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3473         {
3474           struct breakpoint *b;
3475           const char *func_name;
3476           CORE_ADDR addr;
3477
3478           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3479             continue;
3480
3481           func_name = longjmp_names[i];
3482           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3483             {
3484               struct bound_minimal_symbol m;
3485
3486               m = lookup_minimal_symbol_text (func_name, objfile);
3487               if (m.minsym == NULL)
3488                 {
3489                   /* Prevent future lookups in this objfile.  */
3490                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3491                   continue;
3492                 }
3493               bp_objfile_data->longjmp_msym[i] = m;
3494             }
3495
3496           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3497           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3498                                           &internal_breakpoint_ops);
3499           b->addr_string = xstrdup (func_name);
3500           b->enable_state = bp_disabled;
3501         }
3502     }
3503   }
3504   update_global_location_list (1);
3505
3506   do_cleanups (old_chain);
3507 }
3508
3509 /* Create a master std::terminate breakpoint.  */
3510 static void
3511 create_std_terminate_master_breakpoint (void)
3512 {
3513   struct program_space *pspace;
3514   struct cleanup *old_chain;
3515   const char *const func_name = "std::terminate()";
3516
3517   old_chain = save_current_program_space ();
3518
3519   ALL_PSPACES (pspace)
3520   {
3521     struct objfile *objfile;
3522     CORE_ADDR addr;
3523
3524     set_current_program_space (pspace);
3525
3526     ALL_OBJFILES (objfile)
3527     {
3528       struct breakpoint *b;
3529       struct breakpoint_objfile_data *bp_objfile_data;
3530
3531       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3532
3533       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3534         continue;
3535
3536       if (bp_objfile_data->terminate_msym.minsym == NULL)
3537         {
3538           struct bound_minimal_symbol m;
3539
3540           m = lookup_minimal_symbol (func_name, NULL, objfile);
3541           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3542                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3543             {
3544               /* Prevent future lookups in this objfile.  */
3545               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3546               continue;
3547             }
3548           bp_objfile_data->terminate_msym = m;
3549         }
3550
3551       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3552       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3553                                       bp_std_terminate_master,
3554                                       &internal_breakpoint_ops);
3555       b->addr_string = xstrdup (func_name);
3556       b->enable_state = bp_disabled;
3557     }
3558   }
3559
3560   update_global_location_list (1);
3561
3562   do_cleanups (old_chain);
3563 }
3564
3565 /* Install a master breakpoint on the unwinder's debug hook.  */
3566
3567 static void
3568 create_exception_master_breakpoint (void)
3569 {
3570   struct objfile *objfile;
3571   const char *const func_name = "_Unwind_DebugHook";
3572
3573   ALL_OBJFILES (objfile)
3574     {
3575       struct breakpoint *b;
3576       struct gdbarch *gdbarch;
3577       struct breakpoint_objfile_data *bp_objfile_data;
3578       CORE_ADDR addr;
3579
3580       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3581
3582       /* We prefer the SystemTap probe point if it exists.  */
3583       if (!bp_objfile_data->exception_searched)
3584         {
3585           VEC (probe_p) *ret;
3586
3587           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3588
3589           if (ret != NULL)
3590             {
3591               /* We are only interested in checking one element.  */
3592               struct probe *p = VEC_index (probe_p, ret, 0);
3593
3594               if (!can_evaluate_probe_arguments (p))
3595                 {
3596                   /* We cannot use the probe interface here, because it does
3597                      not know how to evaluate arguments.  */
3598                   VEC_free (probe_p, ret);
3599                   ret = NULL;
3600                 }
3601             }
3602           bp_objfile_data->exception_probes = ret;
3603           bp_objfile_data->exception_searched = 1;
3604         }
3605
3606       if (bp_objfile_data->exception_probes != NULL)
3607         {
3608           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3609           int i;
3610           struct probe *probe;
3611
3612           for (i = 0;
3613                VEC_iterate (probe_p,
3614                             bp_objfile_data->exception_probes,
3615                             i, probe);
3616                ++i)
3617             {
3618               struct breakpoint *b;
3619
3620               b = create_internal_breakpoint (gdbarch,
3621                                               get_probe_address (probe,
3622                                                                  objfile),
3623                                               bp_exception_master,
3624                                               &internal_breakpoint_ops);
3625               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3626               b->enable_state = bp_disabled;
3627             }
3628
3629           continue;
3630         }
3631
3632       /* Otherwise, try the hook function.  */
3633
3634       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3635         continue;
3636
3637       gdbarch = get_objfile_arch (objfile);
3638
3639       if (bp_objfile_data->exception_msym.minsym == NULL)
3640         {
3641           struct bound_minimal_symbol debug_hook;
3642
3643           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3644           if (debug_hook.minsym == NULL)
3645             {
3646               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3647               continue;
3648             }
3649
3650           bp_objfile_data->exception_msym = debug_hook;
3651         }
3652
3653       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3654       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3655                                                  &current_target);
3656       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3657                                       &internal_breakpoint_ops);
3658       b->addr_string = xstrdup (func_name);
3659       b->enable_state = bp_disabled;
3660     }
3661
3662   update_global_location_list (1);
3663 }
3664
3665 void
3666 update_breakpoints_after_exec (void)
3667 {
3668   struct breakpoint *b, *b_tmp;
3669   struct bp_location *bploc, **bplocp_tmp;
3670
3671   /* We're about to delete breakpoints from GDB's lists.  If the
3672      INSERTED flag is true, GDB will try to lift the breakpoints by
3673      writing the breakpoints' "shadow contents" back into memory.  The
3674      "shadow contents" are NOT valid after an exec, so GDB should not
3675      do that.  Instead, the target is responsible from marking
3676      breakpoints out as soon as it detects an exec.  We don't do that
3677      here instead, because there may be other attempts to delete
3678      breakpoints after detecting an exec and before reaching here.  */
3679   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3680     if (bploc->pspace == current_program_space)
3681       gdb_assert (!bploc->inserted);
3682
3683   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3684   {
3685     if (b->pspace != current_program_space)
3686       continue;
3687
3688     /* Solib breakpoints must be explicitly reset after an exec().  */
3689     if (b->type == bp_shlib_event)
3690       {
3691         delete_breakpoint (b);
3692         continue;
3693       }
3694
3695     /* JIT breakpoints must be explicitly reset after an exec().  */
3696     if (b->type == bp_jit_event)
3697       {
3698         delete_breakpoint (b);
3699         continue;
3700       }
3701
3702     /* Thread event breakpoints must be set anew after an exec(),
3703        as must overlay event and longjmp master breakpoints.  */
3704     if (b->type == bp_thread_event || b->type == bp_overlay_event
3705         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3706         || b->type == bp_exception_master)
3707       {
3708         delete_breakpoint (b);
3709         continue;
3710       }
3711
3712     /* Step-resume breakpoints are meaningless after an exec().  */
3713     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3714       {
3715         delete_breakpoint (b);
3716         continue;
3717       }
3718
3719     /* Longjmp and longjmp-resume breakpoints are also meaningless
3720        after an exec.  */
3721     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3722         || b->type == bp_longjmp_call_dummy
3723         || b->type == bp_exception || b->type == bp_exception_resume)
3724       {
3725         delete_breakpoint (b);
3726         continue;
3727       }
3728
3729     if (b->type == bp_catchpoint)
3730       {
3731         /* For now, none of the bp_catchpoint breakpoints need to
3732            do anything at this point.  In the future, if some of
3733            the catchpoints need to something, we will need to add
3734            a new method, and call this method from here.  */
3735         continue;
3736       }
3737
3738     /* bp_finish is a special case.  The only way we ought to be able
3739        to see one of these when an exec() has happened, is if the user
3740        caught a vfork, and then said "finish".  Ordinarily a finish just
3741        carries them to the call-site of the current callee, by setting
3742        a temporary bp there and resuming.  But in this case, the finish
3743        will carry them entirely through the vfork & exec.
3744
3745        We don't want to allow a bp_finish to remain inserted now.  But
3746        we can't safely delete it, 'cause finish_command has a handle to
3747        the bp on a bpstat, and will later want to delete it.  There's a
3748        chance (and I've seen it happen) that if we delete the bp_finish
3749        here, that its storage will get reused by the time finish_command
3750        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3751        We really must allow finish_command to delete a bp_finish.
3752
3753        In the absence of a general solution for the "how do we know
3754        it's safe to delete something others may have handles to?"
3755        problem, what we'll do here is just uninsert the bp_finish, and
3756        let finish_command delete it.
3757
3758        (We know the bp_finish is "doomed" in the sense that it's
3759        momentary, and will be deleted as soon as finish_command sees
3760        the inferior stopped.  So it doesn't matter that the bp's
3761        address is probably bogus in the new a.out, unlike e.g., the
3762        solib breakpoints.)  */
3763
3764     if (b->type == bp_finish)
3765       {
3766         continue;
3767       }
3768
3769     /* Without a symbolic address, we have little hope of the
3770        pre-exec() address meaning the same thing in the post-exec()
3771        a.out.  */
3772     if (b->addr_string == NULL)
3773       {
3774         delete_breakpoint (b);
3775         continue;
3776       }
3777   }
3778   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3779   create_overlay_event_breakpoint ();
3780   create_longjmp_master_breakpoint ();
3781   create_std_terminate_master_breakpoint ();
3782   create_exception_master_breakpoint ();
3783 }
3784
3785 int
3786 detach_breakpoints (ptid_t ptid)
3787 {
3788   struct bp_location *bl, **blp_tmp;
3789   int val = 0;
3790   struct cleanup *old_chain = save_inferior_ptid ();
3791   struct inferior *inf = current_inferior ();
3792
3793   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3794     error (_("Cannot detach breakpoints of inferior_ptid"));
3795
3796   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3797   inferior_ptid = ptid;
3798   ALL_BP_LOCATIONS (bl, blp_tmp)
3799   {
3800     if (bl->pspace != inf->pspace)
3801       continue;
3802
3803     /* This function must physically remove breakpoints locations
3804        from the specified ptid, without modifying the breakpoint
3805        package's state.  Locations of type bp_loc_other are only
3806        maintained at GDB side.  So, there is no need to remove
3807        these bp_loc_other locations.  Moreover, removing these
3808        would modify the breakpoint package's state.  */
3809     if (bl->loc_type == bp_loc_other)
3810       continue;
3811
3812     if (bl->inserted)
3813       val |= remove_breakpoint_1 (bl, mark_inserted);
3814   }
3815
3816   /* Detach single-step breakpoints as well.  */
3817   detach_single_step_breakpoints ();
3818
3819   do_cleanups (old_chain);
3820   return val;
3821 }
3822
3823 /* Remove the breakpoint location BL from the current address space.
3824    Note that this is used to detach breakpoints from a child fork.
3825    When we get here, the child isn't in the inferior list, and neither
3826    do we have objects to represent its address space --- we should
3827    *not* look at bl->pspace->aspace here.  */
3828
3829 static int
3830 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3831 {
3832   int val;
3833
3834   /* BL is never in moribund_locations by our callers.  */
3835   gdb_assert (bl->owner != NULL);
3836
3837   if (bl->owner->enable_state == bp_permanent)
3838     /* Permanent breakpoints cannot be inserted or removed.  */
3839     return 0;
3840
3841   /* The type of none suggests that owner is actually deleted.
3842      This should not ever happen.  */
3843   gdb_assert (bl->owner->type != bp_none);
3844
3845   if (bl->loc_type == bp_loc_software_breakpoint
3846       || bl->loc_type == bp_loc_hardware_breakpoint)
3847     {
3848       /* "Normal" instruction breakpoint: either the standard
3849          trap-instruction bp (bp_breakpoint), or a
3850          bp_hardware_breakpoint.  */
3851
3852       /* First check to see if we have to handle an overlay.  */
3853       if (overlay_debugging == ovly_off
3854           || bl->section == NULL
3855           || !(section_is_overlay (bl->section)))
3856         {
3857           /* No overlay handling: just remove the breakpoint.  */
3858
3859           /* If we're trying to uninsert a memory breakpoint that we
3860              know is set in a dynamic object that is marked
3861              shlib_disabled, then either the dynamic object was
3862              removed with "remove-symbol-file" or with
3863              "nosharedlibrary".  In the former case, we don't know
3864              whether another dynamic object might have loaded over the
3865              breakpoint's address -- the user might well let us know
3866              about it next with add-symbol-file (the whole point of
3867              add-symbol-file is letting the user manually maintain a
3868              list of dynamically loaded objects).  If we have the
3869              breakpoint's shadow memory, that is, this is a software
3870              breakpoint managed by GDB, check whether the breakpoint
3871              is still inserted in memory, to avoid overwriting wrong
3872              code with stale saved shadow contents.  Note that HW
3873              breakpoints don't have shadow memory, as they're
3874              implemented using a mechanism that is not dependent on
3875              being able to modify the target's memory, and as such
3876              they should always be removed.  */
3877           if (bl->shlib_disabled
3878               && bl->target_info.shadow_len != 0
3879               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3880             val = 0;
3881           else
3882             val = bl->owner->ops->remove_location (bl);
3883         }
3884       else
3885         {
3886           /* This breakpoint is in an overlay section.
3887              Did we set a breakpoint at the LMA?  */
3888           if (!overlay_events_enabled)
3889               {
3890                 /* Yes -- overlay event support is not active, so we
3891                    should have set a breakpoint at the LMA.  Remove it.  
3892                 */
3893                 /* Ignore any failures: if the LMA is in ROM, we will
3894                    have already warned when we failed to insert it.  */
3895                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3896                   target_remove_hw_breakpoint (bl->gdbarch,
3897                                                &bl->overlay_target_info);
3898                 else
3899                   target_remove_breakpoint (bl->gdbarch,
3900                                             &bl->overlay_target_info);
3901               }
3902           /* Did we set a breakpoint at the VMA? 
3903              If so, we will have marked the breakpoint 'inserted'.  */
3904           if (bl->inserted)
3905             {
3906               /* Yes -- remove it.  Previously we did not bother to
3907                  remove the breakpoint if the section had been
3908                  unmapped, but let's not rely on that being safe.  We
3909                  don't know what the overlay manager might do.  */
3910
3911               /* However, we should remove *software* breakpoints only
3912                  if the section is still mapped, or else we overwrite
3913                  wrong code with the saved shadow contents.  */
3914               if (bl->loc_type == bp_loc_hardware_breakpoint
3915                   || section_is_mapped (bl->section))
3916                 val = bl->owner->ops->remove_location (bl);
3917               else
3918                 val = 0;
3919             }
3920           else
3921             {
3922               /* No -- not inserted, so no need to remove.  No error.  */
3923               val = 0;
3924             }
3925         }
3926
3927       /* In some cases, we might not be able to remove a breakpoint in
3928          a shared library that has already been removed, but we have
3929          not yet processed the shlib unload event.  Similarly for an
3930          unloaded add-symbol-file object - the user might not yet have
3931          had the chance to remove-symbol-file it.  shlib_disabled will
3932          be set if the library/object has already been removed, but
3933          the breakpoint hasn't been uninserted yet, e.g., after
3934          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3935          always-inserted mode.  */
3936       if (val
3937           && (bl->loc_type == bp_loc_software_breakpoint
3938               && (bl->shlib_disabled
3939                   || solib_name_from_address (bl->pspace, bl->address)
3940                   || shared_objfile_contains_address_p (bl->pspace,
3941                                                         bl->address))))
3942         val = 0;
3943
3944       if (val)
3945         return val;
3946       bl->inserted = (is == mark_inserted);
3947     }
3948   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3949     {
3950       gdb_assert (bl->owner->ops != NULL
3951                   && bl->owner->ops->remove_location != NULL);
3952
3953       bl->inserted = (is == mark_inserted);
3954       bl->owner->ops->remove_location (bl);
3955
3956       /* Failure to remove any of the hardware watchpoints comes here.  */
3957       if ((is == mark_uninserted) && (bl->inserted))
3958         warning (_("Could not remove hardware watchpoint %d."),
3959                  bl->owner->number);
3960     }
3961   else if (bl->owner->type == bp_catchpoint
3962            && breakpoint_enabled (bl->owner)
3963            && !bl->duplicate)
3964     {
3965       gdb_assert (bl->owner->ops != NULL
3966                   && bl->owner->ops->remove_location != NULL);
3967
3968       val = bl->owner->ops->remove_location (bl);
3969       if (val)
3970         return val;
3971
3972       bl->inserted = (is == mark_inserted);
3973     }
3974
3975   return 0;
3976 }
3977
3978 static int
3979 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3980 {
3981   int ret;
3982   struct cleanup *old_chain;
3983
3984   /* BL is never in moribund_locations by our callers.  */
3985   gdb_assert (bl->owner != NULL);
3986
3987   if (bl->owner->enable_state == bp_permanent)
3988     /* Permanent breakpoints cannot be inserted or removed.  */
3989     return 0;
3990
3991   /* The type of none suggests that owner is actually deleted.
3992      This should not ever happen.  */
3993   gdb_assert (bl->owner->type != bp_none);
3994
3995   old_chain = save_current_space_and_thread ();
3996
3997   switch_to_program_space_and_thread (bl->pspace);
3998
3999   ret = remove_breakpoint_1 (bl, is);
4000
4001   do_cleanups (old_chain);
4002   return ret;
4003 }
4004
4005 /* Clear the "inserted" flag in all breakpoints.  */
4006
4007 void
4008 mark_breakpoints_out (void)
4009 {
4010   struct bp_location *bl, **blp_tmp;
4011
4012   ALL_BP_LOCATIONS (bl, blp_tmp)
4013     if (bl->pspace == current_program_space)
4014       bl->inserted = 0;
4015 }
4016
4017 /* Clear the "inserted" flag in all breakpoints and delete any
4018    breakpoints which should go away between runs of the program.
4019
4020    Plus other such housekeeping that has to be done for breakpoints
4021    between runs.
4022
4023    Note: this function gets called at the end of a run (by
4024    generic_mourn_inferior) and when a run begins (by
4025    init_wait_for_inferior).  */
4026
4027
4028
4029 void
4030 breakpoint_init_inferior (enum inf_context context)
4031 {
4032   struct breakpoint *b, *b_tmp;
4033   struct bp_location *bl, **blp_tmp;
4034   int ix;
4035   struct program_space *pspace = current_program_space;
4036
4037   /* If breakpoint locations are shared across processes, then there's
4038      nothing to do.  */
4039   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4040     return;
4041
4042   ALL_BP_LOCATIONS (bl, blp_tmp)
4043   {
4044     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4045     if (bl->pspace == pspace
4046         && bl->owner->enable_state != bp_permanent)
4047       bl->inserted = 0;
4048   }
4049
4050   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4051   {
4052     if (b->loc && b->loc->pspace != pspace)
4053       continue;
4054
4055     switch (b->type)
4056       {
4057       case bp_call_dummy:
4058       case bp_longjmp_call_dummy:
4059
4060         /* If the call dummy breakpoint is at the entry point it will
4061            cause problems when the inferior is rerun, so we better get
4062            rid of it.  */
4063
4064       case bp_watchpoint_scope:
4065
4066         /* Also get rid of scope breakpoints.  */
4067
4068       case bp_shlib_event:
4069
4070         /* Also remove solib event breakpoints.  Their addresses may
4071            have changed since the last time we ran the program.
4072            Actually we may now be debugging against different target;
4073            and so the solib backend that installed this breakpoint may
4074            not be used in by the target.  E.g.,
4075
4076            (gdb) file prog-linux
4077            (gdb) run               # native linux target
4078            ...
4079            (gdb) kill
4080            (gdb) file prog-win.exe
4081            (gdb) tar rem :9999     # remote Windows gdbserver.
4082         */
4083
4084       case bp_step_resume:
4085
4086         /* Also remove step-resume breakpoints.  */
4087
4088         delete_breakpoint (b);
4089         break;
4090
4091       case bp_watchpoint:
4092       case bp_hardware_watchpoint:
4093       case bp_read_watchpoint:
4094       case bp_access_watchpoint:
4095         {
4096           struct watchpoint *w = (struct watchpoint *) b;
4097
4098           /* Likewise for watchpoints on local expressions.  */
4099           if (w->exp_valid_block != NULL)
4100             delete_breakpoint (b);
4101           else if (context == inf_starting)
4102             {
4103               /* Reset val field to force reread of starting value in
4104                  insert_breakpoints.  */
4105               if (w->val)
4106                 value_free (w->val);
4107               w->val = NULL;
4108               w->val_valid = 0;
4109           }
4110         }
4111         break;
4112       default:
4113         break;
4114       }
4115   }
4116
4117   /* Get rid of the moribund locations.  */
4118   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4119     decref_bp_location (&bl);
4120   VEC_free (bp_location_p, moribund_locations);
4121 }
4122
4123 /* These functions concern about actual breakpoints inserted in the
4124    target --- to e.g. check if we need to do decr_pc adjustment or if
4125    we need to hop over the bkpt --- so we check for address space
4126    match, not program space.  */
4127
4128 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4129    exists at PC.  It returns ordinary_breakpoint_here if it's an
4130    ordinary breakpoint, or permanent_breakpoint_here if it's a
4131    permanent breakpoint.
4132    - When continuing from a location with an ordinary breakpoint, we
4133      actually single step once before calling insert_breakpoints.
4134    - When continuing from a location with a permanent breakpoint, we
4135      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4136      the target, to advance the PC past the breakpoint.  */
4137
4138 enum breakpoint_here
4139 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4140 {
4141   struct bp_location *bl, **blp_tmp;
4142   int any_breakpoint_here = 0;
4143
4144   ALL_BP_LOCATIONS (bl, blp_tmp)
4145     {
4146       if (bl->loc_type != bp_loc_software_breakpoint
4147           && bl->loc_type != bp_loc_hardware_breakpoint)
4148         continue;
4149
4150       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4151       if ((breakpoint_enabled (bl->owner)
4152            || bl->owner->enable_state == bp_permanent)
4153           && breakpoint_location_address_match (bl, aspace, pc))
4154         {
4155           if (overlay_debugging 
4156               && section_is_overlay (bl->section)
4157               && !section_is_mapped (bl->section))
4158             continue;           /* unmapped overlay -- can't be a match */
4159           else if (bl->owner->enable_state == bp_permanent)
4160             return permanent_breakpoint_here;
4161           else
4162             any_breakpoint_here = 1;
4163         }
4164     }
4165
4166   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4167 }
4168
4169 /* Return true if there's a moribund breakpoint at PC.  */
4170
4171 int
4172 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4173 {
4174   struct bp_location *loc;
4175   int ix;
4176
4177   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4178     if (breakpoint_location_address_match (loc, aspace, pc))
4179       return 1;
4180
4181   return 0;
4182 }
4183
4184 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4185    inserted using regular breakpoint_chain / bp_location array
4186    mechanism.  This does not check for single-step breakpoints, which
4187    are inserted and removed using direct target manipulation.  */
4188
4189 int
4190 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4191                                     CORE_ADDR pc)
4192 {
4193   struct bp_location *bl, **blp_tmp;
4194
4195   ALL_BP_LOCATIONS (bl, blp_tmp)
4196     {
4197       if (bl->loc_type != bp_loc_software_breakpoint
4198           && bl->loc_type != bp_loc_hardware_breakpoint)
4199         continue;
4200
4201       if (bl->inserted
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
4209             return 1;
4210         }
4211     }
4212   return 0;
4213 }
4214
4215 /* Returns non-zero iff there's either regular breakpoint
4216    or a single step breakpoint inserted at PC.  */
4217
4218 int
4219 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4220 {
4221   if (regular_breakpoint_inserted_here_p (aspace, pc))
4222     return 1;
4223
4224   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4225     return 1;
4226
4227   return 0;
4228 }
4229
4230 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4231    software breakpoint inserted at PC.  */
4232
4233 static struct bp_location *
4234 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4235                                                 CORE_ADDR pc)
4236 {
4237   struct bp_location *bl, **blp_tmp;
4238
4239   ALL_BP_LOCATIONS (bl, blp_tmp)
4240     {
4241       if (bl->loc_type != bp_loc_software_breakpoint)
4242         continue;
4243
4244       if (bl->inserted
4245           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4246                                        aspace, pc))
4247         {
4248           if (overlay_debugging 
4249               && section_is_overlay (bl->section)
4250               && !section_is_mapped (bl->section))
4251             continue;           /* unmapped overlay -- can't be a match */
4252           else
4253             return bl;
4254         }
4255     }
4256
4257   return NULL;
4258 }
4259
4260 /* This function returns non-zero iff there is a software breakpoint
4261    inserted at PC.  */
4262
4263 int
4264 software_breakpoint_inserted_here_p (struct address_space *aspace,
4265                                      CORE_ADDR pc)
4266 {
4267   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4268     return 1;
4269
4270   /* Also check for software single-step breakpoints.  */
4271   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4272     return 1;
4273
4274   return 0;
4275 }
4276
4277 int
4278 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4279                                        CORE_ADDR addr, ULONGEST len)
4280 {
4281   struct breakpoint *bpt;
4282
4283   ALL_BREAKPOINTS (bpt)
4284     {
4285       struct bp_location *loc;
4286
4287       if (bpt->type != bp_hardware_watchpoint
4288           && bpt->type != bp_access_watchpoint)
4289         continue;
4290
4291       if (!breakpoint_enabled (bpt))
4292         continue;
4293
4294       for (loc = bpt->loc; loc; loc = loc->next)
4295         if (loc->pspace->aspace == aspace && loc->inserted)
4296           {
4297             CORE_ADDR l, h;
4298
4299             /* Check for intersection.  */
4300             l = max (loc->address, addr);
4301             h = min (loc->address + loc->length, addr + len);
4302             if (l < h)
4303               return 1;
4304           }
4305     }
4306   return 0;
4307 }
4308
4309 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4310    PC is valid for process/thread PTID.  */
4311
4312 int
4313 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4314                          ptid_t ptid)
4315 {
4316   struct bp_location *bl, **blp_tmp;
4317   /* The thread and task IDs associated to PTID, computed lazily.  */
4318   int thread = -1;
4319   int task = 0;
4320   
4321   ALL_BP_LOCATIONS (bl, blp_tmp)
4322     {
4323       if (bl->loc_type != bp_loc_software_breakpoint
4324           && bl->loc_type != bp_loc_hardware_breakpoint)
4325         continue;
4326
4327       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4328       if (!breakpoint_enabled (bl->owner)
4329           && bl->owner->enable_state != bp_permanent)
4330         continue;
4331
4332       if (!breakpoint_location_address_match (bl, aspace, pc))
4333         continue;
4334
4335       if (bl->owner->thread != -1)
4336         {
4337           /* This is a thread-specific breakpoint.  Check that ptid
4338              matches that thread.  If thread hasn't been computed yet,
4339              it is now time to do so.  */
4340           if (thread == -1)
4341             thread = pid_to_thread_id (ptid);
4342           if (bl->owner->thread != thread)
4343             continue;
4344         }
4345
4346       if (bl->owner->task != 0)
4347         {
4348           /* This is a task-specific breakpoint.  Check that ptid
4349              matches that task.  If task hasn't been computed yet,
4350              it is now time to do so.  */
4351           if (task == 0)
4352             task = ada_get_task_number (ptid);
4353           if (bl->owner->task != task)
4354             continue;
4355         }
4356
4357       if (overlay_debugging 
4358           && section_is_overlay (bl->section)
4359           && !section_is_mapped (bl->section))
4360         continue;           /* unmapped overlay -- can't be a match */
4361
4362       return 1;
4363     }
4364
4365   return 0;
4366 }
4367 \f
4368
4369 /* bpstat stuff.  External routines' interfaces are documented
4370    in breakpoint.h.  */
4371
4372 int
4373 is_catchpoint (struct breakpoint *ep)
4374 {
4375   return (ep->type == bp_catchpoint);
4376 }
4377
4378 /* Frees any storage that is part of a bpstat.  Does not walk the
4379    'next' chain.  */
4380
4381 static void
4382 bpstat_free (bpstat bs)
4383 {
4384   if (bs->old_val != NULL)
4385     value_free (bs->old_val);
4386   decref_counted_command_line (&bs->commands);
4387   decref_bp_location (&bs->bp_location_at);
4388   xfree (bs);
4389 }
4390
4391 /* Clear a bpstat so that it says we are not at any breakpoint.
4392    Also free any storage that is part of a bpstat.  */
4393
4394 void
4395 bpstat_clear (bpstat *bsp)
4396 {
4397   bpstat p;
4398   bpstat q;
4399
4400   if (bsp == 0)
4401     return;
4402   p = *bsp;
4403   while (p != NULL)
4404     {
4405       q = p->next;
4406       bpstat_free (p);
4407       p = q;
4408     }
4409   *bsp = NULL;
4410 }
4411
4412 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4413    is part of the bpstat is copied as well.  */
4414
4415 bpstat
4416 bpstat_copy (bpstat bs)
4417 {
4418   bpstat p = NULL;
4419   bpstat tmp;
4420   bpstat retval = NULL;
4421
4422   if (bs == NULL)
4423     return bs;
4424
4425   for (; bs != NULL; bs = bs->next)
4426     {
4427       tmp = (bpstat) xmalloc (sizeof (*tmp));
4428       memcpy (tmp, bs, sizeof (*tmp));
4429       incref_counted_command_line (tmp->commands);
4430       incref_bp_location (tmp->bp_location_at);
4431       if (bs->old_val != NULL)
4432         {
4433           tmp->old_val = value_copy (bs->old_val);
4434           release_value (tmp->old_val);
4435         }
4436
4437       if (p == NULL)
4438         /* This is the first thing in the chain.  */
4439         retval = tmp;
4440       else
4441         p->next = tmp;
4442       p = tmp;
4443     }
4444   p->next = NULL;
4445   return retval;
4446 }
4447
4448 /* Find the bpstat associated with this breakpoint.  */
4449
4450 bpstat
4451 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4452 {
4453   if (bsp == NULL)
4454     return NULL;
4455
4456   for (; bsp != NULL; bsp = bsp->next)
4457     {
4458       if (bsp->breakpoint_at == breakpoint)
4459         return bsp;
4460     }
4461   return NULL;
4462 }
4463
4464 /* See breakpoint.h.  */
4465
4466 int
4467 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4468 {
4469   for (; bsp != NULL; bsp = bsp->next)
4470     {
4471       if (bsp->breakpoint_at == NULL)
4472         {
4473           /* A moribund location can never explain a signal other than
4474              GDB_SIGNAL_TRAP.  */
4475           if (sig == GDB_SIGNAL_TRAP)
4476             return 1;
4477         }
4478       else
4479         {
4480           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4481                                                         sig))
4482             return 1;
4483         }
4484     }
4485
4486   return 0;
4487 }
4488
4489 /* Put in *NUM the breakpoint number of the first breakpoint we are
4490    stopped at.  *BSP upon return is a bpstat which points to the
4491    remaining breakpoints stopped at (but which is not guaranteed to be
4492    good for anything but further calls to bpstat_num).
4493
4494    Return 0 if passed a bpstat which does not indicate any breakpoints.
4495    Return -1 if stopped at a breakpoint that has been deleted since
4496    we set it.
4497    Return 1 otherwise.  */
4498
4499 int
4500 bpstat_num (bpstat *bsp, int *num)
4501 {
4502   struct breakpoint *b;
4503
4504   if ((*bsp) == NULL)
4505     return 0;                   /* No more breakpoint values */
4506
4507   /* We assume we'll never have several bpstats that correspond to a
4508      single breakpoint -- otherwise, this function might return the
4509      same number more than once and this will look ugly.  */
4510   b = (*bsp)->breakpoint_at;
4511   *bsp = (*bsp)->next;
4512   if (b == NULL)
4513     return -1;                  /* breakpoint that's been deleted since */
4514
4515   *num = b->number;             /* We have its number */
4516   return 1;
4517 }
4518
4519 /* See breakpoint.h.  */
4520
4521 void
4522 bpstat_clear_actions (void)
4523 {
4524   struct thread_info *tp;
4525   bpstat bs;
4526
4527   if (ptid_equal (inferior_ptid, null_ptid))
4528     return;
4529
4530   tp = find_thread_ptid (inferior_ptid);
4531   if (tp == NULL)
4532     return;
4533
4534   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4535     {
4536       decref_counted_command_line (&bs->commands);
4537
4538       if (bs->old_val != NULL)
4539         {
4540           value_free (bs->old_val);
4541           bs->old_val = NULL;
4542         }
4543     }
4544 }
4545
4546 /* Called when a command is about to proceed the inferior.  */
4547
4548 static void
4549 breakpoint_about_to_proceed (void)
4550 {
4551   if (!ptid_equal (inferior_ptid, null_ptid))
4552     {
4553       struct thread_info *tp = inferior_thread ();
4554
4555       /* Allow inferior function calls in breakpoint commands to not
4556          interrupt the command list.  When the call finishes
4557          successfully, the inferior will be standing at the same
4558          breakpoint as if nothing happened.  */
4559       if (tp->control.in_infcall)
4560         return;
4561     }
4562
4563   breakpoint_proceeded = 1;
4564 }
4565
4566 /* Stub for cleaning up our state if we error-out of a breakpoint
4567    command.  */
4568 static void
4569 cleanup_executing_breakpoints (void *ignore)
4570 {
4571   executing_breakpoint_commands = 0;
4572 }
4573
4574 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4575    or its equivalent.  */
4576
4577 static int
4578 command_line_is_silent (struct command_line *cmd)
4579 {
4580   return cmd && (strcmp ("silent", cmd->line) == 0
4581                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4582 }
4583
4584 /* Execute all the commands associated with all the breakpoints at
4585    this location.  Any of these commands could cause the process to
4586    proceed beyond this point, etc.  We look out for such changes by
4587    checking the global "breakpoint_proceeded" after each command.
4588
4589    Returns true if a breakpoint command resumed the inferior.  In that
4590    case, it is the caller's responsibility to recall it again with the
4591    bpstat of the current thread.  */
4592
4593 static int
4594 bpstat_do_actions_1 (bpstat *bsp)
4595 {
4596   bpstat bs;
4597   struct cleanup *old_chain;
4598   int again = 0;
4599
4600   /* Avoid endless recursion if a `source' command is contained
4601      in bs->commands.  */
4602   if (executing_breakpoint_commands)
4603     return 0;
4604
4605   executing_breakpoint_commands = 1;
4606   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4607
4608   prevent_dont_repeat ();
4609
4610   /* This pointer will iterate over the list of bpstat's.  */
4611   bs = *bsp;
4612
4613   breakpoint_proceeded = 0;
4614   for (; bs != NULL; bs = bs->next)
4615     {
4616       struct counted_command_line *ccmd;
4617       struct command_line *cmd;
4618       struct cleanup *this_cmd_tree_chain;
4619
4620       /* Take ownership of the BSP's command tree, if it has one.
4621
4622          The command tree could legitimately contain commands like
4623          'step' and 'next', which call clear_proceed_status, which
4624          frees stop_bpstat's command tree.  To make sure this doesn't
4625          free the tree we're executing out from under us, we need to
4626          take ownership of the tree ourselves.  Since a given bpstat's
4627          commands are only executed once, we don't need to copy it; we
4628          can clear the pointer in the bpstat, and make sure we free
4629          the tree when we're done.  */
4630       ccmd = bs->commands;
4631       bs->commands = NULL;
4632       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4633       cmd = ccmd ? ccmd->commands : NULL;
4634       if (command_line_is_silent (cmd))
4635         {
4636           /* The action has been already done by bpstat_stop_status.  */
4637           cmd = cmd->next;
4638         }
4639
4640       while (cmd != NULL)
4641         {
4642           execute_control_command (cmd);
4643
4644           if (breakpoint_proceeded)
4645             break;
4646           else
4647             cmd = cmd->next;
4648         }
4649
4650       /* We can free this command tree now.  */
4651       do_cleanups (this_cmd_tree_chain);
4652
4653       if (breakpoint_proceeded)
4654         {
4655           if (target_can_async_p ())
4656             /* If we are in async mode, then the target might be still
4657                running, not stopped at any breakpoint, so nothing for
4658                us to do here -- just return to the event loop.  */
4659             ;
4660           else
4661             /* In sync mode, when execute_control_command returns
4662                we're already standing on the next breakpoint.
4663                Breakpoint commands for that stop were not run, since
4664                execute_command does not run breakpoint commands --
4665                only command_line_handler does, but that one is not
4666                involved in execution of breakpoint commands.  So, we
4667                can now execute breakpoint commands.  It should be
4668                noted that making execute_command do bpstat actions is
4669                not an option -- in this case we'll have recursive
4670                invocation of bpstat for each breakpoint with a
4671                command, and can easily blow up GDB stack.  Instead, we
4672                return true, which will trigger the caller to recall us
4673                with the new stop_bpstat.  */
4674             again = 1;
4675           break;
4676         }
4677     }
4678   do_cleanups (old_chain);
4679   return again;
4680 }
4681
4682 void
4683 bpstat_do_actions (void)
4684 {
4685   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4686
4687   /* Do any commands attached to breakpoint we are stopped at.  */
4688   while (!ptid_equal (inferior_ptid, null_ptid)
4689          && target_has_execution
4690          && !is_exited (inferior_ptid)
4691          && !is_executing (inferior_ptid))
4692     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4693        and only return when it is stopped at the next breakpoint, we
4694        keep doing breakpoint actions until it returns false to
4695        indicate the inferior was not resumed.  */
4696     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4697       break;
4698
4699   discard_cleanups (cleanup_if_error);
4700 }
4701
4702 /* Print out the (old or new) value associated with a watchpoint.  */
4703
4704 static void
4705 watchpoint_value_print (struct value *val, struct ui_file *stream)
4706 {
4707   if (val == NULL)
4708     fprintf_unfiltered (stream, _("<unreadable>"));
4709   else
4710     {
4711       struct value_print_options opts;
4712       get_user_print_options (&opts);
4713       value_print (val, stream, &opts);
4714     }
4715 }
4716
4717 /* Generic routine for printing messages indicating why we
4718    stopped.  The behavior of this function depends on the value
4719    'print_it' in the bpstat structure.  Under some circumstances we
4720    may decide not to print anything here and delegate the task to
4721    normal_stop().  */
4722
4723 static enum print_stop_action
4724 print_bp_stop_message (bpstat bs)
4725 {
4726   switch (bs->print_it)
4727     {
4728     case print_it_noop:
4729       /* Nothing should be printed for this bpstat entry.  */
4730       return PRINT_UNKNOWN;
4731       break;
4732
4733     case print_it_done:
4734       /* We still want to print the frame, but we already printed the
4735          relevant messages.  */
4736       return PRINT_SRC_AND_LOC;
4737       break;
4738
4739     case print_it_normal:
4740       {
4741         struct breakpoint *b = bs->breakpoint_at;
4742
4743         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4744            which has since been deleted.  */
4745         if (b == NULL)
4746           return PRINT_UNKNOWN;
4747
4748         /* Normal case.  Call the breakpoint's print_it method.  */
4749         return b->ops->print_it (bs);
4750       }
4751       break;
4752
4753     default:
4754       internal_error (__FILE__, __LINE__,
4755                       _("print_bp_stop_message: unrecognized enum value"));
4756       break;
4757     }
4758 }
4759
4760 /* A helper function that prints a shared library stopped event.  */
4761
4762 static void
4763 print_solib_event (int is_catchpoint)
4764 {
4765   int any_deleted
4766     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4767   int any_added
4768     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4769
4770   if (!is_catchpoint)
4771     {
4772       if (any_added || any_deleted)
4773         ui_out_text (current_uiout,
4774                      _("Stopped due to shared library event:\n"));
4775       else
4776         ui_out_text (current_uiout,
4777                      _("Stopped due to shared library event (no "
4778                        "libraries added or removed)\n"));
4779     }
4780
4781   if (ui_out_is_mi_like_p (current_uiout))
4782     ui_out_field_string (current_uiout, "reason",
4783                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4784
4785   if (any_deleted)
4786     {
4787       struct cleanup *cleanup;
4788       char *name;
4789       int ix;
4790
4791       ui_out_text (current_uiout, _("  Inferior unloaded "));
4792       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4793                                                     "removed");
4794       for (ix = 0;
4795            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4796                         ix, name);
4797            ++ix)
4798         {
4799           if (ix > 0)
4800             ui_out_text (current_uiout, "    ");
4801           ui_out_field_string (current_uiout, "library", name);
4802           ui_out_text (current_uiout, "\n");
4803         }
4804
4805       do_cleanups (cleanup);
4806     }
4807
4808   if (any_added)
4809     {
4810       struct so_list *iter;
4811       int ix;
4812       struct cleanup *cleanup;
4813
4814       ui_out_text (current_uiout, _("  Inferior loaded "));
4815       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4816                                                     "added");
4817       for (ix = 0;
4818            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4819                         ix, iter);
4820            ++ix)
4821         {
4822           if (ix > 0)
4823             ui_out_text (current_uiout, "    ");
4824           ui_out_field_string (current_uiout, "library", iter->so_name);
4825           ui_out_text (current_uiout, "\n");
4826         }
4827
4828       do_cleanups (cleanup);
4829     }
4830 }
4831
4832 /* Print a message indicating what happened.  This is called from
4833    normal_stop().  The input to this routine is the head of the bpstat
4834    list - a list of the eventpoints that caused this stop.  KIND is
4835    the target_waitkind for the stopping event.  This
4836    routine calls the generic print routine for printing a message
4837    about reasons for stopping.  This will print (for example) the
4838    "Breakpoint n," part of the output.  The return value of this
4839    routine is one of:
4840
4841    PRINT_UNKNOWN: Means we printed nothing.
4842    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4843    code to print the location.  An example is 
4844    "Breakpoint 1, " which should be followed by
4845    the location.
4846    PRINT_SRC_ONLY: Means we printed something, but there is no need
4847    to also print the location part of the message.
4848    An example is the catch/throw messages, which
4849    don't require a location appended to the end.
4850    PRINT_NOTHING: We have done some printing and we don't need any 
4851    further info to be printed.  */
4852
4853 enum print_stop_action
4854 bpstat_print (bpstat bs, int kind)
4855 {
4856   int val;
4857
4858   /* Maybe another breakpoint in the chain caused us to stop.
4859      (Currently all watchpoints go on the bpstat whether hit or not.
4860      That probably could (should) be changed, provided care is taken
4861      with respect to bpstat_explains_signal).  */
4862   for (; bs; bs = bs->next)
4863     {
4864       val = print_bp_stop_message (bs);
4865       if (val == PRINT_SRC_ONLY 
4866           || val == PRINT_SRC_AND_LOC 
4867           || val == PRINT_NOTHING)
4868         return val;
4869     }
4870
4871   /* If we had hit a shared library event breakpoint,
4872      print_bp_stop_message would print out this message.  If we hit an
4873      OS-level shared library event, do the same thing.  */
4874   if (kind == TARGET_WAITKIND_LOADED)
4875     {
4876       print_solib_event (0);
4877       return PRINT_NOTHING;
4878     }
4879
4880   /* We reached the end of the chain, or we got a null BS to start
4881      with and nothing was printed.  */
4882   return PRINT_UNKNOWN;
4883 }
4884
4885 /* Evaluate the expression EXP and return 1 if value is zero.
4886    This returns the inverse of the condition because it is called
4887    from catch_errors which returns 0 if an exception happened, and if an
4888    exception happens we want execution to stop.
4889    The argument is a "struct expression *" that has been cast to a
4890    "void *" to make it pass through catch_errors.  */
4891
4892 static int
4893 breakpoint_cond_eval (void *exp)
4894 {
4895   struct value *mark = value_mark ();
4896   int i = !value_true (evaluate_expression ((struct expression *) exp));
4897
4898   value_free_to_mark (mark);
4899   return i;
4900 }
4901
4902 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4903
4904 static bpstat
4905 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4906 {
4907   bpstat bs;
4908
4909   bs = (bpstat) xmalloc (sizeof (*bs));
4910   bs->next = NULL;
4911   **bs_link_pointer = bs;
4912   *bs_link_pointer = &bs->next;
4913   bs->breakpoint_at = bl->owner;
4914   bs->bp_location_at = bl;
4915   incref_bp_location (bl);
4916   /* If the condition is false, etc., don't do the commands.  */
4917   bs->commands = NULL;
4918   bs->old_val = NULL;
4919   bs->print_it = print_it_normal;
4920   return bs;
4921 }
4922 \f
4923 /* The target has stopped with waitstatus WS.  Check if any hardware
4924    watchpoints have triggered, according to the target.  */
4925
4926 int
4927 watchpoints_triggered (struct target_waitstatus *ws)
4928 {
4929   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4930   CORE_ADDR addr;
4931   struct breakpoint *b;
4932
4933   if (!stopped_by_watchpoint)
4934     {
4935       /* We were not stopped by a watchpoint.  Mark all watchpoints
4936          as not triggered.  */
4937       ALL_BREAKPOINTS (b)
4938         if (is_hardware_watchpoint (b))
4939           {
4940             struct watchpoint *w = (struct watchpoint *) b;
4941
4942             w->watchpoint_triggered = watch_triggered_no;
4943           }
4944
4945       return 0;
4946     }
4947
4948   if (!target_stopped_data_address (&current_target, &addr))
4949     {
4950       /* We were stopped by a watchpoint, but we don't know where.
4951          Mark all watchpoints as unknown.  */
4952       ALL_BREAKPOINTS (b)
4953         if (is_hardware_watchpoint (b))
4954           {
4955             struct watchpoint *w = (struct watchpoint *) b;
4956
4957             w->watchpoint_triggered = watch_triggered_unknown;
4958           }
4959
4960       return 1;
4961     }
4962
4963   /* The target could report the data address.  Mark watchpoints
4964      affected by this data address as triggered, and all others as not
4965      triggered.  */
4966
4967   ALL_BREAKPOINTS (b)
4968     if (is_hardware_watchpoint (b))
4969       {
4970         struct watchpoint *w = (struct watchpoint *) b;
4971         struct bp_location *loc;
4972
4973         w->watchpoint_triggered = watch_triggered_no;
4974         for (loc = b->loc; loc; loc = loc->next)
4975           {
4976             if (is_masked_watchpoint (b))
4977               {
4978                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4979                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4980
4981                 if (newaddr == start)
4982                   {
4983                     w->watchpoint_triggered = watch_triggered_yes;
4984                     break;
4985                   }
4986               }
4987             /* Exact match not required.  Within range is sufficient.  */
4988             else if (target_watchpoint_addr_within_range (&current_target,
4989                                                          addr, loc->address,
4990                                                          loc->length))
4991               {
4992                 w->watchpoint_triggered = watch_triggered_yes;
4993                 break;
4994               }
4995           }
4996       }
4997
4998   return 1;
4999 }
5000
5001 /* Possible return values for watchpoint_check (this can't be an enum
5002    because of check_errors).  */
5003 /* The watchpoint has been deleted.  */
5004 #define WP_DELETED 1
5005 /* The value has changed.  */
5006 #define WP_VALUE_CHANGED 2
5007 /* The value has not changed.  */
5008 #define WP_VALUE_NOT_CHANGED 3
5009 /* Ignore this watchpoint, no matter if the value changed or not.  */
5010 #define WP_IGNORE 4
5011
5012 #define BP_TEMPFLAG 1
5013 #define BP_HARDWAREFLAG 2
5014
5015 /* Evaluate watchpoint condition expression and check if its value
5016    changed.
5017
5018    P should be a pointer to struct bpstat, but is defined as a void *
5019    in order for this function to be usable with catch_errors.  */
5020
5021 static int
5022 watchpoint_check (void *p)
5023 {
5024   bpstat bs = (bpstat) p;
5025   struct watchpoint *b;
5026   struct frame_info *fr;
5027   int within_current_scope;
5028
5029   /* BS is built from an existing struct breakpoint.  */
5030   gdb_assert (bs->breakpoint_at != NULL);
5031   b = (struct watchpoint *) bs->breakpoint_at;
5032
5033   /* If this is a local watchpoint, we only want to check if the
5034      watchpoint frame is in scope if the current thread is the thread
5035      that was used to create the watchpoint.  */
5036   if (!watchpoint_in_thread_scope (b))
5037     return WP_IGNORE;
5038
5039   if (b->exp_valid_block == NULL)
5040     within_current_scope = 1;
5041   else
5042     {
5043       struct frame_info *frame = get_current_frame ();
5044       struct gdbarch *frame_arch = get_frame_arch (frame);
5045       CORE_ADDR frame_pc = get_frame_pc (frame);
5046
5047       /* in_function_epilogue_p() returns a non-zero value if we're
5048          still in the function but the stack frame has already been
5049          invalidated.  Since we can't rely on the values of local
5050          variables after the stack has been destroyed, we are treating
5051          the watchpoint in that state as `not changed' without further
5052          checking.  Don't mark watchpoints as changed if the current
5053          frame is in an epilogue - even if they are in some other
5054          frame, our view of the stack is likely to be wrong and
5055          frame_find_by_id could error out.  */
5056       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5057         return WP_IGNORE;
5058
5059       fr = frame_find_by_id (b->watchpoint_frame);
5060       within_current_scope = (fr != NULL);
5061
5062       /* If we've gotten confused in the unwinder, we might have
5063          returned a frame that can't describe this variable.  */
5064       if (within_current_scope)
5065         {
5066           struct symbol *function;
5067
5068           function = get_frame_function (fr);
5069           if (function == NULL
5070               || !contained_in (b->exp_valid_block,
5071                                 SYMBOL_BLOCK_VALUE (function)))
5072             within_current_scope = 0;
5073         }
5074
5075       if (within_current_scope)
5076         /* If we end up stopping, the current frame will get selected
5077            in normal_stop.  So this call to select_frame won't affect
5078            the user.  */
5079         select_frame (fr);
5080     }
5081
5082   if (within_current_scope)
5083     {
5084       /* We use value_{,free_to_}mark because it could be a *long*
5085          time before we return to the command level and call
5086          free_all_values.  We can't call free_all_values because we
5087          might be in the middle of evaluating a function call.  */
5088
5089       int pc = 0;
5090       struct value *mark;
5091       struct value *new_val;
5092
5093       if (is_masked_watchpoint (&b->base))
5094         /* Since we don't know the exact trigger address (from
5095            stopped_data_address), just tell the user we've triggered
5096            a mask watchpoint.  */
5097         return WP_VALUE_CHANGED;
5098
5099       mark = value_mark ();
5100       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5101
5102       if (b->val_bitsize != 0)
5103         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5104
5105       /* We use value_equal_contents instead of value_equal because
5106          the latter coerces an array to a pointer, thus comparing just
5107          the address of the array instead of its contents.  This is
5108          not what we want.  */
5109       if ((b->val != NULL) != (new_val != NULL)
5110           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5111         {
5112           if (new_val != NULL)
5113             {
5114               release_value (new_val);
5115               value_free_to_mark (mark);
5116             }
5117           bs->old_val = b->val;
5118           b->val = new_val;
5119           b->val_valid = 1;
5120           return WP_VALUE_CHANGED;
5121         }
5122       else
5123         {
5124           /* Nothing changed.  */
5125           value_free_to_mark (mark);
5126           return WP_VALUE_NOT_CHANGED;
5127         }
5128     }
5129   else
5130     {
5131       struct ui_out *uiout = current_uiout;
5132
5133       /* This seems like the only logical thing to do because
5134          if we temporarily ignored the watchpoint, then when
5135          we reenter the block in which it is valid it contains
5136          garbage (in the case of a function, it may have two
5137          garbage values, one before and one after the prologue).
5138          So we can't even detect the first assignment to it and
5139          watch after that (since the garbage may or may not equal
5140          the first value assigned).  */
5141       /* We print all the stop information in
5142          breakpoint_ops->print_it, but in this case, by the time we
5143          call breakpoint_ops->print_it this bp will be deleted
5144          already.  So we have no choice but print the information
5145          here.  */
5146       if (ui_out_is_mi_like_p (uiout))
5147         ui_out_field_string
5148           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5149       ui_out_text (uiout, "\nWatchpoint ");
5150       ui_out_field_int (uiout, "wpnum", b->base.number);
5151       ui_out_text (uiout,
5152                    " deleted because the program has left the block in\n\
5153 which its expression is valid.\n");     
5154
5155       /* Make sure the watchpoint's commands aren't executed.  */
5156       decref_counted_command_line (&b->base.commands);
5157       watchpoint_del_at_next_stop (b);
5158
5159       return WP_DELETED;
5160     }
5161 }
5162
5163 /* Return true if it looks like target has stopped due to hitting
5164    breakpoint location BL.  This function does not check if we should
5165    stop, only if BL explains the stop.  */
5166
5167 static int
5168 bpstat_check_location (const struct bp_location *bl,
5169                        struct address_space *aspace, CORE_ADDR bp_addr,
5170                        const struct target_waitstatus *ws)
5171 {
5172   struct breakpoint *b = bl->owner;
5173
5174   /* BL is from an existing breakpoint.  */
5175   gdb_assert (b != NULL);
5176
5177   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5178 }
5179
5180 /* Determine if the watched values have actually changed, and we
5181    should stop.  If not, set BS->stop to 0.  */
5182
5183 static void
5184 bpstat_check_watchpoint (bpstat bs)
5185 {
5186   const struct bp_location *bl;
5187   struct watchpoint *b;
5188
5189   /* BS is built for existing struct breakpoint.  */
5190   bl = bs->bp_location_at;
5191   gdb_assert (bl != NULL);
5192   b = (struct watchpoint *) bs->breakpoint_at;
5193   gdb_assert (b != NULL);
5194
5195     {
5196       int must_check_value = 0;
5197       
5198       if (b->base.type == bp_watchpoint)
5199         /* For a software watchpoint, we must always check the
5200            watched value.  */
5201         must_check_value = 1;
5202       else if (b->watchpoint_triggered == watch_triggered_yes)
5203         /* We have a hardware watchpoint (read, write, or access)
5204            and the target earlier reported an address watched by
5205            this watchpoint.  */
5206         must_check_value = 1;
5207       else if (b->watchpoint_triggered == watch_triggered_unknown
5208                && b->base.type == bp_hardware_watchpoint)
5209         /* We were stopped by a hardware watchpoint, but the target could
5210            not report the data address.  We must check the watchpoint's
5211            value.  Access and read watchpoints are out of luck; without
5212            a data address, we can't figure it out.  */
5213         must_check_value = 1;
5214
5215       if (must_check_value)
5216         {
5217           char *message
5218             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5219                           b->base.number);
5220           struct cleanup *cleanups = make_cleanup (xfree, message);
5221           int e = catch_errors (watchpoint_check, bs, message,
5222                                 RETURN_MASK_ALL);
5223           do_cleanups (cleanups);
5224           switch (e)
5225             {
5226             case WP_DELETED:
5227               /* We've already printed what needs to be printed.  */
5228               bs->print_it = print_it_done;
5229               /* Stop.  */
5230               break;
5231             case WP_IGNORE:
5232               bs->print_it = print_it_noop;
5233               bs->stop = 0;
5234               break;
5235             case WP_VALUE_CHANGED:
5236               if (b->base.type == bp_read_watchpoint)
5237                 {
5238                   /* There are two cases to consider here:
5239
5240                      1. We're watching the triggered memory for reads.
5241                      In that case, trust the target, and always report
5242                      the watchpoint hit to the user.  Even though
5243                      reads don't cause value changes, the value may
5244                      have changed since the last time it was read, and
5245                      since we're not trapping writes, we will not see
5246                      those, and as such we should ignore our notion of
5247                      old value.
5248
5249                      2. We're watching the triggered memory for both
5250                      reads and writes.  There are two ways this may
5251                      happen:
5252
5253                      2.1. This is a target that can't break on data
5254                      reads only, but can break on accesses (reads or
5255                      writes), such as e.g., x86.  We detect this case
5256                      at the time we try to insert read watchpoints.
5257
5258                      2.2. Otherwise, the target supports read
5259                      watchpoints, but, the user set an access or write
5260                      watchpoint watching the same memory as this read
5261                      watchpoint.
5262
5263                      If we're watching memory writes as well as reads,
5264                      ignore watchpoint hits when we find that the
5265                      value hasn't changed, as reads don't cause
5266                      changes.  This still gives false positives when
5267                      the program writes the same value to memory as
5268                      what there was already in memory (we will confuse
5269                      it for a read), but it's much better than
5270                      nothing.  */
5271
5272                   int other_write_watchpoint = 0;
5273
5274                   if (bl->watchpoint_type == hw_read)
5275                     {
5276                       struct breakpoint *other_b;
5277
5278                       ALL_BREAKPOINTS (other_b)
5279                         if (other_b->type == bp_hardware_watchpoint
5280                             || other_b->type == bp_access_watchpoint)
5281                           {
5282                             struct watchpoint *other_w =
5283                               (struct watchpoint *) other_b;
5284
5285                             if (other_w->watchpoint_triggered
5286                                 == watch_triggered_yes)
5287                               {
5288                                 other_write_watchpoint = 1;
5289                                 break;
5290                               }
5291                           }
5292                     }
5293
5294                   if (other_write_watchpoint
5295                       || bl->watchpoint_type == hw_access)
5296                     {
5297                       /* We're watching the same memory for writes,
5298                          and the value changed since the last time we
5299                          updated it, so this trap must be for a write.
5300                          Ignore it.  */
5301                       bs->print_it = print_it_noop;
5302                       bs->stop = 0;
5303                     }
5304                 }
5305               break;
5306             case WP_VALUE_NOT_CHANGED:
5307               if (b->base.type == bp_hardware_watchpoint
5308                   || b->base.type == bp_watchpoint)
5309                 {
5310                   /* Don't stop: write watchpoints shouldn't fire if
5311                      the value hasn't changed.  */
5312                   bs->print_it = print_it_noop;
5313                   bs->stop = 0;
5314                 }
5315               /* Stop.  */
5316               break;
5317             default:
5318               /* Can't happen.  */
5319             case 0:
5320               /* Error from catch_errors.  */
5321               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5322               watchpoint_del_at_next_stop (b);
5323               /* We've already printed what needs to be printed.  */
5324               bs->print_it = print_it_done;
5325               break;
5326             }
5327         }
5328       else      /* must_check_value == 0 */
5329         {
5330           /* This is a case where some watchpoint(s) triggered, but
5331              not at the address of this watchpoint, or else no
5332              watchpoint triggered after all.  So don't print
5333              anything for this watchpoint.  */
5334           bs->print_it = print_it_noop;
5335           bs->stop = 0;
5336         }
5337     }
5338 }
5339
5340 /* For breakpoints that are currently marked as telling gdb to stop,
5341    check conditions (condition proper, frame, thread and ignore count)
5342    of breakpoint referred to by BS.  If we should not stop for this
5343    breakpoint, set BS->stop to 0.  */
5344
5345 static void
5346 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5347 {
5348   const struct bp_location *bl;
5349   struct breakpoint *b;
5350   int value_is_zero = 0;
5351   struct expression *cond;
5352
5353   gdb_assert (bs->stop);
5354
5355   /* BS is built for existing struct breakpoint.  */
5356   bl = bs->bp_location_at;
5357   gdb_assert (bl != NULL);
5358   b = bs->breakpoint_at;
5359   gdb_assert (b != NULL);
5360
5361   /* Even if the target evaluated the condition on its end and notified GDB, we
5362      need to do so again since GDB does not know if we stopped due to a
5363      breakpoint or a single step breakpoint.  */
5364
5365   if (frame_id_p (b->frame_id)
5366       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5367     {
5368       bs->stop = 0;
5369       return;
5370     }
5371
5372   /* If this is a thread/task-specific breakpoint, don't waste cpu
5373      evaluating the condition if this isn't the specified
5374      thread/task.  */
5375   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5376       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5377
5378     {
5379       bs->stop = 0;
5380       return;
5381     }
5382
5383   /* Evaluate extension language breakpoints that have a "stop" method
5384      implemented.  */
5385   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5386
5387   if (is_watchpoint (b))
5388     {
5389       struct watchpoint *w = (struct watchpoint *) b;
5390
5391       cond = w->cond_exp;
5392     }
5393   else
5394     cond = bl->cond;
5395
5396   if (cond && b->disposition != disp_del_at_next_stop)
5397     {
5398       int within_current_scope = 1;
5399       struct watchpoint * w;
5400
5401       /* We use value_mark and value_free_to_mark because it could
5402          be a long time before we return to the command level and
5403          call free_all_values.  We can't call free_all_values
5404          because we might be in the middle of evaluating a
5405          function call.  */
5406       struct value *mark = value_mark ();
5407
5408       if (is_watchpoint (b))
5409         w = (struct watchpoint *) b;
5410       else
5411         w = NULL;
5412
5413       /* Need to select the frame, with all that implies so that
5414          the conditions will have the right context.  Because we
5415          use the frame, we will not see an inlined function's
5416          variables when we arrive at a breakpoint at the start
5417          of the inlined function; the current frame will be the
5418          call site.  */
5419       if (w == NULL || w->cond_exp_valid_block == NULL)
5420         select_frame (get_current_frame ());
5421       else
5422         {
5423           struct frame_info *frame;
5424
5425           /* For local watchpoint expressions, which particular
5426              instance of a local is being watched matters, so we
5427              keep track of the frame to evaluate the expression
5428              in.  To evaluate the condition however, it doesn't
5429              really matter which instantiation of the function
5430              where the condition makes sense triggers the
5431              watchpoint.  This allows an expression like "watch
5432              global if q > 10" set in `func', catch writes to
5433              global on all threads that call `func', or catch
5434              writes on all recursive calls of `func' by a single
5435              thread.  We simply always evaluate the condition in
5436              the innermost frame that's executing where it makes
5437              sense to evaluate the condition.  It seems
5438              intuitive.  */
5439           frame = block_innermost_frame (w->cond_exp_valid_block);
5440           if (frame != NULL)
5441             select_frame (frame);
5442           else
5443             within_current_scope = 0;
5444         }
5445       if (within_current_scope)
5446         value_is_zero
5447           = catch_errors (breakpoint_cond_eval, cond,
5448                           "Error in testing breakpoint condition:\n",
5449                           RETURN_MASK_ALL);
5450       else
5451         {
5452           warning (_("Watchpoint condition cannot be tested "
5453                      "in the current scope"));
5454           /* If we failed to set the right context for this
5455              watchpoint, unconditionally report it.  */
5456           value_is_zero = 0;
5457         }
5458       /* FIXME-someday, should give breakpoint #.  */
5459       value_free_to_mark (mark);
5460     }
5461
5462   if (cond && value_is_zero)
5463     {
5464       bs->stop = 0;
5465     }
5466   else if (b->ignore_count > 0)
5467     {
5468       b->ignore_count--;
5469       bs->stop = 0;
5470       /* Increase the hit count even though we don't stop.  */
5471       ++(b->hit_count);
5472       observer_notify_breakpoint_modified (b);
5473     }   
5474 }
5475
5476
5477 /* Get a bpstat associated with having just stopped at address
5478    BP_ADDR in thread PTID.
5479
5480    Determine whether we stopped at a breakpoint, etc, or whether we
5481    don't understand this stop.  Result is a chain of bpstat's such
5482    that:
5483
5484    if we don't understand the stop, the result is a null pointer.
5485
5486    if we understand why we stopped, the result is not null.
5487
5488    Each element of the chain refers to a particular breakpoint or
5489    watchpoint at which we have stopped.  (We may have stopped for
5490    several reasons concurrently.)
5491
5492    Each element of the chain has valid next, breakpoint_at,
5493    commands, FIXME??? fields.  */
5494
5495 bpstat
5496 bpstat_stop_status (struct address_space *aspace,
5497                     CORE_ADDR bp_addr, ptid_t ptid,
5498                     const struct target_waitstatus *ws)
5499 {
5500   struct breakpoint *b = NULL;
5501   struct bp_location *bl;
5502   struct bp_location *loc;
5503   /* First item of allocated bpstat's.  */
5504   bpstat bs_head = NULL, *bs_link = &bs_head;
5505   /* Pointer to the last thing in the chain currently.  */
5506   bpstat bs;
5507   int ix;
5508   int need_remove_insert;
5509   int removed_any;
5510
5511   /* First, build the bpstat chain with locations that explain a
5512      target stop, while being careful to not set the target running,
5513      as that may invalidate locations (in particular watchpoint
5514      locations are recreated).  Resuming will happen here with
5515      breakpoint conditions or watchpoint expressions that include
5516      inferior function calls.  */
5517
5518   ALL_BREAKPOINTS (b)
5519     {
5520       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5521         continue;
5522
5523       for (bl = b->loc; bl != NULL; bl = bl->next)
5524         {
5525           /* For hardware watchpoints, we look only at the first
5526              location.  The watchpoint_check function will work on the
5527              entire expression, not the individual locations.  For
5528              read watchpoints, the watchpoints_triggered function has
5529              checked all locations already.  */
5530           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5531             break;
5532
5533           if (!bl->enabled || bl->shlib_disabled)
5534             continue;
5535
5536           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5537             continue;
5538
5539           /* Come here if it's a watchpoint, or if the break address
5540              matches.  */
5541
5542           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5543                                                    explain stop.  */
5544
5545           /* Assume we stop.  Should we find a watchpoint that is not
5546              actually triggered, or if the condition of the breakpoint
5547              evaluates as false, we'll reset 'stop' to 0.  */
5548           bs->stop = 1;
5549           bs->print = 1;
5550
5551           /* If this is a scope breakpoint, mark the associated
5552              watchpoint as triggered so that we will handle the
5553              out-of-scope event.  We'll get to the watchpoint next
5554              iteration.  */
5555           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5556             {
5557               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5558
5559               w->watchpoint_triggered = watch_triggered_yes;
5560             }
5561         }
5562     }
5563
5564   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5565     {
5566       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5567         {
5568           bs = bpstat_alloc (loc, &bs_link);
5569           /* For hits of moribund locations, we should just proceed.  */
5570           bs->stop = 0;
5571           bs->print = 0;
5572           bs->print_it = print_it_noop;
5573         }
5574     }
5575
5576   /* A bit of special processing for shlib breakpoints.  We need to
5577      process solib loading here, so that the lists of loaded and
5578      unloaded libraries are correct before we handle "catch load" and
5579      "catch unload".  */
5580   for (bs = bs_head; bs != NULL; bs = bs->next)
5581     {
5582       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5583         {
5584           handle_solib_event ();
5585           break;
5586         }
5587     }
5588
5589   /* Now go through the locations that caused the target to stop, and
5590      check whether we're interested in reporting this stop to higher
5591      layers, or whether we should resume the target transparently.  */
5592
5593   removed_any = 0;
5594
5595   for (bs = bs_head; bs != NULL; bs = bs->next)
5596     {
5597       if (!bs->stop)
5598         continue;
5599
5600       b = bs->breakpoint_at;
5601       b->ops->check_status (bs);
5602       if (bs->stop)
5603         {
5604           bpstat_check_breakpoint_conditions (bs, ptid);
5605
5606           if (bs->stop)
5607             {
5608               ++(b->hit_count);
5609               observer_notify_breakpoint_modified (b);
5610
5611               /* We will stop here.  */
5612               if (b->disposition == disp_disable)
5613                 {
5614                   --(b->enable_count);
5615                   if (b->enable_count <= 0
5616                       && b->enable_state != bp_permanent)
5617                     b->enable_state = bp_disabled;
5618                   removed_any = 1;
5619                 }
5620               if (b->silent)
5621                 bs->print = 0;
5622               bs->commands = b->commands;
5623               incref_counted_command_line (bs->commands);
5624               if (command_line_is_silent (bs->commands
5625                                           ? bs->commands->commands : NULL))
5626                 bs->print = 0;
5627
5628               b->ops->after_condition_true (bs);
5629             }
5630
5631         }
5632
5633       /* Print nothing for this entry if we don't stop or don't
5634          print.  */
5635       if (!bs->stop || !bs->print)
5636         bs->print_it = print_it_noop;
5637     }
5638
5639   /* If we aren't stopping, the value of some hardware watchpoint may
5640      not have changed, but the intermediate memory locations we are
5641      watching may have.  Don't bother if we're stopping; this will get
5642      done later.  */
5643   need_remove_insert = 0;
5644   if (! bpstat_causes_stop (bs_head))
5645     for (bs = bs_head; bs != NULL; bs = bs->next)
5646       if (!bs->stop
5647           && bs->breakpoint_at
5648           && is_hardware_watchpoint (bs->breakpoint_at))
5649         {
5650           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5651
5652           update_watchpoint (w, 0 /* don't reparse.  */);
5653           need_remove_insert = 1;
5654         }
5655
5656   if (need_remove_insert)
5657     update_global_location_list (1);
5658   else if (removed_any)
5659     update_global_location_list (0);
5660
5661   return bs_head;
5662 }
5663
5664 static void
5665 handle_jit_event (void)
5666 {
5667   struct frame_info *frame;
5668   struct gdbarch *gdbarch;
5669
5670   /* Switch terminal for any messages produced by
5671      breakpoint_re_set.  */
5672   target_terminal_ours_for_output ();
5673
5674   frame = get_current_frame ();
5675   gdbarch = get_frame_arch (frame);
5676
5677   jit_event_handler (gdbarch);
5678
5679   target_terminal_inferior ();
5680 }
5681
5682 /* Prepare WHAT final decision for infrun.  */
5683
5684 /* Decide what infrun needs to do with this bpstat.  */
5685
5686 struct bpstat_what
5687 bpstat_what (bpstat bs_head)
5688 {
5689   struct bpstat_what retval;
5690   int jit_event = 0;
5691   bpstat bs;
5692
5693   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5694   retval.call_dummy = STOP_NONE;
5695   retval.is_longjmp = 0;
5696
5697   for (bs = bs_head; bs != NULL; bs = bs->next)
5698     {
5699       /* Extract this BS's action.  After processing each BS, we check
5700          if its action overrides all we've seem so far.  */
5701       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5702       enum bptype bptype;
5703
5704       if (bs->breakpoint_at == NULL)
5705         {
5706           /* I suspect this can happen if it was a momentary
5707              breakpoint which has since been deleted.  */
5708           bptype = bp_none;
5709         }
5710       else
5711         bptype = bs->breakpoint_at->type;
5712
5713       switch (bptype)
5714         {
5715         case bp_none:
5716           break;
5717         case bp_breakpoint:
5718         case bp_hardware_breakpoint:
5719         case bp_until:
5720         case bp_finish:
5721         case bp_shlib_event:
5722           if (bs->stop)
5723             {
5724               if (bs->print)
5725                 this_action = BPSTAT_WHAT_STOP_NOISY;
5726               else
5727                 this_action = BPSTAT_WHAT_STOP_SILENT;
5728             }
5729           else
5730             this_action = BPSTAT_WHAT_SINGLE;
5731           break;
5732         case bp_watchpoint:
5733         case bp_hardware_watchpoint:
5734         case bp_read_watchpoint:
5735         case bp_access_watchpoint:
5736           if (bs->stop)
5737             {
5738               if (bs->print)
5739                 this_action = BPSTAT_WHAT_STOP_NOISY;
5740               else
5741                 this_action = BPSTAT_WHAT_STOP_SILENT;
5742             }
5743           else
5744             {
5745               /* There was a watchpoint, but we're not stopping.
5746                  This requires no further action.  */
5747             }
5748           break;
5749         case bp_longjmp:
5750         case bp_longjmp_call_dummy:
5751         case bp_exception:
5752           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5753           retval.is_longjmp = bptype != bp_exception;
5754           break;
5755         case bp_longjmp_resume:
5756         case bp_exception_resume:
5757           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5758           retval.is_longjmp = bptype == bp_longjmp_resume;
5759           break;
5760         case bp_step_resume:
5761           if (bs->stop)
5762             this_action = BPSTAT_WHAT_STEP_RESUME;
5763           else
5764             {
5765               /* It is for the wrong frame.  */
5766               this_action = BPSTAT_WHAT_SINGLE;
5767             }
5768           break;
5769         case bp_hp_step_resume:
5770           if (bs->stop)
5771             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5772           else
5773             {
5774               /* It is for the wrong frame.  */
5775               this_action = BPSTAT_WHAT_SINGLE;
5776             }
5777           break;
5778         case bp_watchpoint_scope:
5779         case bp_thread_event:
5780         case bp_overlay_event:
5781         case bp_longjmp_master:
5782         case bp_std_terminate_master:
5783         case bp_exception_master:
5784           this_action = BPSTAT_WHAT_SINGLE;
5785           break;
5786         case bp_catchpoint:
5787           if (bs->stop)
5788             {
5789               if (bs->print)
5790                 this_action = BPSTAT_WHAT_STOP_NOISY;
5791               else
5792                 this_action = BPSTAT_WHAT_STOP_SILENT;
5793             }
5794           else
5795             {
5796               /* There was a catchpoint, but we're not stopping.
5797                  This requires no further action.  */
5798             }
5799           break;
5800         case bp_jit_event:
5801           jit_event = 1;
5802           this_action = BPSTAT_WHAT_SINGLE;
5803           break;
5804         case bp_call_dummy:
5805           /* Make sure the action is stop (silent or noisy),
5806              so infrun.c pops the dummy frame.  */
5807           retval.call_dummy = STOP_STACK_DUMMY;
5808           this_action = BPSTAT_WHAT_STOP_SILENT;
5809           break;
5810         case bp_std_terminate:
5811           /* Make sure the action is stop (silent or noisy),
5812              so infrun.c pops the dummy frame.  */
5813           retval.call_dummy = STOP_STD_TERMINATE;
5814           this_action = BPSTAT_WHAT_STOP_SILENT;
5815           break;
5816         case bp_tracepoint:
5817         case bp_fast_tracepoint:
5818         case bp_static_tracepoint:
5819           /* Tracepoint hits should not be reported back to GDB, and
5820              if one got through somehow, it should have been filtered
5821              out already.  */
5822           internal_error (__FILE__, __LINE__,
5823                           _("bpstat_what: tracepoint encountered"));
5824           break;
5825         case bp_gnu_ifunc_resolver:
5826           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5827           this_action = BPSTAT_WHAT_SINGLE;
5828           break;
5829         case bp_gnu_ifunc_resolver_return:
5830           /* The breakpoint will be removed, execution will restart from the
5831              PC of the former breakpoint.  */
5832           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5833           break;
5834
5835         case bp_dprintf:
5836           if (bs->stop)
5837             this_action = BPSTAT_WHAT_STOP_SILENT;
5838           else
5839             this_action = BPSTAT_WHAT_SINGLE;
5840           break;
5841
5842         default:
5843           internal_error (__FILE__, __LINE__,
5844                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5845         }
5846
5847       retval.main_action = max (retval.main_action, this_action);
5848     }
5849
5850   /* These operations may affect the bs->breakpoint_at state so they are
5851      delayed after MAIN_ACTION is decided above.  */
5852
5853   if (jit_event)
5854     {
5855       if (debug_infrun)
5856         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5857
5858       handle_jit_event ();
5859     }
5860
5861   for (bs = bs_head; bs != NULL; bs = bs->next)
5862     {
5863       struct breakpoint *b = bs->breakpoint_at;
5864
5865       if (b == NULL)
5866         continue;
5867       switch (b->type)
5868         {
5869         case bp_gnu_ifunc_resolver:
5870           gnu_ifunc_resolver_stop (b);
5871           break;
5872         case bp_gnu_ifunc_resolver_return:
5873           gnu_ifunc_resolver_return_stop (b);
5874           break;
5875         }
5876     }
5877
5878   return retval;
5879 }
5880
5881 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5882    without hardware support).  This isn't related to a specific bpstat,
5883    just to things like whether watchpoints are set.  */
5884
5885 int
5886 bpstat_should_step (void)
5887 {
5888   struct breakpoint *b;
5889
5890   ALL_BREAKPOINTS (b)
5891     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5892       return 1;
5893   return 0;
5894 }
5895
5896 int
5897 bpstat_causes_stop (bpstat bs)
5898 {
5899   for (; bs != NULL; bs = bs->next)
5900     if (bs->stop)
5901       return 1;
5902
5903   return 0;
5904 }
5905
5906 \f
5907
5908 /* Compute a string of spaces suitable to indent the next line
5909    so it starts at the position corresponding to the table column
5910    named COL_NAME in the currently active table of UIOUT.  */
5911
5912 static char *
5913 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5914 {
5915   static char wrap_indent[80];
5916   int i, total_width, width, align;
5917   char *text;
5918
5919   total_width = 0;
5920   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5921     {
5922       if (strcmp (text, col_name) == 0)
5923         {
5924           gdb_assert (total_width < sizeof wrap_indent);
5925           memset (wrap_indent, ' ', total_width);
5926           wrap_indent[total_width] = 0;
5927
5928           return wrap_indent;
5929         }
5930
5931       total_width += width + 1;
5932     }
5933
5934   return NULL;
5935 }
5936
5937 /* Determine if the locations of this breakpoint will have their conditions
5938    evaluated by the target, host or a mix of both.  Returns the following:
5939
5940     "host": Host evals condition.
5941     "host or target": Host or Target evals condition.
5942     "target": Target evals condition.
5943 */
5944
5945 static const char *
5946 bp_condition_evaluator (struct breakpoint *b)
5947 {
5948   struct bp_location *bl;
5949   char host_evals = 0;
5950   char target_evals = 0;
5951
5952   if (!b)
5953     return NULL;
5954
5955   if (!is_breakpoint (b))
5956     return NULL;
5957
5958   if (gdb_evaluates_breakpoint_condition_p ()
5959       || !target_supports_evaluation_of_breakpoint_conditions ())
5960     return condition_evaluation_host;
5961
5962   for (bl = b->loc; bl; bl = bl->next)
5963     {
5964       if (bl->cond_bytecode)
5965         target_evals++;
5966       else
5967         host_evals++;
5968     }
5969
5970   if (host_evals && target_evals)
5971     return condition_evaluation_both;
5972   else if (target_evals)
5973     return condition_evaluation_target;
5974   else
5975     return condition_evaluation_host;
5976 }
5977
5978 /* Determine the breakpoint location's condition evaluator.  This is
5979    similar to bp_condition_evaluator, but for locations.  */
5980
5981 static const char *
5982 bp_location_condition_evaluator (struct bp_location *bl)
5983 {
5984   if (bl && !is_breakpoint (bl->owner))
5985     return NULL;
5986
5987   if (gdb_evaluates_breakpoint_condition_p ()
5988       || !target_supports_evaluation_of_breakpoint_conditions ())
5989     return condition_evaluation_host;
5990
5991   if (bl && bl->cond_bytecode)
5992     return condition_evaluation_target;
5993   else
5994     return condition_evaluation_host;
5995 }
5996
5997 /* Print the LOC location out of the list of B->LOC locations.  */
5998
5999 static void
6000 print_breakpoint_location (struct breakpoint *b,
6001                            struct bp_location *loc)
6002 {
6003   struct ui_out *uiout = current_uiout;
6004   struct cleanup *old_chain = save_current_program_space ();
6005
6006   if (loc != NULL && loc->shlib_disabled)
6007     loc = NULL;
6008
6009   if (loc != NULL)
6010     set_current_program_space (loc->pspace);
6011
6012   if (b->display_canonical)
6013     ui_out_field_string (uiout, "what", b->addr_string);
6014   else if (loc && loc->symtab)
6015     {
6016       struct symbol *sym 
6017         = find_pc_sect_function (loc->address, loc->section);
6018       if (sym)
6019         {
6020           ui_out_text (uiout, "in ");
6021           ui_out_field_string (uiout, "func",
6022                                SYMBOL_PRINT_NAME (sym));
6023           ui_out_text (uiout, " ");
6024           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6025           ui_out_text (uiout, "at ");
6026         }
6027       ui_out_field_string (uiout, "file",
6028                            symtab_to_filename_for_display (loc->symtab));
6029       ui_out_text (uiout, ":");
6030
6031       if (ui_out_is_mi_like_p (uiout))
6032         ui_out_field_string (uiout, "fullname",
6033                              symtab_to_fullname (loc->symtab));
6034       
6035       ui_out_field_int (uiout, "line", loc->line_number);
6036     }
6037   else if (loc)
6038     {
6039       struct ui_file *stb = mem_fileopen ();
6040       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6041
6042       print_address_symbolic (loc->gdbarch, loc->address, stb,
6043                               demangle, "");
6044       ui_out_field_stream (uiout, "at", stb);
6045
6046       do_cleanups (stb_chain);
6047     }
6048   else
6049     ui_out_field_string (uiout, "pending", b->addr_string);
6050
6051   if (loc && is_breakpoint (b)
6052       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6053       && bp_condition_evaluator (b) == condition_evaluation_both)
6054     {
6055       ui_out_text (uiout, " (");
6056       ui_out_field_string (uiout, "evaluated-by",
6057                            bp_location_condition_evaluator (loc));
6058       ui_out_text (uiout, ")");
6059     }
6060
6061   do_cleanups (old_chain);
6062 }
6063
6064 static const char *
6065 bptype_string (enum bptype type)
6066 {
6067   struct ep_type_description
6068     {
6069       enum bptype type;
6070       char *description;
6071     };
6072   static struct ep_type_description bptypes[] =
6073   {
6074     {bp_none, "?deleted?"},
6075     {bp_breakpoint, "breakpoint"},
6076     {bp_hardware_breakpoint, "hw breakpoint"},
6077     {bp_until, "until"},
6078     {bp_finish, "finish"},
6079     {bp_watchpoint, "watchpoint"},
6080     {bp_hardware_watchpoint, "hw watchpoint"},
6081     {bp_read_watchpoint, "read watchpoint"},
6082     {bp_access_watchpoint, "acc watchpoint"},
6083     {bp_longjmp, "longjmp"},
6084     {bp_longjmp_resume, "longjmp resume"},
6085     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6086     {bp_exception, "exception"},
6087     {bp_exception_resume, "exception resume"},
6088     {bp_step_resume, "step resume"},
6089     {bp_hp_step_resume, "high-priority step resume"},
6090     {bp_watchpoint_scope, "watchpoint scope"},
6091     {bp_call_dummy, "call dummy"},
6092     {bp_std_terminate, "std::terminate"},
6093     {bp_shlib_event, "shlib events"},
6094     {bp_thread_event, "thread events"},
6095     {bp_overlay_event, "overlay events"},
6096     {bp_longjmp_master, "longjmp master"},
6097     {bp_std_terminate_master, "std::terminate master"},
6098     {bp_exception_master, "exception master"},
6099     {bp_catchpoint, "catchpoint"},
6100     {bp_tracepoint, "tracepoint"},
6101     {bp_fast_tracepoint, "fast tracepoint"},
6102     {bp_static_tracepoint, "static tracepoint"},
6103     {bp_dprintf, "dprintf"},
6104     {bp_jit_event, "jit events"},
6105     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6106     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6107   };
6108
6109   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6110       || ((int) type != bptypes[(int) type].type))
6111     internal_error (__FILE__, __LINE__,
6112                     _("bptypes table does not describe type #%d."),
6113                     (int) type);
6114
6115   return bptypes[(int) type].description;
6116 }
6117
6118 /* For MI, output a field named 'thread-groups' with a list as the value.
6119    For CLI, prefix the list with the string 'inf'. */
6120
6121 static void
6122 output_thread_groups (struct ui_out *uiout,
6123                       const char *field_name,
6124                       VEC(int) *inf_num,
6125                       int mi_only)
6126 {
6127   struct cleanup *back_to;
6128   int is_mi = ui_out_is_mi_like_p (uiout);
6129   int inf;
6130   int i;
6131
6132   /* For backward compatibility, don't display inferiors in CLI unless
6133      there are several.  Always display them for MI. */
6134   if (!is_mi && mi_only)
6135     return;
6136
6137   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6138
6139   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6140     {
6141       if (is_mi)
6142         {
6143           char mi_group[10];
6144
6145           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6146           ui_out_field_string (uiout, NULL, mi_group);
6147         }
6148       else
6149         {
6150           if (i == 0)
6151             ui_out_text (uiout, " inf ");
6152           else
6153             ui_out_text (uiout, ", ");
6154         
6155           ui_out_text (uiout, plongest (inf));
6156         }
6157     }
6158
6159   do_cleanups (back_to);
6160 }
6161
6162 /* Print B to gdb_stdout.  */
6163
6164 static void
6165 print_one_breakpoint_location (struct breakpoint *b,
6166                                struct bp_location *loc,
6167                                int loc_number,
6168                                struct bp_location **last_loc,
6169                                int allflag)
6170 {
6171   struct command_line *l;
6172   static char bpenables[] = "nynny";
6173
6174   struct ui_out *uiout = current_uiout;
6175   int header_of_multiple = 0;
6176   int part_of_multiple = (loc != NULL);
6177   struct value_print_options opts;
6178
6179   get_user_print_options (&opts);
6180
6181   gdb_assert (!loc || loc_number != 0);
6182   /* See comment in print_one_breakpoint concerning treatment of
6183      breakpoints with single disabled location.  */
6184   if (loc == NULL 
6185       && (b->loc != NULL 
6186           && (b->loc->next != NULL || !b->loc->enabled)))
6187     header_of_multiple = 1;
6188   if (loc == NULL)
6189     loc = b->loc;
6190
6191   annotate_record ();
6192
6193   /* 1 */
6194   annotate_field (0);
6195   if (part_of_multiple)
6196     {
6197       char *formatted;
6198       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6199       ui_out_field_string (uiout, "number", formatted);
6200       xfree (formatted);
6201     }
6202   else
6203     {
6204       ui_out_field_int (uiout, "number", b->number);
6205     }
6206
6207   /* 2 */
6208   annotate_field (1);
6209   if (part_of_multiple)
6210     ui_out_field_skip (uiout, "type");
6211   else
6212     ui_out_field_string (uiout, "type", bptype_string (b->type));
6213
6214   /* 3 */
6215   annotate_field (2);
6216   if (part_of_multiple)
6217     ui_out_field_skip (uiout, "disp");
6218   else
6219     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6220
6221
6222   /* 4 */
6223   annotate_field (3);
6224   if (part_of_multiple)
6225     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6226   else
6227     ui_out_field_fmt (uiout, "enabled", "%c", 
6228                       bpenables[(int) b->enable_state]);
6229   ui_out_spaces (uiout, 2);
6230
6231   
6232   /* 5 and 6 */
6233   if (b->ops != NULL && b->ops->print_one != NULL)
6234     {
6235       /* Although the print_one can possibly print all locations,
6236          calling it here is not likely to get any nice result.  So,
6237          make sure there's just one location.  */
6238       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6239       b->ops->print_one (b, last_loc);
6240     }
6241   else
6242     switch (b->type)
6243       {
6244       case bp_none:
6245         internal_error (__FILE__, __LINE__,
6246                         _("print_one_breakpoint: bp_none encountered\n"));
6247         break;
6248
6249       case bp_watchpoint:
6250       case bp_hardware_watchpoint:
6251       case bp_read_watchpoint:
6252       case bp_access_watchpoint:
6253         {
6254           struct watchpoint *w = (struct watchpoint *) b;
6255
6256           /* Field 4, the address, is omitted (which makes the columns
6257              not line up too nicely with the headers, but the effect
6258              is relatively readable).  */
6259           if (opts.addressprint)
6260             ui_out_field_skip (uiout, "addr");
6261           annotate_field (5);
6262           ui_out_field_string (uiout, "what", w->exp_string);
6263         }
6264         break;
6265
6266       case bp_breakpoint:
6267       case bp_hardware_breakpoint:
6268       case bp_until:
6269       case bp_finish:
6270       case bp_longjmp:
6271       case bp_longjmp_resume:
6272       case bp_longjmp_call_dummy:
6273       case bp_exception:
6274       case bp_exception_resume:
6275       case bp_step_resume:
6276       case bp_hp_step_resume:
6277       case bp_watchpoint_scope:
6278       case bp_call_dummy:
6279       case bp_std_terminate:
6280       case bp_shlib_event:
6281       case bp_thread_event:
6282       case bp_overlay_event:
6283       case bp_longjmp_master:
6284       case bp_std_terminate_master:
6285       case bp_exception_master:
6286       case bp_tracepoint:
6287       case bp_fast_tracepoint:
6288       case bp_static_tracepoint:
6289       case bp_dprintf:
6290       case bp_jit_event:
6291       case bp_gnu_ifunc_resolver:
6292       case bp_gnu_ifunc_resolver_return:
6293         if (opts.addressprint)
6294           {
6295             annotate_field (4);
6296             if (header_of_multiple)
6297               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6298             else if (b->loc == NULL || loc->shlib_disabled)
6299               ui_out_field_string (uiout, "addr", "<PENDING>");
6300             else
6301               ui_out_field_core_addr (uiout, "addr",
6302                                       loc->gdbarch, loc->address);
6303           }
6304         annotate_field (5);
6305         if (!header_of_multiple)
6306           print_breakpoint_location (b, loc);
6307         if (b->loc)
6308           *last_loc = b->loc;
6309         break;
6310       }
6311
6312
6313   if (loc != NULL && !header_of_multiple)
6314     {
6315       struct inferior *inf;
6316       VEC(int) *inf_num = NULL;
6317       int mi_only = 1;
6318
6319       ALL_INFERIORS (inf)
6320         {
6321           if (inf->pspace == loc->pspace)
6322             VEC_safe_push (int, inf_num, inf->num);
6323         }
6324
6325         /* For backward compatibility, don't display inferiors in CLI unless
6326            there are several.  Always display for MI. */
6327         if (allflag
6328             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6329                 && (number_of_program_spaces () > 1
6330                     || number_of_inferiors () > 1)
6331                 /* LOC is for existing B, it cannot be in
6332                    moribund_locations and thus having NULL OWNER.  */
6333                 && loc->owner->type != bp_catchpoint))
6334         mi_only = 0;
6335       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6336       VEC_free (int, inf_num);
6337     }
6338
6339   if (!part_of_multiple)
6340     {
6341       if (b->thread != -1)
6342         {
6343           /* FIXME: This seems to be redundant and lost here; see the
6344              "stop only in" line a little further down.  */
6345           ui_out_text (uiout, " thread ");
6346           ui_out_field_int (uiout, "thread", b->thread);
6347         }
6348       else if (b->task != 0)
6349         {
6350           ui_out_text (uiout, " task ");
6351           ui_out_field_int (uiout, "task", b->task);
6352         }
6353     }
6354
6355   ui_out_text (uiout, "\n");
6356
6357   if (!part_of_multiple)
6358     b->ops->print_one_detail (b, uiout);
6359
6360   if (part_of_multiple && frame_id_p (b->frame_id))
6361     {
6362       annotate_field (6);
6363       ui_out_text (uiout, "\tstop only in stack frame at ");
6364       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6365          the frame ID.  */
6366       ui_out_field_core_addr (uiout, "frame",
6367                               b->gdbarch, b->frame_id.stack_addr);
6368       ui_out_text (uiout, "\n");
6369     }
6370   
6371   if (!part_of_multiple && b->cond_string)
6372     {
6373       annotate_field (7);
6374       if (is_tracepoint (b))
6375         ui_out_text (uiout, "\ttrace only if ");
6376       else
6377         ui_out_text (uiout, "\tstop only if ");
6378       ui_out_field_string (uiout, "cond", b->cond_string);
6379
6380       /* Print whether the target is doing the breakpoint's condition
6381          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6382       if (is_breakpoint (b)
6383           && breakpoint_condition_evaluation_mode ()
6384           == condition_evaluation_target)
6385         {
6386           ui_out_text (uiout, " (");
6387           ui_out_field_string (uiout, "evaluated-by",
6388                                bp_condition_evaluator (b));
6389           ui_out_text (uiout, " evals)");
6390         }
6391       ui_out_text (uiout, "\n");
6392     }
6393
6394   if (!part_of_multiple && b->thread != -1)
6395     {
6396       /* FIXME should make an annotation for this.  */
6397       ui_out_text (uiout, "\tstop only in thread ");
6398       ui_out_field_int (uiout, "thread", b->thread);
6399       ui_out_text (uiout, "\n");
6400     }
6401   
6402   if (!part_of_multiple)
6403     {
6404       if (b->hit_count)
6405         {
6406           /* FIXME should make an annotation for this.  */
6407           if (is_catchpoint (b))
6408             ui_out_text (uiout, "\tcatchpoint");
6409           else if (is_tracepoint (b))
6410             ui_out_text (uiout, "\ttracepoint");
6411           else
6412             ui_out_text (uiout, "\tbreakpoint");
6413           ui_out_text (uiout, " already hit ");
6414           ui_out_field_int (uiout, "times", b->hit_count);
6415           if (b->hit_count == 1)
6416             ui_out_text (uiout, " time\n");
6417           else
6418             ui_out_text (uiout, " times\n");
6419         }
6420       else
6421         {
6422           /* Output the count also if it is zero, but only if this is mi.  */
6423           if (ui_out_is_mi_like_p (uiout))
6424             ui_out_field_int (uiout, "times", b->hit_count);
6425         }
6426     }
6427
6428   if (!part_of_multiple && b->ignore_count)
6429     {
6430       annotate_field (8);
6431       ui_out_text (uiout, "\tignore next ");
6432       ui_out_field_int (uiout, "ignore", b->ignore_count);
6433       ui_out_text (uiout, " hits\n");
6434     }
6435
6436   /* Note that an enable count of 1 corresponds to "enable once"
6437      behavior, which is reported by the combination of enablement and
6438      disposition, so we don't need to mention it here.  */
6439   if (!part_of_multiple && b->enable_count > 1)
6440     {
6441       annotate_field (8);
6442       ui_out_text (uiout, "\tdisable after ");
6443       /* Tweak the wording to clarify that ignore and enable counts
6444          are distinct, and have additive effect.  */
6445       if (b->ignore_count)
6446         ui_out_text (uiout, "additional ");
6447       else
6448         ui_out_text (uiout, "next ");
6449       ui_out_field_int (uiout, "enable", b->enable_count);
6450       ui_out_text (uiout, " hits\n");
6451     }
6452
6453   if (!part_of_multiple && is_tracepoint (b))
6454     {
6455       struct tracepoint *tp = (struct tracepoint *) b;
6456
6457       if (tp->traceframe_usage)
6458         {
6459           ui_out_text (uiout, "\ttrace buffer usage ");
6460           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6461           ui_out_text (uiout, " bytes\n");
6462         }
6463     }
6464
6465   l = b->commands ? b->commands->commands : NULL;
6466   if (!part_of_multiple && l)
6467     {
6468       struct cleanup *script_chain;
6469
6470       annotate_field (9);
6471       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6472       print_command_lines (uiout, l, 4);
6473       do_cleanups (script_chain);
6474     }
6475
6476   if (is_tracepoint (b))
6477     {
6478       struct tracepoint *t = (struct tracepoint *) b;
6479
6480       if (!part_of_multiple && t->pass_count)
6481         {
6482           annotate_field (10);
6483           ui_out_text (uiout, "\tpass count ");
6484           ui_out_field_int (uiout, "pass", t->pass_count);
6485           ui_out_text (uiout, " \n");
6486         }
6487
6488       /* Don't display it when tracepoint or tracepoint location is
6489          pending.   */
6490       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6491         {
6492           annotate_field (11);
6493
6494           if (ui_out_is_mi_like_p (uiout))
6495             ui_out_field_string (uiout, "installed",
6496                                  loc->inserted ? "y" : "n");
6497           else
6498             {
6499               if (loc->inserted)
6500                 ui_out_text (uiout, "\t");
6501               else
6502                 ui_out_text (uiout, "\tnot ");
6503               ui_out_text (uiout, "installed on target\n");
6504             }
6505         }
6506     }
6507
6508   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6509     {
6510       if (is_watchpoint (b))
6511         {
6512           struct watchpoint *w = (struct watchpoint *) b;
6513
6514           ui_out_field_string (uiout, "original-location", w->exp_string);
6515         }
6516       else if (b->addr_string)
6517         ui_out_field_string (uiout, "original-location", b->addr_string);
6518     }
6519 }
6520
6521 static void
6522 print_one_breakpoint (struct breakpoint *b,
6523                       struct bp_location **last_loc, 
6524                       int allflag)
6525 {
6526   struct cleanup *bkpt_chain;
6527   struct ui_out *uiout = current_uiout;
6528
6529   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6530
6531   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6532   do_cleanups (bkpt_chain);
6533
6534   /* If this breakpoint has custom print function,
6535      it's already printed.  Otherwise, print individual
6536      locations, if any.  */
6537   if (b->ops == NULL || b->ops->print_one == NULL)
6538     {
6539       /* If breakpoint has a single location that is disabled, we
6540          print it as if it had several locations, since otherwise it's
6541          hard to represent "breakpoint enabled, location disabled"
6542          situation.
6543
6544          Note that while hardware watchpoints have several locations
6545          internally, that's not a property exposed to user.  */
6546       if (b->loc 
6547           && !is_hardware_watchpoint (b)
6548           && (b->loc->next || !b->loc->enabled))
6549         {
6550           struct bp_location *loc;
6551           int n = 1;
6552
6553           for (loc = b->loc; loc; loc = loc->next, ++n)
6554             {
6555               struct cleanup *inner2 =
6556                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6557               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6558               do_cleanups (inner2);
6559             }
6560         }
6561     }
6562 }
6563
6564 static int
6565 breakpoint_address_bits (struct breakpoint *b)
6566 {
6567   int print_address_bits = 0;
6568   struct bp_location *loc;
6569
6570   for (loc = b->loc; loc; loc = loc->next)
6571     {
6572       int addr_bit;
6573
6574       /* Software watchpoints that aren't watching memory don't have
6575          an address to print.  */
6576       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6577         continue;
6578
6579       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6580       if (addr_bit > print_address_bits)
6581         print_address_bits = addr_bit;
6582     }
6583
6584   return print_address_bits;
6585 }
6586
6587 struct captured_breakpoint_query_args
6588   {
6589     int bnum;
6590   };
6591
6592 static int
6593 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6594 {
6595   struct captured_breakpoint_query_args *args = data;
6596   struct breakpoint *b;
6597   struct bp_location *dummy_loc = NULL;
6598
6599   ALL_BREAKPOINTS (b)
6600     {
6601       if (args->bnum == b->number)
6602         {
6603           print_one_breakpoint (b, &dummy_loc, 0);
6604           return GDB_RC_OK;
6605         }
6606     }
6607   return GDB_RC_NONE;
6608 }
6609
6610 enum gdb_rc
6611 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6612                       char **error_message)
6613 {
6614   struct captured_breakpoint_query_args args;
6615
6616   args.bnum = bnum;
6617   /* For the moment we don't trust print_one_breakpoint() to not throw
6618      an error.  */
6619   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6620                                  error_message, RETURN_MASK_ALL) < 0)
6621     return GDB_RC_FAIL;
6622   else
6623     return GDB_RC_OK;
6624 }
6625
6626 /* Return true if this breakpoint was set by the user, false if it is
6627    internal or momentary.  */
6628
6629 int
6630 user_breakpoint_p (struct breakpoint *b)
6631 {
6632   return b->number > 0;
6633 }
6634
6635 /* Print information on user settable breakpoint (watchpoint, etc)
6636    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6637    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6638    FILTER is non-NULL, call it on each breakpoint and only include the
6639    ones for which it returns non-zero.  Return the total number of
6640    breakpoints listed.  */
6641
6642 static int
6643 breakpoint_1 (char *args, int allflag, 
6644               int (*filter) (const struct breakpoint *))
6645 {
6646   struct breakpoint *b;
6647   struct bp_location *last_loc = NULL;
6648   int nr_printable_breakpoints;
6649   struct cleanup *bkpttbl_chain;
6650   struct value_print_options opts;
6651   int print_address_bits = 0;
6652   int print_type_col_width = 14;
6653   struct ui_out *uiout = current_uiout;
6654
6655   get_user_print_options (&opts);
6656
6657   /* Compute the number of rows in the table, as well as the size
6658      required for address fields.  */
6659   nr_printable_breakpoints = 0;
6660   ALL_BREAKPOINTS (b)
6661     {
6662       /* If we have a filter, only list the breakpoints it accepts.  */
6663       if (filter && !filter (b))
6664         continue;
6665
6666       /* If we have an "args" string, it is a list of breakpoints to 
6667          accept.  Skip the others.  */
6668       if (args != NULL && *args != '\0')
6669         {
6670           if (allflag && parse_and_eval_long (args) != b->number)
6671             continue;
6672           if (!allflag && !number_is_in_list (args, b->number))
6673             continue;
6674         }
6675
6676       if (allflag || user_breakpoint_p (b))
6677         {
6678           int addr_bit, type_len;
6679
6680           addr_bit = breakpoint_address_bits (b);
6681           if (addr_bit > print_address_bits)
6682             print_address_bits = addr_bit;
6683
6684           type_len = strlen (bptype_string (b->type));
6685           if (type_len > print_type_col_width)
6686             print_type_col_width = type_len;
6687
6688           nr_printable_breakpoints++;
6689         }
6690     }
6691
6692   if (opts.addressprint)
6693     bkpttbl_chain 
6694       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6695                                              nr_printable_breakpoints,
6696                                              "BreakpointTable");
6697   else
6698     bkpttbl_chain 
6699       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6700                                              nr_printable_breakpoints,
6701                                              "BreakpointTable");
6702
6703   if (nr_printable_breakpoints > 0)
6704     annotate_breakpoints_headers ();
6705   if (nr_printable_breakpoints > 0)
6706     annotate_field (0);
6707   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6708   if (nr_printable_breakpoints > 0)
6709     annotate_field (1);
6710   ui_out_table_header (uiout, print_type_col_width, ui_left,
6711                        "type", "Type");                         /* 2 */
6712   if (nr_printable_breakpoints > 0)
6713     annotate_field (2);
6714   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6715   if (nr_printable_breakpoints > 0)
6716     annotate_field (3);
6717   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6718   if (opts.addressprint)
6719     {
6720       if (nr_printable_breakpoints > 0)
6721         annotate_field (4);
6722       if (print_address_bits <= 32)
6723         ui_out_table_header (uiout, 10, ui_left, 
6724                              "addr", "Address");                /* 5 */
6725       else
6726         ui_out_table_header (uiout, 18, ui_left, 
6727                              "addr", "Address");                /* 5 */
6728     }
6729   if (nr_printable_breakpoints > 0)
6730     annotate_field (5);
6731   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6732   ui_out_table_body (uiout);
6733   if (nr_printable_breakpoints > 0)
6734     annotate_breakpoints_table ();
6735
6736   ALL_BREAKPOINTS (b)
6737     {
6738       QUIT;
6739       /* If we have a filter, only list the breakpoints it accepts.  */
6740       if (filter && !filter (b))
6741         continue;
6742
6743       /* If we have an "args" string, it is a list of breakpoints to 
6744          accept.  Skip the others.  */
6745
6746       if (args != NULL && *args != '\0')
6747         {
6748           if (allflag)  /* maintenance info breakpoint */
6749             {
6750               if (parse_and_eval_long (args) != b->number)
6751                 continue;
6752             }
6753           else          /* all others */
6754             {
6755               if (!number_is_in_list (args, b->number))
6756                 continue;
6757             }
6758         }
6759       /* We only print out user settable breakpoints unless the
6760          allflag is set.  */
6761       if (allflag || user_breakpoint_p (b))
6762         print_one_breakpoint (b, &last_loc, allflag);
6763     }
6764
6765   do_cleanups (bkpttbl_chain);
6766
6767   if (nr_printable_breakpoints == 0)
6768     {
6769       /* If there's a filter, let the caller decide how to report
6770          empty list.  */
6771       if (!filter)
6772         {
6773           if (args == NULL || *args == '\0')
6774             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6775           else
6776             ui_out_message (uiout, 0, 
6777                             "No breakpoint or watchpoint matching '%s'.\n",
6778                             args);
6779         }
6780     }
6781   else
6782     {
6783       if (last_loc && !server_command)
6784         set_next_address (last_loc->gdbarch, last_loc->address);
6785     }
6786
6787   /* FIXME?  Should this be moved up so that it is only called when
6788      there have been breakpoints? */
6789   annotate_breakpoints_table_end ();
6790
6791   return nr_printable_breakpoints;
6792 }
6793
6794 /* Display the value of default-collect in a way that is generally
6795    compatible with the breakpoint list.  */
6796
6797 static void
6798 default_collect_info (void)
6799 {
6800   struct ui_out *uiout = current_uiout;
6801
6802   /* If it has no value (which is frequently the case), say nothing; a
6803      message like "No default-collect." gets in user's face when it's
6804      not wanted.  */
6805   if (!*default_collect)
6806     return;
6807
6808   /* The following phrase lines up nicely with per-tracepoint collect
6809      actions.  */
6810   ui_out_text (uiout, "default collect ");
6811   ui_out_field_string (uiout, "default-collect", default_collect);
6812   ui_out_text (uiout, " \n");
6813 }
6814   
6815 static void
6816 breakpoints_info (char *args, int from_tty)
6817 {
6818   breakpoint_1 (args, 0, NULL);
6819
6820   default_collect_info ();
6821 }
6822
6823 static void
6824 watchpoints_info (char *args, int from_tty)
6825 {
6826   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6827   struct ui_out *uiout = current_uiout;
6828
6829   if (num_printed == 0)
6830     {
6831       if (args == NULL || *args == '\0')
6832         ui_out_message (uiout, 0, "No watchpoints.\n");
6833       else
6834         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6835     }
6836 }
6837
6838 static void
6839 maintenance_info_breakpoints (char *args, int from_tty)
6840 {
6841   breakpoint_1 (args, 1, NULL);
6842
6843   default_collect_info ();
6844 }
6845
6846 static int
6847 breakpoint_has_pc (struct breakpoint *b,
6848                    struct program_space *pspace,
6849                    CORE_ADDR pc, struct obj_section *section)
6850 {
6851   struct bp_location *bl = b->loc;
6852
6853   for (; bl; bl = bl->next)
6854     {
6855       if (bl->pspace == pspace
6856           && bl->address == pc
6857           && (!overlay_debugging || bl->section == section))
6858         return 1;         
6859     }
6860   return 0;
6861 }
6862
6863 /* Print a message describing any user-breakpoints set at PC.  This
6864    concerns with logical breakpoints, so we match program spaces, not
6865    address spaces.  */
6866
6867 static void
6868 describe_other_breakpoints (struct gdbarch *gdbarch,
6869                             struct program_space *pspace, CORE_ADDR pc,
6870                             struct obj_section *section, int thread)
6871 {
6872   int others = 0;
6873   struct breakpoint *b;
6874
6875   ALL_BREAKPOINTS (b)
6876     others += (user_breakpoint_p (b)
6877                && breakpoint_has_pc (b, pspace, pc, section));
6878   if (others > 0)
6879     {
6880       if (others == 1)
6881         printf_filtered (_("Note: breakpoint "));
6882       else /* if (others == ???) */
6883         printf_filtered (_("Note: breakpoints "));
6884       ALL_BREAKPOINTS (b)
6885         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6886           {
6887             others--;
6888             printf_filtered ("%d", b->number);
6889             if (b->thread == -1 && thread != -1)
6890               printf_filtered (" (all threads)");
6891             else if (b->thread != -1)
6892               printf_filtered (" (thread %d)", b->thread);
6893             printf_filtered ("%s%s ",
6894                              ((b->enable_state == bp_disabled
6895                                || b->enable_state == bp_call_disabled)
6896                               ? " (disabled)"
6897                               : b->enable_state == bp_permanent 
6898                               ? " (permanent)"
6899                               : ""),
6900                              (others > 1) ? "," 
6901                              : ((others == 1) ? " and" : ""));
6902           }
6903       printf_filtered (_("also set at pc "));
6904       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6905       printf_filtered (".\n");
6906     }
6907 }
6908 \f
6909
6910 /* Return true iff it is meaningful to use the address member of
6911    BPT.  For some breakpoint types, the address member is irrelevant
6912    and it makes no sense to attempt to compare it to other addresses
6913    (or use it for any other purpose either).
6914
6915    More specifically, each of the following breakpoint types will
6916    always have a zero valued address and we don't want to mark
6917    breakpoints of any of these types to be a duplicate of an actual
6918    breakpoint at address zero:
6919
6920       bp_watchpoint
6921       bp_catchpoint
6922
6923 */
6924
6925 static int
6926 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6927 {
6928   enum bptype type = bpt->type;
6929
6930   return (type != bp_watchpoint && type != bp_catchpoint);
6931 }
6932
6933 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6934    true if LOC1 and LOC2 represent the same watchpoint location.  */
6935
6936 static int
6937 watchpoint_locations_match (struct bp_location *loc1, 
6938                             struct bp_location *loc2)
6939 {
6940   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6941   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6942
6943   /* Both of them must exist.  */
6944   gdb_assert (w1 != NULL);
6945   gdb_assert (w2 != NULL);
6946
6947   /* If the target can evaluate the condition expression in hardware,
6948      then we we need to insert both watchpoints even if they are at
6949      the same place.  Otherwise the watchpoint will only trigger when
6950      the condition of whichever watchpoint was inserted evaluates to
6951      true, not giving a chance for GDB to check the condition of the
6952      other watchpoint.  */
6953   if ((w1->cond_exp
6954        && target_can_accel_watchpoint_condition (loc1->address, 
6955                                                  loc1->length,
6956                                                  loc1->watchpoint_type,
6957                                                  w1->cond_exp))
6958       || (w2->cond_exp
6959           && target_can_accel_watchpoint_condition (loc2->address, 
6960                                                     loc2->length,
6961                                                     loc2->watchpoint_type,
6962                                                     w2->cond_exp)))
6963     return 0;
6964
6965   /* Note that this checks the owner's type, not the location's.  In
6966      case the target does not support read watchpoints, but does
6967      support access watchpoints, we'll have bp_read_watchpoint
6968      watchpoints with hw_access locations.  Those should be considered
6969      duplicates of hw_read locations.  The hw_read locations will
6970      become hw_access locations later.  */
6971   return (loc1->owner->type == loc2->owner->type
6972           && loc1->pspace->aspace == loc2->pspace->aspace
6973           && loc1->address == loc2->address
6974           && loc1->length == loc2->length);
6975 }
6976
6977 /* See breakpoint.h.  */
6978
6979 int
6980 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6981                           struct address_space *aspace2, CORE_ADDR addr2)
6982 {
6983   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6984            || aspace1 == aspace2)
6985           && addr1 == addr2);
6986 }
6987
6988 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6989    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6990    matches ASPACE2.  On targets that have global breakpoints, the address
6991    space doesn't really matter.  */
6992
6993 static int
6994 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6995                                 int len1, struct address_space *aspace2,
6996                                 CORE_ADDR addr2)
6997 {
6998   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6999            || aspace1 == aspace2)
7000           && addr2 >= addr1 && addr2 < addr1 + len1);
7001 }
7002
7003 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7004    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7005    matches the breakpoint's address space.  On targets that have global
7006    breakpoints, the address space doesn't really matter.  */
7007
7008 static int
7009 breakpoint_location_address_match (struct bp_location *bl,
7010                                    struct address_space *aspace,
7011                                    CORE_ADDR addr)
7012 {
7013   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7014                                     aspace, addr)
7015           || (bl->length
7016               && breakpoint_address_match_range (bl->pspace->aspace,
7017                                                  bl->address, bl->length,
7018                                                  aspace, addr)));
7019 }
7020
7021 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7022    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7023    true, otherwise returns false.  */
7024
7025 static int
7026 tracepoint_locations_match (struct bp_location *loc1,
7027                             struct bp_location *loc2)
7028 {
7029   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7030     /* Since tracepoint locations are never duplicated with others', tracepoint
7031        locations at the same address of different tracepoints are regarded as
7032        different locations.  */
7033     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7034   else
7035     return 0;
7036 }
7037
7038 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7039    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7040    represent the same location.  */
7041
7042 static int
7043 breakpoint_locations_match (struct bp_location *loc1, 
7044                             struct bp_location *loc2)
7045 {
7046   int hw_point1, hw_point2;
7047
7048   /* Both of them must not be in moribund_locations.  */
7049   gdb_assert (loc1->owner != NULL);
7050   gdb_assert (loc2->owner != NULL);
7051
7052   hw_point1 = is_hardware_watchpoint (loc1->owner);
7053   hw_point2 = is_hardware_watchpoint (loc2->owner);
7054
7055   if (hw_point1 != hw_point2)
7056     return 0;
7057   else if (hw_point1)
7058     return watchpoint_locations_match (loc1, loc2);
7059   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7060     return tracepoint_locations_match (loc1, loc2);
7061   else
7062     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7063     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7064                                      loc2->pspace->aspace, loc2->address)
7065             && loc1->length == loc2->length);
7066 }
7067
7068 static void
7069 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7070                                int bnum, int have_bnum)
7071 {
7072   /* The longest string possibly returned by hex_string_custom
7073      is 50 chars.  These must be at least that big for safety.  */
7074   char astr1[64];
7075   char astr2[64];
7076
7077   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7078   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7079   if (have_bnum)
7080     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7081              bnum, astr1, astr2);
7082   else
7083     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7084 }
7085
7086 /* Adjust a breakpoint's address to account for architectural
7087    constraints on breakpoint placement.  Return the adjusted address.
7088    Note: Very few targets require this kind of adjustment.  For most
7089    targets, this function is simply the identity function.  */
7090
7091 static CORE_ADDR
7092 adjust_breakpoint_address (struct gdbarch *gdbarch,
7093                            CORE_ADDR bpaddr, enum bptype bptype)
7094 {
7095   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7096     {
7097       /* Very few targets need any kind of breakpoint adjustment.  */
7098       return bpaddr;
7099     }
7100   else if (bptype == bp_watchpoint
7101            || bptype == bp_hardware_watchpoint
7102            || bptype == bp_read_watchpoint
7103            || bptype == bp_access_watchpoint
7104            || bptype == bp_catchpoint)
7105     {
7106       /* Watchpoints and the various bp_catch_* eventpoints should not
7107          have their addresses modified.  */
7108       return bpaddr;
7109     }
7110   else
7111     {
7112       CORE_ADDR adjusted_bpaddr;
7113
7114       /* Some targets have architectural constraints on the placement
7115          of breakpoint instructions.  Obtain the adjusted address.  */
7116       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7117
7118       /* An adjusted breakpoint address can significantly alter
7119          a user's expectations.  Print a warning if an adjustment
7120          is required.  */
7121       if (adjusted_bpaddr != bpaddr)
7122         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7123
7124       return adjusted_bpaddr;
7125     }
7126 }
7127
7128 void
7129 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7130                   struct breakpoint *owner)
7131 {
7132   memset (loc, 0, sizeof (*loc));
7133
7134   gdb_assert (ops != NULL);
7135
7136   loc->ops = ops;
7137   loc->owner = owner;
7138   loc->cond = NULL;
7139   loc->cond_bytecode = NULL;
7140   loc->shlib_disabled = 0;
7141   loc->enabled = 1;
7142
7143   switch (owner->type)
7144     {
7145     case bp_breakpoint:
7146     case bp_until:
7147     case bp_finish:
7148     case bp_longjmp:
7149     case bp_longjmp_resume:
7150     case bp_longjmp_call_dummy:
7151     case bp_exception:
7152     case bp_exception_resume:
7153     case bp_step_resume:
7154     case bp_hp_step_resume:
7155     case bp_watchpoint_scope:
7156     case bp_call_dummy:
7157     case bp_std_terminate:
7158     case bp_shlib_event:
7159     case bp_thread_event:
7160     case bp_overlay_event:
7161     case bp_jit_event:
7162     case bp_longjmp_master:
7163     case bp_std_terminate_master:
7164     case bp_exception_master:
7165     case bp_gnu_ifunc_resolver:
7166     case bp_gnu_ifunc_resolver_return:
7167     case bp_dprintf:
7168       loc->loc_type = bp_loc_software_breakpoint;
7169       mark_breakpoint_location_modified (loc);
7170       break;
7171     case bp_hardware_breakpoint:
7172       loc->loc_type = bp_loc_hardware_breakpoint;
7173       mark_breakpoint_location_modified (loc);
7174       break;
7175     case bp_hardware_watchpoint:
7176     case bp_read_watchpoint:
7177     case bp_access_watchpoint:
7178       loc->loc_type = bp_loc_hardware_watchpoint;
7179       break;
7180     case bp_watchpoint:
7181     case bp_catchpoint:
7182     case bp_tracepoint:
7183     case bp_fast_tracepoint:
7184     case bp_static_tracepoint:
7185       loc->loc_type = bp_loc_other;
7186       break;
7187     default:
7188       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7189     }
7190
7191   loc->refc = 1;
7192 }
7193
7194 /* Allocate a struct bp_location.  */
7195
7196 static struct bp_location *
7197 allocate_bp_location (struct breakpoint *bpt)
7198 {
7199   return bpt->ops->allocate_location (bpt);
7200 }
7201
7202 static void
7203 free_bp_location (struct bp_location *loc)
7204 {
7205   loc->ops->dtor (loc);
7206   xfree (loc);
7207 }
7208
7209 /* Increment reference count.  */
7210
7211 static void
7212 incref_bp_location (struct bp_location *bl)
7213 {
7214   ++bl->refc;
7215 }
7216
7217 /* Decrement reference count.  If the reference count reaches 0,
7218    destroy the bp_location.  Sets *BLP to NULL.  */
7219
7220 static void
7221 decref_bp_location (struct bp_location **blp)
7222 {
7223   gdb_assert ((*blp)->refc > 0);
7224
7225   if (--(*blp)->refc == 0)
7226     free_bp_location (*blp);
7227   *blp = NULL;
7228 }
7229
7230 /* Add breakpoint B at the end of the global breakpoint chain.  */
7231
7232 static void
7233 add_to_breakpoint_chain (struct breakpoint *b)
7234 {
7235   struct breakpoint *b1;
7236
7237   /* Add this breakpoint to the end of the chain so that a list of
7238      breakpoints will come out in order of increasing numbers.  */
7239
7240   b1 = breakpoint_chain;
7241   if (b1 == 0)
7242     breakpoint_chain = b;
7243   else
7244     {
7245       while (b1->next)
7246         b1 = b1->next;
7247       b1->next = b;
7248     }
7249 }
7250
7251 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7252
7253 static void
7254 init_raw_breakpoint_without_location (struct breakpoint *b,
7255                                       struct gdbarch *gdbarch,
7256                                       enum bptype bptype,
7257                                       const struct breakpoint_ops *ops)
7258 {
7259   memset (b, 0, sizeof (*b));
7260
7261   gdb_assert (ops != NULL);
7262
7263   b->ops = ops;
7264   b->type = bptype;
7265   b->gdbarch = gdbarch;
7266   b->language = current_language->la_language;
7267   b->input_radix = input_radix;
7268   b->thread = -1;
7269   b->enable_state = bp_enabled;
7270   b->next = 0;
7271   b->silent = 0;
7272   b->ignore_count = 0;
7273   b->commands = NULL;
7274   b->frame_id = null_frame_id;
7275   b->condition_not_parsed = 0;
7276   b->py_bp_object = NULL;
7277   b->related_breakpoint = b;
7278 }
7279
7280 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7281    that has type BPTYPE and has no locations as yet.  */
7282
7283 static struct breakpoint *
7284 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7285                                      enum bptype bptype,
7286                                      const struct breakpoint_ops *ops)
7287 {
7288   struct breakpoint *b = XNEW (struct breakpoint);
7289
7290   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7291   add_to_breakpoint_chain (b);
7292   return b;
7293 }
7294
7295 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7296    resolutions should be made as the user specified the location explicitly
7297    enough.  */
7298
7299 static void
7300 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7301 {
7302   gdb_assert (loc->owner != NULL);
7303
7304   if (loc->owner->type == bp_breakpoint
7305       || loc->owner->type == bp_hardware_breakpoint
7306       || is_tracepoint (loc->owner))
7307     {
7308       int is_gnu_ifunc;
7309       const char *function_name;
7310       CORE_ADDR func_addr;
7311
7312       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7313                                           &func_addr, NULL, &is_gnu_ifunc);
7314
7315       if (is_gnu_ifunc && !explicit_loc)
7316         {
7317           struct breakpoint *b = loc->owner;
7318
7319           gdb_assert (loc->pspace == current_program_space);
7320           if (gnu_ifunc_resolve_name (function_name,
7321                                       &loc->requested_address))
7322             {
7323               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7324               loc->address = adjust_breakpoint_address (loc->gdbarch,
7325                                                         loc->requested_address,
7326                                                         b->type);
7327             }
7328           else if (b->type == bp_breakpoint && b->loc == loc
7329                    && loc->next == NULL && b->related_breakpoint == b)
7330             {
7331               /* Create only the whole new breakpoint of this type but do not
7332                  mess more complicated breakpoints with multiple locations.  */
7333               b->type = bp_gnu_ifunc_resolver;
7334               /* Remember the resolver's address for use by the return
7335                  breakpoint.  */
7336               loc->related_address = func_addr;
7337             }
7338         }
7339
7340       if (function_name)
7341         loc->function_name = xstrdup (function_name);
7342     }
7343 }
7344
7345 /* Attempt to determine architecture of location identified by SAL.  */
7346 struct gdbarch *
7347 get_sal_arch (struct symtab_and_line sal)
7348 {
7349   if (sal.section)
7350     return get_objfile_arch (sal.section->objfile);
7351   if (sal.symtab)
7352     return get_objfile_arch (sal.symtab->objfile);
7353
7354   return NULL;
7355 }
7356
7357 /* Low level routine for partially initializing a breakpoint of type
7358    BPTYPE.  The newly created breakpoint's address, section, source
7359    file name, and line number are provided by SAL.
7360
7361    It is expected that the caller will complete the initialization of
7362    the newly created breakpoint struct as well as output any status
7363    information regarding the creation of a new breakpoint.  */
7364
7365 static void
7366 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7367                      struct symtab_and_line sal, enum bptype bptype,
7368                      const struct breakpoint_ops *ops)
7369 {
7370   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7371
7372   add_location_to_breakpoint (b, &sal);
7373
7374   if (bptype != bp_catchpoint)
7375     gdb_assert (sal.pspace != NULL);
7376
7377   /* Store the program space that was used to set the breakpoint,
7378      except for ordinary breakpoints, which are independent of the
7379      program space.  */
7380   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7381     b->pspace = sal.pspace;
7382 }
7383
7384 /* set_raw_breakpoint is a low level routine for allocating and
7385    partially initializing a breakpoint of type BPTYPE.  The newly
7386    created breakpoint's address, section, source file name, and line
7387    number are provided by SAL.  The newly created and partially
7388    initialized breakpoint is added to the breakpoint chain and
7389    is also returned as the value of this function.
7390
7391    It is expected that the caller will complete the initialization of
7392    the newly created breakpoint struct as well as output any status
7393    information regarding the creation of a new breakpoint.  In
7394    particular, set_raw_breakpoint does NOT set the breakpoint
7395    number!  Care should be taken to not allow an error to occur
7396    prior to completing the initialization of the breakpoint.  If this
7397    should happen, a bogus breakpoint will be left on the chain.  */
7398
7399 struct breakpoint *
7400 set_raw_breakpoint (struct gdbarch *gdbarch,
7401                     struct symtab_and_line sal, enum bptype bptype,
7402                     const struct breakpoint_ops *ops)
7403 {
7404   struct breakpoint *b = XNEW (struct breakpoint);
7405
7406   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7407   add_to_breakpoint_chain (b);
7408   return b;
7409 }
7410
7411
7412 /* Note that the breakpoint object B describes a permanent breakpoint
7413    instruction, hard-wired into the inferior's code.  */
7414 void
7415 make_breakpoint_permanent (struct breakpoint *b)
7416 {
7417   struct bp_location *bl;
7418
7419   b->enable_state = bp_permanent;
7420
7421   /* By definition, permanent breakpoints are already present in the
7422      code.  Mark all locations as inserted.  For now,
7423      make_breakpoint_permanent is called in just one place, so it's
7424      hard to say if it's reasonable to have permanent breakpoint with
7425      multiple locations or not, but it's easy to implement.  */
7426   for (bl = b->loc; bl; bl = bl->next)
7427     bl->inserted = 1;
7428 }
7429
7430 /* Call this routine when stepping and nexting to enable a breakpoint
7431    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7432    initiated the operation.  */
7433
7434 void
7435 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7436 {
7437   struct breakpoint *b, *b_tmp;
7438   int thread = tp->num;
7439
7440   /* To avoid having to rescan all objfile symbols at every step,
7441      we maintain a list of continually-inserted but always disabled
7442      longjmp "master" breakpoints.  Here, we simply create momentary
7443      clones of those and enable them for the requested thread.  */
7444   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7445     if (b->pspace == current_program_space
7446         && (b->type == bp_longjmp_master
7447             || b->type == bp_exception_master))
7448       {
7449         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7450         struct breakpoint *clone;
7451
7452         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7453            after their removal.  */
7454         clone = momentary_breakpoint_from_master (b, type,
7455                                                   &longjmp_breakpoint_ops, 1);
7456         clone->thread = thread;
7457       }
7458
7459   tp->initiating_frame = frame;
7460 }
7461
7462 /* Delete all longjmp breakpoints from THREAD.  */
7463 void
7464 delete_longjmp_breakpoint (int thread)
7465 {
7466   struct breakpoint *b, *b_tmp;
7467
7468   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7469     if (b->type == bp_longjmp || b->type == bp_exception)
7470       {
7471         if (b->thread == thread)
7472           delete_breakpoint (b);
7473       }
7474 }
7475
7476 void
7477 delete_longjmp_breakpoint_at_next_stop (int thread)
7478 {
7479   struct breakpoint *b, *b_tmp;
7480
7481   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7482     if (b->type == bp_longjmp || b->type == bp_exception)
7483       {
7484         if (b->thread == thread)
7485           b->disposition = disp_del_at_next_stop;
7486       }
7487 }
7488
7489 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7490    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7491    pointer to any of them.  Return NULL if this system cannot place longjmp
7492    breakpoints.  */
7493
7494 struct breakpoint *
7495 set_longjmp_breakpoint_for_call_dummy (void)
7496 {
7497   struct breakpoint *b, *retval = NULL;
7498
7499   ALL_BREAKPOINTS (b)
7500     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7501       {
7502         struct breakpoint *new_b;
7503
7504         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7505                                                   &momentary_breakpoint_ops,
7506                                                   1);
7507         new_b->thread = pid_to_thread_id (inferior_ptid);
7508
7509         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7510
7511         gdb_assert (new_b->related_breakpoint == new_b);
7512         if (retval == NULL)
7513           retval = new_b;
7514         new_b->related_breakpoint = retval;
7515         while (retval->related_breakpoint != new_b->related_breakpoint)
7516           retval = retval->related_breakpoint;
7517         retval->related_breakpoint = new_b;
7518       }
7519
7520   return retval;
7521 }
7522
7523 /* Verify all existing dummy frames and their associated breakpoints for
7524    TP.  Remove those which can no longer be found in the current frame
7525    stack.
7526
7527    You should call this function only at places where it is safe to currently
7528    unwind the whole stack.  Failed stack unwind would discard live dummy
7529    frames.  */
7530
7531 void
7532 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7533 {
7534   struct breakpoint *b, *b_tmp;
7535
7536   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7537     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7538       {
7539         struct breakpoint *dummy_b = b->related_breakpoint;
7540
7541         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7542           dummy_b = dummy_b->related_breakpoint;
7543         if (dummy_b->type != bp_call_dummy
7544             || frame_find_by_id (dummy_b->frame_id) != NULL)
7545           continue;
7546         
7547         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7548
7549         while (b->related_breakpoint != b)
7550           {
7551             if (b_tmp == b->related_breakpoint)
7552               b_tmp = b->related_breakpoint->next;
7553             delete_breakpoint (b->related_breakpoint);
7554           }
7555         delete_breakpoint (b);
7556       }
7557 }
7558
7559 void
7560 enable_overlay_breakpoints (void)
7561 {
7562   struct breakpoint *b;
7563
7564   ALL_BREAKPOINTS (b)
7565     if (b->type == bp_overlay_event)
7566     {
7567       b->enable_state = bp_enabled;
7568       update_global_location_list (1);
7569       overlay_events_enabled = 1;
7570     }
7571 }
7572
7573 void
7574 disable_overlay_breakpoints (void)
7575 {
7576   struct breakpoint *b;
7577
7578   ALL_BREAKPOINTS (b)
7579     if (b->type == bp_overlay_event)
7580     {
7581       b->enable_state = bp_disabled;
7582       update_global_location_list (0);
7583       overlay_events_enabled = 0;
7584     }
7585 }
7586
7587 /* Set an active std::terminate breakpoint for each std::terminate
7588    master breakpoint.  */
7589 void
7590 set_std_terminate_breakpoint (void)
7591 {
7592   struct breakpoint *b, *b_tmp;
7593
7594   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7595     if (b->pspace == current_program_space
7596         && b->type == bp_std_terminate_master)
7597       {
7598         momentary_breakpoint_from_master (b, bp_std_terminate,
7599                                           &momentary_breakpoint_ops, 1);
7600       }
7601 }
7602
7603 /* Delete all the std::terminate breakpoints.  */
7604 void
7605 delete_std_terminate_breakpoint (void)
7606 {
7607   struct breakpoint *b, *b_tmp;
7608
7609   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7610     if (b->type == bp_std_terminate)
7611       delete_breakpoint (b);
7612 }
7613
7614 struct breakpoint *
7615 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7616 {
7617   struct breakpoint *b;
7618
7619   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7620                                   &internal_breakpoint_ops);
7621
7622   b->enable_state = bp_enabled;
7623   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7624   b->addr_string
7625     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7626
7627   update_global_location_list_nothrow (1);
7628
7629   return b;
7630 }
7631
7632 void
7633 remove_thread_event_breakpoints (void)
7634 {
7635   struct breakpoint *b, *b_tmp;
7636
7637   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7638     if (b->type == bp_thread_event
7639         && b->loc->pspace == current_program_space)
7640       delete_breakpoint (b);
7641 }
7642
7643 struct lang_and_radix
7644   {
7645     enum language lang;
7646     int radix;
7647   };
7648
7649 /* Create a breakpoint for JIT code registration and unregistration.  */
7650
7651 struct breakpoint *
7652 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7653 {
7654   struct breakpoint *b;
7655
7656   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7657                                   &internal_breakpoint_ops);
7658   update_global_location_list_nothrow (1);
7659   return b;
7660 }
7661
7662 /* Remove JIT code registration and unregistration breakpoint(s).  */
7663
7664 void
7665 remove_jit_event_breakpoints (void)
7666 {
7667   struct breakpoint *b, *b_tmp;
7668
7669   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7670     if (b->type == bp_jit_event
7671         && b->loc->pspace == current_program_space)
7672       delete_breakpoint (b);
7673 }
7674
7675 void
7676 remove_solib_event_breakpoints (void)
7677 {
7678   struct breakpoint *b, *b_tmp;
7679
7680   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7681     if (b->type == bp_shlib_event
7682         && b->loc->pspace == current_program_space)
7683       delete_breakpoint (b);
7684 }
7685
7686 /* See breakpoint.h.  */
7687
7688 void
7689 remove_solib_event_breakpoints_at_next_stop (void)
7690 {
7691   struct breakpoint *b, *b_tmp;
7692
7693   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7694     if (b->type == bp_shlib_event
7695         && b->loc->pspace == current_program_space)
7696       b->disposition = disp_del_at_next_stop;
7697 }
7698
7699 struct breakpoint *
7700 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7701 {
7702   struct breakpoint *b;
7703
7704   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7705                                   &internal_breakpoint_ops);
7706   update_global_location_list_nothrow (1);
7707   return b;
7708 }
7709
7710 /* See breakpoint.h.  */
7711
7712 struct breakpoint *
7713 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7714 {
7715   struct breakpoint *b;
7716
7717   b = create_solib_event_breakpoint (gdbarch, address);
7718   if (!breakpoints_always_inserted_mode ())
7719     insert_breakpoint_locations ();
7720   if (!b->loc->inserted)
7721     {
7722       delete_breakpoint (b);
7723       return NULL;
7724     }
7725   return b;
7726 }
7727
7728 /* Disable any breakpoints that are on code in shared libraries.  Only
7729    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7730
7731 void
7732 disable_breakpoints_in_shlibs (void)
7733 {
7734   struct bp_location *loc, **locp_tmp;
7735
7736   ALL_BP_LOCATIONS (loc, locp_tmp)
7737   {
7738     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7739     struct breakpoint *b = loc->owner;
7740
7741     /* We apply the check to all breakpoints, including disabled for
7742        those with loc->duplicate set.  This is so that when breakpoint
7743        becomes enabled, or the duplicate is removed, gdb will try to
7744        insert all breakpoints.  If we don't set shlib_disabled here,
7745        we'll try to insert those breakpoints and fail.  */
7746     if (((b->type == bp_breakpoint)
7747          || (b->type == bp_jit_event)
7748          || (b->type == bp_hardware_breakpoint)
7749          || (is_tracepoint (b)))
7750         && loc->pspace == current_program_space
7751         && !loc->shlib_disabled
7752         && solib_name_from_address (loc->pspace, loc->address)
7753         )
7754       {
7755         loc->shlib_disabled = 1;
7756       }
7757   }
7758 }
7759
7760 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7761    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7762    disabled ones can just stay disabled.  */
7763
7764 static void
7765 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7766 {
7767   struct bp_location *loc, **locp_tmp;
7768   int disabled_shlib_breaks = 0;
7769
7770   /* SunOS a.out shared libraries are always mapped, so do not
7771      disable breakpoints; they will only be reported as unloaded
7772      through clear_solib when GDB discards its shared library
7773      list.  See clear_solib for more information.  */
7774   if (exec_bfd != NULL
7775       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7776     return;
7777
7778   ALL_BP_LOCATIONS (loc, locp_tmp)
7779   {
7780     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7781     struct breakpoint *b = loc->owner;
7782
7783     if (solib->pspace == loc->pspace
7784         && !loc->shlib_disabled
7785         && (((b->type == bp_breakpoint
7786               || b->type == bp_jit_event
7787               || b->type == bp_hardware_breakpoint)
7788              && (loc->loc_type == bp_loc_hardware_breakpoint
7789                  || loc->loc_type == bp_loc_software_breakpoint))
7790             || is_tracepoint (b))
7791         && solib_contains_address_p (solib, loc->address))
7792       {
7793         loc->shlib_disabled = 1;
7794         /* At this point, we cannot rely on remove_breakpoint
7795            succeeding so we must mark the breakpoint as not inserted
7796            to prevent future errors occurring in remove_breakpoints.  */
7797         loc->inserted = 0;
7798
7799         /* This may cause duplicate notifications for the same breakpoint.  */
7800         observer_notify_breakpoint_modified (b);
7801
7802         if (!disabled_shlib_breaks)
7803           {
7804             target_terminal_ours_for_output ();
7805             warning (_("Temporarily disabling breakpoints "
7806                        "for unloaded shared library \"%s\""),
7807                      solib->so_name);
7808           }
7809         disabled_shlib_breaks = 1;
7810       }
7811   }
7812 }
7813
7814 /* Disable any breakpoints and tracepoints in OBJFILE upon
7815    notification of free_objfile.  Only apply to enabled breakpoints,
7816    disabled ones can just stay disabled.  */
7817
7818 static void
7819 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7820 {
7821   struct breakpoint *b;
7822
7823   if (objfile == NULL)
7824     return;
7825
7826   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7827      managed by the user with add-symbol-file/remove-symbol-file.
7828      Similarly to how breakpoints in shared libraries are handled in
7829      response to "nosharedlibrary", mark breakpoints in such modules
7830      shlib_disabled so they end up uninserted on the next global
7831      location list update.  Shared libraries not loaded by the user
7832      aren't handled here -- they're already handled in
7833      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7834      solib_unloaded observer.  We skip objfiles that are not
7835      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7836      main objfile).  */
7837   if ((objfile->flags & OBJF_SHARED) == 0
7838       || (objfile->flags & OBJF_USERLOADED) == 0)
7839     return;
7840
7841   ALL_BREAKPOINTS (b)
7842     {
7843       struct bp_location *loc;
7844       int bp_modified = 0;
7845
7846       if (!is_breakpoint (b) && !is_tracepoint (b))
7847         continue;
7848
7849       for (loc = b->loc; loc != NULL; loc = loc->next)
7850         {
7851           CORE_ADDR loc_addr = loc->address;
7852
7853           if (loc->loc_type != bp_loc_hardware_breakpoint
7854               && loc->loc_type != bp_loc_software_breakpoint)
7855             continue;
7856
7857           if (loc->shlib_disabled != 0)
7858             continue;
7859
7860           if (objfile->pspace != loc->pspace)
7861             continue;
7862
7863           if (loc->loc_type != bp_loc_hardware_breakpoint
7864               && loc->loc_type != bp_loc_software_breakpoint)
7865             continue;
7866
7867           if (is_addr_in_objfile (loc_addr, objfile))
7868             {
7869               loc->shlib_disabled = 1;
7870               /* At this point, we don't know whether the object was
7871                  unmapped from the inferior or not, so leave the
7872                  inserted flag alone.  We'll handle failure to
7873                  uninsert quietly, in case the object was indeed
7874                  unmapped.  */
7875
7876               mark_breakpoint_location_modified (loc);
7877
7878               bp_modified = 1;
7879             }
7880         }
7881
7882       if (bp_modified)
7883         observer_notify_breakpoint_modified (b);
7884     }
7885 }
7886
7887 /* FORK & VFORK catchpoints.  */
7888
7889 /* An instance of this type is used to represent a fork or vfork
7890    catchpoint.  It includes a "struct breakpoint" as a kind of base
7891    class; users downcast to "struct breakpoint *" when needed.  A
7892    breakpoint is really of this type iff its ops pointer points to
7893    CATCH_FORK_BREAKPOINT_OPS.  */
7894
7895 struct fork_catchpoint
7896 {
7897   /* The base class.  */
7898   struct breakpoint base;
7899
7900   /* Process id of a child process whose forking triggered this
7901      catchpoint.  This field is only valid immediately after this
7902      catchpoint has triggered.  */
7903   ptid_t forked_inferior_pid;
7904 };
7905
7906 /* Implement the "insert" breakpoint_ops method for fork
7907    catchpoints.  */
7908
7909 static int
7910 insert_catch_fork (struct bp_location *bl)
7911 {
7912   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7913 }
7914
7915 /* Implement the "remove" breakpoint_ops method for fork
7916    catchpoints.  */
7917
7918 static int
7919 remove_catch_fork (struct bp_location *bl)
7920 {
7921   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7922 }
7923
7924 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7925    catchpoints.  */
7926
7927 static int
7928 breakpoint_hit_catch_fork (const struct bp_location *bl,
7929                            struct address_space *aspace, CORE_ADDR bp_addr,
7930                            const struct target_waitstatus *ws)
7931 {
7932   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7933
7934   if (ws->kind != TARGET_WAITKIND_FORKED)
7935     return 0;
7936
7937   c->forked_inferior_pid = ws->value.related_pid;
7938   return 1;
7939 }
7940
7941 /* Implement the "print_it" breakpoint_ops method for fork
7942    catchpoints.  */
7943
7944 static enum print_stop_action
7945 print_it_catch_fork (bpstat bs)
7946 {
7947   struct ui_out *uiout = current_uiout;
7948   struct breakpoint *b = bs->breakpoint_at;
7949   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7950
7951   annotate_catchpoint (b->number);
7952   if (b->disposition == disp_del)
7953     ui_out_text (uiout, "\nTemporary catchpoint ");
7954   else
7955     ui_out_text (uiout, "\nCatchpoint ");
7956   if (ui_out_is_mi_like_p (uiout))
7957     {
7958       ui_out_field_string (uiout, "reason",
7959                            async_reason_lookup (EXEC_ASYNC_FORK));
7960       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7961     }
7962   ui_out_field_int (uiout, "bkptno", b->number);
7963   ui_out_text (uiout, " (forked process ");
7964   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7965   ui_out_text (uiout, "), ");
7966   return PRINT_SRC_AND_LOC;
7967 }
7968
7969 /* Implement the "print_one" breakpoint_ops method for fork
7970    catchpoints.  */
7971
7972 static void
7973 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7974 {
7975   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7976   struct value_print_options opts;
7977   struct ui_out *uiout = current_uiout;
7978
7979   get_user_print_options (&opts);
7980
7981   /* Field 4, the address, is omitted (which makes the columns not
7982      line up too nicely with the headers, but the effect is relatively
7983      readable).  */
7984   if (opts.addressprint)
7985     ui_out_field_skip (uiout, "addr");
7986   annotate_field (5);
7987   ui_out_text (uiout, "fork");
7988   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7989     {
7990       ui_out_text (uiout, ", process ");
7991       ui_out_field_int (uiout, "what",
7992                         ptid_get_pid (c->forked_inferior_pid));
7993       ui_out_spaces (uiout, 1);
7994     }
7995
7996   if (ui_out_is_mi_like_p (uiout))
7997     ui_out_field_string (uiout, "catch-type", "fork");
7998 }
7999
8000 /* Implement the "print_mention" breakpoint_ops method for fork
8001    catchpoints.  */
8002
8003 static void
8004 print_mention_catch_fork (struct breakpoint *b)
8005 {
8006   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8007 }
8008
8009 /* Implement the "print_recreate" breakpoint_ops method for fork
8010    catchpoints.  */
8011
8012 static void
8013 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8014 {
8015   fprintf_unfiltered (fp, "catch fork");
8016   print_recreate_thread (b, fp);
8017 }
8018
8019 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8020
8021 static struct breakpoint_ops catch_fork_breakpoint_ops;
8022
8023 /* Implement the "insert" breakpoint_ops method for vfork
8024    catchpoints.  */
8025
8026 static int
8027 insert_catch_vfork (struct bp_location *bl)
8028 {
8029   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8030 }
8031
8032 /* Implement the "remove" breakpoint_ops method for vfork
8033    catchpoints.  */
8034
8035 static int
8036 remove_catch_vfork (struct bp_location *bl)
8037 {
8038   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8039 }
8040
8041 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8042    catchpoints.  */
8043
8044 static int
8045 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8046                             struct address_space *aspace, CORE_ADDR bp_addr,
8047                             const struct target_waitstatus *ws)
8048 {
8049   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8050
8051   if (ws->kind != TARGET_WAITKIND_VFORKED)
8052     return 0;
8053
8054   c->forked_inferior_pid = ws->value.related_pid;
8055   return 1;
8056 }
8057
8058 /* Implement the "print_it" breakpoint_ops method for vfork
8059    catchpoints.  */
8060
8061 static enum print_stop_action
8062 print_it_catch_vfork (bpstat bs)
8063 {
8064   struct ui_out *uiout = current_uiout;
8065   struct breakpoint *b = bs->breakpoint_at;
8066   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8067
8068   annotate_catchpoint (b->number);
8069   if (b->disposition == disp_del)
8070     ui_out_text (uiout, "\nTemporary catchpoint ");
8071   else
8072     ui_out_text (uiout, "\nCatchpoint ");
8073   if (ui_out_is_mi_like_p (uiout))
8074     {
8075       ui_out_field_string (uiout, "reason",
8076                            async_reason_lookup (EXEC_ASYNC_VFORK));
8077       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8078     }
8079   ui_out_field_int (uiout, "bkptno", b->number);
8080   ui_out_text (uiout, " (vforked process ");
8081   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8082   ui_out_text (uiout, "), ");
8083   return PRINT_SRC_AND_LOC;
8084 }
8085
8086 /* Implement the "print_one" breakpoint_ops method for vfork
8087    catchpoints.  */
8088
8089 static void
8090 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8091 {
8092   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8093   struct value_print_options opts;
8094   struct ui_out *uiout = current_uiout;
8095
8096   get_user_print_options (&opts);
8097   /* Field 4, the address, is omitted (which makes the columns not
8098      line up too nicely with the headers, but the effect is relatively
8099      readable).  */
8100   if (opts.addressprint)
8101     ui_out_field_skip (uiout, "addr");
8102   annotate_field (5);
8103   ui_out_text (uiout, "vfork");
8104   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8105     {
8106       ui_out_text (uiout, ", process ");
8107       ui_out_field_int (uiout, "what",
8108                         ptid_get_pid (c->forked_inferior_pid));
8109       ui_out_spaces (uiout, 1);
8110     }
8111
8112   if (ui_out_is_mi_like_p (uiout))
8113     ui_out_field_string (uiout, "catch-type", "vfork");
8114 }
8115
8116 /* Implement the "print_mention" breakpoint_ops method for vfork
8117    catchpoints.  */
8118
8119 static void
8120 print_mention_catch_vfork (struct breakpoint *b)
8121 {
8122   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8123 }
8124
8125 /* Implement the "print_recreate" breakpoint_ops method for vfork
8126    catchpoints.  */
8127
8128 static void
8129 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8130 {
8131   fprintf_unfiltered (fp, "catch vfork");
8132   print_recreate_thread (b, fp);
8133 }
8134
8135 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8136
8137 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8138
8139 /* An instance of this type is used to represent an solib catchpoint.
8140    It includes a "struct breakpoint" as a kind of base class; users
8141    downcast to "struct breakpoint *" when needed.  A breakpoint is
8142    really of this type iff its ops pointer points to
8143    CATCH_SOLIB_BREAKPOINT_OPS.  */
8144
8145 struct solib_catchpoint
8146 {
8147   /* The base class.  */
8148   struct breakpoint base;
8149
8150   /* True for "catch load", false for "catch unload".  */
8151   unsigned char is_load;
8152
8153   /* Regular expression to match, if any.  COMPILED is only valid when
8154      REGEX is non-NULL.  */
8155   char *regex;
8156   regex_t compiled;
8157 };
8158
8159 static void
8160 dtor_catch_solib (struct breakpoint *b)
8161 {
8162   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8163
8164   if (self->regex)
8165     regfree (&self->compiled);
8166   xfree (self->regex);
8167
8168   base_breakpoint_ops.dtor (b);
8169 }
8170
8171 static int
8172 insert_catch_solib (struct bp_location *ignore)
8173 {
8174   return 0;
8175 }
8176
8177 static int
8178 remove_catch_solib (struct bp_location *ignore)
8179 {
8180   return 0;
8181 }
8182
8183 static int
8184 breakpoint_hit_catch_solib (const struct bp_location *bl,
8185                             struct address_space *aspace,
8186                             CORE_ADDR bp_addr,
8187                             const struct target_waitstatus *ws)
8188 {
8189   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8190   struct breakpoint *other;
8191
8192   if (ws->kind == TARGET_WAITKIND_LOADED)
8193     return 1;
8194
8195   ALL_BREAKPOINTS (other)
8196   {
8197     struct bp_location *other_bl;
8198
8199     if (other == bl->owner)
8200       continue;
8201
8202     if (other->type != bp_shlib_event)
8203       continue;
8204
8205     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8206       continue;
8207
8208     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8209       {
8210         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8211           return 1;
8212       }
8213   }
8214
8215   return 0;
8216 }
8217
8218 static void
8219 check_status_catch_solib (struct bpstats *bs)
8220 {
8221   struct solib_catchpoint *self
8222     = (struct solib_catchpoint *) bs->breakpoint_at;
8223   int ix;
8224
8225   if (self->is_load)
8226     {
8227       struct so_list *iter;
8228
8229       for (ix = 0;
8230            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8231                         ix, iter);
8232            ++ix)
8233         {
8234           if (!self->regex
8235               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8236             return;
8237         }
8238     }
8239   else
8240     {
8241       char *iter;
8242
8243       for (ix = 0;
8244            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8245                         ix, iter);
8246            ++ix)
8247         {
8248           if (!self->regex
8249               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8250             return;
8251         }
8252     }
8253
8254   bs->stop = 0;
8255   bs->print_it = print_it_noop;
8256 }
8257
8258 static enum print_stop_action
8259 print_it_catch_solib (bpstat bs)
8260 {
8261   struct breakpoint *b = bs->breakpoint_at;
8262   struct ui_out *uiout = current_uiout;
8263
8264   annotate_catchpoint (b->number);
8265   if (b->disposition == disp_del)
8266     ui_out_text (uiout, "\nTemporary catchpoint ");
8267   else
8268     ui_out_text (uiout, "\nCatchpoint ");
8269   ui_out_field_int (uiout, "bkptno", b->number);
8270   ui_out_text (uiout, "\n");
8271   if (ui_out_is_mi_like_p (uiout))
8272     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8273   print_solib_event (1);
8274   return PRINT_SRC_AND_LOC;
8275 }
8276
8277 static void
8278 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8279 {
8280   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8281   struct value_print_options opts;
8282   struct ui_out *uiout = current_uiout;
8283   char *msg;
8284
8285   get_user_print_options (&opts);
8286   /* Field 4, the address, is omitted (which makes the columns not
8287      line up too nicely with the headers, but the effect is relatively
8288      readable).  */
8289   if (opts.addressprint)
8290     {
8291       annotate_field (4);
8292       ui_out_field_skip (uiout, "addr");
8293     }
8294
8295   annotate_field (5);
8296   if (self->is_load)
8297     {
8298       if (self->regex)
8299         msg = xstrprintf (_("load of library matching %s"), self->regex);
8300       else
8301         msg = xstrdup (_("load of library"));
8302     }
8303   else
8304     {
8305       if (self->regex)
8306         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8307       else
8308         msg = xstrdup (_("unload of library"));
8309     }
8310   ui_out_field_string (uiout, "what", msg);
8311   xfree (msg);
8312
8313   if (ui_out_is_mi_like_p (uiout))
8314     ui_out_field_string (uiout, "catch-type",
8315                          self->is_load ? "load" : "unload");
8316 }
8317
8318 static void
8319 print_mention_catch_solib (struct breakpoint *b)
8320 {
8321   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8322
8323   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8324                    self->is_load ? "load" : "unload");
8325 }
8326
8327 static void
8328 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8329 {
8330   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8331
8332   fprintf_unfiltered (fp, "%s %s",
8333                       b->disposition == disp_del ? "tcatch" : "catch",
8334                       self->is_load ? "load" : "unload");
8335   if (self->regex)
8336     fprintf_unfiltered (fp, " %s", self->regex);
8337   fprintf_unfiltered (fp, "\n");
8338 }
8339
8340 static struct breakpoint_ops catch_solib_breakpoint_ops;
8341
8342 /* Shared helper function (MI and CLI) for creating and installing
8343    a shared object event catchpoint.  If IS_LOAD is non-zero then
8344    the events to be caught are load events, otherwise they are
8345    unload events.  If IS_TEMP is non-zero the catchpoint is a
8346    temporary one.  If ENABLED is non-zero the catchpoint is
8347    created in an enabled state.  */
8348
8349 void
8350 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8351 {
8352   struct solib_catchpoint *c;
8353   struct gdbarch *gdbarch = get_current_arch ();
8354   struct cleanup *cleanup;
8355
8356   if (!arg)
8357     arg = "";
8358   arg = skip_spaces (arg);
8359
8360   c = XCNEW (struct solib_catchpoint);
8361   cleanup = make_cleanup (xfree, c);
8362
8363   if (*arg != '\0')
8364     {
8365       int errcode;
8366
8367       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8368       if (errcode != 0)
8369         {
8370           char *err = get_regcomp_error (errcode, &c->compiled);
8371
8372           make_cleanup (xfree, err);
8373           error (_("Invalid regexp (%s): %s"), err, arg);
8374         }
8375       c->regex = xstrdup (arg);
8376     }
8377
8378   c->is_load = is_load;
8379   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8380                    &catch_solib_breakpoint_ops);
8381
8382   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8383
8384   discard_cleanups (cleanup);
8385   install_breakpoint (0, &c->base, 1);
8386 }
8387
8388 /* A helper function that does all the work for "catch load" and
8389    "catch unload".  */
8390
8391 static void
8392 catch_load_or_unload (char *arg, int from_tty, int is_load,
8393                       struct cmd_list_element *command)
8394 {
8395   int tempflag;
8396   const int enabled = 1;
8397
8398   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8399
8400   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8401 }
8402
8403 static void
8404 catch_load_command_1 (char *arg, int from_tty,
8405                       struct cmd_list_element *command)
8406 {
8407   catch_load_or_unload (arg, from_tty, 1, command);
8408 }
8409
8410 static void
8411 catch_unload_command_1 (char *arg, int from_tty,
8412                         struct cmd_list_element *command)
8413 {
8414   catch_load_or_unload (arg, from_tty, 0, command);
8415 }
8416
8417 /* An instance of this type is used to represent a syscall catchpoint.
8418    It includes a "struct breakpoint" as a kind of base class; users
8419    downcast to "struct breakpoint *" when needed.  A breakpoint is
8420    really of this type iff its ops pointer points to
8421    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8422
8423 struct syscall_catchpoint
8424 {
8425   /* The base class.  */
8426   struct breakpoint base;
8427
8428   /* Syscall numbers used for the 'catch syscall' feature.  If no
8429      syscall has been specified for filtering, its value is NULL.
8430      Otherwise, it holds a list of all syscalls to be caught.  The
8431      list elements are allocated with xmalloc.  */
8432   VEC(int) *syscalls_to_be_caught;
8433 };
8434
8435 /* Implement the "dtor" breakpoint_ops method for syscall
8436    catchpoints.  */
8437
8438 static void
8439 dtor_catch_syscall (struct breakpoint *b)
8440 {
8441   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8442
8443   VEC_free (int, c->syscalls_to_be_caught);
8444
8445   base_breakpoint_ops.dtor (b);
8446 }
8447
8448 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8449
8450 struct catch_syscall_inferior_data
8451 {
8452   /* We keep a count of the number of times the user has requested a
8453      particular syscall to be tracked, and pass this information to the
8454      target.  This lets capable targets implement filtering directly.  */
8455
8456   /* Number of times that "any" syscall is requested.  */
8457   int any_syscall_count;
8458
8459   /* Count of each system call.  */
8460   VEC(int) *syscalls_counts;
8461
8462   /* This counts all syscall catch requests, so we can readily determine
8463      if any catching is necessary.  */
8464   int total_syscalls_count;
8465 };
8466
8467 static struct catch_syscall_inferior_data*
8468 get_catch_syscall_inferior_data (struct inferior *inf)
8469 {
8470   struct catch_syscall_inferior_data *inf_data;
8471
8472   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8473   if (inf_data == NULL)
8474     {
8475       inf_data = XCNEW (struct catch_syscall_inferior_data);
8476       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8477     }
8478
8479   return inf_data;
8480 }
8481
8482 static void
8483 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8484 {
8485   xfree (arg);
8486 }
8487
8488
8489 /* Implement the "insert" breakpoint_ops method for syscall
8490    catchpoints.  */
8491
8492 static int
8493 insert_catch_syscall (struct bp_location *bl)
8494 {
8495   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8496   struct inferior *inf = current_inferior ();
8497   struct catch_syscall_inferior_data *inf_data
8498     = get_catch_syscall_inferior_data (inf);
8499
8500   ++inf_data->total_syscalls_count;
8501   if (!c->syscalls_to_be_caught)
8502     ++inf_data->any_syscall_count;
8503   else
8504     {
8505       int i, iter;
8506
8507       for (i = 0;
8508            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8509            i++)
8510         {
8511           int elem;
8512
8513           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8514             {
8515               int old_size = VEC_length (int, inf_data->syscalls_counts);
8516               uintptr_t vec_addr_offset
8517                 = old_size * ((uintptr_t) sizeof (int));
8518               uintptr_t vec_addr;
8519               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8520               vec_addr = ((uintptr_t) VEC_address (int,
8521                                                   inf_data->syscalls_counts)
8522                           + vec_addr_offset);
8523               memset ((void *) vec_addr, 0,
8524                       (iter + 1 - old_size) * sizeof (int));
8525             }
8526           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8527           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8528         }
8529     }
8530
8531   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8532                                         inf_data->total_syscalls_count != 0,
8533                                         inf_data->any_syscall_count,
8534                                         VEC_length (int,
8535                                                     inf_data->syscalls_counts),
8536                                         VEC_address (int,
8537                                                      inf_data->syscalls_counts));
8538 }
8539
8540 /* Implement the "remove" breakpoint_ops method for syscall
8541    catchpoints.  */
8542
8543 static int
8544 remove_catch_syscall (struct bp_location *bl)
8545 {
8546   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8547   struct inferior *inf = current_inferior ();
8548   struct catch_syscall_inferior_data *inf_data
8549     = get_catch_syscall_inferior_data (inf);
8550
8551   --inf_data->total_syscalls_count;
8552   if (!c->syscalls_to_be_caught)
8553     --inf_data->any_syscall_count;
8554   else
8555     {
8556       int i, iter;
8557
8558       for (i = 0;
8559            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8560            i++)
8561         {
8562           int elem;
8563           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8564             /* Shouldn't happen.  */
8565             continue;
8566           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8567           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8568         }
8569     }
8570
8571   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8572                                         inf_data->total_syscalls_count != 0,
8573                                         inf_data->any_syscall_count,
8574                                         VEC_length (int,
8575                                                     inf_data->syscalls_counts),
8576                                         VEC_address (int,
8577                                                      inf_data->syscalls_counts));
8578 }
8579
8580 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8581    catchpoints.  */
8582
8583 static int
8584 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8585                               struct address_space *aspace, CORE_ADDR bp_addr,
8586                               const struct target_waitstatus *ws)
8587 {
8588   /* We must check if we are catching specific syscalls in this
8589      breakpoint.  If we are, then we must guarantee that the called
8590      syscall is the same syscall we are catching.  */
8591   int syscall_number = 0;
8592   const struct syscall_catchpoint *c
8593     = (const struct syscall_catchpoint *) bl->owner;
8594
8595   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8596       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8597     return 0;
8598
8599   syscall_number = ws->value.syscall_number;
8600
8601   /* Now, checking if the syscall is the same.  */
8602   if (c->syscalls_to_be_caught)
8603     {
8604       int i, iter;
8605
8606       for (i = 0;
8607            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8608            i++)
8609         if (syscall_number == iter)
8610           return 1;
8611
8612       return 0;
8613     }
8614
8615   return 1;
8616 }
8617
8618 /* Implement the "print_it" breakpoint_ops method for syscall
8619    catchpoints.  */
8620
8621 static enum print_stop_action
8622 print_it_catch_syscall (bpstat bs)
8623 {
8624   struct ui_out *uiout = current_uiout;
8625   struct breakpoint *b = bs->breakpoint_at;
8626   /* These are needed because we want to know in which state a
8627      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8628      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8629      must print "called syscall" or "returned from syscall".  */
8630   ptid_t ptid;
8631   struct target_waitstatus last;
8632   struct syscall s;
8633
8634   get_last_target_status (&ptid, &last);
8635
8636   get_syscall_by_number (last.value.syscall_number, &s);
8637
8638   annotate_catchpoint (b->number);
8639
8640   if (b->disposition == disp_del)
8641     ui_out_text (uiout, "\nTemporary catchpoint ");
8642   else
8643     ui_out_text (uiout, "\nCatchpoint ");
8644   if (ui_out_is_mi_like_p (uiout))
8645     {
8646       ui_out_field_string (uiout, "reason",
8647                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8648                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8649                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8650       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8651     }
8652   ui_out_field_int (uiout, "bkptno", b->number);
8653
8654   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8655     ui_out_text (uiout, " (call to syscall ");
8656   else
8657     ui_out_text (uiout, " (returned from syscall ");
8658
8659   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8660     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8661   if (s.name != NULL)
8662     ui_out_field_string (uiout, "syscall-name", s.name);
8663
8664   ui_out_text (uiout, "), ");
8665
8666   return PRINT_SRC_AND_LOC;
8667 }
8668
8669 /* Implement the "print_one" breakpoint_ops method for syscall
8670    catchpoints.  */
8671
8672 static void
8673 print_one_catch_syscall (struct breakpoint *b,
8674                          struct bp_location **last_loc)
8675 {
8676   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8677   struct value_print_options opts;
8678   struct ui_out *uiout = current_uiout;
8679
8680   get_user_print_options (&opts);
8681   /* Field 4, the address, is omitted (which makes the columns not
8682      line up too nicely with the headers, but the effect is relatively
8683      readable).  */
8684   if (opts.addressprint)
8685     ui_out_field_skip (uiout, "addr");
8686   annotate_field (5);
8687
8688   if (c->syscalls_to_be_caught
8689       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8690     ui_out_text (uiout, "syscalls \"");
8691   else
8692     ui_out_text (uiout, "syscall \"");
8693
8694   if (c->syscalls_to_be_caught)
8695     {
8696       int i, iter;
8697       char *text = xstrprintf ("%s", "");
8698
8699       for (i = 0;
8700            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8701            i++)
8702         {
8703           char *x = text;
8704           struct syscall s;
8705           get_syscall_by_number (iter, &s);
8706
8707           if (s.name != NULL)
8708             text = xstrprintf ("%s%s, ", text, s.name);
8709           else
8710             text = xstrprintf ("%s%d, ", text, iter);
8711
8712           /* We have to xfree the last 'text' (now stored at 'x')
8713              because xstrprintf dynamically allocates new space for it
8714              on every call.  */
8715           xfree (x);
8716         }
8717       /* Remove the last comma.  */
8718       text[strlen (text) - 2] = '\0';
8719       ui_out_field_string (uiout, "what", text);
8720     }
8721   else
8722     ui_out_field_string (uiout, "what", "<any syscall>");
8723   ui_out_text (uiout, "\" ");
8724
8725   if (ui_out_is_mi_like_p (uiout))
8726     ui_out_field_string (uiout, "catch-type", "syscall");
8727 }
8728
8729 /* Implement the "print_mention" breakpoint_ops method for syscall
8730    catchpoints.  */
8731
8732 static void
8733 print_mention_catch_syscall (struct breakpoint *b)
8734 {
8735   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8736
8737   if (c->syscalls_to_be_caught)
8738     {
8739       int i, iter;
8740
8741       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8742         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8743       else
8744         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8745
8746       for (i = 0;
8747            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8748            i++)
8749         {
8750           struct syscall s;
8751           get_syscall_by_number (iter, &s);
8752
8753           if (s.name)
8754             printf_filtered (" '%s' [%d]", s.name, s.number);
8755           else
8756             printf_filtered (" %d", s.number);
8757         }
8758       printf_filtered (")");
8759     }
8760   else
8761     printf_filtered (_("Catchpoint %d (any syscall)"),
8762                      b->number);
8763 }
8764
8765 /* Implement the "print_recreate" breakpoint_ops method for syscall
8766    catchpoints.  */
8767
8768 static void
8769 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8770 {
8771   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8772
8773   fprintf_unfiltered (fp, "catch syscall");
8774
8775   if (c->syscalls_to_be_caught)
8776     {
8777       int i, iter;
8778
8779       for (i = 0;
8780            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8781            i++)
8782         {
8783           struct syscall s;
8784
8785           get_syscall_by_number (iter, &s);
8786           if (s.name)
8787             fprintf_unfiltered (fp, " %s", s.name);
8788           else
8789             fprintf_unfiltered (fp, " %d", s.number);
8790         }
8791     }
8792   print_recreate_thread (b, fp);
8793 }
8794
8795 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8796
8797 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8798
8799 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8800
8801 static int
8802 syscall_catchpoint_p (struct breakpoint *b)
8803 {
8804   return (b->ops == &catch_syscall_breakpoint_ops);
8805 }
8806
8807 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8808    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8809    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8810    the breakpoint_ops structure associated to the catchpoint.  */
8811
8812 void
8813 init_catchpoint (struct breakpoint *b,
8814                  struct gdbarch *gdbarch, int tempflag,
8815                  char *cond_string,
8816                  const struct breakpoint_ops *ops)
8817 {
8818   struct symtab_and_line sal;
8819
8820   init_sal (&sal);
8821   sal.pspace = current_program_space;
8822
8823   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8824
8825   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8826   b->disposition = tempflag ? disp_del : disp_donttouch;
8827 }
8828
8829 void
8830 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8831 {
8832   add_to_breakpoint_chain (b);
8833   set_breakpoint_number (internal, b);
8834   if (is_tracepoint (b))
8835     set_tracepoint_count (breakpoint_count);
8836   if (!internal)
8837     mention (b);
8838   observer_notify_breakpoint_created (b);
8839
8840   if (update_gll)
8841     update_global_location_list (1);
8842 }
8843
8844 static void
8845 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8846                                     int tempflag, char *cond_string,
8847                                     const struct breakpoint_ops *ops)
8848 {
8849   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8850
8851   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8852
8853   c->forked_inferior_pid = null_ptid;
8854
8855   install_breakpoint (0, &c->base, 1);
8856 }
8857
8858 /* Exec catchpoints.  */
8859
8860 /* An instance of this type is used to represent an exec catchpoint.
8861    It includes a "struct breakpoint" as a kind of base class; users
8862    downcast to "struct breakpoint *" when needed.  A breakpoint is
8863    really of this type iff its ops pointer points to
8864    CATCH_EXEC_BREAKPOINT_OPS.  */
8865
8866 struct exec_catchpoint
8867 {
8868   /* The base class.  */
8869   struct breakpoint base;
8870
8871   /* Filename of a program whose exec triggered this catchpoint.
8872      This field is only valid immediately after this catchpoint has
8873      triggered.  */
8874   char *exec_pathname;
8875 };
8876
8877 /* Implement the "dtor" breakpoint_ops method for exec
8878    catchpoints.  */
8879
8880 static void
8881 dtor_catch_exec (struct breakpoint *b)
8882 {
8883   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8884
8885   xfree (c->exec_pathname);
8886
8887   base_breakpoint_ops.dtor (b);
8888 }
8889
8890 static int
8891 insert_catch_exec (struct bp_location *bl)
8892 {
8893   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8894 }
8895
8896 static int
8897 remove_catch_exec (struct bp_location *bl)
8898 {
8899   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8900 }
8901
8902 static int
8903 breakpoint_hit_catch_exec (const struct bp_location *bl,
8904                            struct address_space *aspace, CORE_ADDR bp_addr,
8905                            const struct target_waitstatus *ws)
8906 {
8907   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8908
8909   if (ws->kind != TARGET_WAITKIND_EXECD)
8910     return 0;
8911
8912   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8913   return 1;
8914 }
8915
8916 static enum print_stop_action
8917 print_it_catch_exec (bpstat bs)
8918 {
8919   struct ui_out *uiout = current_uiout;
8920   struct breakpoint *b = bs->breakpoint_at;
8921   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8922
8923   annotate_catchpoint (b->number);
8924   if (b->disposition == disp_del)
8925     ui_out_text (uiout, "\nTemporary catchpoint ");
8926   else
8927     ui_out_text (uiout, "\nCatchpoint ");
8928   if (ui_out_is_mi_like_p (uiout))
8929     {
8930       ui_out_field_string (uiout, "reason",
8931                            async_reason_lookup (EXEC_ASYNC_EXEC));
8932       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8933     }
8934   ui_out_field_int (uiout, "bkptno", b->number);
8935   ui_out_text (uiout, " (exec'd ");
8936   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8937   ui_out_text (uiout, "), ");
8938
8939   return PRINT_SRC_AND_LOC;
8940 }
8941
8942 static void
8943 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8944 {
8945   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8946   struct value_print_options opts;
8947   struct ui_out *uiout = current_uiout;
8948
8949   get_user_print_options (&opts);
8950
8951   /* Field 4, the address, is omitted (which makes the columns
8952      not line up too nicely with the headers, but the effect
8953      is relatively readable).  */
8954   if (opts.addressprint)
8955     ui_out_field_skip (uiout, "addr");
8956   annotate_field (5);
8957   ui_out_text (uiout, "exec");
8958   if (c->exec_pathname != NULL)
8959     {
8960       ui_out_text (uiout, ", program \"");
8961       ui_out_field_string (uiout, "what", c->exec_pathname);
8962       ui_out_text (uiout, "\" ");
8963     }
8964
8965   if (ui_out_is_mi_like_p (uiout))
8966     ui_out_field_string (uiout, "catch-type", "exec");
8967 }
8968
8969 static void
8970 print_mention_catch_exec (struct breakpoint *b)
8971 {
8972   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8973 }
8974
8975 /* Implement the "print_recreate" breakpoint_ops method for exec
8976    catchpoints.  */
8977
8978 static void
8979 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8980 {
8981   fprintf_unfiltered (fp, "catch exec");
8982   print_recreate_thread (b, fp);
8983 }
8984
8985 static struct breakpoint_ops catch_exec_breakpoint_ops;
8986
8987 static void
8988 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8989                                  const struct breakpoint_ops *ops)
8990 {
8991   struct syscall_catchpoint *c;
8992   struct gdbarch *gdbarch = get_current_arch ();
8993
8994   c = XNEW (struct syscall_catchpoint);
8995   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8996   c->syscalls_to_be_caught = filter;
8997
8998   install_breakpoint (0, &c->base, 1);
8999 }
9000
9001 static int
9002 hw_breakpoint_used_count (void)
9003 {
9004   int i = 0;
9005   struct breakpoint *b;
9006   struct bp_location *bl;
9007
9008   ALL_BREAKPOINTS (b)
9009   {
9010     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9011       for (bl = b->loc; bl; bl = bl->next)
9012         {
9013           /* Special types of hardware breakpoints may use more than
9014              one register.  */
9015           i += b->ops->resources_needed (bl);
9016         }
9017   }
9018
9019   return i;
9020 }
9021
9022 /* Returns the resources B would use if it were a hardware
9023    watchpoint.  */
9024
9025 static int
9026 hw_watchpoint_use_count (struct breakpoint *b)
9027 {
9028   int i = 0;
9029   struct bp_location *bl;
9030
9031   if (!breakpoint_enabled (b))
9032     return 0;
9033
9034   for (bl = b->loc; bl; bl = bl->next)
9035     {
9036       /* Special types of hardware watchpoints may use more than
9037          one register.  */
9038       i += b->ops->resources_needed (bl);
9039     }
9040
9041   return i;
9042 }
9043
9044 /* Returns the sum the used resources of all hardware watchpoints of
9045    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9046    the sum of the used resources of all hardware watchpoints of other
9047    types _not_ TYPE.  */
9048
9049 static int
9050 hw_watchpoint_used_count_others (struct breakpoint *except,
9051                                  enum bptype type, int *other_type_used)
9052 {
9053   int i = 0;
9054   struct breakpoint *b;
9055
9056   *other_type_used = 0;
9057   ALL_BREAKPOINTS (b)
9058     {
9059       if (b == except)
9060         continue;
9061       if (!breakpoint_enabled (b))
9062         continue;
9063
9064       if (b->type == type)
9065         i += hw_watchpoint_use_count (b);
9066       else if (is_hardware_watchpoint (b))
9067         *other_type_used = 1;
9068     }
9069
9070   return i;
9071 }
9072
9073 void
9074 disable_watchpoints_before_interactive_call_start (void)
9075 {
9076   struct breakpoint *b;
9077
9078   ALL_BREAKPOINTS (b)
9079   {
9080     if (is_watchpoint (b) && breakpoint_enabled (b))
9081       {
9082         b->enable_state = bp_call_disabled;
9083         update_global_location_list (0);
9084       }
9085   }
9086 }
9087
9088 void
9089 enable_watchpoints_after_interactive_call_stop (void)
9090 {
9091   struct breakpoint *b;
9092
9093   ALL_BREAKPOINTS (b)
9094   {
9095     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9096       {
9097         b->enable_state = bp_enabled;
9098         update_global_location_list (1);
9099       }
9100   }
9101 }
9102
9103 void
9104 disable_breakpoints_before_startup (void)
9105 {
9106   current_program_space->executing_startup = 1;
9107   update_global_location_list (0);
9108 }
9109
9110 void
9111 enable_breakpoints_after_startup (void)
9112 {
9113   current_program_space->executing_startup = 0;
9114   breakpoint_re_set ();
9115 }
9116
9117
9118 /* Set a breakpoint that will evaporate an end of command
9119    at address specified by SAL.
9120    Restrict it to frame FRAME if FRAME is nonzero.  */
9121
9122 struct breakpoint *
9123 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9124                           struct frame_id frame_id, enum bptype type)
9125 {
9126   struct breakpoint *b;
9127
9128   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9129      tail-called one.  */
9130   gdb_assert (!frame_id_artificial_p (frame_id));
9131
9132   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9133   b->enable_state = bp_enabled;
9134   b->disposition = disp_donttouch;
9135   b->frame_id = frame_id;
9136
9137   /* If we're debugging a multi-threaded program, then we want
9138      momentary breakpoints to be active in only a single thread of
9139      control.  */
9140   if (in_thread_list (inferior_ptid))
9141     b->thread = pid_to_thread_id (inferior_ptid);
9142
9143   update_global_location_list_nothrow (1);
9144
9145   return b;
9146 }
9147
9148 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9149    The new breakpoint will have type TYPE, use OPS as its
9150    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9151
9152 static struct breakpoint *
9153 momentary_breakpoint_from_master (struct breakpoint *orig,
9154                                   enum bptype type,
9155                                   const struct breakpoint_ops *ops,
9156                                   int loc_enabled)
9157 {
9158   struct breakpoint *copy;
9159
9160   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9161   copy->loc = allocate_bp_location (copy);
9162   set_breakpoint_location_function (copy->loc, 1);
9163
9164   copy->loc->gdbarch = orig->loc->gdbarch;
9165   copy->loc->requested_address = orig->loc->requested_address;
9166   copy->loc->address = orig->loc->address;
9167   copy->loc->section = orig->loc->section;
9168   copy->loc->pspace = orig->loc->pspace;
9169   copy->loc->probe = orig->loc->probe;
9170   copy->loc->line_number = orig->loc->line_number;
9171   copy->loc->symtab = orig->loc->symtab;
9172   copy->loc->enabled = loc_enabled;
9173   copy->frame_id = orig->frame_id;
9174   copy->thread = orig->thread;
9175   copy->pspace = orig->pspace;
9176
9177   copy->enable_state = bp_enabled;
9178   copy->disposition = disp_donttouch;
9179   copy->number = internal_breakpoint_number--;
9180
9181   update_global_location_list_nothrow (0);
9182   return copy;
9183 }
9184
9185 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9186    ORIG is NULL.  */
9187
9188 struct breakpoint *
9189 clone_momentary_breakpoint (struct breakpoint *orig)
9190 {
9191   /* If there's nothing to clone, then return nothing.  */
9192   if (orig == NULL)
9193     return NULL;
9194
9195   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9196 }
9197
9198 struct breakpoint *
9199 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9200                                 enum bptype type)
9201 {
9202   struct symtab_and_line sal;
9203
9204   sal = find_pc_line (pc, 0);
9205   sal.pc = pc;
9206   sal.section = find_pc_overlay (pc);
9207   sal.explicit_pc = 1;
9208
9209   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9210 }
9211 \f
9212
9213 /* Tell the user we have just set a breakpoint B.  */
9214
9215 static void
9216 mention (struct breakpoint *b)
9217 {
9218   b->ops->print_mention (b);
9219   if (ui_out_is_mi_like_p (current_uiout))
9220     return;
9221   printf_filtered ("\n");
9222 }
9223 \f
9224
9225 static struct bp_location *
9226 add_location_to_breakpoint (struct breakpoint *b,
9227                             const struct symtab_and_line *sal)
9228 {
9229   struct bp_location *loc, **tmp;
9230   CORE_ADDR adjusted_address;
9231   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9232
9233   if (loc_gdbarch == NULL)
9234     loc_gdbarch = b->gdbarch;
9235
9236   /* Adjust the breakpoint's address prior to allocating a location.
9237      Once we call allocate_bp_location(), that mostly uninitialized
9238      location will be placed on the location chain.  Adjustment of the
9239      breakpoint may cause target_read_memory() to be called and we do
9240      not want its scan of the location chain to find a breakpoint and
9241      location that's only been partially initialized.  */
9242   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9243                                                 sal->pc, b->type);
9244
9245   /* Sort the locations by their ADDRESS.  */
9246   loc = allocate_bp_location (b);
9247   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9248        tmp = &((*tmp)->next))
9249     ;
9250   loc->next = *tmp;
9251   *tmp = loc;
9252
9253   loc->requested_address = sal->pc;
9254   loc->address = adjusted_address;
9255   loc->pspace = sal->pspace;
9256   loc->probe.probe = sal->probe;
9257   loc->probe.objfile = sal->objfile;
9258   gdb_assert (loc->pspace != NULL);
9259   loc->section = sal->section;
9260   loc->gdbarch = loc_gdbarch;
9261   loc->line_number = sal->line;
9262   loc->symtab = sal->symtab;
9263
9264   set_breakpoint_location_function (loc,
9265                                     sal->explicit_pc || sal->explicit_line);
9266   return loc;
9267 }
9268 \f
9269
9270 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9271    return 0 otherwise.  */
9272
9273 static int
9274 bp_loc_is_permanent (struct bp_location *loc)
9275 {
9276   int len;
9277   CORE_ADDR addr;
9278   const gdb_byte *bpoint;
9279   gdb_byte *target_mem;
9280   struct cleanup *cleanup;
9281   int retval = 0;
9282
9283   gdb_assert (loc != NULL);
9284
9285   addr = loc->address;
9286   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9287
9288   /* Software breakpoints unsupported?  */
9289   if (bpoint == NULL)
9290     return 0;
9291
9292   target_mem = alloca (len);
9293
9294   /* Enable the automatic memory restoration from breakpoints while
9295      we read the memory.  Otherwise we could say about our temporary
9296      breakpoints they are permanent.  */
9297   cleanup = save_current_space_and_thread ();
9298
9299   switch_to_program_space_and_thread (loc->pspace);
9300   make_show_memory_breakpoints_cleanup (0);
9301
9302   if (target_read_memory (loc->address, target_mem, len) == 0
9303       && memcmp (target_mem, bpoint, len) == 0)
9304     retval = 1;
9305
9306   do_cleanups (cleanup);
9307
9308   return retval;
9309 }
9310
9311 /* Build a command list for the dprintf corresponding to the current
9312    settings of the dprintf style options.  */
9313
9314 static void
9315 update_dprintf_command_list (struct breakpoint *b)
9316 {
9317   char *dprintf_args = b->extra_string;
9318   char *printf_line = NULL;
9319
9320   if (!dprintf_args)
9321     return;
9322
9323   dprintf_args = skip_spaces (dprintf_args);
9324
9325   /* Allow a comma, as it may have terminated a location, but don't
9326      insist on it.  */
9327   if (*dprintf_args == ',')
9328     ++dprintf_args;
9329   dprintf_args = skip_spaces (dprintf_args);
9330
9331   if (*dprintf_args != '"')
9332     error (_("Bad format string, missing '\"'."));
9333
9334   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9335     printf_line = xstrprintf ("printf %s", dprintf_args);
9336   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9337     {
9338       if (!dprintf_function)
9339         error (_("No function supplied for dprintf call"));
9340
9341       if (dprintf_channel && strlen (dprintf_channel) > 0)
9342         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9343                                   dprintf_function,
9344                                   dprintf_channel,
9345                                   dprintf_args);
9346       else
9347         printf_line = xstrprintf ("call (void) %s (%s)",
9348                                   dprintf_function,
9349                                   dprintf_args);
9350     }
9351   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9352     {
9353       if (target_can_run_breakpoint_commands ())
9354         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9355       else
9356         {
9357           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9358           printf_line = xstrprintf ("printf %s", dprintf_args);
9359         }
9360     }
9361   else
9362     internal_error (__FILE__, __LINE__,
9363                     _("Invalid dprintf style."));
9364
9365   gdb_assert (printf_line != NULL);
9366   /* Manufacture a printf sequence.  */
9367   {
9368     struct command_line *printf_cmd_line
9369       = xmalloc (sizeof (struct command_line));
9370
9371     printf_cmd_line = xmalloc (sizeof (struct command_line));
9372     printf_cmd_line->control_type = simple_control;
9373     printf_cmd_line->body_count = 0;
9374     printf_cmd_line->body_list = NULL;
9375     printf_cmd_line->next = NULL;
9376     printf_cmd_line->line = printf_line;
9377
9378     breakpoint_set_commands (b, printf_cmd_line);
9379   }
9380 }
9381
9382 /* Update all dprintf commands, making their command lists reflect
9383    current style settings.  */
9384
9385 static void
9386 update_dprintf_commands (char *args, int from_tty,
9387                          struct cmd_list_element *c)
9388 {
9389   struct breakpoint *b;
9390
9391   ALL_BREAKPOINTS (b)
9392     {
9393       if (b->type == bp_dprintf)
9394         update_dprintf_command_list (b);
9395     }
9396 }
9397
9398 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9399    as textual description of the location, and COND_STRING
9400    as condition expression.  */
9401
9402 static void
9403 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9404                      struct symtabs_and_lines sals, char *addr_string,
9405                      char *filter, char *cond_string,
9406                      char *extra_string,
9407                      enum bptype type, enum bpdisp disposition,
9408                      int thread, int task, int ignore_count,
9409                      const struct breakpoint_ops *ops, int from_tty,
9410                      int enabled, int internal, unsigned flags,
9411                      int display_canonical)
9412 {
9413   int i;
9414
9415   if (type == bp_hardware_breakpoint)
9416     {
9417       int target_resources_ok;
9418
9419       i = hw_breakpoint_used_count ();
9420       target_resources_ok =
9421         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9422                                             i + 1, 0);
9423       if (target_resources_ok == 0)
9424         error (_("No hardware breakpoint support in the target."));
9425       else if (target_resources_ok < 0)
9426         error (_("Hardware breakpoints used exceeds limit."));
9427     }
9428
9429   gdb_assert (sals.nelts > 0);
9430
9431   for (i = 0; i < sals.nelts; ++i)
9432     {
9433       struct symtab_and_line sal = sals.sals[i];
9434       struct bp_location *loc;
9435
9436       if (from_tty)
9437         {
9438           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9439           if (!loc_gdbarch)
9440             loc_gdbarch = gdbarch;
9441
9442           describe_other_breakpoints (loc_gdbarch,
9443                                       sal.pspace, sal.pc, sal.section, thread);
9444         }
9445
9446       if (i == 0)
9447         {
9448           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9449           b->thread = thread;
9450           b->task = task;
9451
9452           b->cond_string = cond_string;
9453           b->extra_string = extra_string;
9454           b->ignore_count = ignore_count;
9455           b->enable_state = enabled ? bp_enabled : bp_disabled;
9456           b->disposition = disposition;
9457
9458           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9459             b->loc->inserted = 1;
9460
9461           if (type == bp_static_tracepoint)
9462             {
9463               struct tracepoint *t = (struct tracepoint *) b;
9464               struct static_tracepoint_marker marker;
9465
9466               if (strace_marker_p (b))
9467                 {
9468                   /* We already know the marker exists, otherwise, we
9469                      wouldn't see a sal for it.  */
9470                   char *p = &addr_string[3];
9471                   char *endp;
9472                   char *marker_str;
9473
9474                   p = skip_spaces (p);
9475
9476                   endp = skip_to_space (p);
9477
9478                   marker_str = savestring (p, endp - p);
9479                   t->static_trace_marker_id = marker_str;
9480
9481                   printf_filtered (_("Probed static tracepoint "
9482                                      "marker \"%s\"\n"),
9483                                    t->static_trace_marker_id);
9484                 }
9485               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9486                 {
9487                   t->static_trace_marker_id = xstrdup (marker.str_id);
9488                   release_static_tracepoint_marker (&marker);
9489
9490                   printf_filtered (_("Probed static tracepoint "
9491                                      "marker \"%s\"\n"),
9492                                    t->static_trace_marker_id);
9493                 }
9494               else
9495                 warning (_("Couldn't determine the static "
9496                            "tracepoint marker to probe"));
9497             }
9498
9499           loc = b->loc;
9500         }
9501       else
9502         {
9503           loc = add_location_to_breakpoint (b, &sal);
9504           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9505             loc->inserted = 1;
9506         }
9507
9508       if (bp_loc_is_permanent (loc))
9509         make_breakpoint_permanent (b);
9510
9511       if (b->cond_string)
9512         {
9513           const char *arg = b->cond_string;
9514
9515           loc->cond = parse_exp_1 (&arg, loc->address,
9516                                    block_for_pc (loc->address), 0);
9517           if (*arg)
9518               error (_("Garbage '%s' follows condition"), arg);
9519         }
9520
9521       /* Dynamic printf requires and uses additional arguments on the
9522          command line, otherwise it's an error.  */
9523       if (type == bp_dprintf)
9524         {
9525           if (b->extra_string)
9526             update_dprintf_command_list (b);
9527           else
9528             error (_("Format string required"));
9529         }
9530       else if (b->extra_string)
9531         error (_("Garbage '%s' at end of command"), b->extra_string);
9532     }
9533
9534   b->display_canonical = display_canonical;
9535   if (addr_string)
9536     b->addr_string = addr_string;
9537   else
9538     /* addr_string has to be used or breakpoint_re_set will delete
9539        me.  */
9540     b->addr_string
9541       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9542   b->filter = filter;
9543 }
9544
9545 static void
9546 create_breakpoint_sal (struct gdbarch *gdbarch,
9547                        struct symtabs_and_lines sals, char *addr_string,
9548                        char *filter, char *cond_string,
9549                        char *extra_string,
9550                        enum bptype type, enum bpdisp disposition,
9551                        int thread, int task, int ignore_count,
9552                        const struct breakpoint_ops *ops, int from_tty,
9553                        int enabled, int internal, unsigned flags,
9554                        int display_canonical)
9555 {
9556   struct breakpoint *b;
9557   struct cleanup *old_chain;
9558
9559   if (is_tracepoint_type (type))
9560     {
9561       struct tracepoint *t;
9562
9563       t = XCNEW (struct tracepoint);
9564       b = &t->base;
9565     }
9566   else
9567     b = XNEW (struct breakpoint);
9568
9569   old_chain = make_cleanup (xfree, b);
9570
9571   init_breakpoint_sal (b, gdbarch,
9572                        sals, addr_string,
9573                        filter, cond_string, extra_string,
9574                        type, disposition,
9575                        thread, task, ignore_count,
9576                        ops, from_tty,
9577                        enabled, internal, flags,
9578                        display_canonical);
9579   discard_cleanups (old_chain);
9580
9581   install_breakpoint (internal, b, 0);
9582 }
9583
9584 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9585    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9586    value.  COND_STRING, if not NULL, specified the condition to be
9587    used for all breakpoints.  Essentially the only case where
9588    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9589    function.  In that case, it's still not possible to specify
9590    separate conditions for different overloaded functions, so
9591    we take just a single condition string.
9592    
9593    NOTE: If the function succeeds, the caller is expected to cleanup
9594    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9595    array contents).  If the function fails (error() is called), the
9596    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9597    COND and SALS arrays and each of those arrays contents.  */
9598
9599 static void
9600 create_breakpoints_sal (struct gdbarch *gdbarch,
9601                         struct linespec_result *canonical,
9602                         char *cond_string, char *extra_string,
9603                         enum bptype type, enum bpdisp disposition,
9604                         int thread, int task, int ignore_count,
9605                         const struct breakpoint_ops *ops, int from_tty,
9606                         int enabled, int internal, unsigned flags)
9607 {
9608   int i;
9609   struct linespec_sals *lsal;
9610
9611   if (canonical->pre_expanded)
9612     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9613
9614   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9615     {
9616       /* Note that 'addr_string' can be NULL in the case of a plain
9617          'break', without arguments.  */
9618       char *addr_string = (canonical->addr_string
9619                            ? xstrdup (canonical->addr_string)
9620                            : NULL);
9621       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9622       struct cleanup *inner = make_cleanup (xfree, addr_string);
9623
9624       make_cleanup (xfree, filter_string);
9625       create_breakpoint_sal (gdbarch, lsal->sals,
9626                              addr_string,
9627                              filter_string,
9628                              cond_string, extra_string,
9629                              type, disposition,
9630                              thread, task, ignore_count, ops,
9631                              from_tty, enabled, internal, flags,
9632                              canonical->special_display);
9633       discard_cleanups (inner);
9634     }
9635 }
9636
9637 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9638    followed by conditionals.  On return, SALS contains an array of SAL
9639    addresses found.  ADDR_STRING contains a vector of (canonical)
9640    address strings.  ADDRESS points to the end of the SAL.
9641
9642    The array and the line spec strings are allocated on the heap, it is
9643    the caller's responsibility to free them.  */
9644
9645 static void
9646 parse_breakpoint_sals (char **address,
9647                        struct linespec_result *canonical)
9648 {
9649   /* If no arg given, or if first arg is 'if ', use the default
9650      breakpoint.  */
9651   if ((*address) == NULL
9652       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9653     {
9654       /* The last displayed codepoint, if it's valid, is our default breakpoint
9655          address.  */
9656       if (last_displayed_sal_is_valid ())
9657         {
9658           struct linespec_sals lsal;
9659           struct symtab_and_line sal;
9660           CORE_ADDR pc;
9661
9662           init_sal (&sal);              /* Initialize to zeroes.  */
9663           lsal.sals.sals = (struct symtab_and_line *)
9664             xmalloc (sizeof (struct symtab_and_line));
9665
9666           /* Set sal's pspace, pc, symtab, and line to the values
9667              corresponding to the last call to print_frame_info.
9668              Be sure to reinitialize LINE with NOTCURRENT == 0
9669              as the breakpoint line number is inappropriate otherwise.
9670              find_pc_line would adjust PC, re-set it back.  */
9671           get_last_displayed_sal (&sal);
9672           pc = sal.pc;
9673           sal = find_pc_line (pc, 0);
9674
9675           /* "break" without arguments is equivalent to "break *PC"
9676              where PC is the last displayed codepoint's address.  So
9677              make sure to set sal.explicit_pc to prevent GDB from
9678              trying to expand the list of sals to include all other
9679              instances with the same symtab and line.  */
9680           sal.pc = pc;
9681           sal.explicit_pc = 1;
9682
9683           lsal.sals.sals[0] = sal;
9684           lsal.sals.nelts = 1;
9685           lsal.canonical = NULL;
9686
9687           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9688         }
9689       else
9690         error (_("No default breakpoint address now."));
9691     }
9692   else
9693     {
9694       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9695
9696       /* Force almost all breakpoints to be in terms of the
9697          current_source_symtab (which is decode_line_1's default).
9698          This should produce the results we want almost all of the
9699          time while leaving default_breakpoint_* alone.
9700
9701          ObjC: However, don't match an Objective-C method name which
9702          may have a '+' or '-' succeeded by a '['.  */
9703       if (last_displayed_sal_is_valid ()
9704           && (!cursal.symtab
9705               || ((strchr ("+-", (*address)[0]) != NULL)
9706                   && ((*address)[1] != '['))))
9707         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9708                           get_last_displayed_symtab (),
9709                           get_last_displayed_line (),
9710                           canonical, NULL, NULL);
9711       else
9712         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9713                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9714     }
9715 }
9716
9717
9718 /* Convert each SAL into a real PC.  Verify that the PC can be
9719    inserted as a breakpoint.  If it can't throw an error.  */
9720
9721 static void
9722 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9723 {    
9724   int i;
9725
9726   for (i = 0; i < sals->nelts; i++)
9727     resolve_sal_pc (&sals->sals[i]);
9728 }
9729
9730 /* Fast tracepoints may have restrictions on valid locations.  For
9731    instance, a fast tracepoint using a jump instead of a trap will
9732    likely have to overwrite more bytes than a trap would, and so can
9733    only be placed where the instruction is longer than the jump, or a
9734    multi-instruction sequence does not have a jump into the middle of
9735    it, etc.  */
9736
9737 static void
9738 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9739                             struct symtabs_and_lines *sals)
9740 {
9741   int i, rslt;
9742   struct symtab_and_line *sal;
9743   char *msg;
9744   struct cleanup *old_chain;
9745
9746   for (i = 0; i < sals->nelts; i++)
9747     {
9748       struct gdbarch *sarch;
9749
9750       sal = &sals->sals[i];
9751
9752       sarch = get_sal_arch (*sal);
9753       /* We fall back to GDBARCH if there is no architecture
9754          associated with SAL.  */
9755       if (sarch == NULL)
9756         sarch = gdbarch;
9757       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9758                                                NULL, &msg);
9759       old_chain = make_cleanup (xfree, msg);
9760
9761       if (!rslt)
9762         error (_("May not have a fast tracepoint at 0x%s%s"),
9763                paddress (sarch, sal->pc), (msg ? msg : ""));
9764
9765       do_cleanups (old_chain);
9766     }
9767 }
9768
9769 /* Issue an invalid thread ID error.  */
9770
9771 static void ATTRIBUTE_NORETURN
9772 invalid_thread_id_error (int id)
9773 {
9774   error (_("Unknown thread %d."), id);
9775 }
9776
9777 /* Given TOK, a string specification of condition and thread, as
9778    accepted by the 'break' command, extract the condition
9779    string and thread number and set *COND_STRING and *THREAD.
9780    PC identifies the context at which the condition should be parsed.
9781    If no condition is found, *COND_STRING is set to NULL.
9782    If no thread is found, *THREAD is set to -1.  */
9783
9784 static void
9785 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9786                            char **cond_string, int *thread, int *task,
9787                            char **rest)
9788 {
9789   *cond_string = NULL;
9790   *thread = -1;
9791   *task = 0;
9792   *rest = NULL;
9793
9794   while (tok && *tok)
9795     {
9796       const char *end_tok;
9797       int toklen;
9798       const char *cond_start = NULL;
9799       const char *cond_end = NULL;
9800
9801       tok = skip_spaces_const (tok);
9802
9803       if ((*tok == '"' || *tok == ',') && rest)
9804         {
9805           *rest = savestring (tok, strlen (tok));
9806           return;
9807         }
9808
9809       end_tok = skip_to_space_const (tok);
9810
9811       toklen = end_tok - tok;
9812
9813       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9814         {
9815           struct expression *expr;
9816
9817           tok = cond_start = end_tok + 1;
9818           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9819           xfree (expr);
9820           cond_end = tok;
9821           *cond_string = savestring (cond_start, cond_end - cond_start);
9822         }
9823       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9824         {
9825           char *tmptok;
9826
9827           tok = end_tok + 1;
9828           *thread = strtol (tok, &tmptok, 0);
9829           if (tok == tmptok)
9830             error (_("Junk after thread keyword."));
9831           if (!valid_thread_id (*thread))
9832             invalid_thread_id_error (*thread);
9833           tok = tmptok;
9834         }
9835       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9836         {
9837           char *tmptok;
9838
9839           tok = end_tok + 1;
9840           *task = strtol (tok, &tmptok, 0);
9841           if (tok == tmptok)
9842             error (_("Junk after task keyword."));
9843           if (!valid_task_id (*task))
9844             error (_("Unknown task %d."), *task);
9845           tok = tmptok;
9846         }
9847       else if (rest)
9848         {
9849           *rest = savestring (tok, strlen (tok));
9850           return;
9851         }
9852       else
9853         error (_("Junk at end of arguments."));
9854     }
9855 }
9856
9857 /* Decode a static tracepoint marker spec.  */
9858
9859 static struct symtabs_and_lines
9860 decode_static_tracepoint_spec (char **arg_p)
9861 {
9862   VEC(static_tracepoint_marker_p) *markers = NULL;
9863   struct symtabs_and_lines sals;
9864   struct cleanup *old_chain;
9865   char *p = &(*arg_p)[3];
9866   char *endp;
9867   char *marker_str;
9868   int i;
9869
9870   p = skip_spaces (p);
9871
9872   endp = skip_to_space (p);
9873
9874   marker_str = savestring (p, endp - p);
9875   old_chain = make_cleanup (xfree, marker_str);
9876
9877   markers = target_static_tracepoint_markers_by_strid (marker_str);
9878   if (VEC_empty(static_tracepoint_marker_p, markers))
9879     error (_("No known static tracepoint marker named %s"), marker_str);
9880
9881   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9882   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9883
9884   for (i = 0; i < sals.nelts; i++)
9885     {
9886       struct static_tracepoint_marker *marker;
9887
9888       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9889
9890       init_sal (&sals.sals[i]);
9891
9892       sals.sals[i] = find_pc_line (marker->address, 0);
9893       sals.sals[i].pc = marker->address;
9894
9895       release_static_tracepoint_marker (marker);
9896     }
9897
9898   do_cleanups (old_chain);
9899
9900   *arg_p = endp;
9901   return sals;
9902 }
9903
9904 /* Set a breakpoint.  This function is shared between CLI and MI
9905    functions for setting a breakpoint.  This function has two major
9906    modes of operations, selected by the PARSE_ARG parameter.  If
9907    non-zero, the function will parse ARG, extracting location,
9908    condition, thread and extra string.  Otherwise, ARG is just the
9909    breakpoint's location, with condition, thread, and extra string
9910    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9911    If INTERNAL is non-zero, the breakpoint number will be allocated
9912    from the internal breakpoint count.  Returns true if any breakpoint
9913    was created; false otherwise.  */
9914
9915 int
9916 create_breakpoint (struct gdbarch *gdbarch,
9917                    char *arg, char *cond_string,
9918                    int thread, char *extra_string,
9919                    int parse_arg,
9920                    int tempflag, enum bptype type_wanted,
9921                    int ignore_count,
9922                    enum auto_boolean pending_break_support,
9923                    const struct breakpoint_ops *ops,
9924                    int from_tty, int enabled, int internal,
9925                    unsigned flags)
9926 {
9927   volatile struct gdb_exception e;
9928   char *copy_arg = NULL;
9929   char *addr_start = arg;
9930   struct linespec_result canonical;
9931   struct cleanup *old_chain;
9932   struct cleanup *bkpt_chain = NULL;
9933   int pending = 0;
9934   int task = 0;
9935   int prev_bkpt_count = breakpoint_count;
9936
9937   gdb_assert (ops != NULL);
9938
9939   init_linespec_result (&canonical);
9940
9941   TRY_CATCH (e, RETURN_MASK_ALL)
9942     {
9943       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9944                                      addr_start, &copy_arg);
9945     }
9946
9947   /* If caller is interested in rc value from parse, set value.  */
9948   switch (e.reason)
9949     {
9950     case GDB_NO_ERROR:
9951       if (VEC_empty (linespec_sals, canonical.sals))
9952         return 0;
9953       break;
9954     case RETURN_ERROR:
9955       switch (e.error)
9956         {
9957         case NOT_FOUND_ERROR:
9958
9959           /* If pending breakpoint support is turned off, throw
9960              error.  */
9961
9962           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9963             throw_exception (e);
9964
9965           exception_print (gdb_stderr, e);
9966
9967           /* If pending breakpoint support is auto query and the user
9968              selects no, then simply return the error code.  */
9969           if (pending_break_support == AUTO_BOOLEAN_AUTO
9970               && !nquery (_("Make %s pending on future shared library load? "),
9971                           bptype_string (type_wanted)))
9972             return 0;
9973
9974           /* At this point, either the user was queried about setting
9975              a pending breakpoint and selected yes, or pending
9976              breakpoint behavior is on and thus a pending breakpoint
9977              is defaulted on behalf of the user.  */
9978           {
9979             struct linespec_sals lsal;
9980
9981             copy_arg = xstrdup (addr_start);
9982             lsal.canonical = xstrdup (copy_arg);
9983             lsal.sals.nelts = 1;
9984             lsal.sals.sals = XNEW (struct symtab_and_line);
9985             init_sal (&lsal.sals.sals[0]);
9986             pending = 1;
9987             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9988           }
9989           break;
9990         default:
9991           throw_exception (e);
9992         }
9993       break;
9994     default:
9995       throw_exception (e);
9996     }
9997
9998   /* Create a chain of things that always need to be cleaned up.  */
9999   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10000
10001   /* ----------------------------- SNIP -----------------------------
10002      Anything added to the cleanup chain beyond this point is assumed
10003      to be part of a breakpoint.  If the breakpoint create succeeds
10004      then the memory is not reclaimed.  */
10005   bkpt_chain = make_cleanup (null_cleanup, 0);
10006
10007   /* Resolve all line numbers to PC's and verify that the addresses
10008      are ok for the target.  */
10009   if (!pending)
10010     {
10011       int ix;
10012       struct linespec_sals *iter;
10013
10014       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10015         breakpoint_sals_to_pc (&iter->sals);
10016     }
10017
10018   /* Fast tracepoints may have additional restrictions on location.  */
10019   if (!pending && type_wanted == bp_fast_tracepoint)
10020     {
10021       int ix;
10022       struct linespec_sals *iter;
10023
10024       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10025         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10026     }
10027
10028   /* Verify that condition can be parsed, before setting any
10029      breakpoints.  Allocate a separate condition expression for each
10030      breakpoint.  */
10031   if (!pending)
10032     {
10033       if (parse_arg)
10034         {
10035           char *rest;
10036           struct linespec_sals *lsal;
10037
10038           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10039
10040           /* Here we only parse 'arg' to separate condition
10041              from thread number, so parsing in context of first
10042              sal is OK.  When setting the breakpoint we'll
10043              re-parse it in context of each sal.  */
10044
10045           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10046                                      &thread, &task, &rest);
10047           if (cond_string)
10048             make_cleanup (xfree, cond_string);
10049           if (rest)
10050             make_cleanup (xfree, rest);
10051           if (rest)
10052             extra_string = rest;
10053         }
10054       else
10055         {
10056           if (*arg != '\0')
10057             error (_("Garbage '%s' at end of location"), arg);
10058
10059           /* Create a private copy of condition string.  */
10060           if (cond_string)
10061             {
10062               cond_string = xstrdup (cond_string);
10063               make_cleanup (xfree, cond_string);
10064             }
10065           /* Create a private copy of any extra string.  */
10066           if (extra_string)
10067             {
10068               extra_string = xstrdup (extra_string);
10069               make_cleanup (xfree, extra_string);
10070             }
10071         }
10072
10073       ops->create_breakpoints_sal (gdbarch, &canonical,
10074                                    cond_string, extra_string, type_wanted,
10075                                    tempflag ? disp_del : disp_donttouch,
10076                                    thread, task, ignore_count, ops,
10077                                    from_tty, enabled, internal, flags);
10078     }
10079   else
10080     {
10081       struct breakpoint *b;
10082
10083       make_cleanup (xfree, copy_arg);
10084
10085       if (is_tracepoint_type (type_wanted))
10086         {
10087           struct tracepoint *t;
10088
10089           t = XCNEW (struct tracepoint);
10090           b = &t->base;
10091         }
10092       else
10093         b = XNEW (struct breakpoint);
10094
10095       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10096
10097       b->addr_string = copy_arg;
10098       if (parse_arg)
10099         b->cond_string = NULL;
10100       else
10101         {
10102           /* Create a private copy of condition string.  */
10103           if (cond_string)
10104             {
10105               cond_string = xstrdup (cond_string);
10106               make_cleanup (xfree, cond_string);
10107             }
10108           b->cond_string = cond_string;
10109         }
10110       b->extra_string = NULL;
10111       b->ignore_count = ignore_count;
10112       b->disposition = tempflag ? disp_del : disp_donttouch;
10113       b->condition_not_parsed = 1;
10114       b->enable_state = enabled ? bp_enabled : bp_disabled;
10115       if ((type_wanted != bp_breakpoint
10116            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10117         b->pspace = current_program_space;
10118
10119       install_breakpoint (internal, b, 0);
10120     }
10121   
10122   if (VEC_length (linespec_sals, canonical.sals) > 1)
10123     {
10124       warning (_("Multiple breakpoints were set.\nUse the "
10125                  "\"delete\" command to delete unwanted breakpoints."));
10126       prev_breakpoint_count = prev_bkpt_count;
10127     }
10128
10129   /* That's it.  Discard the cleanups for data inserted into the
10130      breakpoint.  */
10131   discard_cleanups (bkpt_chain);
10132   /* But cleanup everything else.  */
10133   do_cleanups (old_chain);
10134
10135   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10136   update_global_location_list (1);
10137
10138   return 1;
10139 }
10140
10141 /* Set a breakpoint.
10142    ARG is a string describing breakpoint address,
10143    condition, and thread.
10144    FLAG specifies if a breakpoint is hardware on,
10145    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10146    and BP_TEMPFLAG.  */
10147
10148 static void
10149 break_command_1 (char *arg, int flag, int from_tty)
10150 {
10151   int tempflag = flag & BP_TEMPFLAG;
10152   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10153                              ? bp_hardware_breakpoint
10154                              : bp_breakpoint);
10155   struct breakpoint_ops *ops;
10156   const char *arg_cp = arg;
10157
10158   /* Matching breakpoints on probes.  */
10159   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10160     ops = &bkpt_probe_breakpoint_ops;
10161   else
10162     ops = &bkpt_breakpoint_ops;
10163
10164   create_breakpoint (get_current_arch (),
10165                      arg,
10166                      NULL, 0, NULL, 1 /* parse arg */,
10167                      tempflag, type_wanted,
10168                      0 /* Ignore count */,
10169                      pending_break_support,
10170                      ops,
10171                      from_tty,
10172                      1 /* enabled */,
10173                      0 /* internal */,
10174                      0);
10175 }
10176
10177 /* Helper function for break_command_1 and disassemble_command.  */
10178
10179 void
10180 resolve_sal_pc (struct symtab_and_line *sal)
10181 {
10182   CORE_ADDR pc;
10183
10184   if (sal->pc == 0 && sal->symtab != NULL)
10185     {
10186       if (!find_line_pc (sal->symtab, sal->line, &pc))
10187         error (_("No line %d in file \"%s\"."),
10188                sal->line, symtab_to_filename_for_display (sal->symtab));
10189       sal->pc = pc;
10190
10191       /* If this SAL corresponds to a breakpoint inserted using a line
10192          number, then skip the function prologue if necessary.  */
10193       if (sal->explicit_line)
10194         skip_prologue_sal (sal);
10195     }
10196
10197   if (sal->section == 0 && sal->symtab != NULL)
10198     {
10199       const struct blockvector *bv;
10200       const struct block *b;
10201       struct symbol *sym;
10202
10203       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10204       if (bv != NULL)
10205         {
10206           sym = block_linkage_function (b);
10207           if (sym != NULL)
10208             {
10209               fixup_symbol_section (sym, sal->symtab->objfile);
10210               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10211             }
10212           else
10213             {
10214               /* It really is worthwhile to have the section, so we'll
10215                  just have to look harder. This case can be executed
10216                  if we have line numbers but no functions (as can
10217                  happen in assembly source).  */
10218
10219               struct bound_minimal_symbol msym;
10220               struct cleanup *old_chain = save_current_space_and_thread ();
10221
10222               switch_to_program_space_and_thread (sal->pspace);
10223
10224               msym = lookup_minimal_symbol_by_pc (sal->pc);
10225               if (msym.minsym)
10226                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10227
10228               do_cleanups (old_chain);
10229             }
10230         }
10231     }
10232 }
10233
10234 void
10235 break_command (char *arg, int from_tty)
10236 {
10237   break_command_1 (arg, 0, from_tty);
10238 }
10239
10240 void
10241 tbreak_command (char *arg, int from_tty)
10242 {
10243   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10244 }
10245
10246 static void
10247 hbreak_command (char *arg, int from_tty)
10248 {
10249   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10250 }
10251
10252 static void
10253 thbreak_command (char *arg, int from_tty)
10254 {
10255   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10256 }
10257
10258 static void
10259 stop_command (char *arg, int from_tty)
10260 {
10261   printf_filtered (_("Specify the type of breakpoint to set.\n\
10262 Usage: stop in <function | address>\n\
10263        stop at <line>\n"));
10264 }
10265
10266 static void
10267 stopin_command (char *arg, int from_tty)
10268 {
10269   int badInput = 0;
10270
10271   if (arg == (char *) NULL)
10272     badInput = 1;
10273   else if (*arg != '*')
10274     {
10275       char *argptr = arg;
10276       int hasColon = 0;
10277
10278       /* Look for a ':'.  If this is a line number specification, then
10279          say it is bad, otherwise, it should be an address or
10280          function/method name.  */
10281       while (*argptr && !hasColon)
10282         {
10283           hasColon = (*argptr == ':');
10284           argptr++;
10285         }
10286
10287       if (hasColon)
10288         badInput = (*argptr != ':');    /* Not a class::method */
10289       else
10290         badInput = isdigit (*arg);      /* a simple line number */
10291     }
10292
10293   if (badInput)
10294     printf_filtered (_("Usage: stop in <function | address>\n"));
10295   else
10296     break_command_1 (arg, 0, from_tty);
10297 }
10298
10299 static void
10300 stopat_command (char *arg, int from_tty)
10301 {
10302   int badInput = 0;
10303
10304   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10305     badInput = 1;
10306   else
10307     {
10308       char *argptr = arg;
10309       int hasColon = 0;
10310
10311       /* Look for a ':'.  If there is a '::' then get out, otherwise
10312          it is probably a line number.  */
10313       while (*argptr && !hasColon)
10314         {
10315           hasColon = (*argptr == ':');
10316           argptr++;
10317         }
10318
10319       if (hasColon)
10320         badInput = (*argptr == ':');    /* we have class::method */
10321       else
10322         badInput = !isdigit (*arg);     /* not a line number */
10323     }
10324
10325   if (badInput)
10326     printf_filtered (_("Usage: stop at <line>\n"));
10327   else
10328     break_command_1 (arg, 0, from_tty);
10329 }
10330
10331 /* The dynamic printf command is mostly like a regular breakpoint, but
10332    with a prewired command list consisting of a single output command,
10333    built from extra arguments supplied on the dprintf command
10334    line.  */
10335
10336 static void
10337 dprintf_command (char *arg, int from_tty)
10338 {
10339   create_breakpoint (get_current_arch (),
10340                      arg,
10341                      NULL, 0, NULL, 1 /* parse arg */,
10342                      0, bp_dprintf,
10343                      0 /* Ignore count */,
10344                      pending_break_support,
10345                      &dprintf_breakpoint_ops,
10346                      from_tty,
10347                      1 /* enabled */,
10348                      0 /* internal */,
10349                      0);
10350 }
10351
10352 static void
10353 agent_printf_command (char *arg, int from_tty)
10354 {
10355   error (_("May only run agent-printf on the target"));
10356 }
10357
10358 /* Implement the "breakpoint_hit" breakpoint_ops method for
10359    ranged breakpoints.  */
10360
10361 static int
10362 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10363                                   struct address_space *aspace,
10364                                   CORE_ADDR bp_addr,
10365                                   const struct target_waitstatus *ws)
10366 {
10367   if (ws->kind != TARGET_WAITKIND_STOPPED
10368       || ws->value.sig != GDB_SIGNAL_TRAP)
10369     return 0;
10370
10371   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10372                                          bl->length, aspace, bp_addr);
10373 }
10374
10375 /* Implement the "resources_needed" breakpoint_ops method for
10376    ranged breakpoints.  */
10377
10378 static int
10379 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10380 {
10381   return target_ranged_break_num_registers ();
10382 }
10383
10384 /* Implement the "print_it" breakpoint_ops method for
10385    ranged breakpoints.  */
10386
10387 static enum print_stop_action
10388 print_it_ranged_breakpoint (bpstat bs)
10389 {
10390   struct breakpoint *b = bs->breakpoint_at;
10391   struct bp_location *bl = b->loc;
10392   struct ui_out *uiout = current_uiout;
10393
10394   gdb_assert (b->type == bp_hardware_breakpoint);
10395
10396   /* Ranged breakpoints have only one location.  */
10397   gdb_assert (bl && bl->next == NULL);
10398
10399   annotate_breakpoint (b->number);
10400   if (b->disposition == disp_del)
10401     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10402   else
10403     ui_out_text (uiout, "\nRanged breakpoint ");
10404   if (ui_out_is_mi_like_p (uiout))
10405     {
10406       ui_out_field_string (uiout, "reason",
10407                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10408       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10409     }
10410   ui_out_field_int (uiout, "bkptno", b->number);
10411   ui_out_text (uiout, ", ");
10412
10413   return PRINT_SRC_AND_LOC;
10414 }
10415
10416 /* Implement the "print_one" breakpoint_ops method for
10417    ranged breakpoints.  */
10418
10419 static void
10420 print_one_ranged_breakpoint (struct breakpoint *b,
10421                              struct bp_location **last_loc)
10422 {
10423   struct bp_location *bl = b->loc;
10424   struct value_print_options opts;
10425   struct ui_out *uiout = current_uiout;
10426
10427   /* Ranged breakpoints have only one location.  */
10428   gdb_assert (bl && bl->next == NULL);
10429
10430   get_user_print_options (&opts);
10431
10432   if (opts.addressprint)
10433     /* We don't print the address range here, it will be printed later
10434        by print_one_detail_ranged_breakpoint.  */
10435     ui_out_field_skip (uiout, "addr");
10436   annotate_field (5);
10437   print_breakpoint_location (b, bl);
10438   *last_loc = bl;
10439 }
10440
10441 /* Implement the "print_one_detail" breakpoint_ops method for
10442    ranged breakpoints.  */
10443
10444 static void
10445 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10446                                     struct ui_out *uiout)
10447 {
10448   CORE_ADDR address_start, address_end;
10449   struct bp_location *bl = b->loc;
10450   struct ui_file *stb = mem_fileopen ();
10451   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10452
10453   gdb_assert (bl);
10454
10455   address_start = bl->address;
10456   address_end = address_start + bl->length - 1;
10457
10458   ui_out_text (uiout, "\taddress range: ");
10459   fprintf_unfiltered (stb, "[%s, %s]",
10460                       print_core_address (bl->gdbarch, address_start),
10461                       print_core_address (bl->gdbarch, address_end));
10462   ui_out_field_stream (uiout, "addr", stb);
10463   ui_out_text (uiout, "\n");
10464
10465   do_cleanups (cleanup);
10466 }
10467
10468 /* Implement the "print_mention" breakpoint_ops method for
10469    ranged breakpoints.  */
10470
10471 static void
10472 print_mention_ranged_breakpoint (struct breakpoint *b)
10473 {
10474   struct bp_location *bl = b->loc;
10475   struct ui_out *uiout = current_uiout;
10476
10477   gdb_assert (bl);
10478   gdb_assert (b->type == bp_hardware_breakpoint);
10479
10480   if (ui_out_is_mi_like_p (uiout))
10481     return;
10482
10483   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10484                    b->number, paddress (bl->gdbarch, bl->address),
10485                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10486 }
10487
10488 /* Implement the "print_recreate" breakpoint_ops method for
10489    ranged breakpoints.  */
10490
10491 static void
10492 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10493 {
10494   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10495                       b->addr_string_range_end);
10496   print_recreate_thread (b, fp);
10497 }
10498
10499 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10500
10501 static struct breakpoint_ops ranged_breakpoint_ops;
10502
10503 /* Find the address where the end of the breakpoint range should be
10504    placed, given the SAL of the end of the range.  This is so that if
10505    the user provides a line number, the end of the range is set to the
10506    last instruction of the given line.  */
10507
10508 static CORE_ADDR
10509 find_breakpoint_range_end (struct symtab_and_line sal)
10510 {
10511   CORE_ADDR end;
10512
10513   /* If the user provided a PC value, use it.  Otherwise,
10514      find the address of the end of the given location.  */
10515   if (sal.explicit_pc)
10516     end = sal.pc;
10517   else
10518     {
10519       int ret;
10520       CORE_ADDR start;
10521
10522       ret = find_line_pc_range (sal, &start, &end);
10523       if (!ret)
10524         error (_("Could not find location of the end of the range."));
10525
10526       /* find_line_pc_range returns the start of the next line.  */
10527       end--;
10528     }
10529
10530   return end;
10531 }
10532
10533 /* Implement the "break-range" CLI command.  */
10534
10535 static void
10536 break_range_command (char *arg, int from_tty)
10537 {
10538   char *arg_start, *addr_string_start, *addr_string_end;
10539   struct linespec_result canonical_start, canonical_end;
10540   int bp_count, can_use_bp, length;
10541   CORE_ADDR end;
10542   struct breakpoint *b;
10543   struct symtab_and_line sal_start, sal_end;
10544   struct cleanup *cleanup_bkpt;
10545   struct linespec_sals *lsal_start, *lsal_end;
10546
10547   /* We don't support software ranged breakpoints.  */
10548   if (target_ranged_break_num_registers () < 0)
10549     error (_("This target does not support hardware ranged breakpoints."));
10550
10551   bp_count = hw_breakpoint_used_count ();
10552   bp_count += target_ranged_break_num_registers ();
10553   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10554                                                    bp_count, 0);
10555   if (can_use_bp < 0)
10556     error (_("Hardware breakpoints used exceeds limit."));
10557
10558   arg = skip_spaces (arg);
10559   if (arg == NULL || arg[0] == '\0')
10560     error(_("No address range specified."));
10561
10562   init_linespec_result (&canonical_start);
10563
10564   arg_start = arg;
10565   parse_breakpoint_sals (&arg, &canonical_start);
10566
10567   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10568
10569   if (arg[0] != ',')
10570     error (_("Too few arguments."));
10571   else if (VEC_empty (linespec_sals, canonical_start.sals))
10572     error (_("Could not find location of the beginning of the range."));
10573
10574   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10575
10576   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10577       || lsal_start->sals.nelts != 1)
10578     error (_("Cannot create a ranged breakpoint with multiple locations."));
10579
10580   sal_start = lsal_start->sals.sals[0];
10581   addr_string_start = savestring (arg_start, arg - arg_start);
10582   make_cleanup (xfree, addr_string_start);
10583
10584   arg++;        /* Skip the comma.  */
10585   arg = skip_spaces (arg);
10586
10587   /* Parse the end location.  */
10588
10589   init_linespec_result (&canonical_end);
10590   arg_start = arg;
10591
10592   /* We call decode_line_full directly here instead of using
10593      parse_breakpoint_sals because we need to specify the start location's
10594      symtab and line as the default symtab and line for the end of the
10595      range.  This makes it possible to have ranges like "foo.c:27, +14",
10596      where +14 means 14 lines from the start location.  */
10597   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10598                     sal_start.symtab, sal_start.line,
10599                     &canonical_end, NULL, NULL);
10600
10601   make_cleanup_destroy_linespec_result (&canonical_end);
10602
10603   if (VEC_empty (linespec_sals, canonical_end.sals))
10604     error (_("Could not find location of the end of the range."));
10605
10606   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10607   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10608       || lsal_end->sals.nelts != 1)
10609     error (_("Cannot create a ranged breakpoint with multiple locations."));
10610
10611   sal_end = lsal_end->sals.sals[0];
10612   addr_string_end = savestring (arg_start, arg - arg_start);
10613   make_cleanup (xfree, addr_string_end);
10614
10615   end = find_breakpoint_range_end (sal_end);
10616   if (sal_start.pc > end)
10617     error (_("Invalid address range, end precedes start."));
10618
10619   length = end - sal_start.pc + 1;
10620   if (length < 0)
10621     /* Length overflowed.  */
10622     error (_("Address range too large."));
10623   else if (length == 1)
10624     {
10625       /* This range is simple enough to be handled by
10626          the `hbreak' command.  */
10627       hbreak_command (addr_string_start, 1);
10628
10629       do_cleanups (cleanup_bkpt);
10630
10631       return;
10632     }
10633
10634   /* Now set up the breakpoint.  */
10635   b = set_raw_breakpoint (get_current_arch (), sal_start,
10636                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10637   set_breakpoint_count (breakpoint_count + 1);
10638   b->number = breakpoint_count;
10639   b->disposition = disp_donttouch;
10640   b->addr_string = xstrdup (addr_string_start);
10641   b->addr_string_range_end = xstrdup (addr_string_end);
10642   b->loc->length = length;
10643
10644   do_cleanups (cleanup_bkpt);
10645
10646   mention (b);
10647   observer_notify_breakpoint_created (b);
10648   update_global_location_list (1);
10649 }
10650
10651 /*  Return non-zero if EXP is verified as constant.  Returned zero
10652     means EXP is variable.  Also the constant detection may fail for
10653     some constant expressions and in such case still falsely return
10654     zero.  */
10655
10656 static int
10657 watchpoint_exp_is_const (const struct expression *exp)
10658 {
10659   int i = exp->nelts;
10660
10661   while (i > 0)
10662     {
10663       int oplenp, argsp;
10664
10665       /* We are only interested in the descriptor of each element.  */
10666       operator_length (exp, i, &oplenp, &argsp);
10667       i -= oplenp;
10668
10669       switch (exp->elts[i].opcode)
10670         {
10671         case BINOP_ADD:
10672         case BINOP_SUB:
10673         case BINOP_MUL:
10674         case BINOP_DIV:
10675         case BINOP_REM:
10676         case BINOP_MOD:
10677         case BINOP_LSH:
10678         case BINOP_RSH:
10679         case BINOP_LOGICAL_AND:
10680         case BINOP_LOGICAL_OR:
10681         case BINOP_BITWISE_AND:
10682         case BINOP_BITWISE_IOR:
10683         case BINOP_BITWISE_XOR:
10684         case BINOP_EQUAL:
10685         case BINOP_NOTEQUAL:
10686         case BINOP_LESS:
10687         case BINOP_GTR:
10688         case BINOP_LEQ:
10689         case BINOP_GEQ:
10690         case BINOP_REPEAT:
10691         case BINOP_COMMA:
10692         case BINOP_EXP:
10693         case BINOP_MIN:
10694         case BINOP_MAX:
10695         case BINOP_INTDIV:
10696         case BINOP_CONCAT:
10697         case TERNOP_COND:
10698         case TERNOP_SLICE:
10699
10700         case OP_LONG:
10701         case OP_DOUBLE:
10702         case OP_DECFLOAT:
10703         case OP_LAST:
10704         case OP_COMPLEX:
10705         case OP_STRING:
10706         case OP_ARRAY:
10707         case OP_TYPE:
10708         case OP_TYPEOF:
10709         case OP_DECLTYPE:
10710         case OP_TYPEID:
10711         case OP_NAME:
10712         case OP_OBJC_NSSTRING:
10713
10714         case UNOP_NEG:
10715         case UNOP_LOGICAL_NOT:
10716         case UNOP_COMPLEMENT:
10717         case UNOP_ADDR:
10718         case UNOP_HIGH:
10719         case UNOP_CAST:
10720
10721         case UNOP_CAST_TYPE:
10722         case UNOP_REINTERPRET_CAST:
10723         case UNOP_DYNAMIC_CAST:
10724           /* Unary, binary and ternary operators: We have to check
10725              their operands.  If they are constant, then so is the
10726              result of that operation.  For instance, if A and B are
10727              determined to be constants, then so is "A + B".
10728
10729              UNOP_IND is one exception to the rule above, because the
10730              value of *ADDR is not necessarily a constant, even when
10731              ADDR is.  */
10732           break;
10733
10734         case OP_VAR_VALUE:
10735           /* Check whether the associated symbol is a constant.
10736
10737              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10738              possible that a buggy compiler could mark a variable as
10739              constant even when it is not, and TYPE_CONST would return
10740              true in this case, while SYMBOL_CLASS wouldn't.
10741
10742              We also have to check for function symbols because they
10743              are always constant.  */
10744           {
10745             struct symbol *s = exp->elts[i + 2].symbol;
10746
10747             if (SYMBOL_CLASS (s) != LOC_BLOCK
10748                 && SYMBOL_CLASS (s) != LOC_CONST
10749                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10750               return 0;
10751             break;
10752           }
10753
10754         /* The default action is to return 0 because we are using
10755            the optimistic approach here: If we don't know something,
10756            then it is not a constant.  */
10757         default:
10758           return 0;
10759         }
10760     }
10761
10762   return 1;
10763 }
10764
10765 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10766
10767 static void
10768 dtor_watchpoint (struct breakpoint *self)
10769 {
10770   struct watchpoint *w = (struct watchpoint *) self;
10771
10772   xfree (w->cond_exp);
10773   xfree (w->exp);
10774   xfree (w->exp_string);
10775   xfree (w->exp_string_reparse);
10776   value_free (w->val);
10777
10778   base_breakpoint_ops.dtor (self);
10779 }
10780
10781 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10782
10783 static void
10784 re_set_watchpoint (struct breakpoint *b)
10785 {
10786   struct watchpoint *w = (struct watchpoint *) b;
10787
10788   /* Watchpoint can be either on expression using entirely global
10789      variables, or it can be on local variables.
10790
10791      Watchpoints of the first kind are never auto-deleted, and even
10792      persist across program restarts.  Since they can use variables
10793      from shared libraries, we need to reparse expression as libraries
10794      are loaded and unloaded.
10795
10796      Watchpoints on local variables can also change meaning as result
10797      of solib event.  For example, if a watchpoint uses both a local
10798      and a global variables in expression, it's a local watchpoint,
10799      but unloading of a shared library will make the expression
10800      invalid.  This is not a very common use case, but we still
10801      re-evaluate expression, to avoid surprises to the user.
10802
10803      Note that for local watchpoints, we re-evaluate it only if
10804      watchpoints frame id is still valid.  If it's not, it means the
10805      watchpoint is out of scope and will be deleted soon.  In fact,
10806      I'm not sure we'll ever be called in this case.
10807
10808      If a local watchpoint's frame id is still valid, then
10809      w->exp_valid_block is likewise valid, and we can safely use it.
10810
10811      Don't do anything about disabled watchpoints, since they will be
10812      reevaluated again when enabled.  */
10813   update_watchpoint (w, 1 /* reparse */);
10814 }
10815
10816 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10817
10818 static int
10819 insert_watchpoint (struct bp_location *bl)
10820 {
10821   struct watchpoint *w = (struct watchpoint *) bl->owner;
10822   int length = w->exact ? 1 : bl->length;
10823
10824   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10825                                    w->cond_exp);
10826 }
10827
10828 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10829
10830 static int
10831 remove_watchpoint (struct bp_location *bl)
10832 {
10833   struct watchpoint *w = (struct watchpoint *) bl->owner;
10834   int length = w->exact ? 1 : bl->length;
10835
10836   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10837                                    w->cond_exp);
10838 }
10839
10840 static int
10841 breakpoint_hit_watchpoint (const struct bp_location *bl,
10842                            struct address_space *aspace, CORE_ADDR bp_addr,
10843                            const struct target_waitstatus *ws)
10844 {
10845   struct breakpoint *b = bl->owner;
10846   struct watchpoint *w = (struct watchpoint *) b;
10847
10848   /* Continuable hardware watchpoints are treated as non-existent if the
10849      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10850      some data address).  Otherwise gdb won't stop on a break instruction
10851      in the code (not from a breakpoint) when a hardware watchpoint has
10852      been defined.  Also skip watchpoints which we know did not trigger
10853      (did not match the data address).  */
10854   if (is_hardware_watchpoint (b)
10855       && w->watchpoint_triggered == watch_triggered_no)
10856     return 0;
10857
10858   return 1;
10859 }
10860
10861 static void
10862 check_status_watchpoint (bpstat bs)
10863 {
10864   gdb_assert (is_watchpoint (bs->breakpoint_at));
10865
10866   bpstat_check_watchpoint (bs);
10867 }
10868
10869 /* Implement the "resources_needed" breakpoint_ops method for
10870    hardware watchpoints.  */
10871
10872 static int
10873 resources_needed_watchpoint (const struct bp_location *bl)
10874 {
10875   struct watchpoint *w = (struct watchpoint *) bl->owner;
10876   int length = w->exact? 1 : bl->length;
10877
10878   return target_region_ok_for_hw_watchpoint (bl->address, length);
10879 }
10880
10881 /* Implement the "works_in_software_mode" breakpoint_ops method for
10882    hardware watchpoints.  */
10883
10884 static int
10885 works_in_software_mode_watchpoint (const struct breakpoint *b)
10886 {
10887   /* Read and access watchpoints only work with hardware support.  */
10888   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10889 }
10890
10891 static enum print_stop_action
10892 print_it_watchpoint (bpstat bs)
10893 {
10894   struct cleanup *old_chain;
10895   struct breakpoint *b;
10896   struct ui_file *stb;
10897   enum print_stop_action result;
10898   struct watchpoint *w;
10899   struct ui_out *uiout = current_uiout;
10900
10901   gdb_assert (bs->bp_location_at != NULL);
10902
10903   b = bs->breakpoint_at;
10904   w = (struct watchpoint *) b;
10905
10906   stb = mem_fileopen ();
10907   old_chain = make_cleanup_ui_file_delete (stb);
10908
10909   switch (b->type)
10910     {
10911     case bp_watchpoint:
10912     case bp_hardware_watchpoint:
10913       annotate_watchpoint (b->number);
10914       if (ui_out_is_mi_like_p (uiout))
10915         ui_out_field_string
10916           (uiout, "reason",
10917            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10918       mention (b);
10919       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10920       ui_out_text (uiout, "\nOld value = ");
10921       watchpoint_value_print (bs->old_val, stb);
10922       ui_out_field_stream (uiout, "old", stb);
10923       ui_out_text (uiout, "\nNew value = ");
10924       watchpoint_value_print (w->val, stb);
10925       ui_out_field_stream (uiout, "new", stb);
10926       ui_out_text (uiout, "\n");
10927       /* More than one watchpoint may have been triggered.  */
10928       result = PRINT_UNKNOWN;
10929       break;
10930
10931     case bp_read_watchpoint:
10932       if (ui_out_is_mi_like_p (uiout))
10933         ui_out_field_string
10934           (uiout, "reason",
10935            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10936       mention (b);
10937       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10938       ui_out_text (uiout, "\nValue = ");
10939       watchpoint_value_print (w->val, stb);
10940       ui_out_field_stream (uiout, "value", stb);
10941       ui_out_text (uiout, "\n");
10942       result = PRINT_UNKNOWN;
10943       break;
10944
10945     case bp_access_watchpoint:
10946       if (bs->old_val != NULL)
10947         {
10948           annotate_watchpoint (b->number);
10949           if (ui_out_is_mi_like_p (uiout))
10950             ui_out_field_string
10951               (uiout, "reason",
10952                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10953           mention (b);
10954           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10955           ui_out_text (uiout, "\nOld value = ");
10956           watchpoint_value_print (bs->old_val, stb);
10957           ui_out_field_stream (uiout, "old", stb);
10958           ui_out_text (uiout, "\nNew value = ");
10959         }
10960       else
10961         {
10962           mention (b);
10963           if (ui_out_is_mi_like_p (uiout))
10964             ui_out_field_string
10965               (uiout, "reason",
10966                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10967           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10968           ui_out_text (uiout, "\nValue = ");
10969         }
10970       watchpoint_value_print (w->val, stb);
10971       ui_out_field_stream (uiout, "new", stb);
10972       ui_out_text (uiout, "\n");
10973       result = PRINT_UNKNOWN;
10974       break;
10975     default:
10976       result = PRINT_UNKNOWN;
10977     }
10978
10979   do_cleanups (old_chain);
10980   return result;
10981 }
10982
10983 /* Implement the "print_mention" breakpoint_ops method for hardware
10984    watchpoints.  */
10985
10986 static void
10987 print_mention_watchpoint (struct breakpoint *b)
10988 {
10989   struct cleanup *ui_out_chain;
10990   struct watchpoint *w = (struct watchpoint *) b;
10991   struct ui_out *uiout = current_uiout;
10992
10993   switch (b->type)
10994     {
10995     case bp_watchpoint:
10996       ui_out_text (uiout, "Watchpoint ");
10997       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10998       break;
10999     case bp_hardware_watchpoint:
11000       ui_out_text (uiout, "Hardware watchpoint ");
11001       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11002       break;
11003     case bp_read_watchpoint:
11004       ui_out_text (uiout, "Hardware read watchpoint ");
11005       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11006       break;
11007     case bp_access_watchpoint:
11008       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11009       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11010       break;
11011     default:
11012       internal_error (__FILE__, __LINE__,
11013                       _("Invalid hardware watchpoint type."));
11014     }
11015
11016   ui_out_field_int (uiout, "number", b->number);
11017   ui_out_text (uiout, ": ");
11018   ui_out_field_string (uiout, "exp", w->exp_string);
11019   do_cleanups (ui_out_chain);
11020 }
11021
11022 /* Implement the "print_recreate" breakpoint_ops method for
11023    watchpoints.  */
11024
11025 static void
11026 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11027 {
11028   struct watchpoint *w = (struct watchpoint *) b;
11029
11030   switch (b->type)
11031     {
11032     case bp_watchpoint:
11033     case bp_hardware_watchpoint:
11034       fprintf_unfiltered (fp, "watch");
11035       break;
11036     case bp_read_watchpoint:
11037       fprintf_unfiltered (fp, "rwatch");
11038       break;
11039     case bp_access_watchpoint:
11040       fprintf_unfiltered (fp, "awatch");
11041       break;
11042     default:
11043       internal_error (__FILE__, __LINE__,
11044                       _("Invalid watchpoint type."));
11045     }
11046
11047   fprintf_unfiltered (fp, " %s", w->exp_string);
11048   print_recreate_thread (b, fp);
11049 }
11050
11051 /* Implement the "explains_signal" breakpoint_ops method for
11052    watchpoints.  */
11053
11054 static int
11055 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11056 {
11057   /* A software watchpoint cannot cause a signal other than
11058      GDB_SIGNAL_TRAP.  */
11059   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11060     return 0;
11061
11062   return 1;
11063 }
11064
11065 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11066
11067 static struct breakpoint_ops watchpoint_breakpoint_ops;
11068
11069 /* Implement the "insert" breakpoint_ops method for
11070    masked hardware watchpoints.  */
11071
11072 static int
11073 insert_masked_watchpoint (struct bp_location *bl)
11074 {
11075   struct watchpoint *w = (struct watchpoint *) bl->owner;
11076
11077   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11078                                         bl->watchpoint_type);
11079 }
11080
11081 /* Implement the "remove" breakpoint_ops method for
11082    masked hardware watchpoints.  */
11083
11084 static int
11085 remove_masked_watchpoint (struct bp_location *bl)
11086 {
11087   struct watchpoint *w = (struct watchpoint *) bl->owner;
11088
11089   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11090                                         bl->watchpoint_type);
11091 }
11092
11093 /* Implement the "resources_needed" breakpoint_ops method for
11094    masked hardware watchpoints.  */
11095
11096 static int
11097 resources_needed_masked_watchpoint (const struct bp_location *bl)
11098 {
11099   struct watchpoint *w = (struct watchpoint *) bl->owner;
11100
11101   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11102 }
11103
11104 /* Implement the "works_in_software_mode" breakpoint_ops method for
11105    masked hardware watchpoints.  */
11106
11107 static int
11108 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11109 {
11110   return 0;
11111 }
11112
11113 /* Implement the "print_it" breakpoint_ops method for
11114    masked hardware watchpoints.  */
11115
11116 static enum print_stop_action
11117 print_it_masked_watchpoint (bpstat bs)
11118 {
11119   struct breakpoint *b = bs->breakpoint_at;
11120   struct ui_out *uiout = current_uiout;
11121
11122   /* Masked watchpoints have only one location.  */
11123   gdb_assert (b->loc && b->loc->next == NULL);
11124
11125   switch (b->type)
11126     {
11127     case bp_hardware_watchpoint:
11128       annotate_watchpoint (b->number);
11129       if (ui_out_is_mi_like_p (uiout))
11130         ui_out_field_string
11131           (uiout, "reason",
11132            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11133       break;
11134
11135     case bp_read_watchpoint:
11136       if (ui_out_is_mi_like_p (uiout))
11137         ui_out_field_string
11138           (uiout, "reason",
11139            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11140       break;
11141
11142     case bp_access_watchpoint:
11143       if (ui_out_is_mi_like_p (uiout))
11144         ui_out_field_string
11145           (uiout, "reason",
11146            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11147       break;
11148     default:
11149       internal_error (__FILE__, __LINE__,
11150                       _("Invalid hardware watchpoint type."));
11151     }
11152
11153   mention (b);
11154   ui_out_text (uiout, _("\n\
11155 Check the underlying instruction at PC for the memory\n\
11156 address and value which triggered this watchpoint.\n"));
11157   ui_out_text (uiout, "\n");
11158
11159   /* More than one watchpoint may have been triggered.  */
11160   return PRINT_UNKNOWN;
11161 }
11162
11163 /* Implement the "print_one_detail" breakpoint_ops method for
11164    masked hardware watchpoints.  */
11165
11166 static void
11167 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11168                                     struct ui_out *uiout)
11169 {
11170   struct watchpoint *w = (struct watchpoint *) b;
11171
11172   /* Masked watchpoints have only one location.  */
11173   gdb_assert (b->loc && b->loc->next == NULL);
11174
11175   ui_out_text (uiout, "\tmask ");
11176   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11177   ui_out_text (uiout, "\n");
11178 }
11179
11180 /* Implement the "print_mention" breakpoint_ops method for
11181    masked hardware watchpoints.  */
11182
11183 static void
11184 print_mention_masked_watchpoint (struct breakpoint *b)
11185 {
11186   struct watchpoint *w = (struct watchpoint *) b;
11187   struct ui_out *uiout = current_uiout;
11188   struct cleanup *ui_out_chain;
11189
11190   switch (b->type)
11191     {
11192     case bp_hardware_watchpoint:
11193       ui_out_text (uiout, "Masked hardware watchpoint ");
11194       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11195       break;
11196     case bp_read_watchpoint:
11197       ui_out_text (uiout, "Masked hardware read watchpoint ");
11198       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11199       break;
11200     case bp_access_watchpoint:
11201       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11202       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11203       break;
11204     default:
11205       internal_error (__FILE__, __LINE__,
11206                       _("Invalid hardware watchpoint type."));
11207     }
11208
11209   ui_out_field_int (uiout, "number", b->number);
11210   ui_out_text (uiout, ": ");
11211   ui_out_field_string (uiout, "exp", w->exp_string);
11212   do_cleanups (ui_out_chain);
11213 }
11214
11215 /* Implement the "print_recreate" breakpoint_ops method for
11216    masked hardware watchpoints.  */
11217
11218 static void
11219 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11220 {
11221   struct watchpoint *w = (struct watchpoint *) b;
11222   char tmp[40];
11223
11224   switch (b->type)
11225     {
11226     case bp_hardware_watchpoint:
11227       fprintf_unfiltered (fp, "watch");
11228       break;
11229     case bp_read_watchpoint:
11230       fprintf_unfiltered (fp, "rwatch");
11231       break;
11232     case bp_access_watchpoint:
11233       fprintf_unfiltered (fp, "awatch");
11234       break;
11235     default:
11236       internal_error (__FILE__, __LINE__,
11237                       _("Invalid hardware watchpoint type."));
11238     }
11239
11240   sprintf_vma (tmp, w->hw_wp_mask);
11241   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11242   print_recreate_thread (b, fp);
11243 }
11244
11245 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11246
11247 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11248
11249 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11250
11251 static int
11252 is_masked_watchpoint (const struct breakpoint *b)
11253 {
11254   return b->ops == &masked_watchpoint_breakpoint_ops;
11255 }
11256
11257 /* accessflag:  hw_write:  watch write, 
11258                 hw_read:   watch read, 
11259                 hw_access: watch access (read or write) */
11260 static void
11261 watch_command_1 (const char *arg, int accessflag, int from_tty,
11262                  int just_location, int internal)
11263 {
11264   volatile struct gdb_exception e;
11265   struct breakpoint *b, *scope_breakpoint = NULL;
11266   struct expression *exp;
11267   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11268   struct value *val, *mark, *result;
11269   int saved_bitpos = 0, saved_bitsize = 0;
11270   struct frame_info *frame;
11271   const char *exp_start = NULL;
11272   const char *exp_end = NULL;
11273   const char *tok, *end_tok;
11274   int toklen = -1;
11275   const char *cond_start = NULL;
11276   const char *cond_end = NULL;
11277   enum bptype bp_type;
11278   int thread = -1;
11279   int pc = 0;
11280   /* Flag to indicate whether we are going to use masks for
11281      the hardware watchpoint.  */
11282   int use_mask = 0;
11283   CORE_ADDR mask = 0;
11284   struct watchpoint *w;
11285   char *expression;
11286   struct cleanup *back_to;
11287
11288   /* Make sure that we actually have parameters to parse.  */
11289   if (arg != NULL && arg[0] != '\0')
11290     {
11291       const char *value_start;
11292
11293       exp_end = arg + strlen (arg);
11294
11295       /* Look for "parameter value" pairs at the end
11296          of the arguments string.  */
11297       for (tok = exp_end - 1; tok > arg; tok--)
11298         {
11299           /* Skip whitespace at the end of the argument list.  */
11300           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11301             tok--;
11302
11303           /* Find the beginning of the last token.
11304              This is the value of the parameter.  */
11305           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11306             tok--;
11307           value_start = tok + 1;
11308
11309           /* Skip whitespace.  */
11310           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11311             tok--;
11312
11313           end_tok = tok;
11314
11315           /* Find the beginning of the second to last token.
11316              This is the parameter itself.  */
11317           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11318             tok--;
11319           tok++;
11320           toklen = end_tok - tok + 1;
11321
11322           if (toklen == 6 && !strncmp (tok, "thread", 6))
11323             {
11324               /* At this point we've found a "thread" token, which means
11325                  the user is trying to set a watchpoint that triggers
11326                  only in a specific thread.  */
11327               char *endp;
11328
11329               if (thread != -1)
11330                 error(_("You can specify only one thread."));
11331
11332               /* Extract the thread ID from the next token.  */
11333               thread = strtol (value_start, &endp, 0);
11334
11335               /* Check if the user provided a valid numeric value for the
11336                  thread ID.  */
11337               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11338                 error (_("Invalid thread ID specification %s."), value_start);
11339
11340               /* Check if the thread actually exists.  */
11341               if (!valid_thread_id (thread))
11342                 invalid_thread_id_error (thread);
11343             }
11344           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11345             {
11346               /* We've found a "mask" token, which means the user wants to
11347                  create a hardware watchpoint that is going to have the mask
11348                  facility.  */
11349               struct value *mask_value, *mark;
11350
11351               if (use_mask)
11352                 error(_("You can specify only one mask."));
11353
11354               use_mask = just_location = 1;
11355
11356               mark = value_mark ();
11357               mask_value = parse_to_comma_and_eval (&value_start);
11358               mask = value_as_address (mask_value);
11359               value_free_to_mark (mark);
11360             }
11361           else
11362             /* We didn't recognize what we found.  We should stop here.  */
11363             break;
11364
11365           /* Truncate the string and get rid of the "parameter value" pair before
11366              the arguments string is parsed by the parse_exp_1 function.  */
11367           exp_end = tok;
11368         }
11369     }
11370   else
11371     exp_end = arg;
11372
11373   /* Parse the rest of the arguments.  From here on out, everything
11374      is in terms of a newly allocated string instead of the original
11375      ARG.  */
11376   innermost_block = NULL;
11377   expression = savestring (arg, exp_end - arg);
11378   back_to = make_cleanup (xfree, expression);
11379   exp_start = arg = expression;
11380   exp = parse_exp_1 (&arg, 0, 0, 0);
11381   exp_end = arg;
11382   /* Remove trailing whitespace from the expression before saving it.
11383      This makes the eventual display of the expression string a bit
11384      prettier.  */
11385   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11386     --exp_end;
11387
11388   /* Checking if the expression is not constant.  */
11389   if (watchpoint_exp_is_const (exp))
11390     {
11391       int len;
11392
11393       len = exp_end - exp_start;
11394       while (len > 0 && isspace (exp_start[len - 1]))
11395         len--;
11396       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11397     }
11398
11399   exp_valid_block = innermost_block;
11400   mark = value_mark ();
11401   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11402
11403   if (val != NULL && just_location)
11404     {
11405       saved_bitpos = value_bitpos (val);
11406       saved_bitsize = value_bitsize (val);
11407     }
11408
11409   if (just_location)
11410     {
11411       int ret;
11412
11413       exp_valid_block = NULL;
11414       val = value_addr (result);
11415       release_value (val);
11416       value_free_to_mark (mark);
11417
11418       if (use_mask)
11419         {
11420           ret = target_masked_watch_num_registers (value_as_address (val),
11421                                                    mask);
11422           if (ret == -1)
11423             error (_("This target does not support masked watchpoints."));
11424           else if (ret == -2)
11425             error (_("Invalid mask or memory region."));
11426         }
11427     }
11428   else if (val != NULL)
11429     release_value (val);
11430
11431   tok = skip_spaces_const (arg);
11432   end_tok = skip_to_space_const (tok);
11433
11434   toklen = end_tok - tok;
11435   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11436     {
11437       struct expression *cond;
11438
11439       innermost_block = NULL;
11440       tok = cond_start = end_tok + 1;
11441       cond = parse_exp_1 (&tok, 0, 0, 0);
11442
11443       /* The watchpoint expression may not be local, but the condition
11444          may still be.  E.g.: `watch global if local > 0'.  */
11445       cond_exp_valid_block = innermost_block;
11446
11447       xfree (cond);
11448       cond_end = tok;
11449     }
11450   if (*tok)
11451     error (_("Junk at end of command."));
11452
11453   frame = block_innermost_frame (exp_valid_block);
11454
11455   /* If the expression is "local", then set up a "watchpoint scope"
11456      breakpoint at the point where we've left the scope of the watchpoint
11457      expression.  Create the scope breakpoint before the watchpoint, so
11458      that we will encounter it first in bpstat_stop_status.  */
11459   if (exp_valid_block && frame)
11460     {
11461       if (frame_id_p (frame_unwind_caller_id (frame)))
11462         {
11463           scope_breakpoint
11464             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11465                                           frame_unwind_caller_pc (frame),
11466                                           bp_watchpoint_scope,
11467                                           &momentary_breakpoint_ops);
11468
11469           scope_breakpoint->enable_state = bp_enabled;
11470
11471           /* Automatically delete the breakpoint when it hits.  */
11472           scope_breakpoint->disposition = disp_del;
11473
11474           /* Only break in the proper frame (help with recursion).  */
11475           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11476
11477           /* Set the address at which we will stop.  */
11478           scope_breakpoint->loc->gdbarch
11479             = frame_unwind_caller_arch (frame);
11480           scope_breakpoint->loc->requested_address
11481             = frame_unwind_caller_pc (frame);
11482           scope_breakpoint->loc->address
11483             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11484                                          scope_breakpoint->loc->requested_address,
11485                                          scope_breakpoint->type);
11486         }
11487     }
11488
11489   /* Now set up the breakpoint.  We create all watchpoints as hardware
11490      watchpoints here even if hardware watchpoints are turned off, a call
11491      to update_watchpoint later in this function will cause the type to
11492      drop back to bp_watchpoint (software watchpoint) if required.  */
11493
11494   if (accessflag == hw_read)
11495     bp_type = bp_read_watchpoint;
11496   else if (accessflag == hw_access)
11497     bp_type = bp_access_watchpoint;
11498   else
11499     bp_type = bp_hardware_watchpoint;
11500
11501   w = XCNEW (struct watchpoint);
11502   b = &w->base;
11503   if (use_mask)
11504     init_raw_breakpoint_without_location (b, NULL, bp_type,
11505                                           &masked_watchpoint_breakpoint_ops);
11506   else
11507     init_raw_breakpoint_without_location (b, NULL, bp_type,
11508                                           &watchpoint_breakpoint_ops);
11509   b->thread = thread;
11510   b->disposition = disp_donttouch;
11511   b->pspace = current_program_space;
11512   w->exp = exp;
11513   w->exp_valid_block = exp_valid_block;
11514   w->cond_exp_valid_block = cond_exp_valid_block;
11515   if (just_location)
11516     {
11517       struct type *t = value_type (val);
11518       CORE_ADDR addr = value_as_address (val);
11519       char *name;
11520
11521       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11522       name = type_to_string (t);
11523
11524       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11525                                           core_addr_to_string (addr));
11526       xfree (name);
11527
11528       w->exp_string = xstrprintf ("-location %.*s",
11529                                   (int) (exp_end - exp_start), exp_start);
11530
11531       /* The above expression is in C.  */
11532       b->language = language_c;
11533     }
11534   else
11535     w->exp_string = savestring (exp_start, exp_end - exp_start);
11536
11537   if (use_mask)
11538     {
11539       w->hw_wp_mask = mask;
11540     }
11541   else
11542     {
11543       w->val = val;
11544       w->val_bitpos = saved_bitpos;
11545       w->val_bitsize = saved_bitsize;
11546       w->val_valid = 1;
11547     }
11548
11549   if (cond_start)
11550     b->cond_string = savestring (cond_start, cond_end - cond_start);
11551   else
11552     b->cond_string = 0;
11553
11554   if (frame)
11555     {
11556       w->watchpoint_frame = get_frame_id (frame);
11557       w->watchpoint_thread = inferior_ptid;
11558     }
11559   else
11560     {
11561       w->watchpoint_frame = null_frame_id;
11562       w->watchpoint_thread = null_ptid;
11563     }
11564
11565   if (scope_breakpoint != NULL)
11566     {
11567       /* The scope breakpoint is related to the watchpoint.  We will
11568          need to act on them together.  */
11569       b->related_breakpoint = scope_breakpoint;
11570       scope_breakpoint->related_breakpoint = b;
11571     }
11572
11573   if (!just_location)
11574     value_free_to_mark (mark);
11575
11576   TRY_CATCH (e, RETURN_MASK_ALL)
11577     {
11578       /* Finally update the new watchpoint.  This creates the locations
11579          that should be inserted.  */
11580       update_watchpoint (w, 1);
11581     }
11582   if (e.reason < 0)
11583     {
11584       delete_breakpoint (b);
11585       throw_exception (e);
11586     }
11587
11588   install_breakpoint (internal, b, 1);
11589   do_cleanups (back_to);
11590 }
11591
11592 /* Return count of debug registers needed to watch the given expression.
11593    If the watchpoint cannot be handled in hardware return zero.  */
11594
11595 static int
11596 can_use_hardware_watchpoint (struct value *v)
11597 {
11598   int found_memory_cnt = 0;
11599   struct value *head = v;
11600
11601   /* Did the user specifically forbid us to use hardware watchpoints? */
11602   if (!can_use_hw_watchpoints)
11603     return 0;
11604
11605   /* Make sure that the value of the expression depends only upon
11606      memory contents, and values computed from them within GDB.  If we
11607      find any register references or function calls, we can't use a
11608      hardware watchpoint.
11609
11610      The idea here is that evaluating an expression generates a series
11611      of values, one holding the value of every subexpression.  (The
11612      expression a*b+c has five subexpressions: a, b, a*b, c, and
11613      a*b+c.)  GDB's values hold almost enough information to establish
11614      the criteria given above --- they identify memory lvalues,
11615      register lvalues, computed values, etcetera.  So we can evaluate
11616      the expression, and then scan the chain of values that leaves
11617      behind to decide whether we can detect any possible change to the
11618      expression's final value using only hardware watchpoints.
11619
11620      However, I don't think that the values returned by inferior
11621      function calls are special in any way.  So this function may not
11622      notice that an expression involving an inferior function call
11623      can't be watched with hardware watchpoints.  FIXME.  */
11624   for (; v; v = value_next (v))
11625     {
11626       if (VALUE_LVAL (v) == lval_memory)
11627         {
11628           if (v != head && value_lazy (v))
11629             /* A lazy memory lvalue in the chain is one that GDB never
11630                needed to fetch; we either just used its address (e.g.,
11631                `a' in `a.b') or we never needed it at all (e.g., `a'
11632                in `a,b').  This doesn't apply to HEAD; if that is
11633                lazy then it was not readable, but watch it anyway.  */
11634             ;
11635           else
11636             {
11637               /* Ahh, memory we actually used!  Check if we can cover
11638                  it with hardware watchpoints.  */
11639               struct type *vtype = check_typedef (value_type (v));
11640
11641               /* We only watch structs and arrays if user asked for it
11642                  explicitly, never if they just happen to appear in a
11643                  middle of some value chain.  */
11644               if (v == head
11645                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11646                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11647                 {
11648                   CORE_ADDR vaddr = value_address (v);
11649                   int len;
11650                   int num_regs;
11651
11652                   len = (target_exact_watchpoints
11653                          && is_scalar_type_recursive (vtype))?
11654                     1 : TYPE_LENGTH (value_type (v));
11655
11656                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11657                   if (!num_regs)
11658                     return 0;
11659                   else
11660                     found_memory_cnt += num_regs;
11661                 }
11662             }
11663         }
11664       else if (VALUE_LVAL (v) != not_lval
11665                && deprecated_value_modifiable (v) == 0)
11666         return 0;       /* These are values from the history (e.g., $1).  */
11667       else if (VALUE_LVAL (v) == lval_register)
11668         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11669     }
11670
11671   /* The expression itself looks suitable for using a hardware
11672      watchpoint, but give the target machine a chance to reject it.  */
11673   return found_memory_cnt;
11674 }
11675
11676 void
11677 watch_command_wrapper (char *arg, int from_tty, int internal)
11678 {
11679   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11680 }
11681
11682 /* A helper function that looks for the "-location" argument and then
11683    calls watch_command_1.  */
11684
11685 static void
11686 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11687 {
11688   int just_location = 0;
11689
11690   if (arg
11691       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11692           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11693     {
11694       arg = skip_spaces (arg);
11695       just_location = 1;
11696     }
11697
11698   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11699 }
11700
11701 static void
11702 watch_command (char *arg, int from_tty)
11703 {
11704   watch_maybe_just_location (arg, hw_write, from_tty);
11705 }
11706
11707 void
11708 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11709 {
11710   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11711 }
11712
11713 static void
11714 rwatch_command (char *arg, int from_tty)
11715 {
11716   watch_maybe_just_location (arg, hw_read, from_tty);
11717 }
11718
11719 void
11720 awatch_command_wrapper (char *arg, int from_tty, int internal)
11721 {
11722   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11723 }
11724
11725 static void
11726 awatch_command (char *arg, int from_tty)
11727 {
11728   watch_maybe_just_location (arg, hw_access, from_tty);
11729 }
11730 \f
11731
11732 /* Helper routines for the until_command routine in infcmd.c.  Here
11733    because it uses the mechanisms of breakpoints.  */
11734
11735 struct until_break_command_continuation_args
11736 {
11737   struct breakpoint *breakpoint;
11738   struct breakpoint *breakpoint2;
11739   int thread_num;
11740 };
11741
11742 /* This function is called by fetch_inferior_event via the
11743    cmd_continuation pointer, to complete the until command.  It takes
11744    care of cleaning up the temporary breakpoints set up by the until
11745    command.  */
11746 static void
11747 until_break_command_continuation (void *arg, int err)
11748 {
11749   struct until_break_command_continuation_args *a = arg;
11750
11751   delete_breakpoint (a->breakpoint);
11752   if (a->breakpoint2)
11753     delete_breakpoint (a->breakpoint2);
11754   delete_longjmp_breakpoint (a->thread_num);
11755 }
11756
11757 void
11758 until_break_command (char *arg, int from_tty, int anywhere)
11759 {
11760   struct symtabs_and_lines sals;
11761   struct symtab_and_line sal;
11762   struct frame_info *frame;
11763   struct gdbarch *frame_gdbarch;
11764   struct frame_id stack_frame_id;
11765   struct frame_id caller_frame_id;
11766   struct breakpoint *breakpoint;
11767   struct breakpoint *breakpoint2 = NULL;
11768   struct cleanup *old_chain;
11769   int thread;
11770   struct thread_info *tp;
11771
11772   clear_proceed_status (0);
11773
11774   /* Set a breakpoint where the user wants it and at return from
11775      this function.  */
11776
11777   if (last_displayed_sal_is_valid ())
11778     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11779                           get_last_displayed_symtab (),
11780                           get_last_displayed_line ());
11781   else
11782     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11783                           (struct symtab *) NULL, 0);
11784
11785   if (sals.nelts != 1)
11786     error (_("Couldn't get information on specified line."));
11787
11788   sal = sals.sals[0];
11789   xfree (sals.sals);    /* malloc'd, so freed.  */
11790
11791   if (*arg)
11792     error (_("Junk at end of arguments."));
11793
11794   resolve_sal_pc (&sal);
11795
11796   tp = inferior_thread ();
11797   thread = tp->num;
11798
11799   old_chain = make_cleanup (null_cleanup, NULL);
11800
11801   /* Note linespec handling above invalidates the frame chain.
11802      Installing a breakpoint also invalidates the frame chain (as it
11803      may need to switch threads), so do any frame handling before
11804      that.  */
11805
11806   frame = get_selected_frame (NULL);
11807   frame_gdbarch = get_frame_arch (frame);
11808   stack_frame_id = get_stack_frame_id (frame);
11809   caller_frame_id = frame_unwind_caller_id (frame);
11810
11811   /* Keep within the current frame, or in frames called by the current
11812      one.  */
11813
11814   if (frame_id_p (caller_frame_id))
11815     {
11816       struct symtab_and_line sal2;
11817
11818       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11819       sal2.pc = frame_unwind_caller_pc (frame);
11820       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11821                                               sal2,
11822                                               caller_frame_id,
11823                                               bp_until);
11824       make_cleanup_delete_breakpoint (breakpoint2);
11825
11826       set_longjmp_breakpoint (tp, caller_frame_id);
11827       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11828     }
11829
11830   /* set_momentary_breakpoint could invalidate FRAME.  */
11831   frame = NULL;
11832
11833   if (anywhere)
11834     /* If the user told us to continue until a specified location,
11835        we don't specify a frame at which we need to stop.  */
11836     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11837                                            null_frame_id, bp_until);
11838   else
11839     /* Otherwise, specify the selected frame, because we want to stop
11840        only at the very same frame.  */
11841     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11842                                            stack_frame_id, bp_until);
11843   make_cleanup_delete_breakpoint (breakpoint);
11844
11845   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11846
11847   /* If we are running asynchronously, and proceed call above has
11848      actually managed to start the target, arrange for breakpoints to
11849      be deleted when the target stops.  Otherwise, we're already
11850      stopped and delete breakpoints via cleanup chain.  */
11851
11852   if (target_can_async_p () && is_running (inferior_ptid))
11853     {
11854       struct until_break_command_continuation_args *args;
11855       args = xmalloc (sizeof (*args));
11856
11857       args->breakpoint = breakpoint;
11858       args->breakpoint2 = breakpoint2;
11859       args->thread_num = thread;
11860
11861       discard_cleanups (old_chain);
11862       add_continuation (inferior_thread (),
11863                         until_break_command_continuation, args,
11864                         xfree);
11865     }
11866   else
11867     do_cleanups (old_chain);
11868 }
11869
11870 /* This function attempts to parse an optional "if <cond>" clause
11871    from the arg string.  If one is not found, it returns NULL.
11872
11873    Else, it returns a pointer to the condition string.  (It does not
11874    attempt to evaluate the string against a particular block.)  And,
11875    it updates arg to point to the first character following the parsed
11876    if clause in the arg string.  */
11877
11878 char *
11879 ep_parse_optional_if_clause (char **arg)
11880 {
11881   char *cond_string;
11882
11883   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11884     return NULL;
11885
11886   /* Skip the "if" keyword.  */
11887   (*arg) += 2;
11888
11889   /* Skip any extra leading whitespace, and record the start of the
11890      condition string.  */
11891   *arg = skip_spaces (*arg);
11892   cond_string = *arg;
11893
11894   /* Assume that the condition occupies the remainder of the arg
11895      string.  */
11896   (*arg) += strlen (cond_string);
11897
11898   return cond_string;
11899 }
11900
11901 /* Commands to deal with catching events, such as signals, exceptions,
11902    process start/exit, etc.  */
11903
11904 typedef enum
11905 {
11906   catch_fork_temporary, catch_vfork_temporary,
11907   catch_fork_permanent, catch_vfork_permanent
11908 }
11909 catch_fork_kind;
11910
11911 static void
11912 catch_fork_command_1 (char *arg, int from_tty, 
11913                       struct cmd_list_element *command)
11914 {
11915   struct gdbarch *gdbarch = get_current_arch ();
11916   char *cond_string = NULL;
11917   catch_fork_kind fork_kind;
11918   int tempflag;
11919
11920   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11921   tempflag = (fork_kind == catch_fork_temporary
11922               || fork_kind == catch_vfork_temporary);
11923
11924   if (!arg)
11925     arg = "";
11926   arg = skip_spaces (arg);
11927
11928   /* The allowed syntax is:
11929      catch [v]fork
11930      catch [v]fork if <cond>
11931
11932      First, check if there's an if clause.  */
11933   cond_string = ep_parse_optional_if_clause (&arg);
11934
11935   if ((*arg != '\0') && !isspace (*arg))
11936     error (_("Junk at end of arguments."));
11937
11938   /* If this target supports it, create a fork or vfork catchpoint
11939      and enable reporting of such events.  */
11940   switch (fork_kind)
11941     {
11942     case catch_fork_temporary:
11943     case catch_fork_permanent:
11944       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11945                                           &catch_fork_breakpoint_ops);
11946       break;
11947     case catch_vfork_temporary:
11948     case catch_vfork_permanent:
11949       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11950                                           &catch_vfork_breakpoint_ops);
11951       break;
11952     default:
11953       error (_("unsupported or unknown fork kind; cannot catch it"));
11954       break;
11955     }
11956 }
11957
11958 static void
11959 catch_exec_command_1 (char *arg, int from_tty, 
11960                       struct cmd_list_element *command)
11961 {
11962   struct exec_catchpoint *c;
11963   struct gdbarch *gdbarch = get_current_arch ();
11964   int tempflag;
11965   char *cond_string = NULL;
11966
11967   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11968
11969   if (!arg)
11970     arg = "";
11971   arg = skip_spaces (arg);
11972
11973   /* The allowed syntax is:
11974      catch exec
11975      catch exec if <cond>
11976
11977      First, check if there's an if clause.  */
11978   cond_string = ep_parse_optional_if_clause (&arg);
11979
11980   if ((*arg != '\0') && !isspace (*arg))
11981     error (_("Junk at end of arguments."));
11982
11983   c = XNEW (struct exec_catchpoint);
11984   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11985                    &catch_exec_breakpoint_ops);
11986   c->exec_pathname = NULL;
11987
11988   install_breakpoint (0, &c->base, 1);
11989 }
11990
11991 void
11992 init_ada_exception_breakpoint (struct breakpoint *b,
11993                                struct gdbarch *gdbarch,
11994                                struct symtab_and_line sal,
11995                                char *addr_string,
11996                                const struct breakpoint_ops *ops,
11997                                int tempflag,
11998                                int enabled,
11999                                int from_tty)
12000 {
12001   if (from_tty)
12002     {
12003       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12004       if (!loc_gdbarch)
12005         loc_gdbarch = gdbarch;
12006
12007       describe_other_breakpoints (loc_gdbarch,
12008                                   sal.pspace, sal.pc, sal.section, -1);
12009       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12010          version for exception catchpoints, because two catchpoints
12011          used for different exception names will use the same address.
12012          In this case, a "breakpoint ... also set at..." warning is
12013          unproductive.  Besides, the warning phrasing is also a bit
12014          inappropriate, we should use the word catchpoint, and tell
12015          the user what type of catchpoint it is.  The above is good
12016          enough for now, though.  */
12017     }
12018
12019   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12020
12021   b->enable_state = enabled ? bp_enabled : bp_disabled;
12022   b->disposition = tempflag ? disp_del : disp_donttouch;
12023   b->addr_string = addr_string;
12024   b->language = language_ada;
12025 }
12026
12027 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12028    filter list, or NULL if no filtering is required.  */
12029 static VEC(int) *
12030 catch_syscall_split_args (char *arg)
12031 {
12032   VEC(int) *result = NULL;
12033   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12034
12035   while (*arg != '\0')
12036     {
12037       int i, syscall_number;
12038       char *endptr;
12039       char cur_name[128];
12040       struct syscall s;
12041
12042       /* Skip whitespace.  */
12043       arg = skip_spaces (arg);
12044
12045       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12046         cur_name[i] = arg[i];
12047       cur_name[i] = '\0';
12048       arg += i;
12049
12050       /* Check if the user provided a syscall name or a number.  */
12051       syscall_number = (int) strtol (cur_name, &endptr, 0);
12052       if (*endptr == '\0')
12053         get_syscall_by_number (syscall_number, &s);
12054       else
12055         {
12056           /* We have a name.  Let's check if it's valid and convert it
12057              to a number.  */
12058           get_syscall_by_name (cur_name, &s);
12059
12060           if (s.number == UNKNOWN_SYSCALL)
12061             /* Here we have to issue an error instead of a warning,
12062                because GDB cannot do anything useful if there's no
12063                syscall number to be caught.  */
12064             error (_("Unknown syscall name '%s'."), cur_name);
12065         }
12066
12067       /* Ok, it's valid.  */
12068       VEC_safe_push (int, result, s.number);
12069     }
12070
12071   discard_cleanups (cleanup);
12072   return result;
12073 }
12074
12075 /* Implement the "catch syscall" command.  */
12076
12077 static void
12078 catch_syscall_command_1 (char *arg, int from_tty, 
12079                          struct cmd_list_element *command)
12080 {
12081   int tempflag;
12082   VEC(int) *filter;
12083   struct syscall s;
12084   struct gdbarch *gdbarch = get_current_arch ();
12085
12086   /* Checking if the feature if supported.  */
12087   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12088     error (_("The feature 'catch syscall' is not supported on \
12089 this architecture yet."));
12090
12091   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12092
12093   arg = skip_spaces (arg);
12094
12095   /* We need to do this first "dummy" translation in order
12096      to get the syscall XML file loaded or, most important,
12097      to display a warning to the user if there's no XML file
12098      for his/her architecture.  */
12099   get_syscall_by_number (0, &s);
12100
12101   /* The allowed syntax is:
12102      catch syscall
12103      catch syscall <name | number> [<name | number> ... <name | number>]
12104
12105      Let's check if there's a syscall name.  */
12106
12107   if (arg != NULL)
12108     filter = catch_syscall_split_args (arg);
12109   else
12110     filter = NULL;
12111
12112   create_syscall_event_catchpoint (tempflag, filter,
12113                                    &catch_syscall_breakpoint_ops);
12114 }
12115
12116 static void
12117 catch_command (char *arg, int from_tty)
12118 {
12119   error (_("Catch requires an event name."));
12120 }
12121 \f
12122
12123 static void
12124 tcatch_command (char *arg, int from_tty)
12125 {
12126   error (_("Catch requires an event name."));
12127 }
12128
12129 /* A qsort comparison function that sorts breakpoints in order.  */
12130
12131 static int
12132 compare_breakpoints (const void *a, const void *b)
12133 {
12134   const breakpoint_p *ba = a;
12135   uintptr_t ua = (uintptr_t) *ba;
12136   const breakpoint_p *bb = b;
12137   uintptr_t ub = (uintptr_t) *bb;
12138
12139   if ((*ba)->number < (*bb)->number)
12140     return -1;
12141   else if ((*ba)->number > (*bb)->number)
12142     return 1;
12143
12144   /* Now sort by address, in case we see, e..g, two breakpoints with
12145      the number 0.  */
12146   if (ua < ub)
12147     return -1;
12148   return ua > ub ? 1 : 0;
12149 }
12150
12151 /* Delete breakpoints by address or line.  */
12152
12153 static void
12154 clear_command (char *arg, int from_tty)
12155 {
12156   struct breakpoint *b, *prev;
12157   VEC(breakpoint_p) *found = 0;
12158   int ix;
12159   int default_match;
12160   struct symtabs_and_lines sals;
12161   struct symtab_and_line sal;
12162   int i;
12163   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12164
12165   if (arg)
12166     {
12167       sals = decode_line_with_current_source (arg,
12168                                               (DECODE_LINE_FUNFIRSTLINE
12169                                                | DECODE_LINE_LIST_MODE));
12170       make_cleanup (xfree, sals.sals);
12171       default_match = 0;
12172     }
12173   else
12174     {
12175       sals.sals = (struct symtab_and_line *)
12176         xmalloc (sizeof (struct symtab_and_line));
12177       make_cleanup (xfree, sals.sals);
12178       init_sal (&sal);          /* Initialize to zeroes.  */
12179
12180       /* Set sal's line, symtab, pc, and pspace to the values
12181          corresponding to the last call to print_frame_info.  If the
12182          codepoint is not valid, this will set all the fields to 0.  */
12183       get_last_displayed_sal (&sal);
12184       if (sal.symtab == 0)
12185         error (_("No source file specified."));
12186
12187       sals.sals[0] = sal;
12188       sals.nelts = 1;
12189
12190       default_match = 1;
12191     }
12192
12193   /* We don't call resolve_sal_pc here.  That's not as bad as it
12194      seems, because all existing breakpoints typically have both
12195      file/line and pc set.  So, if clear is given file/line, we can
12196      match this to existing breakpoint without obtaining pc at all.
12197
12198      We only support clearing given the address explicitly 
12199      present in breakpoint table.  Say, we've set breakpoint 
12200      at file:line.  There were several PC values for that file:line,
12201      due to optimization, all in one block.
12202
12203      We've picked one PC value.  If "clear" is issued with another
12204      PC corresponding to the same file:line, the breakpoint won't
12205      be cleared.  We probably can still clear the breakpoint, but 
12206      since the other PC value is never presented to user, user
12207      can only find it by guessing, and it does not seem important
12208      to support that.  */
12209
12210   /* For each line spec given, delete bps which correspond to it.  Do
12211      it in two passes, solely to preserve the current behavior that
12212      from_tty is forced true if we delete more than one
12213      breakpoint.  */
12214
12215   found = NULL;
12216   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12217   for (i = 0; i < sals.nelts; i++)
12218     {
12219       const char *sal_fullname;
12220
12221       /* If exact pc given, clear bpts at that pc.
12222          If line given (pc == 0), clear all bpts on specified line.
12223          If defaulting, clear all bpts on default line
12224          or at default pc.
12225
12226          defaulting    sal.pc != 0    tests to do
12227
12228          0              1             pc
12229          1              1             pc _and_ line
12230          0              0             line
12231          1              0             <can't happen> */
12232
12233       sal = sals.sals[i];
12234       sal_fullname = (sal.symtab == NULL
12235                       ? NULL : symtab_to_fullname (sal.symtab));
12236
12237       /* Find all matching breakpoints and add them to 'found'.  */
12238       ALL_BREAKPOINTS (b)
12239         {
12240           int match = 0;
12241           /* Are we going to delete b?  */
12242           if (b->type != bp_none && !is_watchpoint (b))
12243             {
12244               struct bp_location *loc = b->loc;
12245               for (; loc; loc = loc->next)
12246                 {
12247                   /* If the user specified file:line, don't allow a PC
12248                      match.  This matches historical gdb behavior.  */
12249                   int pc_match = (!sal.explicit_line
12250                                   && sal.pc
12251                                   && (loc->pspace == sal.pspace)
12252                                   && (loc->address == sal.pc)
12253                                   && (!section_is_overlay (loc->section)
12254                                       || loc->section == sal.section));
12255                   int line_match = 0;
12256
12257                   if ((default_match || sal.explicit_line)
12258                       && loc->symtab != NULL
12259                       && sal_fullname != NULL
12260                       && sal.pspace == loc->pspace
12261                       && loc->line_number == sal.line
12262                       && filename_cmp (symtab_to_fullname (loc->symtab),
12263                                        sal_fullname) == 0)
12264                     line_match = 1;
12265
12266                   if (pc_match || line_match)
12267                     {
12268                       match = 1;
12269                       break;
12270                     }
12271                 }
12272             }
12273
12274           if (match)
12275             VEC_safe_push(breakpoint_p, found, b);
12276         }
12277     }
12278
12279   /* Now go thru the 'found' chain and delete them.  */
12280   if (VEC_empty(breakpoint_p, found))
12281     {
12282       if (arg)
12283         error (_("No breakpoint at %s."), arg);
12284       else
12285         error (_("No breakpoint at this line."));
12286     }
12287
12288   /* Remove duplicates from the vec.  */
12289   qsort (VEC_address (breakpoint_p, found),
12290          VEC_length (breakpoint_p, found),
12291          sizeof (breakpoint_p),
12292          compare_breakpoints);
12293   prev = VEC_index (breakpoint_p, found, 0);
12294   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12295     {
12296       if (b == prev)
12297         {
12298           VEC_ordered_remove (breakpoint_p, found, ix);
12299           --ix;
12300         }
12301     }
12302
12303   if (VEC_length(breakpoint_p, found) > 1)
12304     from_tty = 1;       /* Always report if deleted more than one.  */
12305   if (from_tty)
12306     {
12307       if (VEC_length(breakpoint_p, found) == 1)
12308         printf_unfiltered (_("Deleted breakpoint "));
12309       else
12310         printf_unfiltered (_("Deleted breakpoints "));
12311     }
12312
12313   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12314     {
12315       if (from_tty)
12316         printf_unfiltered ("%d ", b->number);
12317       delete_breakpoint (b);
12318     }
12319   if (from_tty)
12320     putchar_unfiltered ('\n');
12321
12322   do_cleanups (cleanups);
12323 }
12324 \f
12325 /* Delete breakpoint in BS if they are `delete' breakpoints and
12326    all breakpoints that are marked for deletion, whether hit or not.
12327    This is called after any breakpoint is hit, or after errors.  */
12328
12329 void
12330 breakpoint_auto_delete (bpstat bs)
12331 {
12332   struct breakpoint *b, *b_tmp;
12333
12334   for (; bs; bs = bs->next)
12335     if (bs->breakpoint_at
12336         && bs->breakpoint_at->disposition == disp_del
12337         && bs->stop)
12338       delete_breakpoint (bs->breakpoint_at);
12339
12340   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12341   {
12342     if (b->disposition == disp_del_at_next_stop)
12343       delete_breakpoint (b);
12344   }
12345 }
12346
12347 /* A comparison function for bp_location AP and BP being interfaced to
12348    qsort.  Sort elements primarily by their ADDRESS (no matter what
12349    does breakpoint_address_is_meaningful say for its OWNER),
12350    secondarily by ordering first bp_permanent OWNERed elements and
12351    terciarily just ensuring the array is sorted stable way despite
12352    qsort being an unstable algorithm.  */
12353
12354 static int
12355 bp_location_compare (const void *ap, const void *bp)
12356 {
12357   struct bp_location *a = *(void **) ap;
12358   struct bp_location *b = *(void **) bp;
12359   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12360   int a_perm = a->owner->enable_state == bp_permanent;
12361   int b_perm = b->owner->enable_state == bp_permanent;
12362
12363   if (a->address != b->address)
12364     return (a->address > b->address) - (a->address < b->address);
12365
12366   /* Sort locations at the same address by their pspace number, keeping
12367      locations of the same inferior (in a multi-inferior environment)
12368      grouped.  */
12369
12370   if (a->pspace->num != b->pspace->num)
12371     return ((a->pspace->num > b->pspace->num)
12372             - (a->pspace->num < b->pspace->num));
12373
12374   /* Sort permanent breakpoints first.  */
12375   if (a_perm != b_perm)
12376     return (a_perm < b_perm) - (a_perm > b_perm);
12377
12378   /* Make the internal GDB representation stable across GDB runs
12379      where A and B memory inside GDB can differ.  Breakpoint locations of
12380      the same type at the same address can be sorted in arbitrary order.  */
12381
12382   if (a->owner->number != b->owner->number)
12383     return ((a->owner->number > b->owner->number)
12384             - (a->owner->number < b->owner->number));
12385
12386   return (a > b) - (a < b);
12387 }
12388
12389 /* Set bp_location_placed_address_before_address_max and
12390    bp_location_shadow_len_after_address_max according to the current
12391    content of the bp_location array.  */
12392
12393 static void
12394 bp_location_target_extensions_update (void)
12395 {
12396   struct bp_location *bl, **blp_tmp;
12397
12398   bp_location_placed_address_before_address_max = 0;
12399   bp_location_shadow_len_after_address_max = 0;
12400
12401   ALL_BP_LOCATIONS (bl, blp_tmp)
12402     {
12403       CORE_ADDR start, end, addr;
12404
12405       if (!bp_location_has_shadow (bl))
12406         continue;
12407
12408       start = bl->target_info.placed_address;
12409       end = start + bl->target_info.shadow_len;
12410
12411       gdb_assert (bl->address >= start);
12412       addr = bl->address - start;
12413       if (addr > bp_location_placed_address_before_address_max)
12414         bp_location_placed_address_before_address_max = addr;
12415
12416       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12417
12418       gdb_assert (bl->address < end);
12419       addr = end - bl->address;
12420       if (addr > bp_location_shadow_len_after_address_max)
12421         bp_location_shadow_len_after_address_max = addr;
12422     }
12423 }
12424
12425 /* Download tracepoint locations if they haven't been.  */
12426
12427 static void
12428 download_tracepoint_locations (void)
12429 {
12430   struct breakpoint *b;
12431   struct cleanup *old_chain;
12432
12433   if (!target_can_download_tracepoint ())
12434     return;
12435
12436   old_chain = save_current_space_and_thread ();
12437
12438   ALL_TRACEPOINTS (b)
12439     {
12440       struct bp_location *bl;
12441       struct tracepoint *t;
12442       int bp_location_downloaded = 0;
12443
12444       if ((b->type == bp_fast_tracepoint
12445            ? !may_insert_fast_tracepoints
12446            : !may_insert_tracepoints))
12447         continue;
12448
12449       for (bl = b->loc; bl; bl = bl->next)
12450         {
12451           /* In tracepoint, locations are _never_ duplicated, so
12452              should_be_inserted is equivalent to
12453              unduplicated_should_be_inserted.  */
12454           if (!should_be_inserted (bl) || bl->inserted)
12455             continue;
12456
12457           switch_to_program_space_and_thread (bl->pspace);
12458
12459           target_download_tracepoint (bl);
12460
12461           bl->inserted = 1;
12462           bp_location_downloaded = 1;
12463         }
12464       t = (struct tracepoint *) b;
12465       t->number_on_target = b->number;
12466       if (bp_location_downloaded)
12467         observer_notify_breakpoint_modified (b);
12468     }
12469
12470   do_cleanups (old_chain);
12471 }
12472
12473 /* Swap the insertion/duplication state between two locations.  */
12474
12475 static void
12476 swap_insertion (struct bp_location *left, struct bp_location *right)
12477 {
12478   const int left_inserted = left->inserted;
12479   const int left_duplicate = left->duplicate;
12480   const int left_needs_update = left->needs_update;
12481   const struct bp_target_info left_target_info = left->target_info;
12482
12483   /* Locations of tracepoints can never be duplicated.  */
12484   if (is_tracepoint (left->owner))
12485     gdb_assert (!left->duplicate);
12486   if (is_tracepoint (right->owner))
12487     gdb_assert (!right->duplicate);
12488
12489   left->inserted = right->inserted;
12490   left->duplicate = right->duplicate;
12491   left->needs_update = right->needs_update;
12492   left->target_info = right->target_info;
12493   right->inserted = left_inserted;
12494   right->duplicate = left_duplicate;
12495   right->needs_update = left_needs_update;
12496   right->target_info = left_target_info;
12497 }
12498
12499 /* Force the re-insertion of the locations at ADDRESS.  This is called
12500    once a new/deleted/modified duplicate location is found and we are evaluating
12501    conditions on the target's side.  Such conditions need to be updated on
12502    the target.  */
12503
12504 static void
12505 force_breakpoint_reinsertion (struct bp_location *bl)
12506 {
12507   struct bp_location **locp = NULL, **loc2p;
12508   struct bp_location *loc;
12509   CORE_ADDR address = 0;
12510   int pspace_num;
12511
12512   address = bl->address;
12513   pspace_num = bl->pspace->num;
12514
12515   /* This is only meaningful if the target is
12516      evaluating conditions and if the user has
12517      opted for condition evaluation on the target's
12518      side.  */
12519   if (gdb_evaluates_breakpoint_condition_p ()
12520       || !target_supports_evaluation_of_breakpoint_conditions ())
12521     return;
12522
12523   /* Flag all breakpoint locations with this address and
12524      the same program space as the location
12525      as "its condition has changed".  We need to
12526      update the conditions on the target's side.  */
12527   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12528     {
12529       loc = *loc2p;
12530
12531       if (!is_breakpoint (loc->owner)
12532           || pspace_num != loc->pspace->num)
12533         continue;
12534
12535       /* Flag the location appropriately.  We use a different state to
12536          let everyone know that we already updated the set of locations
12537          with addr bl->address and program space bl->pspace.  This is so
12538          we don't have to keep calling these functions just to mark locations
12539          that have already been marked.  */
12540       loc->condition_changed = condition_updated;
12541
12542       /* Free the agent expression bytecode as well.  We will compute
12543          it later on.  */
12544       if (loc->cond_bytecode)
12545         {
12546           free_agent_expr (loc->cond_bytecode);
12547           loc->cond_bytecode = NULL;
12548         }
12549     }
12550 }
12551
12552 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12553    into the inferior, only remove already-inserted locations that no
12554    longer should be inserted.  Functions that delete a breakpoint or
12555    breakpoints should pass false, so that deleting a breakpoint
12556    doesn't have the side effect of inserting the locations of other
12557    breakpoints that are marked not-inserted, but should_be_inserted
12558    returns true on them.
12559
12560    This behaviour is useful is situations close to tear-down -- e.g.,
12561    after an exec, while the target still has execution, but breakpoint
12562    shadows of the previous executable image should *NOT* be restored
12563    to the new image; or before detaching, where the target still has
12564    execution and wants to delete breakpoints from GDB's lists, and all
12565    breakpoints had already been removed from the inferior.  */
12566
12567 static void
12568 update_global_location_list (int should_insert)
12569 {
12570   struct breakpoint *b;
12571   struct bp_location **locp, *loc;
12572   struct cleanup *cleanups;
12573   /* Last breakpoint location address that was marked for update.  */
12574   CORE_ADDR last_addr = 0;
12575   /* Last breakpoint location program space that was marked for update.  */
12576   int last_pspace_num = -1;
12577
12578   /* Used in the duplicates detection below.  When iterating over all
12579      bp_locations, points to the first bp_location of a given address.
12580      Breakpoints and watchpoints of different types are never
12581      duplicates of each other.  Keep one pointer for each type of
12582      breakpoint/watchpoint, so we only need to loop over all locations
12583      once.  */
12584   struct bp_location *bp_loc_first;  /* breakpoint */
12585   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12586   struct bp_location *awp_loc_first; /* access watchpoint */
12587   struct bp_location *rwp_loc_first; /* read watchpoint */
12588
12589   /* Saved former bp_location array which we compare against the newly
12590      built bp_location from the current state of ALL_BREAKPOINTS.  */
12591   struct bp_location **old_location, **old_locp;
12592   unsigned old_location_count;
12593
12594   old_location = bp_location;
12595   old_location_count = bp_location_count;
12596   bp_location = NULL;
12597   bp_location_count = 0;
12598   cleanups = make_cleanup (xfree, old_location);
12599
12600   ALL_BREAKPOINTS (b)
12601     for (loc = b->loc; loc; loc = loc->next)
12602       bp_location_count++;
12603
12604   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12605   locp = bp_location;
12606   ALL_BREAKPOINTS (b)
12607     for (loc = b->loc; loc; loc = loc->next)
12608       *locp++ = loc;
12609   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12610          bp_location_compare);
12611
12612   bp_location_target_extensions_update ();
12613
12614   /* Identify bp_location instances that are no longer present in the
12615      new list, and therefore should be freed.  Note that it's not
12616      necessary that those locations should be removed from inferior --
12617      if there's another location at the same address (previously
12618      marked as duplicate), we don't need to remove/insert the
12619      location.
12620      
12621      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12622      and former bp_location array state respectively.  */
12623
12624   locp = bp_location;
12625   for (old_locp = old_location; old_locp < old_location + old_location_count;
12626        old_locp++)
12627     {
12628       struct bp_location *old_loc = *old_locp;
12629       struct bp_location **loc2p;
12630
12631       /* Tells if 'old_loc' is found among the new locations.  If
12632          not, we have to free it.  */
12633       int found_object = 0;
12634       /* Tells if the location should remain inserted in the target.  */
12635       int keep_in_target = 0;
12636       int removed = 0;
12637
12638       /* Skip LOCP entries which will definitely never be needed.
12639          Stop either at or being the one matching OLD_LOC.  */
12640       while (locp < bp_location + bp_location_count
12641              && (*locp)->address < old_loc->address)
12642         locp++;
12643
12644       for (loc2p = locp;
12645            (loc2p < bp_location + bp_location_count
12646             && (*loc2p)->address == old_loc->address);
12647            loc2p++)
12648         {
12649           /* Check if this is a new/duplicated location or a duplicated
12650              location that had its condition modified.  If so, we want to send
12651              its condition to the target if evaluation of conditions is taking
12652              place there.  */
12653           if ((*loc2p)->condition_changed == condition_modified
12654               && (last_addr != old_loc->address
12655                   || last_pspace_num != old_loc->pspace->num))
12656             {
12657               force_breakpoint_reinsertion (*loc2p);
12658               last_pspace_num = old_loc->pspace->num;
12659             }
12660
12661           if (*loc2p == old_loc)
12662             found_object = 1;
12663         }
12664
12665       /* We have already handled this address, update it so that we don't
12666          have to go through updates again.  */
12667       last_addr = old_loc->address;
12668
12669       /* Target-side condition evaluation: Handle deleted locations.  */
12670       if (!found_object)
12671         force_breakpoint_reinsertion (old_loc);
12672
12673       /* If this location is no longer present, and inserted, look if
12674          there's maybe a new location at the same address.  If so,
12675          mark that one inserted, and don't remove this one.  This is
12676          needed so that we don't have a time window where a breakpoint
12677          at certain location is not inserted.  */
12678
12679       if (old_loc->inserted)
12680         {
12681           /* If the location is inserted now, we might have to remove
12682              it.  */
12683
12684           if (found_object && should_be_inserted (old_loc))
12685             {
12686               /* The location is still present in the location list,
12687                  and still should be inserted.  Don't do anything.  */
12688               keep_in_target = 1;
12689             }
12690           else
12691             {
12692               /* This location still exists, but it won't be kept in the
12693                  target since it may have been disabled.  We proceed to
12694                  remove its target-side condition.  */
12695
12696               /* The location is either no longer present, or got
12697                  disabled.  See if there's another location at the
12698                  same address, in which case we don't need to remove
12699                  this one from the target.  */
12700
12701               /* OLD_LOC comes from existing struct breakpoint.  */
12702               if (breakpoint_address_is_meaningful (old_loc->owner))
12703                 {
12704                   for (loc2p = locp;
12705                        (loc2p < bp_location + bp_location_count
12706                         && (*loc2p)->address == old_loc->address);
12707                        loc2p++)
12708                     {
12709                       struct bp_location *loc2 = *loc2p;
12710
12711                       if (breakpoint_locations_match (loc2, old_loc))
12712                         {
12713                           /* Read watchpoint locations are switched to
12714                              access watchpoints, if the former are not
12715                              supported, but the latter are.  */
12716                           if (is_hardware_watchpoint (old_loc->owner))
12717                             {
12718                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12719                               loc2->watchpoint_type = old_loc->watchpoint_type;
12720                             }
12721
12722                           /* loc2 is a duplicated location. We need to check
12723                              if it should be inserted in case it will be
12724                              unduplicated.  */
12725                           if (loc2 != old_loc
12726                               && unduplicated_should_be_inserted (loc2))
12727                             {
12728                               swap_insertion (old_loc, loc2);
12729                               keep_in_target = 1;
12730                               break;
12731                             }
12732                         }
12733                     }
12734                 }
12735             }
12736
12737           if (!keep_in_target)
12738             {
12739               if (remove_breakpoint (old_loc, mark_uninserted))
12740                 {
12741                   /* This is just about all we can do.  We could keep
12742                      this location on the global list, and try to
12743                      remove it next time, but there's no particular
12744                      reason why we will succeed next time.
12745                      
12746                      Note that at this point, old_loc->owner is still
12747                      valid, as delete_breakpoint frees the breakpoint
12748                      only after calling us.  */
12749                   printf_filtered (_("warning: Error removing "
12750                                      "breakpoint %d\n"), 
12751                                    old_loc->owner->number);
12752                 }
12753               removed = 1;
12754             }
12755         }
12756
12757       if (!found_object)
12758         {
12759           if (removed && non_stop
12760               && breakpoint_address_is_meaningful (old_loc->owner)
12761               && !is_hardware_watchpoint (old_loc->owner))
12762             {
12763               /* This location was removed from the target.  In
12764                  non-stop mode, a race condition is possible where
12765                  we've removed a breakpoint, but stop events for that
12766                  breakpoint are already queued and will arrive later.
12767                  We apply an heuristic to be able to distinguish such
12768                  SIGTRAPs from other random SIGTRAPs: we keep this
12769                  breakpoint location for a bit, and will retire it
12770                  after we see some number of events.  The theory here
12771                  is that reporting of events should, "on the average",
12772                  be fair, so after a while we'll see events from all
12773                  threads that have anything of interest, and no longer
12774                  need to keep this breakpoint location around.  We
12775                  don't hold locations forever so to reduce chances of
12776                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12777                  SIGTRAP.
12778
12779                  The heuristic failing can be disastrous on
12780                  decr_pc_after_break targets.
12781
12782                  On decr_pc_after_break targets, like e.g., x86-linux,
12783                  if we fail to recognize a late breakpoint SIGTRAP,
12784                  because events_till_retirement has reached 0 too
12785                  soon, we'll fail to do the PC adjustment, and report
12786                  a random SIGTRAP to the user.  When the user resumes
12787                  the inferior, it will most likely immediately crash
12788                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12789                  corrupted, because of being resumed e.g., in the
12790                  middle of a multi-byte instruction, or skipped a
12791                  one-byte instruction.  This was actually seen happen
12792                  on native x86-linux, and should be less rare on
12793                  targets that do not support new thread events, like
12794                  remote, due to the heuristic depending on
12795                  thread_count.
12796
12797                  Mistaking a random SIGTRAP for a breakpoint trap
12798                  causes similar symptoms (PC adjustment applied when
12799                  it shouldn't), but then again, playing with SIGTRAPs
12800                  behind the debugger's back is asking for trouble.
12801
12802                  Since hardware watchpoint traps are always
12803                  distinguishable from other traps, so we don't need to
12804                  apply keep hardware watchpoint moribund locations
12805                  around.  We simply always ignore hardware watchpoint
12806                  traps we can no longer explain.  */
12807
12808               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12809               old_loc->owner = NULL;
12810
12811               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12812             }
12813           else
12814             {
12815               old_loc->owner = NULL;
12816               decref_bp_location (&old_loc);
12817             }
12818         }
12819     }
12820
12821   /* Rescan breakpoints at the same address and section, marking the
12822      first one as "first" and any others as "duplicates".  This is so
12823      that the bpt instruction is only inserted once.  If we have a
12824      permanent breakpoint at the same place as BPT, make that one the
12825      official one, and the rest as duplicates.  Permanent breakpoints
12826      are sorted first for the same address.
12827
12828      Do the same for hardware watchpoints, but also considering the
12829      watchpoint's type (regular/access/read) and length.  */
12830
12831   bp_loc_first = NULL;
12832   wp_loc_first = NULL;
12833   awp_loc_first = NULL;
12834   rwp_loc_first = NULL;
12835   ALL_BP_LOCATIONS (loc, locp)
12836     {
12837       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12838          non-NULL.  */
12839       struct bp_location **loc_first_p;
12840       b = loc->owner;
12841
12842       if (!unduplicated_should_be_inserted (loc)
12843           || !breakpoint_address_is_meaningful (b)
12844           /* Don't detect duplicate for tracepoint locations because they are
12845            never duplicated.  See the comments in field `duplicate' of
12846            `struct bp_location'.  */
12847           || is_tracepoint (b))
12848         {
12849           /* Clear the condition modification flag.  */
12850           loc->condition_changed = condition_unchanged;
12851           continue;
12852         }
12853
12854       /* Permanent breakpoint should always be inserted.  */
12855       if (b->enable_state == bp_permanent && ! loc->inserted)
12856         internal_error (__FILE__, __LINE__,
12857                         _("allegedly permanent breakpoint is not "
12858                         "actually inserted"));
12859
12860       if (b->type == bp_hardware_watchpoint)
12861         loc_first_p = &wp_loc_first;
12862       else if (b->type == bp_read_watchpoint)
12863         loc_first_p = &rwp_loc_first;
12864       else if (b->type == bp_access_watchpoint)
12865         loc_first_p = &awp_loc_first;
12866       else
12867         loc_first_p = &bp_loc_first;
12868
12869       if (*loc_first_p == NULL
12870           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12871           || !breakpoint_locations_match (loc, *loc_first_p))
12872         {
12873           *loc_first_p = loc;
12874           loc->duplicate = 0;
12875
12876           if (is_breakpoint (loc->owner) && loc->condition_changed)
12877             {
12878               loc->needs_update = 1;
12879               /* Clear the condition modification flag.  */
12880               loc->condition_changed = condition_unchanged;
12881             }
12882           continue;
12883         }
12884
12885
12886       /* This and the above ensure the invariant that the first location
12887          is not duplicated, and is the inserted one.
12888          All following are marked as duplicated, and are not inserted.  */
12889       if (loc->inserted)
12890         swap_insertion (loc, *loc_first_p);
12891       loc->duplicate = 1;
12892
12893       /* Clear the condition modification flag.  */
12894       loc->condition_changed = condition_unchanged;
12895
12896       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12897           && b->enable_state != bp_permanent)
12898         internal_error (__FILE__, __LINE__,
12899                         _("another breakpoint was inserted on top of "
12900                         "a permanent breakpoint"));
12901     }
12902
12903   if (breakpoints_always_inserted_mode ()
12904       && (have_live_inferiors ()
12905           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12906     {
12907       if (should_insert)
12908         insert_breakpoint_locations ();
12909       else
12910         {
12911           /* Though should_insert is false, we may need to update conditions
12912              on the target's side if it is evaluating such conditions.  We
12913              only update conditions for locations that are marked
12914              "needs_update".  */
12915           update_inserted_breakpoint_locations ();
12916         }
12917     }
12918
12919   if (should_insert)
12920     download_tracepoint_locations ();
12921
12922   do_cleanups (cleanups);
12923 }
12924
12925 void
12926 breakpoint_retire_moribund (void)
12927 {
12928   struct bp_location *loc;
12929   int ix;
12930
12931   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12932     if (--(loc->events_till_retirement) == 0)
12933       {
12934         decref_bp_location (&loc);
12935         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12936         --ix;
12937       }
12938 }
12939
12940 static void
12941 update_global_location_list_nothrow (int inserting)
12942 {
12943   volatile struct gdb_exception e;
12944
12945   TRY_CATCH (e, RETURN_MASK_ERROR)
12946     update_global_location_list (inserting);
12947 }
12948
12949 /* Clear BKP from a BPS.  */
12950
12951 static void
12952 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12953 {
12954   bpstat bs;
12955
12956   for (bs = bps; bs; bs = bs->next)
12957     if (bs->breakpoint_at == bpt)
12958       {
12959         bs->breakpoint_at = NULL;
12960         bs->old_val = NULL;
12961         /* bs->commands will be freed later.  */
12962       }
12963 }
12964
12965 /* Callback for iterate_over_threads.  */
12966 static int
12967 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12968 {
12969   struct breakpoint *bpt = data;
12970
12971   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12972   return 0;
12973 }
12974
12975 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12976    callbacks.  */
12977
12978 static void
12979 say_where (struct breakpoint *b)
12980 {
12981   struct value_print_options opts;
12982
12983   get_user_print_options (&opts);
12984
12985   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12986      single string.  */
12987   if (b->loc == NULL)
12988     {
12989       printf_filtered (_(" (%s) pending."), b->addr_string);
12990     }
12991   else
12992     {
12993       if (opts.addressprint || b->loc->symtab == NULL)
12994         {
12995           printf_filtered (" at ");
12996           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12997                           gdb_stdout);
12998         }
12999       if (b->loc->symtab != NULL)
13000         {
13001           /* If there is a single location, we can print the location
13002              more nicely.  */
13003           if (b->loc->next == NULL)
13004             printf_filtered (": file %s, line %d.",
13005                              symtab_to_filename_for_display (b->loc->symtab),
13006                              b->loc->line_number);
13007           else
13008             /* This is not ideal, but each location may have a
13009                different file name, and this at least reflects the
13010                real situation somewhat.  */
13011             printf_filtered (": %s.", b->addr_string);
13012         }
13013
13014       if (b->loc->next)
13015         {
13016           struct bp_location *loc = b->loc;
13017           int n = 0;
13018           for (; loc; loc = loc->next)
13019             ++n;
13020           printf_filtered (" (%d locations)", n);
13021         }
13022     }
13023 }
13024
13025 /* Default bp_location_ops methods.  */
13026
13027 static void
13028 bp_location_dtor (struct bp_location *self)
13029 {
13030   xfree (self->cond);
13031   if (self->cond_bytecode)
13032     free_agent_expr (self->cond_bytecode);
13033   xfree (self->function_name);
13034
13035   VEC_free (agent_expr_p, self->target_info.conditions);
13036   VEC_free (agent_expr_p, self->target_info.tcommands);
13037 }
13038
13039 static const struct bp_location_ops bp_location_ops =
13040 {
13041   bp_location_dtor
13042 };
13043
13044 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13045    inherit from.  */
13046
13047 static void
13048 base_breakpoint_dtor (struct breakpoint *self)
13049 {
13050   decref_counted_command_line (&self->commands);
13051   xfree (self->cond_string);
13052   xfree (self->extra_string);
13053   xfree (self->addr_string);
13054   xfree (self->filter);
13055   xfree (self->addr_string_range_end);
13056 }
13057
13058 static struct bp_location *
13059 base_breakpoint_allocate_location (struct breakpoint *self)
13060 {
13061   struct bp_location *loc;
13062
13063   loc = XNEW (struct bp_location);
13064   init_bp_location (loc, &bp_location_ops, self);
13065   return loc;
13066 }
13067
13068 static void
13069 base_breakpoint_re_set (struct breakpoint *b)
13070 {
13071   /* Nothing to re-set. */
13072 }
13073
13074 #define internal_error_pure_virtual_called() \
13075   gdb_assert_not_reached ("pure virtual function called")
13076
13077 static int
13078 base_breakpoint_insert_location (struct bp_location *bl)
13079 {
13080   internal_error_pure_virtual_called ();
13081 }
13082
13083 static int
13084 base_breakpoint_remove_location (struct bp_location *bl)
13085 {
13086   internal_error_pure_virtual_called ();
13087 }
13088
13089 static int
13090 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13091                                 struct address_space *aspace,
13092                                 CORE_ADDR bp_addr,
13093                                 const struct target_waitstatus *ws)
13094 {
13095   internal_error_pure_virtual_called ();
13096 }
13097
13098 static void
13099 base_breakpoint_check_status (bpstat bs)
13100 {
13101   /* Always stop.   */
13102 }
13103
13104 /* A "works_in_software_mode" breakpoint_ops method that just internal
13105    errors.  */
13106
13107 static int
13108 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13109 {
13110   internal_error_pure_virtual_called ();
13111 }
13112
13113 /* A "resources_needed" breakpoint_ops method that just internal
13114    errors.  */
13115
13116 static int
13117 base_breakpoint_resources_needed (const struct bp_location *bl)
13118 {
13119   internal_error_pure_virtual_called ();
13120 }
13121
13122 static enum print_stop_action
13123 base_breakpoint_print_it (bpstat bs)
13124 {
13125   internal_error_pure_virtual_called ();
13126 }
13127
13128 static void
13129 base_breakpoint_print_one_detail (const struct breakpoint *self,
13130                                   struct ui_out *uiout)
13131 {
13132   /* nothing */
13133 }
13134
13135 static void
13136 base_breakpoint_print_mention (struct breakpoint *b)
13137 {
13138   internal_error_pure_virtual_called ();
13139 }
13140
13141 static void
13142 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13143 {
13144   internal_error_pure_virtual_called ();
13145 }
13146
13147 static void
13148 base_breakpoint_create_sals_from_address (char **arg,
13149                                           struct linespec_result *canonical,
13150                                           enum bptype type_wanted,
13151                                           char *addr_start,
13152                                           char **copy_arg)
13153 {
13154   internal_error_pure_virtual_called ();
13155 }
13156
13157 static void
13158 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13159                                         struct linespec_result *c,
13160                                         char *cond_string,
13161                                         char *extra_string,
13162                                         enum bptype type_wanted,
13163                                         enum bpdisp disposition,
13164                                         int thread,
13165                                         int task, int ignore_count,
13166                                         const struct breakpoint_ops *o,
13167                                         int from_tty, int enabled,
13168                                         int internal, unsigned flags)
13169 {
13170   internal_error_pure_virtual_called ();
13171 }
13172
13173 static void
13174 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13175                                  struct symtabs_and_lines *sals)
13176 {
13177   internal_error_pure_virtual_called ();
13178 }
13179
13180 /* The default 'explains_signal' method.  */
13181
13182 static int
13183 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13184 {
13185   return 1;
13186 }
13187
13188 /* The default "after_condition_true" method.  */
13189
13190 static void
13191 base_breakpoint_after_condition_true (struct bpstats *bs)
13192 {
13193   /* Nothing to do.   */
13194 }
13195
13196 struct breakpoint_ops base_breakpoint_ops =
13197 {
13198   base_breakpoint_dtor,
13199   base_breakpoint_allocate_location,
13200   base_breakpoint_re_set,
13201   base_breakpoint_insert_location,
13202   base_breakpoint_remove_location,
13203   base_breakpoint_breakpoint_hit,
13204   base_breakpoint_check_status,
13205   base_breakpoint_resources_needed,
13206   base_breakpoint_works_in_software_mode,
13207   base_breakpoint_print_it,
13208   NULL,
13209   base_breakpoint_print_one_detail,
13210   base_breakpoint_print_mention,
13211   base_breakpoint_print_recreate,
13212   base_breakpoint_create_sals_from_address,
13213   base_breakpoint_create_breakpoints_sal,
13214   base_breakpoint_decode_linespec,
13215   base_breakpoint_explains_signal,
13216   base_breakpoint_after_condition_true,
13217 };
13218
13219 /* Default breakpoint_ops methods.  */
13220
13221 static void
13222 bkpt_re_set (struct breakpoint *b)
13223 {
13224   /* FIXME: is this still reachable?  */
13225   if (b->addr_string == NULL)
13226     {
13227       /* Anything without a string can't be re-set.  */
13228       delete_breakpoint (b);
13229       return;
13230     }
13231
13232   breakpoint_re_set_default (b);
13233 }
13234
13235 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13236    inserted DEST, so we can remove it later, in case SRC is removed
13237    first.  */
13238
13239 static void
13240 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13241                                      const struct bp_target_info *src)
13242 {
13243   dest->shadow_len = src->shadow_len;
13244   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13245   dest->placed_size = src->placed_size;
13246 }
13247
13248 static int
13249 bkpt_insert_location (struct bp_location *bl)
13250 {
13251   if (bl->loc_type == bp_loc_hardware_breakpoint)
13252     return target_insert_hw_breakpoint (bl->gdbarch,
13253                                         &bl->target_info);
13254   else
13255     {
13256       struct bp_target_info *bp_tgt = &bl->target_info;
13257       int ret;
13258       int sss_slot;
13259
13260       /* There is no need to insert a breakpoint if an unconditional
13261          raw/sss breakpoint is already inserted at that location.  */
13262       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13263                                               bp_tgt->placed_address);
13264       if (sss_slot >= 0)
13265         {
13266           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13267
13268           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13269           return 0;
13270         }
13271
13272       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13273     }
13274 }
13275
13276 static int
13277 bkpt_remove_location (struct bp_location *bl)
13278 {
13279   if (bl->loc_type == bp_loc_hardware_breakpoint)
13280     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13281   else
13282     {
13283       struct bp_target_info *bp_tgt = &bl->target_info;
13284       struct address_space *aspace = bp_tgt->placed_address_space;
13285       CORE_ADDR address = bp_tgt->placed_address;
13286
13287       /* Only remove the breakpoint if there is no raw/sss breakpoint
13288          still inserted at this location.  Otherwise, we would be
13289          effectively disabling the raw/sss breakpoint.  */
13290       if (single_step_breakpoint_inserted_here_p (aspace, address))
13291         return 0;
13292
13293       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13294     }
13295 }
13296
13297 static int
13298 bkpt_breakpoint_hit (const struct bp_location *bl,
13299                      struct address_space *aspace, CORE_ADDR bp_addr,
13300                      const struct target_waitstatus *ws)
13301 {
13302   if (ws->kind != TARGET_WAITKIND_STOPPED
13303       || ws->value.sig != GDB_SIGNAL_TRAP)
13304     return 0;
13305
13306   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13307                                  aspace, bp_addr))
13308     return 0;
13309
13310   if (overlay_debugging         /* unmapped overlay section */
13311       && section_is_overlay (bl->section)
13312       && !section_is_mapped (bl->section))
13313     return 0;
13314
13315   return 1;
13316 }
13317
13318 static int
13319 dprintf_breakpoint_hit (const struct bp_location *bl,
13320                         struct address_space *aspace, CORE_ADDR bp_addr,
13321                         const struct target_waitstatus *ws)
13322 {
13323   if (dprintf_style == dprintf_style_agent
13324       && target_can_run_breakpoint_commands ())
13325     {
13326       /* An agent-style dprintf never causes a stop.  If we see a trap
13327          for this address it must be for a breakpoint that happens to
13328          be set at the same address.  */
13329       return 0;
13330     }
13331
13332   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13333 }
13334
13335 static int
13336 bkpt_resources_needed (const struct bp_location *bl)
13337 {
13338   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13339
13340   return 1;
13341 }
13342
13343 static enum print_stop_action
13344 bkpt_print_it (bpstat bs)
13345 {
13346   struct breakpoint *b;
13347   const struct bp_location *bl;
13348   int bp_temp;
13349   struct ui_out *uiout = current_uiout;
13350
13351   gdb_assert (bs->bp_location_at != NULL);
13352
13353   bl = bs->bp_location_at;
13354   b = bs->breakpoint_at;
13355
13356   bp_temp = b->disposition == disp_del;
13357   if (bl->address != bl->requested_address)
13358     breakpoint_adjustment_warning (bl->requested_address,
13359                                    bl->address,
13360                                    b->number, 1);
13361   annotate_breakpoint (b->number);
13362   if (bp_temp)
13363     ui_out_text (uiout, "\nTemporary breakpoint ");
13364   else
13365     ui_out_text (uiout, "\nBreakpoint ");
13366   if (ui_out_is_mi_like_p (uiout))
13367     {
13368       ui_out_field_string (uiout, "reason",
13369                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13370       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13371     }
13372   ui_out_field_int (uiout, "bkptno", b->number);
13373   ui_out_text (uiout, ", ");
13374
13375   return PRINT_SRC_AND_LOC;
13376 }
13377
13378 static void
13379 bkpt_print_mention (struct breakpoint *b)
13380 {
13381   if (ui_out_is_mi_like_p (current_uiout))
13382     return;
13383
13384   switch (b->type)
13385     {
13386     case bp_breakpoint:
13387     case bp_gnu_ifunc_resolver:
13388       if (b->disposition == disp_del)
13389         printf_filtered (_("Temporary breakpoint"));
13390       else
13391         printf_filtered (_("Breakpoint"));
13392       printf_filtered (_(" %d"), b->number);
13393       if (b->type == bp_gnu_ifunc_resolver)
13394         printf_filtered (_(" at gnu-indirect-function resolver"));
13395       break;
13396     case bp_hardware_breakpoint:
13397       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13398       break;
13399     case bp_dprintf:
13400       printf_filtered (_("Dprintf %d"), b->number);
13401       break;
13402     }
13403
13404   say_where (b);
13405 }
13406
13407 static void
13408 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13409 {
13410   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13411     fprintf_unfiltered (fp, "tbreak");
13412   else if (tp->type == bp_breakpoint)
13413     fprintf_unfiltered (fp, "break");
13414   else if (tp->type == bp_hardware_breakpoint
13415            && tp->disposition == disp_del)
13416     fprintf_unfiltered (fp, "thbreak");
13417   else if (tp->type == bp_hardware_breakpoint)
13418     fprintf_unfiltered (fp, "hbreak");
13419   else
13420     internal_error (__FILE__, __LINE__,
13421                     _("unhandled breakpoint type %d"), (int) tp->type);
13422
13423   fprintf_unfiltered (fp, " %s", tp->addr_string);
13424   print_recreate_thread (tp, fp);
13425 }
13426
13427 static void
13428 bkpt_create_sals_from_address (char **arg,
13429                                struct linespec_result *canonical,
13430                                enum bptype type_wanted,
13431                                char *addr_start, char **copy_arg)
13432 {
13433   create_sals_from_address_default (arg, canonical, type_wanted,
13434                                     addr_start, copy_arg);
13435 }
13436
13437 static void
13438 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13439                              struct linespec_result *canonical,
13440                              char *cond_string,
13441                              char *extra_string,
13442                              enum bptype type_wanted,
13443                              enum bpdisp disposition,
13444                              int thread,
13445                              int task, int ignore_count,
13446                              const struct breakpoint_ops *ops,
13447                              int from_tty, int enabled,
13448                              int internal, unsigned flags)
13449 {
13450   create_breakpoints_sal_default (gdbarch, canonical,
13451                                   cond_string, extra_string,
13452                                   type_wanted,
13453                                   disposition, thread, task,
13454                                   ignore_count, ops, from_tty,
13455                                   enabled, internal, flags);
13456 }
13457
13458 static void
13459 bkpt_decode_linespec (struct breakpoint *b, char **s,
13460                       struct symtabs_and_lines *sals)
13461 {
13462   decode_linespec_default (b, s, sals);
13463 }
13464
13465 /* Virtual table for internal breakpoints.  */
13466
13467 static void
13468 internal_bkpt_re_set (struct breakpoint *b)
13469 {
13470   switch (b->type)
13471     {
13472       /* Delete overlay event and longjmp master breakpoints; they
13473          will be reset later by breakpoint_re_set.  */
13474     case bp_overlay_event:
13475     case bp_longjmp_master:
13476     case bp_std_terminate_master:
13477     case bp_exception_master:
13478       delete_breakpoint (b);
13479       break;
13480
13481       /* This breakpoint is special, it's set up when the inferior
13482          starts and we really don't want to touch it.  */
13483     case bp_shlib_event:
13484
13485       /* Like bp_shlib_event, this breakpoint type is special.  Once
13486          it is set up, we do not want to touch it.  */
13487     case bp_thread_event:
13488       break;
13489     }
13490 }
13491
13492 static void
13493 internal_bkpt_check_status (bpstat bs)
13494 {
13495   if (bs->breakpoint_at->type == bp_shlib_event)
13496     {
13497       /* If requested, stop when the dynamic linker notifies GDB of
13498          events.  This allows the user to get control and place
13499          breakpoints in initializer routines for dynamically loaded
13500          objects (among other things).  */
13501       bs->stop = stop_on_solib_events;
13502       bs->print = stop_on_solib_events;
13503     }
13504   else
13505     bs->stop = 0;
13506 }
13507
13508 static enum print_stop_action
13509 internal_bkpt_print_it (bpstat bs)
13510 {
13511   struct breakpoint *b;
13512
13513   b = bs->breakpoint_at;
13514
13515   switch (b->type)
13516     {
13517     case bp_shlib_event:
13518       /* Did we stop because the user set the stop_on_solib_events
13519          variable?  (If so, we report this as a generic, "Stopped due
13520          to shlib event" message.) */
13521       print_solib_event (0);
13522       break;
13523
13524     case bp_thread_event:
13525       /* Not sure how we will get here.
13526          GDB should not stop for these breakpoints.  */
13527       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13528       break;
13529
13530     case bp_overlay_event:
13531       /* By analogy with the thread event, GDB should not stop for these.  */
13532       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13533       break;
13534
13535     case bp_longjmp_master:
13536       /* These should never be enabled.  */
13537       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13538       break;
13539
13540     case bp_std_terminate_master:
13541       /* These should never be enabled.  */
13542       printf_filtered (_("std::terminate Master Breakpoint: "
13543                          "gdb should not stop!\n"));
13544       break;
13545
13546     case bp_exception_master:
13547       /* These should never be enabled.  */
13548       printf_filtered (_("Exception Master Breakpoint: "
13549                          "gdb should not stop!\n"));
13550       break;
13551     }
13552
13553   return PRINT_NOTHING;
13554 }
13555
13556 static void
13557 internal_bkpt_print_mention (struct breakpoint *b)
13558 {
13559   /* Nothing to mention.  These breakpoints are internal.  */
13560 }
13561
13562 /* Virtual table for momentary breakpoints  */
13563
13564 static void
13565 momentary_bkpt_re_set (struct breakpoint *b)
13566 {
13567   /* Keep temporary breakpoints, which can be encountered when we step
13568      over a dlopen call and solib_add is resetting the breakpoints.
13569      Otherwise these should have been blown away via the cleanup chain
13570      or by breakpoint_init_inferior when we rerun the executable.  */
13571 }
13572
13573 static void
13574 momentary_bkpt_check_status (bpstat bs)
13575 {
13576   /* Nothing.  The point of these breakpoints is causing a stop.  */
13577 }
13578
13579 static enum print_stop_action
13580 momentary_bkpt_print_it (bpstat bs)
13581 {
13582   struct ui_out *uiout = current_uiout;
13583
13584   if (ui_out_is_mi_like_p (uiout))
13585     {
13586       struct breakpoint *b = bs->breakpoint_at;
13587
13588       switch (b->type)
13589         {
13590         case bp_finish:
13591           ui_out_field_string
13592             (uiout, "reason",
13593              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13594           break;
13595
13596         case bp_until:
13597           ui_out_field_string
13598             (uiout, "reason",
13599              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13600           break;
13601         }
13602     }
13603
13604   return PRINT_UNKNOWN;
13605 }
13606
13607 static void
13608 momentary_bkpt_print_mention (struct breakpoint *b)
13609 {
13610   /* Nothing to mention.  These breakpoints are internal.  */
13611 }
13612
13613 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13614
13615    It gets cleared already on the removal of the first one of such placed
13616    breakpoints.  This is OK as they get all removed altogether.  */
13617
13618 static void
13619 longjmp_bkpt_dtor (struct breakpoint *self)
13620 {
13621   struct thread_info *tp = find_thread_id (self->thread);
13622
13623   if (tp)
13624     tp->initiating_frame = null_frame_id;
13625
13626   momentary_breakpoint_ops.dtor (self);
13627 }
13628
13629 /* Specific methods for probe breakpoints.  */
13630
13631 static int
13632 bkpt_probe_insert_location (struct bp_location *bl)
13633 {
13634   int v = bkpt_insert_location (bl);
13635
13636   if (v == 0)
13637     {
13638       /* The insertion was successful, now let's set the probe's semaphore
13639          if needed.  */
13640       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13641                                             bl->probe.objfile,
13642                                             bl->gdbarch);
13643     }
13644
13645   return v;
13646 }
13647
13648 static int
13649 bkpt_probe_remove_location (struct bp_location *bl)
13650 {
13651   /* Let's clear the semaphore before removing the location.  */
13652   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13653                                           bl->probe.objfile,
13654                                           bl->gdbarch);
13655
13656   return bkpt_remove_location (bl);
13657 }
13658
13659 static void
13660 bkpt_probe_create_sals_from_address (char **arg,
13661                                      struct linespec_result *canonical,
13662                                      enum bptype type_wanted,
13663                                      char *addr_start, char **copy_arg)
13664 {
13665   struct linespec_sals lsal;
13666
13667   lsal.sals = parse_probes (arg, canonical);
13668
13669   *copy_arg = xstrdup (canonical->addr_string);
13670   lsal.canonical = xstrdup (*copy_arg);
13671
13672   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13673 }
13674
13675 static void
13676 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13677                             struct symtabs_and_lines *sals)
13678 {
13679   *sals = parse_probes (s, NULL);
13680   if (!sals->sals)
13681     error (_("probe not found"));
13682 }
13683
13684 /* The breakpoint_ops structure to be used in tracepoints.  */
13685
13686 static void
13687 tracepoint_re_set (struct breakpoint *b)
13688 {
13689   breakpoint_re_set_default (b);
13690 }
13691
13692 static int
13693 tracepoint_breakpoint_hit (const struct bp_location *bl,
13694                            struct address_space *aspace, CORE_ADDR bp_addr,
13695                            const struct target_waitstatus *ws)
13696 {
13697   /* By definition, the inferior does not report stops at
13698      tracepoints.  */
13699   return 0;
13700 }
13701
13702 static void
13703 tracepoint_print_one_detail (const struct breakpoint *self,
13704                              struct ui_out *uiout)
13705 {
13706   struct tracepoint *tp = (struct tracepoint *) self;
13707   if (tp->static_trace_marker_id)
13708     {
13709       gdb_assert (self->type == bp_static_tracepoint);
13710
13711       ui_out_text (uiout, "\tmarker id is ");
13712       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13713                            tp->static_trace_marker_id);
13714       ui_out_text (uiout, "\n");
13715     }
13716 }
13717
13718 static void
13719 tracepoint_print_mention (struct breakpoint *b)
13720 {
13721   if (ui_out_is_mi_like_p (current_uiout))
13722     return;
13723
13724   switch (b->type)
13725     {
13726     case bp_tracepoint:
13727       printf_filtered (_("Tracepoint"));
13728       printf_filtered (_(" %d"), b->number);
13729       break;
13730     case bp_fast_tracepoint:
13731       printf_filtered (_("Fast tracepoint"));
13732       printf_filtered (_(" %d"), b->number);
13733       break;
13734     case bp_static_tracepoint:
13735       printf_filtered (_("Static tracepoint"));
13736       printf_filtered (_(" %d"), b->number);
13737       break;
13738     default:
13739       internal_error (__FILE__, __LINE__,
13740                       _("unhandled tracepoint type %d"), (int) b->type);
13741     }
13742
13743   say_where (b);
13744 }
13745
13746 static void
13747 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13748 {
13749   struct tracepoint *tp = (struct tracepoint *) self;
13750
13751   if (self->type == bp_fast_tracepoint)
13752     fprintf_unfiltered (fp, "ftrace");
13753   if (self->type == bp_static_tracepoint)
13754     fprintf_unfiltered (fp, "strace");
13755   else if (self->type == bp_tracepoint)
13756     fprintf_unfiltered (fp, "trace");
13757   else
13758     internal_error (__FILE__, __LINE__,
13759                     _("unhandled tracepoint type %d"), (int) self->type);
13760
13761   fprintf_unfiltered (fp, " %s", self->addr_string);
13762   print_recreate_thread (self, fp);
13763
13764   if (tp->pass_count)
13765     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13766 }
13767
13768 static void
13769 tracepoint_create_sals_from_address (char **arg,
13770                                      struct linespec_result *canonical,
13771                                      enum bptype type_wanted,
13772                                      char *addr_start, char **copy_arg)
13773 {
13774   create_sals_from_address_default (arg, canonical, type_wanted,
13775                                     addr_start, copy_arg);
13776 }
13777
13778 static void
13779 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13780                                    struct linespec_result *canonical,
13781                                    char *cond_string,
13782                                    char *extra_string,
13783                                    enum bptype type_wanted,
13784                                    enum bpdisp disposition,
13785                                    int thread,
13786                                    int task, int ignore_count,
13787                                    const struct breakpoint_ops *ops,
13788                                    int from_tty, int enabled,
13789                                    int internal, unsigned flags)
13790 {
13791   create_breakpoints_sal_default (gdbarch, canonical,
13792                                   cond_string, extra_string,
13793                                   type_wanted,
13794                                   disposition, thread, task,
13795                                   ignore_count, ops, from_tty,
13796                                   enabled, internal, flags);
13797 }
13798
13799 static void
13800 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13801                             struct symtabs_and_lines *sals)
13802 {
13803   decode_linespec_default (b, s, sals);
13804 }
13805
13806 struct breakpoint_ops tracepoint_breakpoint_ops;
13807
13808 /* The breakpoint_ops structure to be use on tracepoints placed in a
13809    static probe.  */
13810
13811 static void
13812 tracepoint_probe_create_sals_from_address (char **arg,
13813                                            struct linespec_result *canonical,
13814                                            enum bptype type_wanted,
13815                                            char *addr_start, char **copy_arg)
13816 {
13817   /* We use the same method for breakpoint on probes.  */
13818   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13819                                        addr_start, copy_arg);
13820 }
13821
13822 static void
13823 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13824                                   struct symtabs_and_lines *sals)
13825 {
13826   /* We use the same method for breakpoint on probes.  */
13827   bkpt_probe_decode_linespec (b, s, sals);
13828 }
13829
13830 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13831
13832 /* Dprintf breakpoint_ops methods.  */
13833
13834 static void
13835 dprintf_re_set (struct breakpoint *b)
13836 {
13837   breakpoint_re_set_default (b);
13838
13839   /* This breakpoint could have been pending, and be resolved now, and
13840      if so, we should now have the extra string.  If we don't, the
13841      dprintf was malformed when created, but we couldn't tell because
13842      we can't extract the extra string until the location is
13843      resolved.  */
13844   if (b->loc != NULL && b->extra_string == NULL)
13845     error (_("Format string required"));
13846
13847   /* 1 - connect to target 1, that can run breakpoint commands.
13848      2 - create a dprintf, which resolves fine.
13849      3 - disconnect from target 1
13850      4 - connect to target 2, that can NOT run breakpoint commands.
13851
13852      After steps #3/#4, you'll want the dprintf command list to
13853      be updated, because target 1 and 2 may well return different
13854      answers for target_can_run_breakpoint_commands().
13855      Given absence of finer grained resetting, we get to do
13856      it all the time.  */
13857   if (b->extra_string != NULL)
13858     update_dprintf_command_list (b);
13859 }
13860
13861 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13862
13863 static void
13864 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13865 {
13866   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13867                       tp->extra_string);
13868   print_recreate_thread (tp, fp);
13869 }
13870
13871 /* Implement the "after_condition_true" breakpoint_ops method for
13872    dprintf.
13873
13874    dprintf's are implemented with regular commands in their command
13875    list, but we run the commands here instead of before presenting the
13876    stop to the user, as dprintf's don't actually cause a stop.  This
13877    also makes it so that the commands of multiple dprintfs at the same
13878    address are all handled.  */
13879
13880 static void
13881 dprintf_after_condition_true (struct bpstats *bs)
13882 {
13883   struct cleanup *old_chain;
13884   struct bpstats tmp_bs = { NULL };
13885   struct bpstats *tmp_bs_p = &tmp_bs;
13886
13887   /* dprintf's never cause a stop.  This wasn't set in the
13888      check_status hook instead because that would make the dprintf's
13889      condition not be evaluated.  */
13890   bs->stop = 0;
13891
13892   /* Run the command list here.  Take ownership of it instead of
13893      copying.  We never want these commands to run later in
13894      bpstat_do_actions, if a breakpoint that causes a stop happens to
13895      be set at same address as this dprintf, or even if running the
13896      commands here throws.  */
13897   tmp_bs.commands = bs->commands;
13898   bs->commands = NULL;
13899   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13900
13901   bpstat_do_actions_1 (&tmp_bs_p);
13902
13903   /* 'tmp_bs.commands' will usually be NULL by now, but
13904      bpstat_do_actions_1 may return early without processing the whole
13905      list.  */
13906   do_cleanups (old_chain);
13907 }
13908
13909 /* The breakpoint_ops structure to be used on static tracepoints with
13910    markers (`-m').  */
13911
13912 static void
13913 strace_marker_create_sals_from_address (char **arg,
13914                                         struct linespec_result *canonical,
13915                                         enum bptype type_wanted,
13916                                         char *addr_start, char **copy_arg)
13917 {
13918   struct linespec_sals lsal;
13919
13920   lsal.sals = decode_static_tracepoint_spec (arg);
13921
13922   *copy_arg = savestring (addr_start, *arg - addr_start);
13923
13924   canonical->addr_string = xstrdup (*copy_arg);
13925   lsal.canonical = xstrdup (*copy_arg);
13926   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13927 }
13928
13929 static void
13930 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13931                                       struct linespec_result *canonical,
13932                                       char *cond_string,
13933                                       char *extra_string,
13934                                       enum bptype type_wanted,
13935                                       enum bpdisp disposition,
13936                                       int thread,
13937                                       int task, int ignore_count,
13938                                       const struct breakpoint_ops *ops,
13939                                       int from_tty, int enabled,
13940                                       int internal, unsigned flags)
13941 {
13942   int i;
13943   struct linespec_sals *lsal = VEC_index (linespec_sals,
13944                                           canonical->sals, 0);
13945
13946   /* If the user is creating a static tracepoint by marker id
13947      (strace -m MARKER_ID), then store the sals index, so that
13948      breakpoint_re_set can try to match up which of the newly
13949      found markers corresponds to this one, and, don't try to
13950      expand multiple locations for each sal, given than SALS
13951      already should contain all sals for MARKER_ID.  */
13952
13953   for (i = 0; i < lsal->sals.nelts; ++i)
13954     {
13955       struct symtabs_and_lines expanded;
13956       struct tracepoint *tp;
13957       struct cleanup *old_chain;
13958       char *addr_string;
13959
13960       expanded.nelts = 1;
13961       expanded.sals = &lsal->sals.sals[i];
13962
13963       addr_string = xstrdup (canonical->addr_string);
13964       old_chain = make_cleanup (xfree, addr_string);
13965
13966       tp = XCNEW (struct tracepoint);
13967       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13968                            addr_string, NULL,
13969                            cond_string, extra_string,
13970                            type_wanted, disposition,
13971                            thread, task, ignore_count, ops,
13972                            from_tty, enabled, internal, flags,
13973                            canonical->special_display);
13974       /* Given that its possible to have multiple markers with
13975          the same string id, if the user is creating a static
13976          tracepoint by marker id ("strace -m MARKER_ID"), then
13977          store the sals index, so that breakpoint_re_set can
13978          try to match up which of the newly found markers
13979          corresponds to this one  */
13980       tp->static_trace_marker_id_idx = i;
13981
13982       install_breakpoint (internal, &tp->base, 0);
13983
13984       discard_cleanups (old_chain);
13985     }
13986 }
13987
13988 static void
13989 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13990                                struct symtabs_and_lines *sals)
13991 {
13992   struct tracepoint *tp = (struct tracepoint *) b;
13993
13994   *sals = decode_static_tracepoint_spec (s);
13995   if (sals->nelts > tp->static_trace_marker_id_idx)
13996     {
13997       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13998       sals->nelts = 1;
13999     }
14000   else
14001     error (_("marker %s not found"), tp->static_trace_marker_id);
14002 }
14003
14004 static struct breakpoint_ops strace_marker_breakpoint_ops;
14005
14006 static int
14007 strace_marker_p (struct breakpoint *b)
14008 {
14009   return b->ops == &strace_marker_breakpoint_ops;
14010 }
14011
14012 /* Delete a breakpoint and clean up all traces of it in the data
14013    structures.  */
14014
14015 void
14016 delete_breakpoint (struct breakpoint *bpt)
14017 {
14018   struct breakpoint *b;
14019
14020   gdb_assert (bpt != NULL);
14021
14022   /* Has this bp already been deleted?  This can happen because
14023      multiple lists can hold pointers to bp's.  bpstat lists are
14024      especial culprits.
14025
14026      One example of this happening is a watchpoint's scope bp.  When
14027      the scope bp triggers, we notice that the watchpoint is out of
14028      scope, and delete it.  We also delete its scope bp.  But the
14029      scope bp is marked "auto-deleting", and is already on a bpstat.
14030      That bpstat is then checked for auto-deleting bp's, which are
14031      deleted.
14032
14033      A real solution to this problem might involve reference counts in
14034      bp's, and/or giving them pointers back to their referencing
14035      bpstat's, and teaching delete_breakpoint to only free a bp's
14036      storage when no more references were extent.  A cheaper bandaid
14037      was chosen.  */
14038   if (bpt->type == bp_none)
14039     return;
14040
14041   /* At least avoid this stale reference until the reference counting
14042      of breakpoints gets resolved.  */
14043   if (bpt->related_breakpoint != bpt)
14044     {
14045       struct breakpoint *related;
14046       struct watchpoint *w;
14047
14048       if (bpt->type == bp_watchpoint_scope)
14049         w = (struct watchpoint *) bpt->related_breakpoint;
14050       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14051         w = (struct watchpoint *) bpt;
14052       else
14053         w = NULL;
14054       if (w != NULL)
14055         watchpoint_del_at_next_stop (w);
14056
14057       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14058       for (related = bpt; related->related_breakpoint != bpt;
14059            related = related->related_breakpoint);
14060       related->related_breakpoint = bpt->related_breakpoint;
14061       bpt->related_breakpoint = bpt;
14062     }
14063
14064   /* watch_command_1 creates a watchpoint but only sets its number if
14065      update_watchpoint succeeds in creating its bp_locations.  If there's
14066      a problem in that process, we'll be asked to delete the half-created
14067      watchpoint.  In that case, don't announce the deletion.  */
14068   if (bpt->number)
14069     observer_notify_breakpoint_deleted (bpt);
14070
14071   if (breakpoint_chain == bpt)
14072     breakpoint_chain = bpt->next;
14073
14074   ALL_BREAKPOINTS (b)
14075     if (b->next == bpt)
14076     {
14077       b->next = bpt->next;
14078       break;
14079     }
14080
14081   /* Be sure no bpstat's are pointing at the breakpoint after it's
14082      been freed.  */
14083   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14084      in all threads for now.  Note that we cannot just remove bpstats
14085      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14086      commands are associated with the bpstat; if we remove it here,
14087      then the later call to bpstat_do_actions (&stop_bpstat); in
14088      event-top.c won't do anything, and temporary breakpoints with
14089      commands won't work.  */
14090
14091   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14092
14093   /* Now that breakpoint is removed from breakpoint list, update the
14094      global location list.  This will remove locations that used to
14095      belong to this breakpoint.  Do this before freeing the breakpoint
14096      itself, since remove_breakpoint looks at location's owner.  It
14097      might be better design to have location completely
14098      self-contained, but it's not the case now.  */
14099   update_global_location_list (0);
14100
14101   bpt->ops->dtor (bpt);
14102   /* On the chance that someone will soon try again to delete this
14103      same bp, we mark it as deleted before freeing its storage.  */
14104   bpt->type = bp_none;
14105   xfree (bpt);
14106 }
14107
14108 static void
14109 do_delete_breakpoint_cleanup (void *b)
14110 {
14111   delete_breakpoint (b);
14112 }
14113
14114 struct cleanup *
14115 make_cleanup_delete_breakpoint (struct breakpoint *b)
14116 {
14117   return make_cleanup (do_delete_breakpoint_cleanup, b);
14118 }
14119
14120 /* Iterator function to call a user-provided callback function once
14121    for each of B and its related breakpoints.  */
14122
14123 static void
14124 iterate_over_related_breakpoints (struct breakpoint *b,
14125                                   void (*function) (struct breakpoint *,
14126                                                     void *),
14127                                   void *data)
14128 {
14129   struct breakpoint *related;
14130
14131   related = b;
14132   do
14133     {
14134       struct breakpoint *next;
14135
14136       /* FUNCTION may delete RELATED.  */
14137       next = related->related_breakpoint;
14138
14139       if (next == related)
14140         {
14141           /* RELATED is the last ring entry.  */
14142           function (related, data);
14143
14144           /* FUNCTION may have deleted it, so we'd never reach back to
14145              B.  There's nothing left to do anyway, so just break
14146              out.  */
14147           break;
14148         }
14149       else
14150         function (related, data);
14151
14152       related = next;
14153     }
14154   while (related != b);
14155 }
14156
14157 static void
14158 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14159 {
14160   delete_breakpoint (b);
14161 }
14162
14163 /* A callback for map_breakpoint_numbers that calls
14164    delete_breakpoint.  */
14165
14166 static void
14167 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14168 {
14169   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14170 }
14171
14172 void
14173 delete_command (char *arg, int from_tty)
14174 {
14175   struct breakpoint *b, *b_tmp;
14176
14177   dont_repeat ();
14178
14179   if (arg == 0)
14180     {
14181       int breaks_to_delete = 0;
14182
14183       /* Delete all breakpoints if no argument.  Do not delete
14184          internal breakpoints, these have to be deleted with an
14185          explicit breakpoint number argument.  */
14186       ALL_BREAKPOINTS (b)
14187         if (user_breakpoint_p (b))
14188           {
14189             breaks_to_delete = 1;
14190             break;
14191           }
14192
14193       /* Ask user only if there are some breakpoints to delete.  */
14194       if (!from_tty
14195           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14196         {
14197           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14198             if (user_breakpoint_p (b))
14199               delete_breakpoint (b);
14200         }
14201     }
14202   else
14203     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14204 }
14205
14206 static int
14207 all_locations_are_pending (struct bp_location *loc)
14208 {
14209   for (; loc; loc = loc->next)
14210     if (!loc->shlib_disabled
14211         && !loc->pspace->executing_startup)
14212       return 0;
14213   return 1;
14214 }
14215
14216 /* Subroutine of update_breakpoint_locations to simplify it.
14217    Return non-zero if multiple fns in list LOC have the same name.
14218    Null names are ignored.  */
14219
14220 static int
14221 ambiguous_names_p (struct bp_location *loc)
14222 {
14223   struct bp_location *l;
14224   htab_t htab = htab_create_alloc (13, htab_hash_string,
14225                                    (int (*) (const void *, 
14226                                              const void *)) streq,
14227                                    NULL, xcalloc, xfree);
14228
14229   for (l = loc; l != NULL; l = l->next)
14230     {
14231       const char **slot;
14232       const char *name = l->function_name;
14233
14234       /* Allow for some names to be NULL, ignore them.  */
14235       if (name == NULL)
14236         continue;
14237
14238       slot = (const char **) htab_find_slot (htab, (const void *) name,
14239                                              INSERT);
14240       /* NOTE: We can assume slot != NULL here because xcalloc never
14241          returns NULL.  */
14242       if (*slot != NULL)
14243         {
14244           htab_delete (htab);
14245           return 1;
14246         }
14247       *slot = name;
14248     }
14249
14250   htab_delete (htab);
14251   return 0;
14252 }
14253
14254 /* When symbols change, it probably means the sources changed as well,
14255    and it might mean the static tracepoint markers are no longer at
14256    the same address or line numbers they used to be at last we
14257    checked.  Losing your static tracepoints whenever you rebuild is
14258    undesirable.  This function tries to resync/rematch gdb static
14259    tracepoints with the markers on the target, for static tracepoints
14260    that have not been set by marker id.  Static tracepoint that have
14261    been set by marker id are reset by marker id in breakpoint_re_set.
14262    The heuristic is:
14263
14264    1) For a tracepoint set at a specific address, look for a marker at
14265    the old PC.  If one is found there, assume to be the same marker.
14266    If the name / string id of the marker found is different from the
14267    previous known name, assume that means the user renamed the marker
14268    in the sources, and output a warning.
14269
14270    2) For a tracepoint set at a given line number, look for a marker
14271    at the new address of the old line number.  If one is found there,
14272    assume to be the same marker.  If the name / string id of the
14273    marker found is different from the previous known name, assume that
14274    means the user renamed the marker in the sources, and output a
14275    warning.
14276
14277    3) If a marker is no longer found at the same address or line, it
14278    may mean the marker no longer exists.  But it may also just mean
14279    the code changed a bit.  Maybe the user added a few lines of code
14280    that made the marker move up or down (in line number terms).  Ask
14281    the target for info about the marker with the string id as we knew
14282    it.  If found, update line number and address in the matching
14283    static tracepoint.  This will get confused if there's more than one
14284    marker with the same ID (possible in UST, although unadvised
14285    precisely because it confuses tools).  */
14286
14287 static struct symtab_and_line
14288 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14289 {
14290   struct tracepoint *tp = (struct tracepoint *) b;
14291   struct static_tracepoint_marker marker;
14292   CORE_ADDR pc;
14293
14294   pc = sal.pc;
14295   if (sal.line)
14296     find_line_pc (sal.symtab, sal.line, &pc);
14297
14298   if (target_static_tracepoint_marker_at (pc, &marker))
14299     {
14300       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14301         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14302                  b->number,
14303                  tp->static_trace_marker_id, marker.str_id);
14304
14305       xfree (tp->static_trace_marker_id);
14306       tp->static_trace_marker_id = xstrdup (marker.str_id);
14307       release_static_tracepoint_marker (&marker);
14308
14309       return sal;
14310     }
14311
14312   /* Old marker wasn't found on target at lineno.  Try looking it up
14313      by string ID.  */
14314   if (!sal.explicit_pc
14315       && sal.line != 0
14316       && sal.symtab != NULL
14317       && tp->static_trace_marker_id != NULL)
14318     {
14319       VEC(static_tracepoint_marker_p) *markers;
14320
14321       markers
14322         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14323
14324       if (!VEC_empty(static_tracepoint_marker_p, markers))
14325         {
14326           struct symtab_and_line sal2;
14327           struct symbol *sym;
14328           struct static_tracepoint_marker *tpmarker;
14329           struct ui_out *uiout = current_uiout;
14330
14331           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14332
14333           xfree (tp->static_trace_marker_id);
14334           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14335
14336           warning (_("marker for static tracepoint %d (%s) not "
14337                      "found at previous line number"),
14338                    b->number, tp->static_trace_marker_id);
14339
14340           init_sal (&sal2);
14341
14342           sal2.pc = tpmarker->address;
14343
14344           sal2 = find_pc_line (tpmarker->address, 0);
14345           sym = find_pc_sect_function (tpmarker->address, NULL);
14346           ui_out_text (uiout, "Now in ");
14347           if (sym)
14348             {
14349               ui_out_field_string (uiout, "func",
14350                                    SYMBOL_PRINT_NAME (sym));
14351               ui_out_text (uiout, " at ");
14352             }
14353           ui_out_field_string (uiout, "file",
14354                                symtab_to_filename_for_display (sal2.symtab));
14355           ui_out_text (uiout, ":");
14356
14357           if (ui_out_is_mi_like_p (uiout))
14358             {
14359               const char *fullname = symtab_to_fullname (sal2.symtab);
14360
14361               ui_out_field_string (uiout, "fullname", fullname);
14362             }
14363
14364           ui_out_field_int (uiout, "line", sal2.line);
14365           ui_out_text (uiout, "\n");
14366
14367           b->loc->line_number = sal2.line;
14368           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14369
14370           xfree (b->addr_string);
14371           b->addr_string = xstrprintf ("%s:%d",
14372                                    symtab_to_filename_for_display (sal2.symtab),
14373                                        b->loc->line_number);
14374
14375           /* Might be nice to check if function changed, and warn if
14376              so.  */
14377
14378           release_static_tracepoint_marker (tpmarker);
14379         }
14380     }
14381   return sal;
14382 }
14383
14384 /* Returns 1 iff locations A and B are sufficiently same that
14385    we don't need to report breakpoint as changed.  */
14386
14387 static int
14388 locations_are_equal (struct bp_location *a, struct bp_location *b)
14389 {
14390   while (a && b)
14391     {
14392       if (a->address != b->address)
14393         return 0;
14394
14395       if (a->shlib_disabled != b->shlib_disabled)
14396         return 0;
14397
14398       if (a->enabled != b->enabled)
14399         return 0;
14400
14401       a = a->next;
14402       b = b->next;
14403     }
14404
14405   if ((a == NULL) != (b == NULL))
14406     return 0;
14407
14408   return 1;
14409 }
14410
14411 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14412    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14413    a ranged breakpoint.  */
14414
14415 void
14416 update_breakpoint_locations (struct breakpoint *b,
14417                              struct symtabs_and_lines sals,
14418                              struct symtabs_and_lines sals_end)
14419 {
14420   int i;
14421   struct bp_location *existing_locations = b->loc;
14422
14423   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14424     {
14425       /* Ranged breakpoints have only one start location and one end
14426          location.  */
14427       b->enable_state = bp_disabled;
14428       update_global_location_list (1);
14429       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14430                            "multiple locations found\n"),
14431                          b->number);
14432       return;
14433     }
14434
14435   /* If there's no new locations, and all existing locations are
14436      pending, don't do anything.  This optimizes the common case where
14437      all locations are in the same shared library, that was unloaded.
14438      We'd like to retain the location, so that when the library is
14439      loaded again, we don't loose the enabled/disabled status of the
14440      individual locations.  */
14441   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14442     return;
14443
14444   b->loc = NULL;
14445
14446   for (i = 0; i < sals.nelts; ++i)
14447     {
14448       struct bp_location *new_loc;
14449
14450       switch_to_program_space_and_thread (sals.sals[i].pspace);
14451
14452       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14453
14454       /* Reparse conditions, they might contain references to the
14455          old symtab.  */
14456       if (b->cond_string != NULL)
14457         {
14458           const char *s;
14459           volatile struct gdb_exception e;
14460
14461           s = b->cond_string;
14462           TRY_CATCH (e, RETURN_MASK_ERROR)
14463             {
14464               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14465                                            block_for_pc (sals.sals[i].pc), 
14466                                            0);
14467             }
14468           if (e.reason < 0)
14469             {
14470               warning (_("failed to reevaluate condition "
14471                          "for breakpoint %d: %s"), 
14472                        b->number, e.message);
14473               new_loc->enabled = 0;
14474             }
14475         }
14476
14477       if (sals_end.nelts)
14478         {
14479           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14480
14481           new_loc->length = end - sals.sals[0].pc + 1;
14482         }
14483     }
14484
14485   /* Update locations of permanent breakpoints.  */
14486   if (b->enable_state == bp_permanent)
14487     make_breakpoint_permanent (b);
14488
14489   /* If possible, carry over 'disable' status from existing
14490      breakpoints.  */
14491   {
14492     struct bp_location *e = existing_locations;
14493     /* If there are multiple breakpoints with the same function name,
14494        e.g. for inline functions, comparing function names won't work.
14495        Instead compare pc addresses; this is just a heuristic as things
14496        may have moved, but in practice it gives the correct answer
14497        often enough until a better solution is found.  */
14498     int have_ambiguous_names = ambiguous_names_p (b->loc);
14499
14500     for (; e; e = e->next)
14501       {
14502         if (!e->enabled && e->function_name)
14503           {
14504             struct bp_location *l = b->loc;
14505             if (have_ambiguous_names)
14506               {
14507                 for (; l; l = l->next)
14508                   if (breakpoint_locations_match (e, l))
14509                     {
14510                       l->enabled = 0;
14511                       break;
14512                     }
14513               }
14514             else
14515               {
14516                 for (; l; l = l->next)
14517                   if (l->function_name
14518                       && strcmp (e->function_name, l->function_name) == 0)
14519                     {
14520                       l->enabled = 0;
14521                       break;
14522                     }
14523               }
14524           }
14525       }
14526   }
14527
14528   if (!locations_are_equal (existing_locations, b->loc))
14529     observer_notify_breakpoint_modified (b);
14530
14531   update_global_location_list (1);
14532 }
14533
14534 /* Find the SaL locations corresponding to the given ADDR_STRING.
14535    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14536
14537 static struct symtabs_and_lines
14538 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14539 {
14540   char *s;
14541   struct symtabs_and_lines sals = {0};
14542   volatile struct gdb_exception e;
14543
14544   gdb_assert (b->ops != NULL);
14545   s = addr_string;
14546
14547   TRY_CATCH (e, RETURN_MASK_ERROR)
14548     {
14549       b->ops->decode_linespec (b, &s, &sals);
14550     }
14551   if (e.reason < 0)
14552     {
14553       int not_found_and_ok = 0;
14554       /* For pending breakpoints, it's expected that parsing will
14555          fail until the right shared library is loaded.  User has
14556          already told to create pending breakpoints and don't need
14557          extra messages.  If breakpoint is in bp_shlib_disabled
14558          state, then user already saw the message about that
14559          breakpoint being disabled, and don't want to see more
14560          errors.  */
14561       if (e.error == NOT_FOUND_ERROR
14562           && (b->condition_not_parsed 
14563               || (b->loc && b->loc->shlib_disabled)
14564               || (b->loc && b->loc->pspace->executing_startup)
14565               || b->enable_state == bp_disabled))
14566         not_found_and_ok = 1;
14567
14568       if (!not_found_and_ok)
14569         {
14570           /* We surely don't want to warn about the same breakpoint
14571              10 times.  One solution, implemented here, is disable
14572              the breakpoint on error.  Another solution would be to
14573              have separate 'warning emitted' flag.  Since this
14574              happens only when a binary has changed, I don't know
14575              which approach is better.  */
14576           b->enable_state = bp_disabled;
14577           throw_exception (e);
14578         }
14579     }
14580
14581   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14582     {
14583       int i;
14584
14585       for (i = 0; i < sals.nelts; ++i)
14586         resolve_sal_pc (&sals.sals[i]);
14587       if (b->condition_not_parsed && s && s[0])
14588         {
14589           char *cond_string, *extra_string;
14590           int thread, task;
14591
14592           find_condition_and_thread (s, sals.sals[0].pc,
14593                                      &cond_string, &thread, &task,
14594                                      &extra_string);
14595           if (cond_string)
14596             b->cond_string = cond_string;
14597           b->thread = thread;
14598           b->task = task;
14599           if (extra_string)
14600             b->extra_string = extra_string;
14601           b->condition_not_parsed = 0;
14602         }
14603
14604       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14605         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14606
14607       *found = 1;
14608     }
14609   else
14610     *found = 0;
14611
14612   return sals;
14613 }
14614
14615 /* The default re_set method, for typical hardware or software
14616    breakpoints.  Reevaluate the breakpoint and recreate its
14617    locations.  */
14618
14619 static void
14620 breakpoint_re_set_default (struct breakpoint *b)
14621 {
14622   int found;
14623   struct symtabs_and_lines sals, sals_end;
14624   struct symtabs_and_lines expanded = {0};
14625   struct symtabs_and_lines expanded_end = {0};
14626
14627   sals = addr_string_to_sals (b, b->addr_string, &found);
14628   if (found)
14629     {
14630       make_cleanup (xfree, sals.sals);
14631       expanded = sals;
14632     }
14633
14634   if (b->addr_string_range_end)
14635     {
14636       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14637       if (found)
14638         {
14639           make_cleanup (xfree, sals_end.sals);
14640           expanded_end = sals_end;
14641         }
14642     }
14643
14644   update_breakpoint_locations (b, expanded, expanded_end);
14645 }
14646
14647 /* Default method for creating SALs from an address string.  It basically
14648    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14649
14650 static void
14651 create_sals_from_address_default (char **arg,
14652                                   struct linespec_result *canonical,
14653                                   enum bptype type_wanted,
14654                                   char *addr_start, char **copy_arg)
14655 {
14656   parse_breakpoint_sals (arg, canonical);
14657 }
14658
14659 /* Call create_breakpoints_sal for the given arguments.  This is the default
14660    function for the `create_breakpoints_sal' method of
14661    breakpoint_ops.  */
14662
14663 static void
14664 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14665                                 struct linespec_result *canonical,
14666                                 char *cond_string,
14667                                 char *extra_string,
14668                                 enum bptype type_wanted,
14669                                 enum bpdisp disposition,
14670                                 int thread,
14671                                 int task, int ignore_count,
14672                                 const struct breakpoint_ops *ops,
14673                                 int from_tty, int enabled,
14674                                 int internal, unsigned flags)
14675 {
14676   create_breakpoints_sal (gdbarch, canonical, cond_string,
14677                           extra_string,
14678                           type_wanted, disposition,
14679                           thread, task, ignore_count, ops, from_tty,
14680                           enabled, internal, flags);
14681 }
14682
14683 /* Decode the line represented by S by calling decode_line_full.  This is the
14684    default function for the `decode_linespec' method of breakpoint_ops.  */
14685
14686 static void
14687 decode_linespec_default (struct breakpoint *b, char **s,
14688                          struct symtabs_and_lines *sals)
14689 {
14690   struct linespec_result canonical;
14691
14692   init_linespec_result (&canonical);
14693   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14694                     (struct symtab *) NULL, 0,
14695                     &canonical, multiple_symbols_all,
14696                     b->filter);
14697
14698   /* We should get 0 or 1 resulting SALs.  */
14699   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14700
14701   if (VEC_length (linespec_sals, canonical.sals) > 0)
14702     {
14703       struct linespec_sals *lsal;
14704
14705       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14706       *sals = lsal->sals;
14707       /* Arrange it so the destructor does not free the
14708          contents.  */
14709       lsal->sals.sals = NULL;
14710     }
14711
14712   destroy_linespec_result (&canonical);
14713 }
14714
14715 /* Prepare the global context for a re-set of breakpoint B.  */
14716
14717 static struct cleanup *
14718 prepare_re_set_context (struct breakpoint *b)
14719 {
14720   struct cleanup *cleanups;
14721
14722   input_radix = b->input_radix;
14723   cleanups = save_current_space_and_thread ();
14724   if (b->pspace != NULL)
14725     switch_to_program_space_and_thread (b->pspace);
14726   set_language (b->language);
14727
14728   return cleanups;
14729 }
14730
14731 /* Reset a breakpoint given it's struct breakpoint * BINT.
14732    The value we return ends up being the return value from catch_errors.
14733    Unused in this case.  */
14734
14735 static int
14736 breakpoint_re_set_one (void *bint)
14737 {
14738   /* Get past catch_errs.  */
14739   struct breakpoint *b = (struct breakpoint *) bint;
14740   struct cleanup *cleanups;
14741
14742   cleanups = prepare_re_set_context (b);
14743   b->ops->re_set (b);
14744   do_cleanups (cleanups);
14745   return 0;
14746 }
14747
14748 /* Re-set all breakpoints after symbols have been re-loaded.  */
14749 void
14750 breakpoint_re_set (void)
14751 {
14752   struct breakpoint *b, *b_tmp;
14753   enum language save_language;
14754   int save_input_radix;
14755   struct cleanup *old_chain;
14756
14757   save_language = current_language->la_language;
14758   save_input_radix = input_radix;
14759   old_chain = save_current_program_space ();
14760
14761   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14762   {
14763     /* Format possible error msg.  */
14764     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14765                                 b->number);
14766     struct cleanup *cleanups = make_cleanup (xfree, message);
14767     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14768     do_cleanups (cleanups);
14769   }
14770   set_language (save_language);
14771   input_radix = save_input_radix;
14772
14773   jit_breakpoint_re_set ();
14774
14775   do_cleanups (old_chain);
14776
14777   create_overlay_event_breakpoint ();
14778   create_longjmp_master_breakpoint ();
14779   create_std_terminate_master_breakpoint ();
14780   create_exception_master_breakpoint ();
14781 }
14782 \f
14783 /* Reset the thread number of this breakpoint:
14784
14785    - If the breakpoint is for all threads, leave it as-is.
14786    - Else, reset it to the current thread for inferior_ptid.  */
14787 void
14788 breakpoint_re_set_thread (struct breakpoint *b)
14789 {
14790   if (b->thread != -1)
14791     {
14792       if (in_thread_list (inferior_ptid))
14793         b->thread = pid_to_thread_id (inferior_ptid);
14794
14795       /* We're being called after following a fork.  The new fork is
14796          selected as current, and unless this was a vfork will have a
14797          different program space from the original thread.  Reset that
14798          as well.  */
14799       b->loc->pspace = current_program_space;
14800     }
14801 }
14802
14803 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14804    If from_tty is nonzero, it prints a message to that effect,
14805    which ends with a period (no newline).  */
14806
14807 void
14808 set_ignore_count (int bptnum, int count, int from_tty)
14809 {
14810   struct breakpoint *b;
14811
14812   if (count < 0)
14813     count = 0;
14814
14815   ALL_BREAKPOINTS (b)
14816     if (b->number == bptnum)
14817     {
14818       if (is_tracepoint (b))
14819         {
14820           if (from_tty && count != 0)
14821             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14822                              bptnum);
14823           return;
14824         }
14825       
14826       b->ignore_count = count;
14827       if (from_tty)
14828         {
14829           if (count == 0)
14830             printf_filtered (_("Will stop next time "
14831                                "breakpoint %d is reached."),
14832                              bptnum);
14833           else if (count == 1)
14834             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14835                              bptnum);
14836           else
14837             printf_filtered (_("Will ignore next %d "
14838                                "crossings of breakpoint %d."),
14839                              count, bptnum);
14840         }
14841       observer_notify_breakpoint_modified (b);
14842       return;
14843     }
14844
14845   error (_("No breakpoint number %d."), bptnum);
14846 }
14847
14848 /* Command to set ignore-count of breakpoint N to COUNT.  */
14849
14850 static void
14851 ignore_command (char *args, int from_tty)
14852 {
14853   char *p = args;
14854   int num;
14855
14856   if (p == 0)
14857     error_no_arg (_("a breakpoint number"));
14858
14859   num = get_number (&p);
14860   if (num == 0)
14861     error (_("bad breakpoint number: '%s'"), args);
14862   if (*p == 0)
14863     error (_("Second argument (specified ignore-count) is missing."));
14864
14865   set_ignore_count (num,
14866                     longest_to_int (value_as_long (parse_and_eval (p))),
14867                     from_tty);
14868   if (from_tty)
14869     printf_filtered ("\n");
14870 }
14871 \f
14872 /* Call FUNCTION on each of the breakpoints
14873    whose numbers are given in ARGS.  */
14874
14875 static void
14876 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14877                                                       void *),
14878                         void *data)
14879 {
14880   int num;
14881   struct breakpoint *b, *tmp;
14882   int match;
14883   struct get_number_or_range_state state;
14884
14885   if (args == 0)
14886     error_no_arg (_("one or more breakpoint numbers"));
14887
14888   init_number_or_range (&state, args);
14889
14890   while (!state.finished)
14891     {
14892       const char *p = state.string;
14893
14894       match = 0;
14895
14896       num = get_number_or_range (&state);
14897       if (num == 0)
14898         {
14899           warning (_("bad breakpoint number at or near '%s'"), p);
14900         }
14901       else
14902         {
14903           ALL_BREAKPOINTS_SAFE (b, tmp)
14904             if (b->number == num)
14905               {
14906                 match = 1;
14907                 function (b, data);
14908                 break;
14909               }
14910           if (match == 0)
14911             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14912         }
14913     }
14914 }
14915
14916 static struct bp_location *
14917 find_location_by_number (char *number)
14918 {
14919   char *dot = strchr (number, '.');
14920   char *p1;
14921   int bp_num;
14922   int loc_num;
14923   struct breakpoint *b;
14924   struct bp_location *loc;  
14925
14926   *dot = '\0';
14927
14928   p1 = number;
14929   bp_num = get_number (&p1);
14930   if (bp_num == 0)
14931     error (_("Bad breakpoint number '%s'"), number);
14932
14933   ALL_BREAKPOINTS (b)
14934     if (b->number == bp_num)
14935       {
14936         break;
14937       }
14938
14939   if (!b || b->number != bp_num)
14940     error (_("Bad breakpoint number '%s'"), number);
14941   
14942   p1 = dot+1;
14943   loc_num = get_number (&p1);
14944   if (loc_num == 0)
14945     error (_("Bad breakpoint location number '%s'"), number);
14946
14947   --loc_num;
14948   loc = b->loc;
14949   for (;loc_num && loc; --loc_num, loc = loc->next)
14950     ;
14951   if (!loc)
14952     error (_("Bad breakpoint location number '%s'"), dot+1);
14953     
14954   return loc;  
14955 }
14956
14957
14958 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14959    If from_tty is nonzero, it prints a message to that effect,
14960    which ends with a period (no newline).  */
14961
14962 void
14963 disable_breakpoint (struct breakpoint *bpt)
14964 {
14965   /* Never disable a watchpoint scope breakpoint; we want to
14966      hit them when we leave scope so we can delete both the
14967      watchpoint and its scope breakpoint at that time.  */
14968   if (bpt->type == bp_watchpoint_scope)
14969     return;
14970
14971   /* You can't disable permanent breakpoints.  */
14972   if (bpt->enable_state == bp_permanent)
14973     return;
14974
14975   bpt->enable_state = bp_disabled;
14976
14977   /* Mark breakpoint locations modified.  */
14978   mark_breakpoint_modified (bpt);
14979
14980   if (target_supports_enable_disable_tracepoint ()
14981       && current_trace_status ()->running && is_tracepoint (bpt))
14982     {
14983       struct bp_location *location;
14984      
14985       for (location = bpt->loc; location; location = location->next)
14986         target_disable_tracepoint (location);
14987     }
14988
14989   update_global_location_list (0);
14990
14991   observer_notify_breakpoint_modified (bpt);
14992 }
14993
14994 /* A callback for iterate_over_related_breakpoints.  */
14995
14996 static void
14997 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14998 {
14999   disable_breakpoint (b);
15000 }
15001
15002 /* A callback for map_breakpoint_numbers that calls
15003    disable_breakpoint.  */
15004
15005 static void
15006 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15007 {
15008   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15009 }
15010
15011 static void
15012 disable_command (char *args, int from_tty)
15013 {
15014   if (args == 0)
15015     {
15016       struct breakpoint *bpt;
15017
15018       ALL_BREAKPOINTS (bpt)
15019         if (user_breakpoint_p (bpt))
15020           disable_breakpoint (bpt);
15021     }
15022   else
15023     {
15024       char *num = extract_arg (&args);
15025
15026       while (num)
15027         {
15028           if (strchr (num, '.'))
15029             {
15030               struct bp_location *loc = find_location_by_number (num);
15031
15032               if (loc)
15033                 {
15034                   if (loc->enabled)
15035                     {
15036                       loc->enabled = 0;
15037                       mark_breakpoint_location_modified (loc);
15038                     }
15039                   if (target_supports_enable_disable_tracepoint ()
15040                       && current_trace_status ()->running && loc->owner
15041                       && is_tracepoint (loc->owner))
15042                     target_disable_tracepoint (loc);
15043                 }
15044               update_global_location_list (0);
15045             }
15046           else
15047             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15048           num = extract_arg (&args);
15049         }
15050     }
15051 }
15052
15053 static void
15054 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15055                         int count)
15056 {
15057   int target_resources_ok;
15058
15059   if (bpt->type == bp_hardware_breakpoint)
15060     {
15061       int i;
15062       i = hw_breakpoint_used_count ();
15063       target_resources_ok = 
15064         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15065                                             i + 1, 0);
15066       if (target_resources_ok == 0)
15067         error (_("No hardware breakpoint support in the target."));
15068       else if (target_resources_ok < 0)
15069         error (_("Hardware breakpoints used exceeds limit."));
15070     }
15071
15072   if (is_watchpoint (bpt))
15073     {
15074       /* Initialize it just to avoid a GCC false warning.  */
15075       enum enable_state orig_enable_state = 0;
15076       volatile struct gdb_exception e;
15077
15078       TRY_CATCH (e, RETURN_MASK_ALL)
15079         {
15080           struct watchpoint *w = (struct watchpoint *) bpt;
15081
15082           orig_enable_state = bpt->enable_state;
15083           bpt->enable_state = bp_enabled;
15084           update_watchpoint (w, 1 /* reparse */);
15085         }
15086       if (e.reason < 0)
15087         {
15088           bpt->enable_state = orig_enable_state;
15089           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15090                              bpt->number);
15091           return;
15092         }
15093     }
15094
15095   if (bpt->enable_state != bp_permanent)
15096     bpt->enable_state = bp_enabled;
15097
15098   bpt->enable_state = bp_enabled;
15099
15100   /* Mark breakpoint locations modified.  */
15101   mark_breakpoint_modified (bpt);
15102
15103   if (target_supports_enable_disable_tracepoint ()
15104       && current_trace_status ()->running && is_tracepoint (bpt))
15105     {
15106       struct bp_location *location;
15107
15108       for (location = bpt->loc; location; location = location->next)
15109         target_enable_tracepoint (location);
15110     }
15111
15112   bpt->disposition = disposition;
15113   bpt->enable_count = count;
15114   update_global_location_list (1);
15115
15116   observer_notify_breakpoint_modified (bpt);
15117 }
15118
15119
15120 void
15121 enable_breakpoint (struct breakpoint *bpt)
15122 {
15123   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15124 }
15125
15126 static void
15127 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15128 {
15129   enable_breakpoint (bpt);
15130 }
15131
15132 /* A callback for map_breakpoint_numbers that calls
15133    enable_breakpoint.  */
15134
15135 static void
15136 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15137 {
15138   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15139 }
15140
15141 /* The enable command enables the specified breakpoints (or all defined
15142    breakpoints) so they once again become (or continue to be) effective
15143    in stopping the inferior.  */
15144
15145 static void
15146 enable_command (char *args, int from_tty)
15147 {
15148   if (args == 0)
15149     {
15150       struct breakpoint *bpt;
15151
15152       ALL_BREAKPOINTS (bpt)
15153         if (user_breakpoint_p (bpt))
15154           enable_breakpoint (bpt);
15155     }
15156   else
15157     {
15158       char *num = extract_arg (&args);
15159
15160       while (num)
15161         {
15162           if (strchr (num, '.'))
15163             {
15164               struct bp_location *loc = find_location_by_number (num);
15165
15166               if (loc)
15167                 {
15168                   if (!loc->enabled)
15169                     {
15170                       loc->enabled = 1;
15171                       mark_breakpoint_location_modified (loc);
15172                     }
15173                   if (target_supports_enable_disable_tracepoint ()
15174                       && current_trace_status ()->running && loc->owner
15175                       && is_tracepoint (loc->owner))
15176                     target_enable_tracepoint (loc);
15177                 }
15178               update_global_location_list (1);
15179             }
15180           else
15181             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15182           num = extract_arg (&args);
15183         }
15184     }
15185 }
15186
15187 /* This struct packages up disposition data for application to multiple
15188    breakpoints.  */
15189
15190 struct disp_data
15191 {
15192   enum bpdisp disp;
15193   int count;
15194 };
15195
15196 static void
15197 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15198 {
15199   struct disp_data disp_data = *(struct disp_data *) arg;
15200
15201   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15202 }
15203
15204 static void
15205 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15206 {
15207   struct disp_data disp = { disp_disable, 1 };
15208
15209   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15210 }
15211
15212 static void
15213 enable_once_command (char *args, int from_tty)
15214 {
15215   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15216 }
15217
15218 static void
15219 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15220 {
15221   struct disp_data disp = { disp_disable, *(int *) countptr };
15222
15223   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15224 }
15225
15226 static void
15227 enable_count_command (char *args, int from_tty)
15228 {
15229   int count = get_number (&args);
15230
15231   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15232 }
15233
15234 static void
15235 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15236 {
15237   struct disp_data disp = { disp_del, 1 };
15238
15239   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15240 }
15241
15242 static void
15243 enable_delete_command (char *args, int from_tty)
15244 {
15245   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15246 }
15247 \f
15248 static void
15249 set_breakpoint_cmd (char *args, int from_tty)
15250 {
15251 }
15252
15253 static void
15254 show_breakpoint_cmd (char *args, int from_tty)
15255 {
15256 }
15257
15258 /* Invalidate last known value of any hardware watchpoint if
15259    the memory which that value represents has been written to by
15260    GDB itself.  */
15261
15262 static void
15263 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15264                                       CORE_ADDR addr, ssize_t len,
15265                                       const bfd_byte *data)
15266 {
15267   struct breakpoint *bp;
15268
15269   ALL_BREAKPOINTS (bp)
15270     if (bp->enable_state == bp_enabled
15271         && bp->type == bp_hardware_watchpoint)
15272       {
15273         struct watchpoint *wp = (struct watchpoint *) bp;
15274
15275         if (wp->val_valid && wp->val)
15276           {
15277             struct bp_location *loc;
15278
15279             for (loc = bp->loc; loc != NULL; loc = loc->next)
15280               if (loc->loc_type == bp_loc_hardware_watchpoint
15281                   && loc->address + loc->length > addr
15282                   && addr + len > loc->address)
15283                 {
15284                   value_free (wp->val);
15285                   wp->val = NULL;
15286                   wp->val_valid = 0;
15287                 }
15288           }
15289       }
15290 }
15291
15292 /* Create and insert a raw software breakpoint at PC.  Return an
15293    identifier, which should be used to remove the breakpoint later.
15294    In general, places which call this should be using something on the
15295    breakpoint chain instead; this function should be eliminated
15296    someday.  */
15297
15298 void *
15299 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15300                                   struct address_space *aspace, CORE_ADDR pc)
15301 {
15302   struct bp_target_info *bp_tgt;
15303   struct bp_location *bl;
15304
15305   bp_tgt = XCNEW (struct bp_target_info);
15306
15307   bp_tgt->placed_address_space = aspace;
15308   bp_tgt->placed_address = pc;
15309
15310   /* If an unconditional non-raw breakpoint is already inserted at
15311      that location, there's no need to insert another.  However, with
15312      target-side evaluation of breakpoint conditions, if the
15313      breakpoint that is currently inserted on the target is
15314      conditional, we need to make it unconditional.  Note that a
15315      breakpoint with target-side commands is not reported even if
15316      unconditional, so we need to remove the commands from the target
15317      as well.  */
15318   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15319   if (bl != NULL
15320       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15321       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15322     {
15323       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15324       return bp_tgt;
15325     }
15326
15327   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15328     {
15329       /* Could not insert the breakpoint.  */
15330       xfree (bp_tgt);
15331       return NULL;
15332     }
15333
15334   return bp_tgt;
15335 }
15336
15337 /* Remove a breakpoint BP inserted by
15338    deprecated_insert_raw_breakpoint.  */
15339
15340 int
15341 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15342 {
15343   struct bp_target_info *bp_tgt = bp;
15344   struct address_space *aspace = bp_tgt->placed_address_space;
15345   CORE_ADDR address = bp_tgt->placed_address;
15346   struct bp_location *bl;
15347   int ret;
15348
15349   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15350
15351   /* Only remove the raw breakpoint if there are no other non-raw
15352      breakpoints still inserted at this location.  Otherwise, we would
15353      be effectively disabling those breakpoints.  */
15354   if (bl == NULL)
15355     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15356   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15357            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15358     {
15359       /* The target is evaluating conditions, and when we inserted the
15360          software single-step breakpoint, we had made the breakpoint
15361          unconditional and command-less on the target side.  Reinsert
15362          to restore the conditions/commands.  */
15363       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15364     }
15365   else
15366     ret = 0;
15367
15368   xfree (bp_tgt);
15369
15370   return ret;
15371 }
15372
15373 /* Create and insert a breakpoint for software single step.  */
15374
15375 void
15376 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15377                                struct address_space *aspace, 
15378                                CORE_ADDR next_pc)
15379 {
15380   void **bpt_p;
15381
15382   if (single_step_breakpoints[0] == NULL)
15383     {
15384       bpt_p = &single_step_breakpoints[0];
15385       single_step_gdbarch[0] = gdbarch;
15386     }
15387   else
15388     {
15389       gdb_assert (single_step_breakpoints[1] == NULL);
15390       bpt_p = &single_step_breakpoints[1];
15391       single_step_gdbarch[1] = gdbarch;
15392     }
15393
15394   /* NOTE drow/2006-04-11: A future improvement to this function would
15395      be to only create the breakpoints once, and actually put them on
15396      the breakpoint chain.  That would let us use set_raw_breakpoint.
15397      We could adjust the addresses each time they were needed.  Doing
15398      this requires corresponding changes elsewhere where single step
15399      breakpoints are handled, however.  So, for now, we use this.  */
15400
15401   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15402   if (*bpt_p == NULL)
15403     error (_("Could not insert single-step breakpoint at %s"),
15404              paddress (gdbarch, next_pc));
15405 }
15406
15407 /* Check if the breakpoints used for software single stepping
15408    were inserted or not.  */
15409
15410 int
15411 single_step_breakpoints_inserted (void)
15412 {
15413   return (single_step_breakpoints[0] != NULL
15414           || single_step_breakpoints[1] != NULL);
15415 }
15416
15417 /* Remove and delete any breakpoints used for software single step.  */
15418
15419 void
15420 remove_single_step_breakpoints (void)
15421 {
15422   gdb_assert (single_step_breakpoints[0] != NULL);
15423
15424   /* See insert_single_step_breakpoint for more about this deprecated
15425      call.  */
15426   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15427                                     single_step_breakpoints[0]);
15428   single_step_gdbarch[0] = NULL;
15429   single_step_breakpoints[0] = NULL;
15430
15431   if (single_step_breakpoints[1] != NULL)
15432     {
15433       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15434                                         single_step_breakpoints[1]);
15435       single_step_gdbarch[1] = NULL;
15436       single_step_breakpoints[1] = NULL;
15437     }
15438 }
15439
15440 /* Delete software single step breakpoints without removing them from
15441    the inferior.  This is intended to be used if the inferior's address
15442    space where they were inserted is already gone, e.g. after exit or
15443    exec.  */
15444
15445 void
15446 cancel_single_step_breakpoints (void)
15447 {
15448   int i;
15449
15450   for (i = 0; i < 2; i++)
15451     if (single_step_breakpoints[i])
15452       {
15453         xfree (single_step_breakpoints[i]);
15454         single_step_breakpoints[i] = NULL;
15455         single_step_gdbarch[i] = NULL;
15456       }
15457 }
15458
15459 /* Detach software single-step breakpoints from INFERIOR_PTID without
15460    removing them.  */
15461
15462 static void
15463 detach_single_step_breakpoints (void)
15464 {
15465   int i;
15466
15467   for (i = 0; i < 2; i++)
15468     if (single_step_breakpoints[i])
15469       target_remove_breakpoint (single_step_gdbarch[i],
15470                                 single_step_breakpoints[i]);
15471 }
15472
15473 /* Find the software single-step breakpoint that inserted at PC.
15474    Returns its slot if found, and -1 if not found.  */
15475
15476 static int
15477 find_single_step_breakpoint (struct address_space *aspace,
15478                              CORE_ADDR pc)
15479 {
15480   int i;
15481
15482   for (i = 0; i < 2; i++)
15483     {
15484       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15485       if (bp_tgt
15486           && breakpoint_address_match (bp_tgt->placed_address_space,
15487                                        bp_tgt->placed_address,
15488                                        aspace, pc))
15489         return i;
15490     }
15491
15492   return -1;
15493 }
15494
15495 /* Check whether a software single-step breakpoint is inserted at
15496    PC.  */
15497
15498 int
15499 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15500                                         CORE_ADDR pc)
15501 {
15502   return find_single_step_breakpoint (aspace, pc) >= 0;
15503 }
15504
15505 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15506    non-zero otherwise.  */
15507 static int
15508 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15509 {
15510   if (syscall_catchpoint_p (bp)
15511       && bp->enable_state != bp_disabled
15512       && bp->enable_state != bp_call_disabled)
15513     return 1;
15514   else
15515     return 0;
15516 }
15517
15518 int
15519 catch_syscall_enabled (void)
15520 {
15521   struct catch_syscall_inferior_data *inf_data
15522     = get_catch_syscall_inferior_data (current_inferior ());
15523
15524   return inf_data->total_syscalls_count != 0;
15525 }
15526
15527 int
15528 catching_syscall_number (int syscall_number)
15529 {
15530   struct breakpoint *bp;
15531
15532   ALL_BREAKPOINTS (bp)
15533     if (is_syscall_catchpoint_enabled (bp))
15534       {
15535         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15536
15537         if (c->syscalls_to_be_caught)
15538           {
15539             int i, iter;
15540             for (i = 0;
15541                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15542                  i++)
15543               if (syscall_number == iter)
15544                 return 1;
15545           }
15546         else
15547           return 1;
15548       }
15549
15550   return 0;
15551 }
15552
15553 /* Complete syscall names.  Used by "catch syscall".  */
15554 static VEC (char_ptr) *
15555 catch_syscall_completer (struct cmd_list_element *cmd,
15556                          const char *text, const char *word)
15557 {
15558   const char **list = get_syscall_names ();
15559   VEC (char_ptr) *retlist
15560     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15561
15562   xfree (list);
15563   return retlist;
15564 }
15565
15566 /* Tracepoint-specific operations.  */
15567
15568 /* Set tracepoint count to NUM.  */
15569 static void
15570 set_tracepoint_count (int num)
15571 {
15572   tracepoint_count = num;
15573   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15574 }
15575
15576 static void
15577 trace_command (char *arg, int from_tty)
15578 {
15579   struct breakpoint_ops *ops;
15580   const char *arg_cp = arg;
15581
15582   if (arg && probe_linespec_to_ops (&arg_cp))
15583     ops = &tracepoint_probe_breakpoint_ops;
15584   else
15585     ops = &tracepoint_breakpoint_ops;
15586
15587   create_breakpoint (get_current_arch (),
15588                      arg,
15589                      NULL, 0, NULL, 1 /* parse arg */,
15590                      0 /* tempflag */,
15591                      bp_tracepoint /* type_wanted */,
15592                      0 /* Ignore count */,
15593                      pending_break_support,
15594                      ops,
15595                      from_tty,
15596                      1 /* enabled */,
15597                      0 /* internal */, 0);
15598 }
15599
15600 static void
15601 ftrace_command (char *arg, int from_tty)
15602 {
15603   create_breakpoint (get_current_arch (),
15604                      arg,
15605                      NULL, 0, NULL, 1 /* parse arg */,
15606                      0 /* tempflag */,
15607                      bp_fast_tracepoint /* type_wanted */,
15608                      0 /* Ignore count */,
15609                      pending_break_support,
15610                      &tracepoint_breakpoint_ops,
15611                      from_tty,
15612                      1 /* enabled */,
15613                      0 /* internal */, 0);
15614 }
15615
15616 /* strace command implementation.  Creates a static tracepoint.  */
15617
15618 static void
15619 strace_command (char *arg, int from_tty)
15620 {
15621   struct breakpoint_ops *ops;
15622
15623   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15624      or with a normal static tracepoint.  */
15625   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15626     ops = &strace_marker_breakpoint_ops;
15627   else
15628     ops = &tracepoint_breakpoint_ops;
15629
15630   create_breakpoint (get_current_arch (),
15631                      arg,
15632                      NULL, 0, NULL, 1 /* parse arg */,
15633                      0 /* tempflag */,
15634                      bp_static_tracepoint /* type_wanted */,
15635                      0 /* Ignore count */,
15636                      pending_break_support,
15637                      ops,
15638                      from_tty,
15639                      1 /* enabled */,
15640                      0 /* internal */, 0);
15641 }
15642
15643 /* Set up a fake reader function that gets command lines from a linked
15644    list that was acquired during tracepoint uploading.  */
15645
15646 static struct uploaded_tp *this_utp;
15647 static int next_cmd;
15648
15649 static char *
15650 read_uploaded_action (void)
15651 {
15652   char *rslt;
15653
15654   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15655
15656   next_cmd++;
15657
15658   return rslt;
15659 }
15660
15661 /* Given information about a tracepoint as recorded on a target (which
15662    can be either a live system or a trace file), attempt to create an
15663    equivalent GDB tracepoint.  This is not a reliable process, since
15664    the target does not necessarily have all the information used when
15665    the tracepoint was originally defined.  */
15666   
15667 struct tracepoint *
15668 create_tracepoint_from_upload (struct uploaded_tp *utp)
15669 {
15670   char *addr_str, small_buf[100];
15671   struct tracepoint *tp;
15672
15673   if (utp->at_string)
15674     addr_str = utp->at_string;
15675   else
15676     {
15677       /* In the absence of a source location, fall back to raw
15678          address.  Since there is no way to confirm that the address
15679          means the same thing as when the trace was started, warn the
15680          user.  */
15681       warning (_("Uploaded tracepoint %d has no "
15682                  "source location, using raw address"),
15683                utp->number);
15684       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15685       addr_str = small_buf;
15686     }
15687
15688   /* There's not much we can do with a sequence of bytecodes.  */
15689   if (utp->cond && !utp->cond_string)
15690     warning (_("Uploaded tracepoint %d condition "
15691                "has no source form, ignoring it"),
15692              utp->number);
15693
15694   if (!create_breakpoint (get_current_arch (),
15695                           addr_str,
15696                           utp->cond_string, -1, NULL,
15697                           0 /* parse cond/thread */,
15698                           0 /* tempflag */,
15699                           utp->type /* type_wanted */,
15700                           0 /* Ignore count */,
15701                           pending_break_support,
15702                           &tracepoint_breakpoint_ops,
15703                           0 /* from_tty */,
15704                           utp->enabled /* enabled */,
15705                           0 /* internal */,
15706                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15707     return NULL;
15708
15709   /* Get the tracepoint we just created.  */
15710   tp = get_tracepoint (tracepoint_count);
15711   gdb_assert (tp != NULL);
15712
15713   if (utp->pass > 0)
15714     {
15715       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15716                  tp->base.number);
15717
15718       trace_pass_command (small_buf, 0);
15719     }
15720
15721   /* If we have uploaded versions of the original commands, set up a
15722      special-purpose "reader" function and call the usual command line
15723      reader, then pass the result to the breakpoint command-setting
15724      function.  */
15725   if (!VEC_empty (char_ptr, utp->cmd_strings))
15726     {
15727       struct command_line *cmd_list;
15728
15729       this_utp = utp;
15730       next_cmd = 0;
15731
15732       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15733
15734       breakpoint_set_commands (&tp->base, cmd_list);
15735     }
15736   else if (!VEC_empty (char_ptr, utp->actions)
15737            || !VEC_empty (char_ptr, utp->step_actions))
15738     warning (_("Uploaded tracepoint %d actions "
15739                "have no source form, ignoring them"),
15740              utp->number);
15741
15742   /* Copy any status information that might be available.  */
15743   tp->base.hit_count = utp->hit_count;
15744   tp->traceframe_usage = utp->traceframe_usage;
15745
15746   return tp;
15747 }
15748   
15749 /* Print information on tracepoint number TPNUM_EXP, or all if
15750    omitted.  */
15751
15752 static void
15753 tracepoints_info (char *args, int from_tty)
15754 {
15755   struct ui_out *uiout = current_uiout;
15756   int num_printed;
15757
15758   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15759
15760   if (num_printed == 0)
15761     {
15762       if (args == NULL || *args == '\0')
15763         ui_out_message (uiout, 0, "No tracepoints.\n");
15764       else
15765         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15766     }
15767
15768   default_collect_info ();
15769 }
15770
15771 /* The 'enable trace' command enables tracepoints.
15772    Not supported by all targets.  */
15773 static void
15774 enable_trace_command (char *args, int from_tty)
15775 {
15776   enable_command (args, from_tty);
15777 }
15778
15779 /* The 'disable trace' command disables tracepoints.
15780    Not supported by all targets.  */
15781 static void
15782 disable_trace_command (char *args, int from_tty)
15783 {
15784   disable_command (args, from_tty);
15785 }
15786
15787 /* Remove a tracepoint (or all if no argument).  */
15788 static void
15789 delete_trace_command (char *arg, int from_tty)
15790 {
15791   struct breakpoint *b, *b_tmp;
15792
15793   dont_repeat ();
15794
15795   if (arg == 0)
15796     {
15797       int breaks_to_delete = 0;
15798
15799       /* Delete all breakpoints if no argument.
15800          Do not delete internal or call-dummy breakpoints, these
15801          have to be deleted with an explicit breakpoint number 
15802          argument.  */
15803       ALL_TRACEPOINTS (b)
15804         if (is_tracepoint (b) && user_breakpoint_p (b))
15805           {
15806             breaks_to_delete = 1;
15807             break;
15808           }
15809
15810       /* Ask user only if there are some breakpoints to delete.  */
15811       if (!from_tty
15812           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15813         {
15814           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15815             if (is_tracepoint (b) && user_breakpoint_p (b))
15816               delete_breakpoint (b);
15817         }
15818     }
15819   else
15820     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15821 }
15822
15823 /* Helper function for trace_pass_command.  */
15824
15825 static void
15826 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15827 {
15828   tp->pass_count = count;
15829   observer_notify_breakpoint_modified (&tp->base);
15830   if (from_tty)
15831     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15832                      tp->base.number, count);
15833 }
15834
15835 /* Set passcount for tracepoint.
15836
15837    First command argument is passcount, second is tracepoint number.
15838    If tracepoint number omitted, apply to most recently defined.
15839    Also accepts special argument "all".  */
15840
15841 static void
15842 trace_pass_command (char *args, int from_tty)
15843 {
15844   struct tracepoint *t1;
15845   unsigned int count;
15846
15847   if (args == 0 || *args == 0)
15848     error (_("passcount command requires an "
15849              "argument (count + optional TP num)"));
15850
15851   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15852
15853   args = skip_spaces (args);
15854   if (*args && strncasecmp (args, "all", 3) == 0)
15855     {
15856       struct breakpoint *b;
15857
15858       args += 3;                        /* Skip special argument "all".  */
15859       if (*args)
15860         error (_("Junk at end of arguments."));
15861
15862       ALL_TRACEPOINTS (b)
15863       {
15864         t1 = (struct tracepoint *) b;
15865         trace_pass_set_count (t1, count, from_tty);
15866       }
15867     }
15868   else if (*args == '\0')
15869     {
15870       t1 = get_tracepoint_by_number (&args, NULL);
15871       if (t1)
15872         trace_pass_set_count (t1, count, from_tty);
15873     }
15874   else
15875     {
15876       struct get_number_or_range_state state;
15877
15878       init_number_or_range (&state, args);
15879       while (!state.finished)
15880         {
15881           t1 = get_tracepoint_by_number (&args, &state);
15882           if (t1)
15883             trace_pass_set_count (t1, count, from_tty);
15884         }
15885     }
15886 }
15887
15888 struct tracepoint *
15889 get_tracepoint (int num)
15890 {
15891   struct breakpoint *t;
15892
15893   ALL_TRACEPOINTS (t)
15894     if (t->number == num)
15895       return (struct tracepoint *) t;
15896
15897   return NULL;
15898 }
15899
15900 /* Find the tracepoint with the given target-side number (which may be
15901    different from the tracepoint number after disconnecting and
15902    reconnecting).  */
15903
15904 struct tracepoint *
15905 get_tracepoint_by_number_on_target (int num)
15906 {
15907   struct breakpoint *b;
15908
15909   ALL_TRACEPOINTS (b)
15910     {
15911       struct tracepoint *t = (struct tracepoint *) b;
15912
15913       if (t->number_on_target == num)
15914         return t;
15915     }
15916
15917   return NULL;
15918 }
15919
15920 /* Utility: parse a tracepoint number and look it up in the list.
15921    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15922    If the argument is missing, the most recent tracepoint
15923    (tracepoint_count) is returned.  */
15924
15925 struct tracepoint *
15926 get_tracepoint_by_number (char **arg,
15927                           struct get_number_or_range_state *state)
15928 {
15929   struct breakpoint *t;
15930   int tpnum;
15931   char *instring = arg == NULL ? NULL : *arg;
15932
15933   if (state)
15934     {
15935       gdb_assert (!state->finished);
15936       tpnum = get_number_or_range (state);
15937     }
15938   else if (arg == NULL || *arg == NULL || ! **arg)
15939     tpnum = tracepoint_count;
15940   else
15941     tpnum = get_number (arg);
15942
15943   if (tpnum <= 0)
15944     {
15945       if (instring && *instring)
15946         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15947                          instring);
15948       else
15949         printf_filtered (_("No previous tracepoint\n"));
15950       return NULL;
15951     }
15952
15953   ALL_TRACEPOINTS (t)
15954     if (t->number == tpnum)
15955     {
15956       return (struct tracepoint *) t;
15957     }
15958
15959   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15960   return NULL;
15961 }
15962
15963 void
15964 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15965 {
15966   if (b->thread != -1)
15967     fprintf_unfiltered (fp, " thread %d", b->thread);
15968
15969   if (b->task != 0)
15970     fprintf_unfiltered (fp, " task %d", b->task);
15971
15972   fprintf_unfiltered (fp, "\n");
15973 }
15974
15975 /* Save information on user settable breakpoints (watchpoints, etc) to
15976    a new script file named FILENAME.  If FILTER is non-NULL, call it
15977    on each breakpoint and only include the ones for which it returns
15978    non-zero.  */
15979
15980 static void
15981 save_breakpoints (char *filename, int from_tty,
15982                   int (*filter) (const struct breakpoint *))
15983 {
15984   struct breakpoint *tp;
15985   int any = 0;
15986   struct cleanup *cleanup;
15987   struct ui_file *fp;
15988   int extra_trace_bits = 0;
15989
15990   if (filename == 0 || *filename == 0)
15991     error (_("Argument required (file name in which to save)"));
15992
15993   /* See if we have anything to save.  */
15994   ALL_BREAKPOINTS (tp)
15995   {
15996     /* Skip internal and momentary breakpoints.  */
15997     if (!user_breakpoint_p (tp))
15998       continue;
15999
16000     /* If we have a filter, only save the breakpoints it accepts.  */
16001     if (filter && !filter (tp))
16002       continue;
16003
16004     any = 1;
16005
16006     if (is_tracepoint (tp))
16007       {
16008         extra_trace_bits = 1;
16009
16010         /* We can stop searching.  */
16011         break;
16012       }
16013   }
16014
16015   if (!any)
16016     {
16017       warning (_("Nothing to save."));
16018       return;
16019     }
16020
16021   filename = tilde_expand (filename);
16022   cleanup = make_cleanup (xfree, filename);
16023   fp = gdb_fopen (filename, "w");
16024   if (!fp)
16025     error (_("Unable to open file '%s' for saving (%s)"),
16026            filename, safe_strerror (errno));
16027   make_cleanup_ui_file_delete (fp);
16028
16029   if (extra_trace_bits)
16030     save_trace_state_variables (fp);
16031
16032   ALL_BREAKPOINTS (tp)
16033   {
16034     /* Skip internal and momentary breakpoints.  */
16035     if (!user_breakpoint_p (tp))
16036       continue;
16037
16038     /* If we have a filter, only save the breakpoints it accepts.  */
16039     if (filter && !filter (tp))
16040       continue;
16041
16042     tp->ops->print_recreate (tp, fp);
16043
16044     /* Note, we can't rely on tp->number for anything, as we can't
16045        assume the recreated breakpoint numbers will match.  Use $bpnum
16046        instead.  */
16047
16048     if (tp->cond_string)
16049       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
16050
16051     if (tp->ignore_count)
16052       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
16053
16054     if (tp->type != bp_dprintf && tp->commands)
16055       {
16056         volatile struct gdb_exception ex;       
16057
16058         fprintf_unfiltered (fp, "  commands\n");
16059         
16060         ui_out_redirect (current_uiout, fp);
16061         TRY_CATCH (ex, RETURN_MASK_ALL)
16062           {
16063             print_command_lines (current_uiout, tp->commands->commands, 2);
16064           }
16065         ui_out_redirect (current_uiout, NULL);
16066
16067         if (ex.reason < 0)
16068           throw_exception (ex);
16069
16070         fprintf_unfiltered (fp, "  end\n");
16071       }
16072
16073     if (tp->enable_state == bp_disabled)
16074       fprintf_unfiltered (fp, "disable\n");
16075
16076     /* If this is a multi-location breakpoint, check if the locations
16077        should be individually disabled.  Watchpoint locations are
16078        special, and not user visible.  */
16079     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
16080       {
16081         struct bp_location *loc;
16082         int n = 1;
16083
16084         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
16085           if (!loc->enabled)
16086             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
16087       }
16088   }
16089
16090   if (extra_trace_bits && *default_collect)
16091     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
16092
16093   if (from_tty)
16094     printf_filtered (_("Saved to file '%s'.\n"), filename);
16095   do_cleanups (cleanup);
16096 }
16097
16098 /* The `save breakpoints' command.  */
16099
16100 static void
16101 save_breakpoints_command (char *args, int from_tty)
16102 {
16103   save_breakpoints (args, from_tty, NULL);
16104 }
16105
16106 /* The `save tracepoints' command.  */
16107
16108 static void
16109 save_tracepoints_command (char *args, int from_tty)
16110 {
16111   save_breakpoints (args, from_tty, is_tracepoint);
16112 }
16113
16114 /* Create a vector of all tracepoints.  */
16115
16116 VEC(breakpoint_p) *
16117 all_tracepoints (void)
16118 {
16119   VEC(breakpoint_p) *tp_vec = 0;
16120   struct breakpoint *tp;
16121
16122   ALL_TRACEPOINTS (tp)
16123   {
16124     VEC_safe_push (breakpoint_p, tp_vec, tp);
16125   }
16126
16127   return tp_vec;
16128 }
16129
16130 \f
16131 /* This help string is used for the break, hbreak, tbreak and thbreak
16132    commands.  It is defined as a macro to prevent duplication.
16133    COMMAND should be a string constant containing the name of the
16134    command.  */
16135 #define BREAK_ARGS_HELP(command) \
16136 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16137 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16138 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16139 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16140 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16141 If a line number is specified, break at start of code for that line.\n\
16142 If a function is specified, break at start of code for that function.\n\
16143 If an address is specified, break at that exact address.\n\
16144 With no LOCATION, uses current execution address of the selected\n\
16145 stack frame.  This is useful for breaking on return to a stack frame.\n\
16146 \n\
16147 THREADNUM is the number from \"info threads\".\n\
16148 CONDITION is a boolean expression.\n\
16149 \n\
16150 Multiple breakpoints at one place are permitted, and useful if their\n\
16151 conditions are different.\n\
16152 \n\
16153 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16154
16155 /* List of subcommands for "catch".  */
16156 static struct cmd_list_element *catch_cmdlist;
16157
16158 /* List of subcommands for "tcatch".  */
16159 static struct cmd_list_element *tcatch_cmdlist;
16160
16161 void
16162 add_catch_command (char *name, char *docstring,
16163                    cmd_sfunc_ftype *sfunc,
16164                    completer_ftype *completer,
16165                    void *user_data_catch,
16166                    void *user_data_tcatch)
16167 {
16168   struct cmd_list_element *command;
16169
16170   command = add_cmd (name, class_breakpoint, NULL, docstring,
16171                      &catch_cmdlist);
16172   set_cmd_sfunc (command, sfunc);
16173   set_cmd_context (command, user_data_catch);
16174   set_cmd_completer (command, completer);
16175
16176   command = add_cmd (name, class_breakpoint, NULL, docstring,
16177                      &tcatch_cmdlist);
16178   set_cmd_sfunc (command, sfunc);
16179   set_cmd_context (command, user_data_tcatch);
16180   set_cmd_completer (command, completer);
16181 }
16182
16183 static void
16184 clear_syscall_counts (struct inferior *inf)
16185 {
16186   struct catch_syscall_inferior_data *inf_data
16187     = get_catch_syscall_inferior_data (inf);
16188
16189   inf_data->total_syscalls_count = 0;
16190   inf_data->any_syscall_count = 0;
16191   VEC_free (int, inf_data->syscalls_counts);
16192 }
16193
16194 static void
16195 save_command (char *arg, int from_tty)
16196 {
16197   printf_unfiltered (_("\"save\" must be followed by "
16198                        "the name of a save subcommand.\n"));
16199   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16200 }
16201
16202 struct breakpoint *
16203 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16204                           void *data)
16205 {
16206   struct breakpoint *b, *b_tmp;
16207
16208   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16209     {
16210       if ((*callback) (b, data))
16211         return b;
16212     }
16213
16214   return NULL;
16215 }
16216
16217 /* Zero if any of the breakpoint's locations could be a location where
16218    functions have been inlined, nonzero otherwise.  */
16219
16220 static int
16221 is_non_inline_function (struct breakpoint *b)
16222 {
16223   /* The shared library event breakpoint is set on the address of a
16224      non-inline function.  */
16225   if (b->type == bp_shlib_event)
16226     return 1;
16227
16228   return 0;
16229 }
16230
16231 /* Nonzero if the specified PC cannot be a location where functions
16232    have been inlined.  */
16233
16234 int
16235 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16236                            const struct target_waitstatus *ws)
16237 {
16238   struct breakpoint *b;
16239   struct bp_location *bl;
16240
16241   ALL_BREAKPOINTS (b)
16242     {
16243       if (!is_non_inline_function (b))
16244         continue;
16245
16246       for (bl = b->loc; bl != NULL; bl = bl->next)
16247         {
16248           if (!bl->shlib_disabled
16249               && bpstat_check_location (bl, aspace, pc, ws))
16250             return 1;
16251         }
16252     }
16253
16254   return 0;
16255 }
16256
16257 /* Remove any references to OBJFILE which is going to be freed.  */
16258
16259 void
16260 breakpoint_free_objfile (struct objfile *objfile)
16261 {
16262   struct bp_location **locp, *loc;
16263
16264   ALL_BP_LOCATIONS (loc, locp)
16265     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16266       loc->symtab = NULL;
16267 }
16268
16269 void
16270 initialize_breakpoint_ops (void)
16271 {
16272   static int initialized = 0;
16273
16274   struct breakpoint_ops *ops;
16275
16276   if (initialized)
16277     return;
16278   initialized = 1;
16279
16280   /* The breakpoint_ops structure to be inherit by all kinds of
16281      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16282      internal and momentary breakpoints, etc.).  */
16283   ops = &bkpt_base_breakpoint_ops;
16284   *ops = base_breakpoint_ops;
16285   ops->re_set = bkpt_re_set;
16286   ops->insert_location = bkpt_insert_location;
16287   ops->remove_location = bkpt_remove_location;
16288   ops->breakpoint_hit = bkpt_breakpoint_hit;
16289   ops->create_sals_from_address = bkpt_create_sals_from_address;
16290   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16291   ops->decode_linespec = bkpt_decode_linespec;
16292
16293   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16294   ops = &bkpt_breakpoint_ops;
16295   *ops = bkpt_base_breakpoint_ops;
16296   ops->re_set = bkpt_re_set;
16297   ops->resources_needed = bkpt_resources_needed;
16298   ops->print_it = bkpt_print_it;
16299   ops->print_mention = bkpt_print_mention;
16300   ops->print_recreate = bkpt_print_recreate;
16301
16302   /* Ranged breakpoints.  */
16303   ops = &ranged_breakpoint_ops;
16304   *ops = bkpt_breakpoint_ops;
16305   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16306   ops->resources_needed = resources_needed_ranged_breakpoint;
16307   ops->print_it = print_it_ranged_breakpoint;
16308   ops->print_one = print_one_ranged_breakpoint;
16309   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16310   ops->print_mention = print_mention_ranged_breakpoint;
16311   ops->print_recreate = print_recreate_ranged_breakpoint;
16312
16313   /* Internal breakpoints.  */
16314   ops = &internal_breakpoint_ops;
16315   *ops = bkpt_base_breakpoint_ops;
16316   ops->re_set = internal_bkpt_re_set;
16317   ops->check_status = internal_bkpt_check_status;
16318   ops->print_it = internal_bkpt_print_it;
16319   ops->print_mention = internal_bkpt_print_mention;
16320
16321   /* Momentary breakpoints.  */
16322   ops = &momentary_breakpoint_ops;
16323   *ops = bkpt_base_breakpoint_ops;
16324   ops->re_set = momentary_bkpt_re_set;
16325   ops->check_status = momentary_bkpt_check_status;
16326   ops->print_it = momentary_bkpt_print_it;
16327   ops->print_mention = momentary_bkpt_print_mention;
16328
16329   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16330   ops = &longjmp_breakpoint_ops;
16331   *ops = momentary_breakpoint_ops;
16332   ops->dtor = longjmp_bkpt_dtor;
16333
16334   /* Probe breakpoints.  */
16335   ops = &bkpt_probe_breakpoint_ops;
16336   *ops = bkpt_breakpoint_ops;
16337   ops->insert_location = bkpt_probe_insert_location;
16338   ops->remove_location = bkpt_probe_remove_location;
16339   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16340   ops->decode_linespec = bkpt_probe_decode_linespec;
16341
16342   /* Watchpoints.  */
16343   ops = &watchpoint_breakpoint_ops;
16344   *ops = base_breakpoint_ops;
16345   ops->dtor = dtor_watchpoint;
16346   ops->re_set = re_set_watchpoint;
16347   ops->insert_location = insert_watchpoint;
16348   ops->remove_location = remove_watchpoint;
16349   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16350   ops->check_status = check_status_watchpoint;
16351   ops->resources_needed = resources_needed_watchpoint;
16352   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16353   ops->print_it = print_it_watchpoint;
16354   ops->print_mention = print_mention_watchpoint;
16355   ops->print_recreate = print_recreate_watchpoint;
16356   ops->explains_signal = explains_signal_watchpoint;
16357
16358   /* Masked watchpoints.  */
16359   ops = &masked_watchpoint_breakpoint_ops;
16360   *ops = watchpoint_breakpoint_ops;
16361   ops->insert_location = insert_masked_watchpoint;
16362   ops->remove_location = remove_masked_watchpoint;
16363   ops->resources_needed = resources_needed_masked_watchpoint;
16364   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16365   ops->print_it = print_it_masked_watchpoint;
16366   ops->print_one_detail = print_one_detail_masked_watchpoint;
16367   ops->print_mention = print_mention_masked_watchpoint;
16368   ops->print_recreate = print_recreate_masked_watchpoint;
16369
16370   /* Tracepoints.  */
16371   ops = &tracepoint_breakpoint_ops;
16372   *ops = base_breakpoint_ops;
16373   ops->re_set = tracepoint_re_set;
16374   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16375   ops->print_one_detail = tracepoint_print_one_detail;
16376   ops->print_mention = tracepoint_print_mention;
16377   ops->print_recreate = tracepoint_print_recreate;
16378   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16379   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16380   ops->decode_linespec = tracepoint_decode_linespec;
16381
16382   /* Probe tracepoints.  */
16383   ops = &tracepoint_probe_breakpoint_ops;
16384   *ops = tracepoint_breakpoint_ops;
16385   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16386   ops->decode_linespec = tracepoint_probe_decode_linespec;
16387
16388   /* Static tracepoints with marker (`-m').  */
16389   ops = &strace_marker_breakpoint_ops;
16390   *ops = tracepoint_breakpoint_ops;
16391   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16392   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16393   ops->decode_linespec = strace_marker_decode_linespec;
16394
16395   /* Fork catchpoints.  */
16396   ops = &catch_fork_breakpoint_ops;
16397   *ops = base_breakpoint_ops;
16398   ops->insert_location = insert_catch_fork;
16399   ops->remove_location = remove_catch_fork;
16400   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16401   ops->print_it = print_it_catch_fork;
16402   ops->print_one = print_one_catch_fork;
16403   ops->print_mention = print_mention_catch_fork;
16404   ops->print_recreate = print_recreate_catch_fork;
16405
16406   /* Vfork catchpoints.  */
16407   ops = &catch_vfork_breakpoint_ops;
16408   *ops = base_breakpoint_ops;
16409   ops->insert_location = insert_catch_vfork;
16410   ops->remove_location = remove_catch_vfork;
16411   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16412   ops->print_it = print_it_catch_vfork;
16413   ops->print_one = print_one_catch_vfork;
16414   ops->print_mention = print_mention_catch_vfork;
16415   ops->print_recreate = print_recreate_catch_vfork;
16416
16417   /* Exec catchpoints.  */
16418   ops = &catch_exec_breakpoint_ops;
16419   *ops = base_breakpoint_ops;
16420   ops->dtor = dtor_catch_exec;
16421   ops->insert_location = insert_catch_exec;
16422   ops->remove_location = remove_catch_exec;
16423   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16424   ops->print_it = print_it_catch_exec;
16425   ops->print_one = print_one_catch_exec;
16426   ops->print_mention = print_mention_catch_exec;
16427   ops->print_recreate = print_recreate_catch_exec;
16428
16429   /* Syscall catchpoints.  */
16430   ops = &catch_syscall_breakpoint_ops;
16431   *ops = base_breakpoint_ops;
16432   ops->dtor = dtor_catch_syscall;
16433   ops->insert_location = insert_catch_syscall;
16434   ops->remove_location = remove_catch_syscall;
16435   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16436   ops->print_it = print_it_catch_syscall;
16437   ops->print_one = print_one_catch_syscall;
16438   ops->print_mention = print_mention_catch_syscall;
16439   ops->print_recreate = print_recreate_catch_syscall;
16440
16441   /* Solib-related catchpoints.  */
16442   ops = &catch_solib_breakpoint_ops;
16443   *ops = base_breakpoint_ops;
16444   ops->dtor = dtor_catch_solib;
16445   ops->insert_location = insert_catch_solib;
16446   ops->remove_location = remove_catch_solib;
16447   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16448   ops->check_status = check_status_catch_solib;
16449   ops->print_it = print_it_catch_solib;
16450   ops->print_one = print_one_catch_solib;
16451   ops->print_mention = print_mention_catch_solib;
16452   ops->print_recreate = print_recreate_catch_solib;
16453
16454   ops = &dprintf_breakpoint_ops;
16455   *ops = bkpt_base_breakpoint_ops;
16456   ops->re_set = dprintf_re_set;
16457   ops->resources_needed = bkpt_resources_needed;
16458   ops->print_it = bkpt_print_it;
16459   ops->print_mention = bkpt_print_mention;
16460   ops->print_recreate = dprintf_print_recreate;
16461   ops->after_condition_true = dprintf_after_condition_true;
16462   ops->breakpoint_hit = dprintf_breakpoint_hit;
16463 }
16464
16465 /* Chain containing all defined "enable breakpoint" subcommands.  */
16466
16467 static struct cmd_list_element *enablebreaklist = NULL;
16468
16469 void
16470 _initialize_breakpoint (void)
16471 {
16472   struct cmd_list_element *c;
16473
16474   initialize_breakpoint_ops ();
16475
16476   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16477   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16478   observer_attach_inferior_exit (clear_syscall_counts);
16479   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16480
16481   breakpoint_objfile_key
16482     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16483
16484   catch_syscall_inferior_data
16485     = register_inferior_data_with_cleanup (NULL,
16486                                            catch_syscall_inferior_data_cleanup);
16487
16488   breakpoint_chain = 0;
16489   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16490      before a breakpoint is set.  */
16491   breakpoint_count = 0;
16492
16493   tracepoint_count = 0;
16494
16495   add_com ("ignore", class_breakpoint, ignore_command, _("\
16496 Set ignore-count of breakpoint number N to COUNT.\n\
16497 Usage is `ignore N COUNT'."));
16498   if (xdb_commands)
16499     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16500
16501   add_com ("commands", class_breakpoint, commands_command, _("\
16502 Set commands to be executed when a breakpoint is hit.\n\
16503 Give breakpoint number as argument after \"commands\".\n\
16504 With no argument, the targeted breakpoint is the last one set.\n\
16505 The commands themselves follow starting on the next line.\n\
16506 Type a line containing \"end\" to indicate the end of them.\n\
16507 Give \"silent\" as the first line to make the breakpoint silent;\n\
16508 then no output is printed when it is hit, except what the commands print."));
16509
16510   c = add_com ("condition", class_breakpoint, condition_command, _("\
16511 Specify breakpoint number N to break only if COND is true.\n\
16512 Usage is `condition N COND', where N is an integer and COND is an\n\
16513 expression to be evaluated whenever breakpoint N is reached."));
16514   set_cmd_completer (c, condition_completer);
16515
16516   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16517 Set a temporary breakpoint.\n\
16518 Like \"break\" except the breakpoint is only temporary,\n\
16519 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16520 by using \"enable delete\" on the breakpoint number.\n\
16521 \n"
16522 BREAK_ARGS_HELP ("tbreak")));
16523   set_cmd_completer (c, location_completer);
16524
16525   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16526 Set a hardware assisted breakpoint.\n\
16527 Like \"break\" except the breakpoint requires hardware support,\n\
16528 some target hardware may not have this support.\n\
16529 \n"
16530 BREAK_ARGS_HELP ("hbreak")));
16531   set_cmd_completer (c, location_completer);
16532
16533   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16534 Set a temporary hardware assisted breakpoint.\n\
16535 Like \"hbreak\" except the breakpoint is only temporary,\n\
16536 so it will be deleted when hit.\n\
16537 \n"
16538 BREAK_ARGS_HELP ("thbreak")));
16539   set_cmd_completer (c, location_completer);
16540
16541   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16542 Enable some breakpoints.\n\
16543 Give breakpoint numbers (separated by spaces) as arguments.\n\
16544 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16545 This is used to cancel the effect of the \"disable\" command.\n\
16546 With a subcommand you can enable temporarily."),
16547                   &enablelist, "enable ", 1, &cmdlist);
16548   if (xdb_commands)
16549     add_com ("ab", class_breakpoint, enable_command, _("\
16550 Enable some breakpoints.\n\
16551 Give breakpoint numbers (separated by spaces) as arguments.\n\
16552 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16553 This is used to cancel the effect of the \"disable\" command.\n\
16554 With a subcommand you can enable temporarily."));
16555
16556   add_com_alias ("en", "enable", class_breakpoint, 1);
16557
16558   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16559 Enable some breakpoints.\n\
16560 Give breakpoint numbers (separated by spaces) as arguments.\n\
16561 This is used to cancel the effect of the \"disable\" command.\n\
16562 May be abbreviated to simply \"enable\".\n"),
16563                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16564
16565   add_cmd ("once", no_class, enable_once_command, _("\
16566 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16567 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16568            &enablebreaklist);
16569
16570   add_cmd ("delete", no_class, enable_delete_command, _("\
16571 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16572 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16573            &enablebreaklist);
16574
16575   add_cmd ("count", no_class, enable_count_command, _("\
16576 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16577 If a breakpoint is hit while enabled in this fashion,\n\
16578 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16579            &enablebreaklist);
16580
16581   add_cmd ("delete", no_class, enable_delete_command, _("\
16582 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16583 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16584            &enablelist);
16585
16586   add_cmd ("once", no_class, enable_once_command, _("\
16587 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16588 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16589            &enablelist);
16590
16591   add_cmd ("count", no_class, enable_count_command, _("\
16592 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16593 If a breakpoint is hit while enabled in this fashion,\n\
16594 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16595            &enablelist);
16596
16597   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16598 Disable some breakpoints.\n\
16599 Arguments are breakpoint numbers with spaces in between.\n\
16600 To disable all breakpoints, give no argument.\n\
16601 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16602                   &disablelist, "disable ", 1, &cmdlist);
16603   add_com_alias ("dis", "disable", class_breakpoint, 1);
16604   add_com_alias ("disa", "disable", class_breakpoint, 1);
16605   if (xdb_commands)
16606     add_com ("sb", class_breakpoint, disable_command, _("\
16607 Disable some breakpoints.\n\
16608 Arguments are breakpoint numbers with spaces in between.\n\
16609 To disable all breakpoints, give no argument.\n\
16610 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16611
16612   add_cmd ("breakpoints", class_alias, disable_command, _("\
16613 Disable some breakpoints.\n\
16614 Arguments are breakpoint numbers with spaces in between.\n\
16615 To disable all breakpoints, give no argument.\n\
16616 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16617 This command may be abbreviated \"disable\"."),
16618            &disablelist);
16619
16620   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16621 Delete some breakpoints or auto-display expressions.\n\
16622 Arguments are breakpoint numbers with spaces in between.\n\
16623 To delete all breakpoints, give no argument.\n\
16624 \n\
16625 Also a prefix command for deletion of other GDB objects.\n\
16626 The \"unset\" command is also an alias for \"delete\"."),
16627                   &deletelist, "delete ", 1, &cmdlist);
16628   add_com_alias ("d", "delete", class_breakpoint, 1);
16629   add_com_alias ("del", "delete", class_breakpoint, 1);
16630   if (xdb_commands)
16631     add_com ("db", class_breakpoint, delete_command, _("\
16632 Delete some breakpoints.\n\
16633 Arguments are breakpoint numbers with spaces in between.\n\
16634 To delete all breakpoints, give no argument.\n"));
16635
16636   add_cmd ("breakpoints", class_alias, delete_command, _("\
16637 Delete some breakpoints or auto-display expressions.\n\
16638 Arguments are breakpoint numbers with spaces in between.\n\
16639 To delete all breakpoints, give no argument.\n\
16640 This command may be abbreviated \"delete\"."),
16641            &deletelist);
16642
16643   add_com ("clear", class_breakpoint, clear_command, _("\
16644 Clear breakpoint at specified line or function.\n\
16645 Argument may be line number, function name, or \"*\" and an address.\n\
16646 If line number is specified, all breakpoints in that line are cleared.\n\
16647 If function is specified, breakpoints at beginning of function are cleared.\n\
16648 If an address is specified, breakpoints at that address are cleared.\n\
16649 \n\
16650 With no argument, clears all breakpoints in the line that the selected frame\n\
16651 is executing in.\n\
16652 \n\
16653 See also the \"delete\" command which clears breakpoints by number."));
16654   add_com_alias ("cl", "clear", class_breakpoint, 1);
16655
16656   c = add_com ("break", class_breakpoint, break_command, _("\
16657 Set breakpoint at specified line or function.\n"
16658 BREAK_ARGS_HELP ("break")));
16659   set_cmd_completer (c, location_completer);
16660
16661   add_com_alias ("b", "break", class_run, 1);
16662   add_com_alias ("br", "break", class_run, 1);
16663   add_com_alias ("bre", "break", class_run, 1);
16664   add_com_alias ("brea", "break", class_run, 1);
16665
16666   if (xdb_commands)
16667    add_com_alias ("ba", "break", class_breakpoint, 1);
16668
16669   if (dbx_commands)
16670     {
16671       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16672 Break in function/address or break at a line in the current file."),
16673                              &stoplist, "stop ", 1, &cmdlist);
16674       add_cmd ("in", class_breakpoint, stopin_command,
16675                _("Break in function or address."), &stoplist);
16676       add_cmd ("at", class_breakpoint, stopat_command,
16677                _("Break at a line in the current file."), &stoplist);
16678       add_com ("status", class_info, breakpoints_info, _("\
16679 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16680 The \"Type\" column indicates one of:\n\
16681 \tbreakpoint     - normal breakpoint\n\
16682 \twatchpoint     - watchpoint\n\
16683 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16684 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16685 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16686 address and file/line number respectively.\n\
16687 \n\
16688 Convenience variable \"$_\" and default examine address for \"x\"\n\
16689 are set to the address of the last breakpoint listed unless the command\n\
16690 is prefixed with \"server \".\n\n\
16691 Convenience variable \"$bpnum\" contains the number of the last\n\
16692 breakpoint set."));
16693     }
16694
16695   add_info ("breakpoints", breakpoints_info, _("\
16696 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16697 The \"Type\" column indicates one of:\n\
16698 \tbreakpoint     - normal breakpoint\n\
16699 \twatchpoint     - watchpoint\n\
16700 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16701 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16702 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16703 address and file/line number respectively.\n\
16704 \n\
16705 Convenience variable \"$_\" and default examine address for \"x\"\n\
16706 are set to the address of the last breakpoint listed unless the command\n\
16707 is prefixed with \"server \".\n\n\
16708 Convenience variable \"$bpnum\" contains the number of the last\n\
16709 breakpoint set."));
16710
16711   add_info_alias ("b", "breakpoints", 1);
16712
16713   if (xdb_commands)
16714     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16715 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16716 The \"Type\" column indicates one of:\n\
16717 \tbreakpoint     - normal breakpoint\n\
16718 \twatchpoint     - watchpoint\n\
16719 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16720 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16721 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16722 address and file/line number respectively.\n\
16723 \n\
16724 Convenience variable \"$_\" and default examine address for \"x\"\n\
16725 are set to the address of the last breakpoint listed unless the command\n\
16726 is prefixed with \"server \".\n\n\
16727 Convenience variable \"$bpnum\" contains the number of the last\n\
16728 breakpoint set."));
16729
16730   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16731 Status of all breakpoints, or breakpoint number NUMBER.\n\
16732 The \"Type\" column indicates one of:\n\
16733 \tbreakpoint     - normal breakpoint\n\
16734 \twatchpoint     - watchpoint\n\
16735 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16736 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16737 \tuntil          - internal breakpoint used by the \"until\" command\n\
16738 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16739 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16740 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16741 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16742 address and file/line number respectively.\n\
16743 \n\
16744 Convenience variable \"$_\" and default examine address for \"x\"\n\
16745 are set to the address of the last breakpoint listed unless the command\n\
16746 is prefixed with \"server \".\n\n\
16747 Convenience variable \"$bpnum\" contains the number of the last\n\
16748 breakpoint set."),
16749            &maintenanceinfolist);
16750
16751   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16752 Set catchpoints to catch events."),
16753                   &catch_cmdlist, "catch ",
16754                   0/*allow-unknown*/, &cmdlist);
16755
16756   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16757 Set temporary catchpoints to catch events."),
16758                   &tcatch_cmdlist, "tcatch ",
16759                   0/*allow-unknown*/, &cmdlist);
16760
16761   add_catch_command ("fork", _("Catch calls to fork."),
16762                      catch_fork_command_1,
16763                      NULL,
16764                      (void *) (uintptr_t) catch_fork_permanent,
16765                      (void *) (uintptr_t) catch_fork_temporary);
16766   add_catch_command ("vfork", _("Catch calls to vfork."),
16767                      catch_fork_command_1,
16768                      NULL,
16769                      (void *) (uintptr_t) catch_vfork_permanent,
16770                      (void *) (uintptr_t) catch_vfork_temporary);
16771   add_catch_command ("exec", _("Catch calls to exec."),
16772                      catch_exec_command_1,
16773                      NULL,
16774                      CATCH_PERMANENT,
16775                      CATCH_TEMPORARY);
16776   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16777 Usage: catch load [REGEX]\n\
16778 If REGEX is given, only stop for libraries matching the regular expression."),
16779                      catch_load_command_1,
16780                      NULL,
16781                      CATCH_PERMANENT,
16782                      CATCH_TEMPORARY);
16783   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16784 Usage: catch unload [REGEX]\n\
16785 If REGEX is given, only stop for libraries matching the regular expression."),
16786                      catch_unload_command_1,
16787                      NULL,
16788                      CATCH_PERMANENT,
16789                      CATCH_TEMPORARY);
16790   add_catch_command ("syscall", _("\
16791 Catch system calls by their names and/or numbers.\n\
16792 Arguments say which system calls to catch.  If no arguments\n\
16793 are given, every system call will be caught.\n\
16794 Arguments, if given, should be one or more system call names\n\
16795 (if your system supports that), or system call numbers."),
16796                      catch_syscall_command_1,
16797                      catch_syscall_completer,
16798                      CATCH_PERMANENT,
16799                      CATCH_TEMPORARY);
16800
16801   c = add_com ("watch", class_breakpoint, watch_command, _("\
16802 Set a watchpoint for an expression.\n\
16803 Usage: watch [-l|-location] EXPRESSION\n\
16804 A watchpoint stops execution of your program whenever the value of\n\
16805 an expression changes.\n\
16806 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16807 the memory to which it refers."));
16808   set_cmd_completer (c, expression_completer);
16809
16810   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16811 Set a read watchpoint for an expression.\n\
16812 Usage: rwatch [-l|-location] EXPRESSION\n\
16813 A watchpoint stops execution of your program whenever the value of\n\
16814 an expression is read.\n\
16815 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16816 the memory to which it refers."));
16817   set_cmd_completer (c, expression_completer);
16818
16819   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16820 Set a watchpoint for an expression.\n\
16821 Usage: awatch [-l|-location] EXPRESSION\n\
16822 A watchpoint stops execution of your program whenever the value of\n\
16823 an expression is either read or written.\n\
16824 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16825 the memory to which it refers."));
16826   set_cmd_completer (c, expression_completer);
16827
16828   add_info ("watchpoints", watchpoints_info, _("\
16829 Status of specified watchpoints (all watchpoints if no argument)."));
16830
16831   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16832      respond to changes - contrary to the description.  */
16833   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16834                             &can_use_hw_watchpoints, _("\
16835 Set debugger's willingness to use watchpoint hardware."), _("\
16836 Show debugger's willingness to use watchpoint hardware."), _("\
16837 If zero, gdb will not use hardware for new watchpoints, even if\n\
16838 such is available.  (However, any hardware watchpoints that were\n\
16839 created before setting this to nonzero, will continue to use watchpoint\n\
16840 hardware.)"),
16841                             NULL,
16842                             show_can_use_hw_watchpoints,
16843                             &setlist, &showlist);
16844
16845   can_use_hw_watchpoints = 1;
16846
16847   /* Tracepoint manipulation commands.  */
16848
16849   c = add_com ("trace", class_breakpoint, trace_command, _("\
16850 Set a tracepoint at specified line or function.\n\
16851 \n"
16852 BREAK_ARGS_HELP ("trace") "\n\
16853 Do \"help tracepoints\" for info on other tracepoint commands."));
16854   set_cmd_completer (c, location_completer);
16855
16856   add_com_alias ("tp", "trace", class_alias, 0);
16857   add_com_alias ("tr", "trace", class_alias, 1);
16858   add_com_alias ("tra", "trace", class_alias, 1);
16859   add_com_alias ("trac", "trace", class_alias, 1);
16860
16861   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16862 Set a fast tracepoint at specified line or function.\n\
16863 \n"
16864 BREAK_ARGS_HELP ("ftrace") "\n\
16865 Do \"help tracepoints\" for info on other tracepoint commands."));
16866   set_cmd_completer (c, location_completer);
16867
16868   c = add_com ("strace", class_breakpoint, strace_command, _("\
16869 Set a static tracepoint at specified line, function or marker.\n\
16870 \n\
16871 strace [LOCATION] [if CONDITION]\n\
16872 LOCATION may be a line number, function name, \"*\" and an address,\n\
16873 or -m MARKER_ID.\n\
16874 If a line number is specified, probe the marker at start of code\n\
16875 for that line.  If a function is specified, probe the marker at start\n\
16876 of code for that function.  If an address is specified, probe the marker\n\
16877 at that exact address.  If a marker id is specified, probe the marker\n\
16878 with that name.  With no LOCATION, uses current execution address of\n\
16879 the selected stack frame.\n\
16880 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16881 This collects arbitrary user data passed in the probe point call to the\n\
16882 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16883 by printing the $_sdata variable like any other convenience variable.\n\
16884 \n\
16885 CONDITION is a boolean expression.\n\
16886 \n\
16887 Multiple tracepoints at one place are permitted, and useful if their\n\
16888 conditions are different.\n\
16889 \n\
16890 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16891 Do \"help tracepoints\" for info on other tracepoint commands."));
16892   set_cmd_completer (c, location_completer);
16893
16894   add_info ("tracepoints", tracepoints_info, _("\
16895 Status of specified tracepoints (all tracepoints if no argument).\n\
16896 Convenience variable \"$tpnum\" contains the number of the\n\
16897 last tracepoint set."));
16898
16899   add_info_alias ("tp", "tracepoints", 1);
16900
16901   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16902 Delete specified tracepoints.\n\
16903 Arguments are tracepoint numbers, separated by spaces.\n\
16904 No argument means delete all tracepoints."),
16905            &deletelist);
16906   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16907
16908   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16909 Disable specified tracepoints.\n\
16910 Arguments are tracepoint numbers, separated by spaces.\n\
16911 No argument means disable all tracepoints."),
16912            &disablelist);
16913   deprecate_cmd (c, "disable");
16914
16915   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16916 Enable specified tracepoints.\n\
16917 Arguments are tracepoint numbers, separated by spaces.\n\
16918 No argument means enable all tracepoints."),
16919            &enablelist);
16920   deprecate_cmd (c, "enable");
16921
16922   add_com ("passcount", class_trace, trace_pass_command, _("\
16923 Set the passcount for a tracepoint.\n\
16924 The trace will end when the tracepoint has been passed 'count' times.\n\
16925 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16926 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16927
16928   add_prefix_cmd ("save", class_breakpoint, save_command,
16929                   _("Save breakpoint definitions as a script."),
16930                   &save_cmdlist, "save ",
16931                   0/*allow-unknown*/, &cmdlist);
16932
16933   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16934 Save current breakpoint definitions as a script.\n\
16935 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16936 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16937 session to restore them."),
16938                &save_cmdlist);
16939   set_cmd_completer (c, filename_completer);
16940
16941   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16942 Save current tracepoint definitions as a script.\n\
16943 Use the 'source' command in another debug session to restore them."),
16944                &save_cmdlist);
16945   set_cmd_completer (c, filename_completer);
16946
16947   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16948   deprecate_cmd (c, "save tracepoints");
16949
16950   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16951 Breakpoint specific settings\n\
16952 Configure various breakpoint-specific variables such as\n\
16953 pending breakpoint behavior"),
16954                   &breakpoint_set_cmdlist, "set breakpoint ",
16955                   0/*allow-unknown*/, &setlist);
16956   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16957 Breakpoint specific settings\n\
16958 Configure various breakpoint-specific variables such as\n\
16959 pending breakpoint behavior"),
16960                   &breakpoint_show_cmdlist, "show breakpoint ",
16961                   0/*allow-unknown*/, &showlist);
16962
16963   add_setshow_auto_boolean_cmd ("pending", no_class,
16964                                 &pending_break_support, _("\
16965 Set debugger's behavior regarding pending breakpoints."), _("\
16966 Show debugger's behavior regarding pending breakpoints."), _("\
16967 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16968 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16969 an error.  If auto, an unrecognized breakpoint location results in a\n\
16970 user-query to see if a pending breakpoint should be created."),
16971                                 NULL,
16972                                 show_pending_break_support,
16973                                 &breakpoint_set_cmdlist,
16974                                 &breakpoint_show_cmdlist);
16975
16976   pending_break_support = AUTO_BOOLEAN_AUTO;
16977
16978   add_setshow_boolean_cmd ("auto-hw", no_class,
16979                            &automatic_hardware_breakpoints, _("\
16980 Set automatic usage of hardware breakpoints."), _("\
16981 Show automatic usage of hardware breakpoints."), _("\
16982 If set, the debugger will automatically use hardware breakpoints for\n\
16983 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16984 a warning will be emitted for such breakpoints."),
16985                            NULL,
16986                            show_automatic_hardware_breakpoints,
16987                            &breakpoint_set_cmdlist,
16988                            &breakpoint_show_cmdlist);
16989
16990   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16991                                 &always_inserted_mode, _("\
16992 Set mode for inserting breakpoints."), _("\
16993 Show mode for inserting breakpoints."), _("\
16994 When this mode is off, breakpoints are inserted in inferior when it is\n\
16995 resumed, and removed when execution stops.  When this mode is on,\n\
16996 breakpoints are inserted immediately and removed only when the user\n\
16997 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16998 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16999 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
17000 behaves as if always-inserted mode is on; if gdb is controlling the\n\
17001 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
17002                                 NULL,
17003                                 &show_always_inserted_mode,
17004                                 &breakpoint_set_cmdlist,
17005                                 &breakpoint_show_cmdlist);
17006
17007   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
17008                         condition_evaluation_enums,
17009                         &condition_evaluation_mode_1, _("\
17010 Set mode of breakpoint condition evaluation."), _("\
17011 Show mode of breakpoint condition evaluation."), _("\
17012 When this is set to \"host\", breakpoint conditions will be\n\
17013 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
17014 breakpoint conditions will be downloaded to the target (if the target\n\
17015 supports such feature) and conditions will be evaluated on the target's side.\n\
17016 If this is set to \"auto\" (default), this will be automatically set to\n\
17017 \"target\" if it supports condition evaluation, otherwise it will\n\
17018 be set to \"gdb\""),
17019                            &set_condition_evaluation_mode,
17020                            &show_condition_evaluation_mode,
17021                            &breakpoint_set_cmdlist,
17022                            &breakpoint_show_cmdlist);
17023
17024   add_com ("break-range", class_breakpoint, break_range_command, _("\
17025 Set a breakpoint for an address range.\n\
17026 break-range START-LOCATION, END-LOCATION\n\
17027 where START-LOCATION and END-LOCATION can be one of the following:\n\
17028   LINENUM, for that line in the current file,\n\
17029   FILE:LINENUM, for that line in that file,\n\
17030   +OFFSET, for that number of lines after the current line\n\
17031            or the start of the range\n\
17032   FUNCTION, for the first line in that function,\n\
17033   FILE:FUNCTION, to distinguish among like-named static functions.\n\
17034   *ADDRESS, for the instruction at that address.\n\
17035 \n\
17036 The breakpoint will stop execution of the inferior whenever it executes\n\
17037 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
17038 range (including START-LOCATION and END-LOCATION)."));
17039
17040   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
17041 Set a dynamic printf at specified line or function.\n\
17042 dprintf location,format string,arg1,arg2,...\n\
17043 location may be a line number, function name, or \"*\" and an address.\n\
17044 If a line number is specified, break at start of code for that line.\n\
17045 If a function is specified, break at start of code for that function."));
17046   set_cmd_completer (c, location_completer);
17047
17048   add_setshow_enum_cmd ("dprintf-style", class_support,
17049                         dprintf_style_enums, &dprintf_style, _("\
17050 Set the style of usage for dynamic printf."), _("\
17051 Show the style of usage for dynamic printf."), _("\
17052 This setting chooses how GDB will do a dynamic printf.\n\
17053 If the value is \"gdb\", then the printing is done by GDB to its own\n\
17054 console, as with the \"printf\" command.\n\
17055 If the value is \"call\", the print is done by calling a function in your\n\
17056 program; by default printf(), but you can choose a different function or\n\
17057 output stream by setting dprintf-function and dprintf-channel."),
17058                         update_dprintf_commands, NULL,
17059                         &setlist, &showlist);
17060
17061   dprintf_function = xstrdup ("printf");
17062   add_setshow_string_cmd ("dprintf-function", class_support,
17063                           &dprintf_function, _("\
17064 Set the function to use for dynamic printf"), _("\
17065 Show the function to use for dynamic printf"), NULL,
17066                           update_dprintf_commands, NULL,
17067                           &setlist, &showlist);
17068
17069   dprintf_channel = xstrdup ("");
17070   add_setshow_string_cmd ("dprintf-channel", class_support,
17071                           &dprintf_channel, _("\
17072 Set the channel to use for dynamic printf"), _("\
17073 Show the channel to use for dynamic printf"), NULL,
17074                           update_dprintf_commands, NULL,
17075                           &setlist, &showlist);
17076
17077   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
17078                            &disconnected_dprintf, _("\
17079 Set whether dprintf continues after GDB disconnects."), _("\
17080 Show whether dprintf continues after GDB disconnects."), _("\
17081 Use this to let dprintf commands continue to hit and produce output\n\
17082 even if GDB disconnects or detaches from the target."),
17083                            NULL,
17084                            NULL,
17085                            &setlist, &showlist);
17086
17087   add_com ("agent-printf", class_vars, agent_printf_command, _("\
17088 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
17089 (target agent only) This is useful for formatted output in user-defined commands."));
17090
17091   automatic_hardware_breakpoints = 1;
17092
17093   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
17094   observer_attach_thread_exit (remove_threaded_breakpoints);
17095 }