Include string.h in common-defs.h
[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 /* Assuming that B is a watchpoint:
1707    - Reparse watchpoint expression, if REPARSE is non-zero
1708    - Evaluate expression and store the result in B->val
1709    - Evaluate the condition if there is one, and store the result
1710      in b->loc->cond.
1711    - Update the list of values that must be watched in B->loc.
1712
1713    If the watchpoint disposition is disp_del_at_next_stop, then do
1714    nothing.  If this is local watchpoint that is out of scope, delete
1715    it.
1716
1717    Even with `set breakpoint always-inserted on' the watchpoints are
1718    removed + inserted on each stop here.  Normal breakpoints must
1719    never be removed because they might be missed by a running thread
1720    when debugging in non-stop mode.  On the other hand, hardware
1721    watchpoints (is_hardware_watchpoint; processed here) are specific
1722    to each LWP since they are stored in each LWP's hardware debug
1723    registers.  Therefore, such LWP must be stopped first in order to
1724    be able to modify its hardware watchpoints.
1725
1726    Hardware watchpoints must be reset exactly once after being
1727    presented to the user.  It cannot be done sooner, because it would
1728    reset the data used to present the watchpoint hit to the user.  And
1729    it must not be done later because it could display the same single
1730    watchpoint hit during multiple GDB stops.  Note that the latter is
1731    relevant only to the hardware watchpoint types bp_read_watchpoint
1732    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1733    not user-visible - its hit is suppressed if the memory content has
1734    not changed.
1735
1736    The following constraints influence the location where we can reset
1737    hardware watchpoints:
1738
1739    * target_stopped_by_watchpoint and target_stopped_data_address are
1740      called several times when GDB stops.
1741
1742    [linux] 
1743    * Multiple hardware watchpoints can be hit at the same time,
1744      causing GDB to stop.  GDB only presents one hardware watchpoint
1745      hit at a time as the reason for stopping, and all the other hits
1746      are presented later, one after the other, each time the user
1747      requests the execution to be resumed.  Execution is not resumed
1748      for the threads still having pending hit event stored in
1749      LWP_INFO->STATUS.  While the watchpoint is already removed from
1750      the inferior on the first stop the thread hit event is kept being
1751      reported from its cached value by linux_nat_stopped_data_address
1752      until the real thread resume happens after the watchpoint gets
1753      presented and thus its LWP_INFO->STATUS gets reset.
1754
1755    Therefore the hardware watchpoint hit can get safely reset on the
1756    watchpoint removal from inferior.  */
1757
1758 static void
1759 update_watchpoint (struct watchpoint *b, int reparse)
1760 {
1761   int within_current_scope;
1762   struct frame_id saved_frame_id;
1763   int frame_saved;
1764
1765   /* If this is a local watchpoint, we only want to check if the
1766      watchpoint frame is in scope if the current thread is the thread
1767      that was used to create the watchpoint.  */
1768   if (!watchpoint_in_thread_scope (b))
1769     return;
1770
1771   if (b->base.disposition == disp_del_at_next_stop)
1772     return;
1773  
1774   frame_saved = 0;
1775
1776   /* Determine if the watchpoint is within scope.  */
1777   if (b->exp_valid_block == NULL)
1778     within_current_scope = 1;
1779   else
1780     {
1781       struct frame_info *fi = get_current_frame ();
1782       struct gdbarch *frame_arch = get_frame_arch (fi);
1783       CORE_ADDR frame_pc = get_frame_pc (fi);
1784
1785       /* If we're in a function epilogue, unwinding may not work
1786          properly, so do not attempt to recreate locations at this
1787          point.  See similar comments in watchpoint_check.  */
1788       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1789         return;
1790
1791       /* Save the current frame's ID so we can restore it after
1792          evaluating the watchpoint expression on its own frame.  */
1793       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1794          took a frame parameter, so that we didn't have to change the
1795          selected frame.  */
1796       frame_saved = 1;
1797       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1798
1799       fi = frame_find_by_id (b->watchpoint_frame);
1800       within_current_scope = (fi != NULL);
1801       if (within_current_scope)
1802         select_frame (fi);
1803     }
1804
1805   /* We don't free locations.  They are stored in the bp_location array
1806      and update_global_location_list will eventually delete them and
1807      remove breakpoints if needed.  */
1808   b->base.loc = NULL;
1809
1810   if (within_current_scope && reparse)
1811     {
1812       const char *s;
1813
1814       if (b->exp)
1815         {
1816           xfree (b->exp);
1817           b->exp = NULL;
1818         }
1819       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1820       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1821       /* If the meaning of expression itself changed, the old value is
1822          no longer relevant.  We don't want to report a watchpoint hit
1823          to the user when the old value and the new value may actually
1824          be completely different objects.  */
1825       value_free (b->val);
1826       b->val = NULL;
1827       b->val_valid = 0;
1828
1829       /* Note that unlike with breakpoints, the watchpoint's condition
1830          expression is stored in the breakpoint object, not in the
1831          locations (re)created below.  */
1832       if (b->base.cond_string != NULL)
1833         {
1834           if (b->cond_exp != NULL)
1835             {
1836               xfree (b->cond_exp);
1837               b->cond_exp = NULL;
1838             }
1839
1840           s = b->base.cond_string;
1841           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1842         }
1843     }
1844
1845   /* If we failed to parse the expression, for example because
1846      it refers to a global variable in a not-yet-loaded shared library,
1847      don't try to insert watchpoint.  We don't automatically delete
1848      such watchpoint, though, since failure to parse expression
1849      is different from out-of-scope watchpoint.  */
1850   if (!target_has_execution)
1851     {
1852       /* Without execution, memory can't change.  No use to try and
1853          set watchpoint locations.  The watchpoint will be reset when
1854          the target gains execution, through breakpoint_re_set.  */
1855       if (!can_use_hw_watchpoints)
1856         {
1857           if (b->base.ops->works_in_software_mode (&b->base))
1858             b->base.type = bp_watchpoint;
1859           else
1860             error (_("Can't set read/access watchpoint when "
1861                      "hardware watchpoints are disabled."));
1862         }
1863     }
1864   else if (within_current_scope && b->exp)
1865     {
1866       int pc = 0;
1867       struct value *val_chain, *v, *result, *next;
1868       struct program_space *frame_pspace;
1869
1870       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1871
1872       /* Avoid setting b->val if it's already set.  The meaning of
1873          b->val is 'the last value' user saw, and we should update
1874          it only if we reported that last value to user.  As it
1875          happens, the code that reports it updates b->val directly.
1876          We don't keep track of the memory value for masked
1877          watchpoints.  */
1878       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1879         {
1880           b->val = v;
1881           b->val_valid = 1;
1882         }
1883
1884       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1885
1886       /* Look at each value on the value chain.  */
1887       for (v = val_chain; v; v = value_next (v))
1888         {
1889           /* If it's a memory location, and GDB actually needed
1890              its contents to evaluate the expression, then we
1891              must watch it.  If the first value returned is
1892              still lazy, that means an error occurred reading it;
1893              watch it anyway in case it becomes readable.  */
1894           if (VALUE_LVAL (v) == lval_memory
1895               && (v == val_chain || ! value_lazy (v)))
1896             {
1897               struct type *vtype = check_typedef (value_type (v));
1898
1899               /* We only watch structs and arrays if user asked
1900                  for it explicitly, never if they just happen to
1901                  appear in the middle of some value chain.  */
1902               if (v == result
1903                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1904                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1905                 {
1906                   CORE_ADDR addr;
1907                   int type;
1908                   struct bp_location *loc, **tmp;
1909
1910                   addr = value_address (v);
1911                   type = hw_write;
1912                   if (b->base.type == bp_read_watchpoint)
1913                     type = hw_read;
1914                   else if (b->base.type == bp_access_watchpoint)
1915                     type = hw_access;
1916
1917                   loc = allocate_bp_location (&b->base);
1918                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1919                     ;
1920                   *tmp = loc;
1921                   loc->gdbarch = get_type_arch (value_type (v));
1922
1923                   loc->pspace = frame_pspace;
1924                   loc->address = addr;
1925                   loc->length = TYPE_LENGTH (value_type (v));
1926                   loc->watchpoint_type = type;
1927                 }
1928             }
1929         }
1930
1931       /* Change the type of breakpoint between hardware assisted or
1932          an ordinary watchpoint depending on the hardware support
1933          and free hardware slots.  REPARSE is set when the inferior
1934          is started.  */
1935       if (reparse)
1936         {
1937           int reg_cnt;
1938           enum bp_loc_type loc_type;
1939           struct bp_location *bl;
1940
1941           reg_cnt = can_use_hardware_watchpoint (val_chain);
1942
1943           if (reg_cnt)
1944             {
1945               int i, target_resources_ok, other_type_used;
1946               enum bptype type;
1947
1948               /* Use an exact watchpoint when there's only one memory region to be
1949                  watched, and only one debug register is needed to watch it.  */
1950               b->exact = target_exact_watchpoints && reg_cnt == 1;
1951
1952               /* We need to determine how many resources are already
1953                  used for all other hardware watchpoints plus this one
1954                  to see if we still have enough resources to also fit
1955                  this watchpoint in as well.  */
1956
1957               /* If this is a software watchpoint, we try to turn it
1958                  to a hardware one -- count resources as if B was of
1959                  hardware watchpoint type.  */
1960               type = b->base.type;
1961               if (type == bp_watchpoint)
1962                 type = bp_hardware_watchpoint;
1963
1964               /* This watchpoint may or may not have been placed on
1965                  the list yet at this point (it won't be in the list
1966                  if we're trying to create it for the first time,
1967                  through watch_command), so always account for it
1968                  manually.  */
1969
1970               /* Count resources used by all watchpoints except B.  */
1971               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1972
1973               /* Add in the resources needed for B.  */
1974               i += hw_watchpoint_use_count (&b->base);
1975
1976               target_resources_ok
1977                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1978               if (target_resources_ok <= 0)
1979                 {
1980                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1981
1982                   if (target_resources_ok == 0 && !sw_mode)
1983                     error (_("Target does not support this type of "
1984                              "hardware watchpoint."));
1985                   else if (target_resources_ok < 0 && !sw_mode)
1986                     error (_("There are not enough available hardware "
1987                              "resources for this watchpoint."));
1988
1989                   /* Downgrade to software watchpoint.  */
1990                   b->base.type = bp_watchpoint;
1991                 }
1992               else
1993                 {
1994                   /* If this was a software watchpoint, we've just
1995                      found we have enough resources to turn it to a
1996                      hardware watchpoint.  Otherwise, this is a
1997                      nop.  */
1998                   b->base.type = type;
1999                 }
2000             }
2001           else if (!b->base.ops->works_in_software_mode (&b->base))
2002             {
2003               if (!can_use_hw_watchpoints)
2004                 error (_("Can't set read/access watchpoint when "
2005                          "hardware watchpoints are disabled."));
2006               else
2007                 error (_("Expression cannot be implemented with "
2008                          "read/access watchpoint."));
2009             }
2010           else
2011             b->base.type = bp_watchpoint;
2012
2013           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2014                       : bp_loc_hardware_watchpoint);
2015           for (bl = b->base.loc; bl; bl = bl->next)
2016             bl->loc_type = loc_type;
2017         }
2018
2019       for (v = val_chain; v; v = next)
2020         {
2021           next = value_next (v);
2022           if (v != b->val)
2023             value_free (v);
2024         }
2025
2026       /* If a software watchpoint is not watching any memory, then the
2027          above left it without any location set up.  But,
2028          bpstat_stop_status requires a location to be able to report
2029          stops, so make sure there's at least a dummy one.  */
2030       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2031         {
2032           struct breakpoint *base = &b->base;
2033           base->loc = allocate_bp_location (base);
2034           base->loc->pspace = frame_pspace;
2035           base->loc->address = -1;
2036           base->loc->length = -1;
2037           base->loc->watchpoint_type = -1;
2038         }
2039     }
2040   else if (!within_current_scope)
2041     {
2042       printf_filtered (_("\
2043 Watchpoint %d deleted because the program has left the block\n\
2044 in which its expression is valid.\n"),
2045                        b->base.number);
2046       watchpoint_del_at_next_stop (b);
2047     }
2048
2049   /* Restore the selected frame.  */
2050   if (frame_saved)
2051     select_frame (frame_find_by_id (saved_frame_id));
2052 }
2053
2054
2055 /* Returns 1 iff breakpoint location should be
2056    inserted in the inferior.  We don't differentiate the type of BL's owner
2057    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2058    breakpoint_ops is not defined, because in insert_bp_location,
2059    tracepoint's insert_location will not be called.  */
2060 static int
2061 should_be_inserted (struct bp_location *bl)
2062 {
2063   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2064     return 0;
2065
2066   if (bl->owner->disposition == disp_del_at_next_stop)
2067     return 0;
2068
2069   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2070     return 0;
2071
2072   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2073     return 0;
2074
2075   /* This is set for example, when we're attached to the parent of a
2076      vfork, and have detached from the child.  The child is running
2077      free, and we expect it to do an exec or exit, at which point the
2078      OS makes the parent schedulable again (and the target reports
2079      that the vfork is done).  Until the child is done with the shared
2080      memory region, do not insert breakpoints in the parent, otherwise
2081      the child could still trip on the parent's breakpoints.  Since
2082      the parent is blocked anyway, it won't miss any breakpoint.  */
2083   if (bl->pspace->breakpoints_not_allowed)
2084     return 0;
2085
2086   /* Don't insert a breakpoint if we're trying to step past its
2087      location.  */
2088   if ((bl->loc_type == bp_loc_software_breakpoint
2089        || bl->loc_type == bp_loc_hardware_breakpoint)
2090       && stepping_past_instruction_at (bl->pspace->aspace,
2091                                        bl->address))
2092     return 0;
2093
2094   return 1;
2095 }
2096
2097 /* Same as should_be_inserted but does the check assuming
2098    that the location is not duplicated.  */
2099
2100 static int
2101 unduplicated_should_be_inserted (struct bp_location *bl)
2102 {
2103   int result;
2104   const int save_duplicate = bl->duplicate;
2105
2106   bl->duplicate = 0;
2107   result = should_be_inserted (bl);
2108   bl->duplicate = save_duplicate;
2109   return result;
2110 }
2111
2112 /* Parses a conditional described by an expression COND into an
2113    agent expression bytecode suitable for evaluation
2114    by the bytecode interpreter.  Return NULL if there was
2115    any error during parsing.  */
2116
2117 static struct agent_expr *
2118 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2119 {
2120   struct agent_expr *aexpr = NULL;
2121   volatile struct gdb_exception ex;
2122
2123   if (!cond)
2124     return NULL;
2125
2126   /* We don't want to stop processing, so catch any errors
2127      that may show up.  */
2128   TRY_CATCH (ex, RETURN_MASK_ERROR)
2129     {
2130       aexpr = gen_eval_for_expr (scope, cond);
2131     }
2132
2133   if (ex.reason < 0)
2134     {
2135       /* If we got here, it means the condition could not be parsed to a valid
2136          bytecode expression and thus can't be evaluated on the target's side.
2137          It's no use iterating through the conditions.  */
2138       return NULL;
2139     }
2140
2141   /* We have a valid agent expression.  */
2142   return aexpr;
2143 }
2144
2145 /* Based on location BL, create a list of breakpoint conditions to be
2146    passed on to the target.  If we have duplicated locations with different
2147    conditions, we will add such conditions to the list.  The idea is that the
2148    target will evaluate the list of conditions and will only notify GDB when
2149    one of them is true.  */
2150
2151 static void
2152 build_target_condition_list (struct bp_location *bl)
2153 {
2154   struct bp_location **locp = NULL, **loc2p;
2155   int null_condition_or_parse_error = 0;
2156   int modified = bl->needs_update;
2157   struct bp_location *loc;
2158
2159   /* Release conditions left over from a previous insert.  */
2160   VEC_free (agent_expr_p, bl->target_info.conditions);
2161
2162   /* This is only meaningful if the target is
2163      evaluating conditions and if the user has
2164      opted for condition evaluation on the target's
2165      side.  */
2166   if (gdb_evaluates_breakpoint_condition_p ()
2167       || !target_supports_evaluation_of_breakpoint_conditions ())
2168     return;
2169
2170   /* Do a first pass to check for locations with no assigned
2171      conditions or conditions that fail to parse to a valid agent expression
2172      bytecode.  If any of these happen, then it's no use to send conditions
2173      to the target since this location will always trigger and generate a
2174      response back to GDB.  */
2175   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2176     {
2177       loc = (*loc2p);
2178       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2179         {
2180           if (modified)
2181             {
2182               struct agent_expr *aexpr;
2183
2184               /* Re-parse the conditions since something changed.  In that
2185                  case we already freed the condition bytecodes (see
2186                  force_breakpoint_reinsertion).  We just
2187                  need to parse the condition to bytecodes again.  */
2188               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2189               loc->cond_bytecode = aexpr;
2190
2191               /* Check if we managed to parse the conditional expression
2192                  correctly.  If not, we will not send this condition
2193                  to the target.  */
2194               if (aexpr)
2195                 continue;
2196             }
2197
2198           /* If we have a NULL bytecode expression, it means something
2199              went wrong or we have a null condition expression.  */
2200           if (!loc->cond_bytecode)
2201             {
2202               null_condition_or_parse_error = 1;
2203               break;
2204             }
2205         }
2206     }
2207
2208   /* If any of these happened, it means we will have to evaluate the conditions
2209      for the location's address on gdb's side.  It is no use keeping bytecodes
2210      for all the other duplicate locations, thus we free all of them here.
2211
2212      This is so we have a finer control over which locations' conditions are
2213      being evaluated by GDB or the remote stub.  */
2214   if (null_condition_or_parse_error)
2215     {
2216       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2217         {
2218           loc = (*loc2p);
2219           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2220             {
2221               /* Only go as far as the first NULL bytecode is
2222                  located.  */
2223               if (!loc->cond_bytecode)
2224                 return;
2225
2226               free_agent_expr (loc->cond_bytecode);
2227               loc->cond_bytecode = NULL;
2228             }
2229         }
2230     }
2231
2232   /* No NULL conditions or failed bytecode generation.  Build a condition list
2233      for this location's address.  */
2234   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2235     {
2236       loc = (*loc2p);
2237       if (loc->cond
2238           && is_breakpoint (loc->owner)
2239           && loc->pspace->num == bl->pspace->num
2240           && loc->owner->enable_state == bp_enabled
2241           && loc->enabled)
2242         /* Add the condition to the vector.  This will be used later to send the
2243            conditions to the target.  */
2244         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2245                        loc->cond_bytecode);
2246     }
2247
2248   return;
2249 }
2250
2251 /* Parses a command described by string CMD into an agent expression
2252    bytecode suitable for evaluation by the bytecode interpreter.
2253    Return NULL if there was any error during parsing.  */
2254
2255 static struct agent_expr *
2256 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2257 {
2258   struct cleanup *old_cleanups = 0;
2259   struct expression *expr, **argvec;
2260   struct agent_expr *aexpr = NULL;
2261   volatile struct gdb_exception ex;
2262   const char *cmdrest;
2263   const char *format_start, *format_end;
2264   struct format_piece *fpieces;
2265   int nargs;
2266   struct gdbarch *gdbarch = get_current_arch ();
2267
2268   if (!cmd)
2269     return NULL;
2270
2271   cmdrest = cmd;
2272
2273   if (*cmdrest == ',')
2274     ++cmdrest;
2275   cmdrest = skip_spaces_const (cmdrest);
2276
2277   if (*cmdrest++ != '"')
2278     error (_("No format string following the location"));
2279
2280   format_start = cmdrest;
2281
2282   fpieces = parse_format_string (&cmdrest);
2283
2284   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2285
2286   format_end = cmdrest;
2287
2288   if (*cmdrest++ != '"')
2289     error (_("Bad format string, non-terminated '\"'."));
2290   
2291   cmdrest = skip_spaces_const (cmdrest);
2292
2293   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2294     error (_("Invalid argument syntax"));
2295
2296   if (*cmdrest == ',')
2297     cmdrest++;
2298   cmdrest = skip_spaces_const (cmdrest);
2299
2300   /* For each argument, make an expression.  */
2301
2302   argvec = (struct expression **) alloca (strlen (cmd)
2303                                          * sizeof (struct expression *));
2304
2305   nargs = 0;
2306   while (*cmdrest != '\0')
2307     {
2308       const char *cmd1;
2309
2310       cmd1 = cmdrest;
2311       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2312       argvec[nargs++] = expr;
2313       cmdrest = cmd1;
2314       if (*cmdrest == ',')
2315         ++cmdrest;
2316     }
2317
2318   /* We don't want to stop processing, so catch any errors
2319      that may show up.  */
2320   TRY_CATCH (ex, RETURN_MASK_ERROR)
2321     {
2322       aexpr = gen_printf (scope, gdbarch, 0, 0,
2323                           format_start, format_end - format_start,
2324                           fpieces, nargs, argvec);
2325     }
2326
2327   do_cleanups (old_cleanups);
2328
2329   if (ex.reason < 0)
2330     {
2331       /* If we got here, it means the command could not be parsed to a valid
2332          bytecode expression and thus can't be evaluated on the target's side.
2333          It's no use iterating through the other commands.  */
2334       return NULL;
2335     }
2336
2337   /* We have a valid agent expression, return it.  */
2338   return aexpr;
2339 }
2340
2341 /* Based on location BL, create a list of breakpoint commands to be
2342    passed on to the target.  If we have duplicated locations with
2343    different commands, we will add any such to the list.  */
2344
2345 static void
2346 build_target_command_list (struct bp_location *bl)
2347 {
2348   struct bp_location **locp = NULL, **loc2p;
2349   int null_command_or_parse_error = 0;
2350   int modified = bl->needs_update;
2351   struct bp_location *loc;
2352
2353   /* Release commands left over from a previous insert.  */
2354   VEC_free (agent_expr_p, bl->target_info.tcommands);
2355
2356   if (!target_can_run_breakpoint_commands ())
2357     return;
2358
2359   /* For now, limit to agent-style dprintf breakpoints.  */
2360   if (dprintf_style != dprintf_style_agent)
2361     return;
2362
2363   /* For now, if we have any duplicate location that isn't a dprintf,
2364      don't install the target-side commands, as that would make the
2365      breakpoint not be reported to the core, and we'd lose
2366      control.  */
2367   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2368     {
2369       loc = (*loc2p);
2370       if (is_breakpoint (loc->owner)
2371           && loc->pspace->num == bl->pspace->num
2372           && loc->owner->type != bp_dprintf)
2373         return;
2374     }
2375
2376   /* Do a first pass to check for locations with no assigned
2377      conditions or conditions that fail to parse to a valid agent expression
2378      bytecode.  If any of these happen, then it's no use to send conditions
2379      to the target since this location will always trigger and generate a
2380      response back to GDB.  */
2381   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2382     {
2383       loc = (*loc2p);
2384       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2385         {
2386           if (modified)
2387             {
2388               struct agent_expr *aexpr;
2389
2390               /* Re-parse the commands since something changed.  In that
2391                  case we already freed the command bytecodes (see
2392                  force_breakpoint_reinsertion).  We just
2393                  need to parse the command to bytecodes again.  */
2394               aexpr = parse_cmd_to_aexpr (bl->address,
2395                                           loc->owner->extra_string);
2396               loc->cmd_bytecode = aexpr;
2397
2398               if (!aexpr)
2399                 continue;
2400             }
2401
2402           /* If we have a NULL bytecode expression, it means something
2403              went wrong or we have a null command expression.  */
2404           if (!loc->cmd_bytecode)
2405             {
2406               null_command_or_parse_error = 1;
2407               break;
2408             }
2409         }
2410     }
2411
2412   /* If anything failed, then we're not doing target-side commands,
2413      and so clean up.  */
2414   if (null_command_or_parse_error)
2415     {
2416       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2417         {
2418           loc = (*loc2p);
2419           if (is_breakpoint (loc->owner)
2420               && loc->pspace->num == bl->pspace->num)
2421             {
2422               /* Only go as far as the first NULL bytecode is
2423                  located.  */
2424               if (loc->cmd_bytecode == NULL)
2425                 return;
2426
2427               free_agent_expr (loc->cmd_bytecode);
2428               loc->cmd_bytecode = NULL;
2429             }
2430         }
2431     }
2432
2433   /* No NULL commands or failed bytecode generation.  Build a command list
2434      for this location's address.  */
2435   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2436     {
2437       loc = (*loc2p);
2438       if (loc->owner->extra_string
2439           && is_breakpoint (loc->owner)
2440           && loc->pspace->num == bl->pspace->num
2441           && loc->owner->enable_state == bp_enabled
2442           && loc->enabled)
2443         /* Add the command to the vector.  This will be used later
2444            to send the commands to the target.  */
2445         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2446                        loc->cmd_bytecode);
2447     }
2448
2449   bl->target_info.persist = 0;
2450   /* Maybe flag this location as persistent.  */
2451   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2452     bl->target_info.persist = 1;
2453 }
2454
2455 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2456    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2457    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2458    Returns 0 for success, 1 if the bp_location type is not supported or
2459    -1 for failure.
2460
2461    NOTE drow/2003-09-09: This routine could be broken down to an
2462    object-style method for each breakpoint or catchpoint type.  */
2463 static int
2464 insert_bp_location (struct bp_location *bl,
2465                     struct ui_file *tmp_error_stream,
2466                     int *disabled_breaks,
2467                     int *hw_breakpoint_error,
2468                     int *hw_bp_error_explained_already)
2469 {
2470   enum errors bp_err = GDB_NO_ERROR;
2471   const char *bp_err_message = NULL;
2472   volatile struct gdb_exception e;
2473
2474   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2475     return 0;
2476
2477   /* Note we don't initialize bl->target_info, as that wipes out
2478      the breakpoint location's shadow_contents if the breakpoint
2479      is still inserted at that location.  This in turn breaks
2480      target_read_memory which depends on these buffers when
2481      a memory read is requested at the breakpoint location:
2482      Once the target_info has been wiped, we fail to see that
2483      we have a breakpoint inserted at that address and thus
2484      read the breakpoint instead of returning the data saved in
2485      the breakpoint location's shadow contents.  */
2486   bl->target_info.placed_address = bl->address;
2487   bl->target_info.placed_address_space = bl->pspace->aspace;
2488   bl->target_info.length = bl->length;
2489
2490   /* When working with target-side conditions, we must pass all the conditions
2491      for the same breakpoint address down to the target since GDB will not
2492      insert those locations.  With a list of breakpoint conditions, the target
2493      can decide when to stop and notify GDB.  */
2494
2495   if (is_breakpoint (bl->owner))
2496     {
2497       build_target_condition_list (bl);
2498       build_target_command_list (bl);
2499       /* Reset the modification marker.  */
2500       bl->needs_update = 0;
2501     }
2502
2503   if (bl->loc_type == bp_loc_software_breakpoint
2504       || bl->loc_type == bp_loc_hardware_breakpoint)
2505     {
2506       if (bl->owner->type != bp_hardware_breakpoint)
2507         {
2508           /* If the explicitly specified breakpoint type
2509              is not hardware breakpoint, check the memory map to see
2510              if the breakpoint address is in read only memory or not.
2511
2512              Two important cases are:
2513              - location type is not hardware breakpoint, memory
2514              is readonly.  We change the type of the location to
2515              hardware breakpoint.
2516              - location type is hardware breakpoint, memory is
2517              read-write.  This means we've previously made the
2518              location hardware one, but then the memory map changed,
2519              so we undo.
2520              
2521              When breakpoints are removed, remove_breakpoints will use
2522              location types we've just set here, the only possible
2523              problem is that memory map has changed during running
2524              program, but it's not going to work anyway with current
2525              gdb.  */
2526           struct mem_region *mr 
2527             = lookup_mem_region (bl->target_info.placed_address);
2528           
2529           if (mr)
2530             {
2531               if (automatic_hardware_breakpoints)
2532                 {
2533                   enum bp_loc_type new_type;
2534                   
2535                   if (mr->attrib.mode != MEM_RW)
2536                     new_type = bp_loc_hardware_breakpoint;
2537                   else 
2538                     new_type = bp_loc_software_breakpoint;
2539                   
2540                   if (new_type != bl->loc_type)
2541                     {
2542                       static int said = 0;
2543
2544                       bl->loc_type = new_type;
2545                       if (!said)
2546                         {
2547                           fprintf_filtered (gdb_stdout,
2548                                             _("Note: automatically using "
2549                                               "hardware breakpoints for "
2550                                               "read-only addresses.\n"));
2551                           said = 1;
2552                         }
2553                     }
2554                 }
2555               else if (bl->loc_type == bp_loc_software_breakpoint
2556                        && mr->attrib.mode != MEM_RW)        
2557                 warning (_("cannot set software breakpoint "
2558                            "at readonly address %s"),
2559                          paddress (bl->gdbarch, bl->address));
2560             }
2561         }
2562         
2563       /* First check to see if we have to handle an overlay.  */
2564       if (overlay_debugging == ovly_off
2565           || bl->section == NULL
2566           || !(section_is_overlay (bl->section)))
2567         {
2568           /* No overlay handling: just set the breakpoint.  */
2569           TRY_CATCH (e, RETURN_MASK_ALL)
2570             {
2571               int val;
2572
2573               val = bl->owner->ops->insert_location (bl);
2574               if (val)
2575                 bp_err = GENERIC_ERROR;
2576             }
2577           if (e.reason < 0)
2578             {
2579               bp_err = e.error;
2580               bp_err_message = e.message;
2581             }
2582         }
2583       else
2584         {
2585           /* This breakpoint is in an overlay section.
2586              Shall we set a breakpoint at the LMA?  */
2587           if (!overlay_events_enabled)
2588             {
2589               /* Yes -- overlay event support is not active, 
2590                  so we must try to set a breakpoint at the LMA.
2591                  This will not work for a hardware breakpoint.  */
2592               if (bl->loc_type == bp_loc_hardware_breakpoint)
2593                 warning (_("hardware breakpoint %d not supported in overlay!"),
2594                          bl->owner->number);
2595               else
2596                 {
2597                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2598                                                              bl->section);
2599                   /* Set a software (trap) breakpoint at the LMA.  */
2600                   bl->overlay_target_info = bl->target_info;
2601                   bl->overlay_target_info.placed_address = addr;
2602
2603                   /* No overlay handling: just set the breakpoint.  */
2604                   TRY_CATCH (e, RETURN_MASK_ALL)
2605                     {
2606                       int val;
2607
2608                       val = target_insert_breakpoint (bl->gdbarch,
2609                                                       &bl->overlay_target_info);
2610                       if (val)
2611                         bp_err = GENERIC_ERROR;
2612                     }
2613                   if (e.reason < 0)
2614                     {
2615                       bp_err = e.error;
2616                       bp_err_message = e.message;
2617                     }
2618
2619                   if (bp_err != GDB_NO_ERROR)
2620                     fprintf_unfiltered (tmp_error_stream,
2621                                         "Overlay breakpoint %d "
2622                                         "failed: in ROM?\n",
2623                                         bl->owner->number);
2624                 }
2625             }
2626           /* Shall we set a breakpoint at the VMA? */
2627           if (section_is_mapped (bl->section))
2628             {
2629               /* Yes.  This overlay section is mapped into memory.  */
2630               TRY_CATCH (e, RETURN_MASK_ALL)
2631                 {
2632                   int val;
2633
2634                   val = bl->owner->ops->insert_location (bl);
2635                   if (val)
2636                     bp_err = GENERIC_ERROR;
2637                 }
2638               if (e.reason < 0)
2639                 {
2640                   bp_err = e.error;
2641                   bp_err_message = e.message;
2642                 }
2643             }
2644           else
2645             {
2646               /* No.  This breakpoint will not be inserted.  
2647                  No error, but do not mark the bp as 'inserted'.  */
2648               return 0;
2649             }
2650         }
2651
2652       if (bp_err != GDB_NO_ERROR)
2653         {
2654           /* Can't set the breakpoint.  */
2655
2656           /* In some cases, we might not be able to insert a
2657              breakpoint in a shared library that has already been
2658              removed, but we have not yet processed the shlib unload
2659              event.  Unfortunately, some targets that implement
2660              breakpoint insertion themselves can't tell why the
2661              breakpoint insertion failed (e.g., the remote target
2662              doesn't define error codes), so we must treat generic
2663              errors as memory errors.  */
2664           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2665               && bl->loc_type == bp_loc_software_breakpoint
2666               && (solib_name_from_address (bl->pspace, bl->address)
2667                   || shared_objfile_contains_address_p (bl->pspace,
2668                                                         bl->address)))
2669             {
2670               /* See also: disable_breakpoints_in_shlibs.  */
2671               bl->shlib_disabled = 1;
2672               observer_notify_breakpoint_modified (bl->owner);
2673               if (!*disabled_breaks)
2674                 {
2675                   fprintf_unfiltered (tmp_error_stream, 
2676                                       "Cannot insert breakpoint %d.\n", 
2677                                       bl->owner->number);
2678                   fprintf_unfiltered (tmp_error_stream, 
2679                                       "Temporarily disabling shared "
2680                                       "library breakpoints:\n");
2681                 }
2682               *disabled_breaks = 1;
2683               fprintf_unfiltered (tmp_error_stream,
2684                                   "breakpoint #%d\n", bl->owner->number);
2685               return 0;
2686             }
2687           else
2688             {
2689               if (bl->loc_type == bp_loc_hardware_breakpoint)
2690                 {
2691                   *hw_breakpoint_error = 1;
2692                   *hw_bp_error_explained_already = bp_err_message != NULL;
2693                   fprintf_unfiltered (tmp_error_stream,
2694                                       "Cannot insert hardware breakpoint %d%s",
2695                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2696                   if (bp_err_message != NULL)
2697                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2698                 }
2699               else
2700                 {
2701                   if (bp_err_message == NULL)
2702                     {
2703                       char *message
2704                         = memory_error_message (TARGET_XFER_E_IO,
2705                                                 bl->gdbarch, bl->address);
2706                       struct cleanup *old_chain = make_cleanup (xfree, message);
2707
2708                       fprintf_unfiltered (tmp_error_stream,
2709                                           "Cannot insert breakpoint %d.\n"
2710                                           "%s\n",
2711                                           bl->owner->number, message);
2712                       do_cleanups (old_chain);
2713                     }
2714                   else
2715                     {
2716                       fprintf_unfiltered (tmp_error_stream,
2717                                           "Cannot insert breakpoint %d: %s\n",
2718                                           bl->owner->number,
2719                                           bp_err_message);
2720                     }
2721                 }
2722               return 1;
2723
2724             }
2725         }
2726       else
2727         bl->inserted = 1;
2728
2729       return 0;
2730     }
2731
2732   else if (bl->loc_type == bp_loc_hardware_watchpoint
2733            /* NOTE drow/2003-09-08: This state only exists for removing
2734               watchpoints.  It's not clear that it's necessary...  */
2735            && bl->owner->disposition != disp_del_at_next_stop)
2736     {
2737       int val;
2738
2739       gdb_assert (bl->owner->ops != NULL
2740                   && bl->owner->ops->insert_location != NULL);
2741
2742       val = bl->owner->ops->insert_location (bl);
2743
2744       /* If trying to set a read-watchpoint, and it turns out it's not
2745          supported, try emulating one with an access watchpoint.  */
2746       if (val == 1 && bl->watchpoint_type == hw_read)
2747         {
2748           struct bp_location *loc, **loc_temp;
2749
2750           /* But don't try to insert it, if there's already another
2751              hw_access location that would be considered a duplicate
2752              of this one.  */
2753           ALL_BP_LOCATIONS (loc, loc_temp)
2754             if (loc != bl
2755                 && loc->watchpoint_type == hw_access
2756                 && watchpoint_locations_match (bl, loc))
2757               {
2758                 bl->duplicate = 1;
2759                 bl->inserted = 1;
2760                 bl->target_info = loc->target_info;
2761                 bl->watchpoint_type = hw_access;
2762                 val = 0;
2763                 break;
2764               }
2765
2766           if (val == 1)
2767             {
2768               bl->watchpoint_type = hw_access;
2769               val = bl->owner->ops->insert_location (bl);
2770
2771               if (val)
2772                 /* Back to the original value.  */
2773                 bl->watchpoint_type = hw_read;
2774             }
2775         }
2776
2777       bl->inserted = (val == 0);
2778     }
2779
2780   else if (bl->owner->type == bp_catchpoint)
2781     {
2782       int val;
2783
2784       gdb_assert (bl->owner->ops != NULL
2785                   && bl->owner->ops->insert_location != NULL);
2786
2787       val = bl->owner->ops->insert_location (bl);
2788       if (val)
2789         {
2790           bl->owner->enable_state = bp_disabled;
2791
2792           if (val == 1)
2793             warning (_("\
2794 Error inserting catchpoint %d: Your system does not support this type\n\
2795 of catchpoint."), bl->owner->number);
2796           else
2797             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2798         }
2799
2800       bl->inserted = (val == 0);
2801
2802       /* We've already printed an error message if there was a problem
2803          inserting this catchpoint, and we've disabled the catchpoint,
2804          so just return success.  */
2805       return 0;
2806     }
2807
2808   return 0;
2809 }
2810
2811 /* This function is called when program space PSPACE is about to be
2812    deleted.  It takes care of updating breakpoints to not reference
2813    PSPACE anymore.  */
2814
2815 void
2816 breakpoint_program_space_exit (struct program_space *pspace)
2817 {
2818   struct breakpoint *b, *b_temp;
2819   struct bp_location *loc, **loc_temp;
2820
2821   /* Remove any breakpoint that was set through this program space.  */
2822   ALL_BREAKPOINTS_SAFE (b, b_temp)
2823     {
2824       if (b->pspace == pspace)
2825         delete_breakpoint (b);
2826     }
2827
2828   /* Breakpoints set through other program spaces could have locations
2829      bound to PSPACE as well.  Remove those.  */
2830   ALL_BP_LOCATIONS (loc, loc_temp)
2831     {
2832       struct bp_location *tmp;
2833
2834       if (loc->pspace == pspace)
2835         {
2836           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2837           if (loc->owner->loc == loc)
2838             loc->owner->loc = loc->next;
2839           else
2840             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2841               if (tmp->next == loc)
2842                 {
2843                   tmp->next = loc->next;
2844                   break;
2845                 }
2846         }
2847     }
2848
2849   /* Now update the global location list to permanently delete the
2850      removed locations above.  */
2851   update_global_location_list (0);
2852 }
2853
2854 /* Make sure all breakpoints are inserted in inferior.
2855    Throws exception on any error.
2856    A breakpoint that is already inserted won't be inserted
2857    again, so calling this function twice is safe.  */
2858 void
2859 insert_breakpoints (void)
2860 {
2861   struct breakpoint *bpt;
2862
2863   ALL_BREAKPOINTS (bpt)
2864     if (is_hardware_watchpoint (bpt))
2865       {
2866         struct watchpoint *w = (struct watchpoint *) bpt;
2867
2868         update_watchpoint (w, 0 /* don't reparse.  */);
2869       }
2870
2871   update_global_location_list (1);
2872
2873   /* update_global_location_list does not insert breakpoints when
2874      always_inserted_mode is not enabled.  Explicitly insert them
2875      now.  */
2876   if (!breakpoints_always_inserted_mode ())
2877     insert_breakpoint_locations ();
2878 }
2879
2880 /* Invoke CALLBACK for each of bp_location.  */
2881
2882 void
2883 iterate_over_bp_locations (walk_bp_location_callback callback)
2884 {
2885   struct bp_location *loc, **loc_tmp;
2886
2887   ALL_BP_LOCATIONS (loc, loc_tmp)
2888     {
2889       callback (loc, NULL);
2890     }
2891 }
2892
2893 /* This is used when we need to synch breakpoint conditions between GDB and the
2894    target.  It is the case with deleting and disabling of breakpoints when using
2895    always-inserted mode.  */
2896
2897 static void
2898 update_inserted_breakpoint_locations (void)
2899 {
2900   struct bp_location *bl, **blp_tmp;
2901   int error_flag = 0;
2902   int val = 0;
2903   int disabled_breaks = 0;
2904   int hw_breakpoint_error = 0;
2905   int hw_bp_details_reported = 0;
2906
2907   struct ui_file *tmp_error_stream = mem_fileopen ();
2908   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2909
2910   /* Explicitly mark the warning -- this will only be printed if
2911      there was an error.  */
2912   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2913
2914   save_current_space_and_thread ();
2915
2916   ALL_BP_LOCATIONS (bl, blp_tmp)
2917     {
2918       /* We only want to update software breakpoints and hardware
2919          breakpoints.  */
2920       if (!is_breakpoint (bl->owner))
2921         continue;
2922
2923       /* We only want to update locations that are already inserted
2924          and need updating.  This is to avoid unwanted insertion during
2925          deletion of breakpoints.  */
2926       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2927         continue;
2928
2929       switch_to_program_space_and_thread (bl->pspace);
2930
2931       /* For targets that support global breakpoints, there's no need
2932          to select an inferior to insert breakpoint to.  In fact, even
2933          if we aren't attached to any process yet, we should still
2934          insert breakpoints.  */
2935       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2936           && ptid_equal (inferior_ptid, null_ptid))
2937         continue;
2938
2939       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2940                                     &hw_breakpoint_error, &hw_bp_details_reported);
2941       if (val)
2942         error_flag = val;
2943     }
2944
2945   if (error_flag)
2946     {
2947       target_terminal_ours_for_output ();
2948       error_stream (tmp_error_stream);
2949     }
2950
2951   do_cleanups (cleanups);
2952 }
2953
2954 /* Used when starting or continuing the program.  */
2955
2956 static void
2957 insert_breakpoint_locations (void)
2958 {
2959   struct breakpoint *bpt;
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_error_explained_already = 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       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2979         continue;
2980
2981       /* There is no point inserting thread-specific breakpoints if
2982          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2983          has BL->OWNER always non-NULL.  */
2984       if (bl->owner->thread != -1
2985           && !valid_thread_id (bl->owner->thread))
2986         continue;
2987
2988       switch_to_program_space_and_thread (bl->pspace);
2989
2990       /* For targets that support global breakpoints, there's no need
2991          to select an inferior to insert breakpoint to.  In fact, even
2992          if we aren't attached to any process yet, we should still
2993          insert breakpoints.  */
2994       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2995           && ptid_equal (inferior_ptid, null_ptid))
2996         continue;
2997
2998       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2999                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3000       if (val)
3001         error_flag = val;
3002     }
3003
3004   /* If we failed to insert all locations of a watchpoint, remove
3005      them, as half-inserted watchpoint is of limited use.  */
3006   ALL_BREAKPOINTS (bpt)  
3007     {
3008       int some_failed = 0;
3009       struct bp_location *loc;
3010
3011       if (!is_hardware_watchpoint (bpt))
3012         continue;
3013
3014       if (!breakpoint_enabled (bpt))
3015         continue;
3016
3017       if (bpt->disposition == disp_del_at_next_stop)
3018         continue;
3019       
3020       for (loc = bpt->loc; loc; loc = loc->next)
3021         if (!loc->inserted && should_be_inserted (loc))
3022           {
3023             some_failed = 1;
3024             break;
3025           }
3026       if (some_failed)
3027         {
3028           for (loc = bpt->loc; loc; loc = loc->next)
3029             if (loc->inserted)
3030               remove_breakpoint (loc, mark_uninserted);
3031
3032           hw_breakpoint_error = 1;
3033           fprintf_unfiltered (tmp_error_stream,
3034                               "Could not insert hardware watchpoint %d.\n", 
3035                               bpt->number);
3036           error_flag = -1;
3037         }
3038     }
3039
3040   if (error_flag)
3041     {
3042       /* If a hardware breakpoint or watchpoint was inserted, add a
3043          message about possibly exhausted resources.  */
3044       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3045         {
3046           fprintf_unfiltered (tmp_error_stream, 
3047                               "Could not insert hardware breakpoints:\n\
3048 You may have requested too many hardware breakpoints/watchpoints.\n");
3049         }
3050       target_terminal_ours_for_output ();
3051       error_stream (tmp_error_stream);
3052     }
3053
3054   do_cleanups (cleanups);
3055 }
3056
3057 /* Used when the program stops.
3058    Returns zero if successful, or non-zero if there was a problem
3059    removing a breakpoint location.  */
3060
3061 int
3062 remove_breakpoints (void)
3063 {
3064   struct bp_location *bl, **blp_tmp;
3065   int val = 0;
3066
3067   ALL_BP_LOCATIONS (bl, blp_tmp)
3068   {
3069     if (bl->inserted && !is_tracepoint (bl->owner))
3070       val |= remove_breakpoint (bl, mark_uninserted);
3071   }
3072   return val;
3073 }
3074
3075 /* When a thread exits, remove breakpoints that are related to
3076    that thread.  */
3077
3078 static void
3079 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3080 {
3081   struct breakpoint *b, *b_tmp;
3082
3083   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3084     {
3085       if (b->thread == tp->num && user_breakpoint_p (b))
3086         {
3087           b->disposition = disp_del_at_next_stop;
3088
3089           printf_filtered (_("\
3090 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3091                           b->number, tp->num);
3092
3093           /* Hide it from the user.  */
3094           b->number = 0;
3095        }
3096     }
3097 }
3098
3099 /* Remove breakpoints of process PID.  */
3100
3101 int
3102 remove_breakpoints_pid (int pid)
3103 {
3104   struct bp_location *bl, **blp_tmp;
3105   int val;
3106   struct inferior *inf = find_inferior_pid (pid);
3107
3108   ALL_BP_LOCATIONS (bl, blp_tmp)
3109   {
3110     if (bl->pspace != inf->pspace)
3111       continue;
3112
3113     if (bl->owner->type == bp_dprintf)
3114       continue;
3115
3116     if (bl->inserted)
3117       {
3118         val = remove_breakpoint (bl, mark_uninserted);
3119         if (val != 0)
3120           return val;
3121       }
3122   }
3123   return 0;
3124 }
3125
3126 int
3127 reattach_breakpoints (int pid)
3128 {
3129   struct cleanup *old_chain;
3130   struct bp_location *bl, **blp_tmp;
3131   int val;
3132   struct ui_file *tmp_error_stream;
3133   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3134   struct inferior *inf;
3135   struct thread_info *tp;
3136
3137   tp = any_live_thread_of_process (pid);
3138   if (tp == NULL)
3139     return 1;
3140
3141   inf = find_inferior_pid (pid);
3142   old_chain = save_inferior_ptid ();
3143
3144   inferior_ptid = tp->ptid;
3145
3146   tmp_error_stream = mem_fileopen ();
3147   make_cleanup_ui_file_delete (tmp_error_stream);
3148
3149   ALL_BP_LOCATIONS (bl, blp_tmp)
3150   {
3151     if (bl->pspace != inf->pspace)
3152       continue;
3153
3154     if (bl->inserted)
3155       {
3156         bl->inserted = 0;
3157         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3158         if (val != 0)
3159           {
3160             do_cleanups (old_chain);
3161             return val;
3162           }
3163       }
3164   }
3165   do_cleanups (old_chain);
3166   return 0;
3167 }
3168
3169 static int internal_breakpoint_number = -1;
3170
3171 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3172    If INTERNAL is non-zero, the breakpoint number will be populated
3173    from internal_breakpoint_number and that variable decremented.
3174    Otherwise the breakpoint number will be populated from
3175    breakpoint_count and that value incremented.  Internal breakpoints
3176    do not set the internal var bpnum.  */
3177 static void
3178 set_breakpoint_number (int internal, struct breakpoint *b)
3179 {
3180   if (internal)
3181     b->number = internal_breakpoint_number--;
3182   else
3183     {
3184       set_breakpoint_count (breakpoint_count + 1);
3185       b->number = breakpoint_count;
3186     }
3187 }
3188
3189 static struct breakpoint *
3190 create_internal_breakpoint (struct gdbarch *gdbarch,
3191                             CORE_ADDR address, enum bptype type,
3192                             const struct breakpoint_ops *ops)
3193 {
3194   struct symtab_and_line sal;
3195   struct breakpoint *b;
3196
3197   init_sal (&sal);              /* Initialize to zeroes.  */
3198
3199   sal.pc = address;
3200   sal.section = find_pc_overlay (sal.pc);
3201   sal.pspace = current_program_space;
3202
3203   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3204   b->number = internal_breakpoint_number--;
3205   b->disposition = disp_donttouch;
3206
3207   return b;
3208 }
3209
3210 static const char *const longjmp_names[] =
3211   {
3212     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3213   };
3214 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3215
3216 /* Per-objfile data private to breakpoint.c.  */
3217 struct breakpoint_objfile_data
3218 {
3219   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3220   struct bound_minimal_symbol overlay_msym;
3221
3222   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3223   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3224
3225   /* True if we have looked for longjmp probes.  */
3226   int longjmp_searched;
3227
3228   /* SystemTap probe points for longjmp (if any).  */
3229   VEC (probe_p) *longjmp_probes;
3230
3231   /* Minimal symbol for "std::terminate()" (if any).  */
3232   struct bound_minimal_symbol terminate_msym;
3233
3234   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3235   struct bound_minimal_symbol exception_msym;
3236
3237   /* True if we have looked for exception probes.  */
3238   int exception_searched;
3239
3240   /* SystemTap probe points for unwinding (if any).  */
3241   VEC (probe_p) *exception_probes;
3242 };
3243
3244 static const struct objfile_data *breakpoint_objfile_key;
3245
3246 /* Minimal symbol not found sentinel.  */
3247 static struct minimal_symbol msym_not_found;
3248
3249 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3250
3251 static int
3252 msym_not_found_p (const struct minimal_symbol *msym)
3253 {
3254   return msym == &msym_not_found;
3255 }
3256
3257 /* Return per-objfile data needed by breakpoint.c.
3258    Allocate the data if necessary.  */
3259
3260 static struct breakpoint_objfile_data *
3261 get_breakpoint_objfile_data (struct objfile *objfile)
3262 {
3263   struct breakpoint_objfile_data *bp_objfile_data;
3264
3265   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3266   if (bp_objfile_data == NULL)
3267     {
3268       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3269                                        sizeof (*bp_objfile_data));
3270
3271       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3272       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3273     }
3274   return bp_objfile_data;
3275 }
3276
3277 static void
3278 free_breakpoint_probes (struct objfile *obj, void *data)
3279 {
3280   struct breakpoint_objfile_data *bp_objfile_data = data;
3281
3282   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3283   VEC_free (probe_p, bp_objfile_data->exception_probes);
3284 }
3285
3286 static void
3287 create_overlay_event_breakpoint (void)
3288 {
3289   struct objfile *objfile;
3290   const char *const func_name = "_ovly_debug_event";
3291
3292   ALL_OBJFILES (objfile)
3293     {
3294       struct breakpoint *b;
3295       struct breakpoint_objfile_data *bp_objfile_data;
3296       CORE_ADDR addr;
3297
3298       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3299
3300       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3301         continue;
3302
3303       if (bp_objfile_data->overlay_msym.minsym == NULL)
3304         {
3305           struct bound_minimal_symbol m;
3306
3307           m = lookup_minimal_symbol_text (func_name, objfile);
3308           if (m.minsym == NULL)
3309             {
3310               /* Avoid future lookups in this objfile.  */
3311               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3312               continue;
3313             }
3314           bp_objfile_data->overlay_msym = m;
3315         }
3316
3317       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3318       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3319                                       bp_overlay_event,
3320                                       &internal_breakpoint_ops);
3321       b->addr_string = xstrdup (func_name);
3322
3323       if (overlay_debugging == ovly_auto)
3324         {
3325           b->enable_state = bp_enabled;
3326           overlay_events_enabled = 1;
3327         }
3328       else
3329        {
3330          b->enable_state = bp_disabled;
3331          overlay_events_enabled = 0;
3332        }
3333     }
3334   update_global_location_list (1);
3335 }
3336
3337 static void
3338 create_longjmp_master_breakpoint (void)
3339 {
3340   struct program_space *pspace;
3341   struct cleanup *old_chain;
3342
3343   old_chain = save_current_program_space ();
3344
3345   ALL_PSPACES (pspace)
3346   {
3347     struct objfile *objfile;
3348
3349     set_current_program_space (pspace);
3350
3351     ALL_OBJFILES (objfile)
3352     {
3353       int i;
3354       struct gdbarch *gdbarch;
3355       struct breakpoint_objfile_data *bp_objfile_data;
3356
3357       gdbarch = get_objfile_arch (objfile);
3358
3359       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3360
3361       if (!bp_objfile_data->longjmp_searched)
3362         {
3363           VEC (probe_p) *ret;
3364
3365           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3366           if (ret != NULL)
3367             {
3368               /* We are only interested in checking one element.  */
3369               struct probe *p = VEC_index (probe_p, ret, 0);
3370
3371               if (!can_evaluate_probe_arguments (p))
3372                 {
3373                   /* We cannot use the probe interface here, because it does
3374                      not know how to evaluate arguments.  */
3375                   VEC_free (probe_p, ret);
3376                   ret = NULL;
3377                 }
3378             }
3379           bp_objfile_data->longjmp_probes = ret;
3380           bp_objfile_data->longjmp_searched = 1;
3381         }
3382
3383       if (bp_objfile_data->longjmp_probes != NULL)
3384         {
3385           int i;
3386           struct probe *probe;
3387           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3388
3389           for (i = 0;
3390                VEC_iterate (probe_p,
3391                             bp_objfile_data->longjmp_probes,
3392                             i, probe);
3393                ++i)
3394             {
3395               struct breakpoint *b;
3396
3397               b = create_internal_breakpoint (gdbarch,
3398                                               get_probe_address (probe,
3399                                                                  objfile),
3400                                               bp_longjmp_master,
3401                                               &internal_breakpoint_ops);
3402               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3403               b->enable_state = bp_disabled;
3404             }
3405
3406           continue;
3407         }
3408
3409       if (!gdbarch_get_longjmp_target_p (gdbarch))
3410         continue;
3411
3412       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3413         {
3414           struct breakpoint *b;
3415           const char *func_name;
3416           CORE_ADDR addr;
3417
3418           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3419             continue;
3420
3421           func_name = longjmp_names[i];
3422           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3423             {
3424               struct bound_minimal_symbol m;
3425
3426               m = lookup_minimal_symbol_text (func_name, objfile);
3427               if (m.minsym == NULL)
3428                 {
3429                   /* Prevent future lookups in this objfile.  */
3430                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3431                   continue;
3432                 }
3433               bp_objfile_data->longjmp_msym[i] = m;
3434             }
3435
3436           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3437           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3438                                           &internal_breakpoint_ops);
3439           b->addr_string = xstrdup (func_name);
3440           b->enable_state = bp_disabled;
3441         }
3442     }
3443   }
3444   update_global_location_list (1);
3445
3446   do_cleanups (old_chain);
3447 }
3448
3449 /* Create a master std::terminate breakpoint.  */
3450 static void
3451 create_std_terminate_master_breakpoint (void)
3452 {
3453   struct program_space *pspace;
3454   struct cleanup *old_chain;
3455   const char *const func_name = "std::terminate()";
3456
3457   old_chain = save_current_program_space ();
3458
3459   ALL_PSPACES (pspace)
3460   {
3461     struct objfile *objfile;
3462     CORE_ADDR addr;
3463
3464     set_current_program_space (pspace);
3465
3466     ALL_OBJFILES (objfile)
3467     {
3468       struct breakpoint *b;
3469       struct breakpoint_objfile_data *bp_objfile_data;
3470
3471       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3472
3473       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3474         continue;
3475
3476       if (bp_objfile_data->terminate_msym.minsym == NULL)
3477         {
3478           struct bound_minimal_symbol m;
3479
3480           m = lookup_minimal_symbol (func_name, NULL, objfile);
3481           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3482                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3483             {
3484               /* Prevent future lookups in this objfile.  */
3485               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3486               continue;
3487             }
3488           bp_objfile_data->terminate_msym = m;
3489         }
3490
3491       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3492       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3493                                       bp_std_terminate_master,
3494                                       &internal_breakpoint_ops);
3495       b->addr_string = xstrdup (func_name);
3496       b->enable_state = bp_disabled;
3497     }
3498   }
3499
3500   update_global_location_list (1);
3501
3502   do_cleanups (old_chain);
3503 }
3504
3505 /* Install a master breakpoint on the unwinder's debug hook.  */
3506
3507 static void
3508 create_exception_master_breakpoint (void)
3509 {
3510   struct objfile *objfile;
3511   const char *const func_name = "_Unwind_DebugHook";
3512
3513   ALL_OBJFILES (objfile)
3514     {
3515       struct breakpoint *b;
3516       struct gdbarch *gdbarch;
3517       struct breakpoint_objfile_data *bp_objfile_data;
3518       CORE_ADDR addr;
3519
3520       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3521
3522       /* We prefer the SystemTap probe point if it exists.  */
3523       if (!bp_objfile_data->exception_searched)
3524         {
3525           VEC (probe_p) *ret;
3526
3527           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3528
3529           if (ret != NULL)
3530             {
3531               /* We are only interested in checking one element.  */
3532               struct probe *p = VEC_index (probe_p, ret, 0);
3533
3534               if (!can_evaluate_probe_arguments (p))
3535                 {
3536                   /* We cannot use the probe interface here, because it does
3537                      not know how to evaluate arguments.  */
3538                   VEC_free (probe_p, ret);
3539                   ret = NULL;
3540                 }
3541             }
3542           bp_objfile_data->exception_probes = ret;
3543           bp_objfile_data->exception_searched = 1;
3544         }
3545
3546       if (bp_objfile_data->exception_probes != NULL)
3547         {
3548           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3549           int i;
3550           struct probe *probe;
3551
3552           for (i = 0;
3553                VEC_iterate (probe_p,
3554                             bp_objfile_data->exception_probes,
3555                             i, probe);
3556                ++i)
3557             {
3558               struct breakpoint *b;
3559
3560               b = create_internal_breakpoint (gdbarch,
3561                                               get_probe_address (probe,
3562                                                                  objfile),
3563                                               bp_exception_master,
3564                                               &internal_breakpoint_ops);
3565               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3566               b->enable_state = bp_disabled;
3567             }
3568
3569           continue;
3570         }
3571
3572       /* Otherwise, try the hook function.  */
3573
3574       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3575         continue;
3576
3577       gdbarch = get_objfile_arch (objfile);
3578
3579       if (bp_objfile_data->exception_msym.minsym == NULL)
3580         {
3581           struct bound_minimal_symbol debug_hook;
3582
3583           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3584           if (debug_hook.minsym == NULL)
3585             {
3586               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3587               continue;
3588             }
3589
3590           bp_objfile_data->exception_msym = debug_hook;
3591         }
3592
3593       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3594       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3595                                                  &current_target);
3596       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3597                                       &internal_breakpoint_ops);
3598       b->addr_string = xstrdup (func_name);
3599       b->enable_state = bp_disabled;
3600     }
3601
3602   update_global_location_list (1);
3603 }
3604
3605 void
3606 update_breakpoints_after_exec (void)
3607 {
3608   struct breakpoint *b, *b_tmp;
3609   struct bp_location *bploc, **bplocp_tmp;
3610
3611   /* We're about to delete breakpoints from GDB's lists.  If the
3612      INSERTED flag is true, GDB will try to lift the breakpoints by
3613      writing the breakpoints' "shadow contents" back into memory.  The
3614      "shadow contents" are NOT valid after an exec, so GDB should not
3615      do that.  Instead, the target is responsible from marking
3616      breakpoints out as soon as it detects an exec.  We don't do that
3617      here instead, because there may be other attempts to delete
3618      breakpoints after detecting an exec and before reaching here.  */
3619   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3620     if (bploc->pspace == current_program_space)
3621       gdb_assert (!bploc->inserted);
3622
3623   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3624   {
3625     if (b->pspace != current_program_space)
3626       continue;
3627
3628     /* Solib breakpoints must be explicitly reset after an exec().  */
3629     if (b->type == bp_shlib_event)
3630       {
3631         delete_breakpoint (b);
3632         continue;
3633       }
3634
3635     /* JIT breakpoints must be explicitly reset after an exec().  */
3636     if (b->type == bp_jit_event)
3637       {
3638         delete_breakpoint (b);
3639         continue;
3640       }
3641
3642     /* Thread event breakpoints must be set anew after an exec(),
3643        as must overlay event and longjmp master breakpoints.  */
3644     if (b->type == bp_thread_event || b->type == bp_overlay_event
3645         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3646         || b->type == bp_exception_master)
3647       {
3648         delete_breakpoint (b);
3649         continue;
3650       }
3651
3652     /* Step-resume breakpoints are meaningless after an exec().  */
3653     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3654       {
3655         delete_breakpoint (b);
3656         continue;
3657       }
3658
3659     /* Longjmp and longjmp-resume breakpoints are also meaningless
3660        after an exec.  */
3661     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3662         || b->type == bp_longjmp_call_dummy
3663         || b->type == bp_exception || b->type == bp_exception_resume)
3664       {
3665         delete_breakpoint (b);
3666         continue;
3667       }
3668
3669     if (b->type == bp_catchpoint)
3670       {
3671         /* For now, none of the bp_catchpoint breakpoints need to
3672            do anything at this point.  In the future, if some of
3673            the catchpoints need to something, we will need to add
3674            a new method, and call this method from here.  */
3675         continue;
3676       }
3677
3678     /* bp_finish is a special case.  The only way we ought to be able
3679        to see one of these when an exec() has happened, is if the user
3680        caught a vfork, and then said "finish".  Ordinarily a finish just
3681        carries them to the call-site of the current callee, by setting
3682        a temporary bp there and resuming.  But in this case, the finish
3683        will carry them entirely through the vfork & exec.
3684
3685        We don't want to allow a bp_finish to remain inserted now.  But
3686        we can't safely delete it, 'cause finish_command has a handle to
3687        the bp on a bpstat, and will later want to delete it.  There's a
3688        chance (and I've seen it happen) that if we delete the bp_finish
3689        here, that its storage will get reused by the time finish_command
3690        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3691        We really must allow finish_command to delete a bp_finish.
3692
3693        In the absence of a general solution for the "how do we know
3694        it's safe to delete something others may have handles to?"
3695        problem, what we'll do here is just uninsert the bp_finish, and
3696        let finish_command delete it.
3697
3698        (We know the bp_finish is "doomed" in the sense that it's
3699        momentary, and will be deleted as soon as finish_command sees
3700        the inferior stopped.  So it doesn't matter that the bp's
3701        address is probably bogus in the new a.out, unlike e.g., the
3702        solib breakpoints.)  */
3703
3704     if (b->type == bp_finish)
3705       {
3706         continue;
3707       }
3708
3709     /* Without a symbolic address, we have little hope of the
3710        pre-exec() address meaning the same thing in the post-exec()
3711        a.out.  */
3712     if (b->addr_string == NULL)
3713       {
3714         delete_breakpoint (b);
3715         continue;
3716       }
3717   }
3718   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3719   create_overlay_event_breakpoint ();
3720   create_longjmp_master_breakpoint ();
3721   create_std_terminate_master_breakpoint ();
3722   create_exception_master_breakpoint ();
3723 }
3724
3725 int
3726 detach_breakpoints (ptid_t ptid)
3727 {
3728   struct bp_location *bl, **blp_tmp;
3729   int val = 0;
3730   struct cleanup *old_chain = save_inferior_ptid ();
3731   struct inferior *inf = current_inferior ();
3732
3733   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3734     error (_("Cannot detach breakpoints of inferior_ptid"));
3735
3736   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3737   inferior_ptid = ptid;
3738   ALL_BP_LOCATIONS (bl, blp_tmp)
3739   {
3740     if (bl->pspace != inf->pspace)
3741       continue;
3742
3743     /* This function must physically remove breakpoints locations
3744        from the specified ptid, without modifying the breakpoint
3745        package's state.  Locations of type bp_loc_other are only
3746        maintained at GDB side.  So, there is no need to remove
3747        these bp_loc_other locations.  Moreover, removing these
3748        would modify the breakpoint package's state.  */
3749     if (bl->loc_type == bp_loc_other)
3750       continue;
3751
3752     if (bl->inserted)
3753       val |= remove_breakpoint_1 (bl, mark_inserted);
3754   }
3755
3756   /* Detach single-step breakpoints as well.  */
3757   detach_single_step_breakpoints ();
3758
3759   do_cleanups (old_chain);
3760   return val;
3761 }
3762
3763 /* Remove the breakpoint location BL from the current address space.
3764    Note that this is used to detach breakpoints from a child fork.
3765    When we get here, the child isn't in the inferior list, and neither
3766    do we have objects to represent its address space --- we should
3767    *not* look at bl->pspace->aspace here.  */
3768
3769 static int
3770 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3771 {
3772   int val;
3773
3774   /* BL is never in moribund_locations by our callers.  */
3775   gdb_assert (bl->owner != NULL);
3776
3777   if (bl->owner->enable_state == bp_permanent)
3778     /* Permanent breakpoints cannot be inserted or removed.  */
3779     return 0;
3780
3781   /* The type of none suggests that owner is actually deleted.
3782      This should not ever happen.  */
3783   gdb_assert (bl->owner->type != bp_none);
3784
3785   if (bl->loc_type == bp_loc_software_breakpoint
3786       || bl->loc_type == bp_loc_hardware_breakpoint)
3787     {
3788       /* "Normal" instruction breakpoint: either the standard
3789          trap-instruction bp (bp_breakpoint), or a
3790          bp_hardware_breakpoint.  */
3791
3792       /* First check to see if we have to handle an overlay.  */
3793       if (overlay_debugging == ovly_off
3794           || bl->section == NULL
3795           || !(section_is_overlay (bl->section)))
3796         {
3797           /* No overlay handling: just remove the breakpoint.  */
3798
3799           /* If we're trying to uninsert a memory breakpoint that we
3800              know is set in a dynamic object that is marked
3801              shlib_disabled, then either the dynamic object was
3802              removed with "remove-symbol-file" or with
3803              "nosharedlibrary".  In the former case, we don't know
3804              whether another dynamic object might have loaded over the
3805              breakpoint's address -- the user might well let us know
3806              about it next with add-symbol-file (the whole point of
3807              add-symbol-file is letting the user manually maintain a
3808              list of dynamically loaded objects).  If we have the
3809              breakpoint's shadow memory, that is, this is a software
3810              breakpoint managed by GDB, check whether the breakpoint
3811              is still inserted in memory, to avoid overwriting wrong
3812              code with stale saved shadow contents.  Note that HW
3813              breakpoints don't have shadow memory, as they're
3814              implemented using a mechanism that is not dependent on
3815              being able to modify the target's memory, and as such
3816              they should always be removed.  */
3817           if (bl->shlib_disabled
3818               && bl->target_info.shadow_len != 0
3819               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3820             val = 0;
3821           else
3822             val = bl->owner->ops->remove_location (bl);
3823         }
3824       else
3825         {
3826           /* This breakpoint is in an overlay section.
3827              Did we set a breakpoint at the LMA?  */
3828           if (!overlay_events_enabled)
3829               {
3830                 /* Yes -- overlay event support is not active, so we
3831                    should have set a breakpoint at the LMA.  Remove it.  
3832                 */
3833                 /* Ignore any failures: if the LMA is in ROM, we will
3834                    have already warned when we failed to insert it.  */
3835                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3836                   target_remove_hw_breakpoint (bl->gdbarch,
3837                                                &bl->overlay_target_info);
3838                 else
3839                   target_remove_breakpoint (bl->gdbarch,
3840                                             &bl->overlay_target_info);
3841               }
3842           /* Did we set a breakpoint at the VMA? 
3843              If so, we will have marked the breakpoint 'inserted'.  */
3844           if (bl->inserted)
3845             {
3846               /* Yes -- remove it.  Previously we did not bother to
3847                  remove the breakpoint if the section had been
3848                  unmapped, but let's not rely on that being safe.  We
3849                  don't know what the overlay manager might do.  */
3850
3851               /* However, we should remove *software* breakpoints only
3852                  if the section is still mapped, or else we overwrite
3853                  wrong code with the saved shadow contents.  */
3854               if (bl->loc_type == bp_loc_hardware_breakpoint
3855                   || section_is_mapped (bl->section))
3856                 val = bl->owner->ops->remove_location (bl);
3857               else
3858                 val = 0;
3859             }
3860           else
3861             {
3862               /* No -- not inserted, so no need to remove.  No error.  */
3863               val = 0;
3864             }
3865         }
3866
3867       /* In some cases, we might not be able to remove a breakpoint in
3868          a shared library that has already been removed, but we have
3869          not yet processed the shlib unload event.  Similarly for an
3870          unloaded add-symbol-file object - the user might not yet have
3871          had the chance to remove-symbol-file it.  shlib_disabled will
3872          be set if the library/object has already been removed, but
3873          the breakpoint hasn't been uninserted yet, e.g., after
3874          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3875          always-inserted mode.  */
3876       if (val
3877           && (bl->loc_type == bp_loc_software_breakpoint
3878               && (bl->shlib_disabled
3879                   || solib_name_from_address (bl->pspace, bl->address)
3880                   || shared_objfile_contains_address_p (bl->pspace,
3881                                                         bl->address))))
3882         val = 0;
3883
3884       if (val)
3885         return val;
3886       bl->inserted = (is == mark_inserted);
3887     }
3888   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3889     {
3890       gdb_assert (bl->owner->ops != NULL
3891                   && bl->owner->ops->remove_location != NULL);
3892
3893       bl->inserted = (is == mark_inserted);
3894       bl->owner->ops->remove_location (bl);
3895
3896       /* Failure to remove any of the hardware watchpoints comes here.  */
3897       if ((is == mark_uninserted) && (bl->inserted))
3898         warning (_("Could not remove hardware watchpoint %d."),
3899                  bl->owner->number);
3900     }
3901   else if (bl->owner->type == bp_catchpoint
3902            && breakpoint_enabled (bl->owner)
3903            && !bl->duplicate)
3904     {
3905       gdb_assert (bl->owner->ops != NULL
3906                   && bl->owner->ops->remove_location != NULL);
3907
3908       val = bl->owner->ops->remove_location (bl);
3909       if (val)
3910         return val;
3911
3912       bl->inserted = (is == mark_inserted);
3913     }
3914
3915   return 0;
3916 }
3917
3918 static int
3919 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3920 {
3921   int ret;
3922   struct cleanup *old_chain;
3923
3924   /* BL is never in moribund_locations by our callers.  */
3925   gdb_assert (bl->owner != NULL);
3926
3927   if (bl->owner->enable_state == bp_permanent)
3928     /* Permanent breakpoints cannot be inserted or removed.  */
3929     return 0;
3930
3931   /* The type of none suggests that owner is actually deleted.
3932      This should not ever happen.  */
3933   gdb_assert (bl->owner->type != bp_none);
3934
3935   old_chain = save_current_space_and_thread ();
3936
3937   switch_to_program_space_and_thread (bl->pspace);
3938
3939   ret = remove_breakpoint_1 (bl, is);
3940
3941   do_cleanups (old_chain);
3942   return ret;
3943 }
3944
3945 /* Clear the "inserted" flag in all breakpoints.  */
3946
3947 void
3948 mark_breakpoints_out (void)
3949 {
3950   struct bp_location *bl, **blp_tmp;
3951
3952   ALL_BP_LOCATIONS (bl, blp_tmp)
3953     if (bl->pspace == current_program_space)
3954       bl->inserted = 0;
3955 }
3956
3957 /* Clear the "inserted" flag in all breakpoints and delete any
3958    breakpoints which should go away between runs of the program.
3959
3960    Plus other such housekeeping that has to be done for breakpoints
3961    between runs.
3962
3963    Note: this function gets called at the end of a run (by
3964    generic_mourn_inferior) and when a run begins (by
3965    init_wait_for_inferior).  */
3966
3967
3968
3969 void
3970 breakpoint_init_inferior (enum inf_context context)
3971 {
3972   struct breakpoint *b, *b_tmp;
3973   struct bp_location *bl, **blp_tmp;
3974   int ix;
3975   struct program_space *pspace = current_program_space;
3976
3977   /* If breakpoint locations are shared across processes, then there's
3978      nothing to do.  */
3979   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3980     return;
3981
3982   ALL_BP_LOCATIONS (bl, blp_tmp)
3983   {
3984     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3985     if (bl->pspace == pspace
3986         && bl->owner->enable_state != bp_permanent)
3987       bl->inserted = 0;
3988   }
3989
3990   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3991   {
3992     if (b->loc && b->loc->pspace != pspace)
3993       continue;
3994
3995     switch (b->type)
3996       {
3997       case bp_call_dummy:
3998       case bp_longjmp_call_dummy:
3999
4000         /* If the call dummy breakpoint is at the entry point it will
4001            cause problems when the inferior is rerun, so we better get
4002            rid of it.  */
4003
4004       case bp_watchpoint_scope:
4005
4006         /* Also get rid of scope breakpoints.  */
4007
4008       case bp_shlib_event:
4009
4010         /* Also remove solib event breakpoints.  Their addresses may
4011            have changed since the last time we ran the program.
4012            Actually we may now be debugging against different target;
4013            and so the solib backend that installed this breakpoint may
4014            not be used in by the target.  E.g.,
4015
4016            (gdb) file prog-linux
4017            (gdb) run               # native linux target
4018            ...
4019            (gdb) kill
4020            (gdb) file prog-win.exe
4021            (gdb) tar rem :9999     # remote Windows gdbserver.
4022         */
4023
4024       case bp_step_resume:
4025
4026         /* Also remove step-resume breakpoints.  */
4027
4028         delete_breakpoint (b);
4029         break;
4030
4031       case bp_watchpoint:
4032       case bp_hardware_watchpoint:
4033       case bp_read_watchpoint:
4034       case bp_access_watchpoint:
4035         {
4036           struct watchpoint *w = (struct watchpoint *) b;
4037
4038           /* Likewise for watchpoints on local expressions.  */
4039           if (w->exp_valid_block != NULL)
4040             delete_breakpoint (b);
4041           else if (context == inf_starting)
4042             {
4043               /* Reset val field to force reread of starting value in
4044                  insert_breakpoints.  */
4045               if (w->val)
4046                 value_free (w->val);
4047               w->val = NULL;
4048               w->val_valid = 0;
4049           }
4050         }
4051         break;
4052       default:
4053         break;
4054       }
4055   }
4056
4057   /* Get rid of the moribund locations.  */
4058   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4059     decref_bp_location (&bl);
4060   VEC_free (bp_location_p, moribund_locations);
4061 }
4062
4063 /* These functions concern about actual breakpoints inserted in the
4064    target --- to e.g. check if we need to do decr_pc adjustment or if
4065    we need to hop over the bkpt --- so we check for address space
4066    match, not program space.  */
4067
4068 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4069    exists at PC.  It returns ordinary_breakpoint_here if it's an
4070    ordinary breakpoint, or permanent_breakpoint_here if it's a
4071    permanent breakpoint.
4072    - When continuing from a location with an ordinary breakpoint, we
4073      actually single step once before calling insert_breakpoints.
4074    - When continuing from a location with a permanent breakpoint, we
4075      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4076      the target, to advance the PC past the breakpoint.  */
4077
4078 enum breakpoint_here
4079 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4080 {
4081   struct bp_location *bl, **blp_tmp;
4082   int any_breakpoint_here = 0;
4083
4084   ALL_BP_LOCATIONS (bl, blp_tmp)
4085     {
4086       if (bl->loc_type != bp_loc_software_breakpoint
4087           && bl->loc_type != bp_loc_hardware_breakpoint)
4088         continue;
4089
4090       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4091       if ((breakpoint_enabled (bl->owner)
4092            || bl->owner->enable_state == bp_permanent)
4093           && breakpoint_location_address_match (bl, aspace, pc))
4094         {
4095           if (overlay_debugging 
4096               && section_is_overlay (bl->section)
4097               && !section_is_mapped (bl->section))
4098             continue;           /* unmapped overlay -- can't be a match */
4099           else if (bl->owner->enable_state == bp_permanent)
4100             return permanent_breakpoint_here;
4101           else
4102             any_breakpoint_here = 1;
4103         }
4104     }
4105
4106   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4107 }
4108
4109 /* Return true if there's a moribund breakpoint at PC.  */
4110
4111 int
4112 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4113 {
4114   struct bp_location *loc;
4115   int ix;
4116
4117   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4118     if (breakpoint_location_address_match (loc, aspace, pc))
4119       return 1;
4120
4121   return 0;
4122 }
4123
4124 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4125    inserted using regular breakpoint_chain / bp_location array
4126    mechanism.  This does not check for single-step breakpoints, which
4127    are inserted and removed using direct target manipulation.  */
4128
4129 int
4130 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4131                                     CORE_ADDR pc)
4132 {
4133   struct bp_location *bl, **blp_tmp;
4134
4135   ALL_BP_LOCATIONS (bl, blp_tmp)
4136     {
4137       if (bl->loc_type != bp_loc_software_breakpoint
4138           && bl->loc_type != bp_loc_hardware_breakpoint)
4139         continue;
4140
4141       if (bl->inserted
4142           && breakpoint_location_address_match (bl, aspace, pc))
4143         {
4144           if (overlay_debugging 
4145               && section_is_overlay (bl->section)
4146               && !section_is_mapped (bl->section))
4147             continue;           /* unmapped overlay -- can't be a match */
4148           else
4149             return 1;
4150         }
4151     }
4152   return 0;
4153 }
4154
4155 /* Returns non-zero iff there's either regular breakpoint
4156    or a single step breakpoint inserted at PC.  */
4157
4158 int
4159 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4160 {
4161   if (regular_breakpoint_inserted_here_p (aspace, pc))
4162     return 1;
4163
4164   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4165     return 1;
4166
4167   return 0;
4168 }
4169
4170 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4171    software breakpoint inserted at PC.  */
4172
4173 static struct bp_location *
4174 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4175                                                 CORE_ADDR pc)
4176 {
4177   struct bp_location *bl, **blp_tmp;
4178
4179   ALL_BP_LOCATIONS (bl, blp_tmp)
4180     {
4181       if (bl->loc_type != bp_loc_software_breakpoint)
4182         continue;
4183
4184       if (bl->inserted
4185           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4186                                        aspace, pc))
4187         {
4188           if (overlay_debugging 
4189               && section_is_overlay (bl->section)
4190               && !section_is_mapped (bl->section))
4191             continue;           /* unmapped overlay -- can't be a match */
4192           else
4193             return bl;
4194         }
4195     }
4196
4197   return NULL;
4198 }
4199
4200 /* This function returns non-zero iff there is a software breakpoint
4201    inserted at PC.  */
4202
4203 int
4204 software_breakpoint_inserted_here_p (struct address_space *aspace,
4205                                      CORE_ADDR pc)
4206 {
4207   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4208     return 1;
4209
4210   /* Also check for software single-step breakpoints.  */
4211   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4212     return 1;
4213
4214   return 0;
4215 }
4216
4217 int
4218 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4219                                        CORE_ADDR addr, ULONGEST len)
4220 {
4221   struct breakpoint *bpt;
4222
4223   ALL_BREAKPOINTS (bpt)
4224     {
4225       struct bp_location *loc;
4226
4227       if (bpt->type != bp_hardware_watchpoint
4228           && bpt->type != bp_access_watchpoint)
4229         continue;
4230
4231       if (!breakpoint_enabled (bpt))
4232         continue;
4233
4234       for (loc = bpt->loc; loc; loc = loc->next)
4235         if (loc->pspace->aspace == aspace && loc->inserted)
4236           {
4237             CORE_ADDR l, h;
4238
4239             /* Check for intersection.  */
4240             l = max (loc->address, addr);
4241             h = min (loc->address + loc->length, addr + len);
4242             if (l < h)
4243               return 1;
4244           }
4245     }
4246   return 0;
4247 }
4248
4249 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4250    PC is valid for process/thread PTID.  */
4251
4252 int
4253 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4254                          ptid_t ptid)
4255 {
4256   struct bp_location *bl, **blp_tmp;
4257   /* The thread and task IDs associated to PTID, computed lazily.  */
4258   int thread = -1;
4259   int task = 0;
4260   
4261   ALL_BP_LOCATIONS (bl, blp_tmp)
4262     {
4263       if (bl->loc_type != bp_loc_software_breakpoint
4264           && bl->loc_type != bp_loc_hardware_breakpoint)
4265         continue;
4266
4267       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4268       if (!breakpoint_enabled (bl->owner)
4269           && bl->owner->enable_state != bp_permanent)
4270         continue;
4271
4272       if (!breakpoint_location_address_match (bl, aspace, pc))
4273         continue;
4274
4275       if (bl->owner->thread != -1)
4276         {
4277           /* This is a thread-specific breakpoint.  Check that ptid
4278              matches that thread.  If thread hasn't been computed yet,
4279              it is now time to do so.  */
4280           if (thread == -1)
4281             thread = pid_to_thread_id (ptid);
4282           if (bl->owner->thread != thread)
4283             continue;
4284         }
4285
4286       if (bl->owner->task != 0)
4287         {
4288           /* This is a task-specific breakpoint.  Check that ptid
4289              matches that task.  If task hasn't been computed yet,
4290              it is now time to do so.  */
4291           if (task == 0)
4292             task = ada_get_task_number (ptid);
4293           if (bl->owner->task != task)
4294             continue;
4295         }
4296
4297       if (overlay_debugging 
4298           && section_is_overlay (bl->section)
4299           && !section_is_mapped (bl->section))
4300         continue;           /* unmapped overlay -- can't be a match */
4301
4302       return 1;
4303     }
4304
4305   return 0;
4306 }
4307 \f
4308
4309 /* bpstat stuff.  External routines' interfaces are documented
4310    in breakpoint.h.  */
4311
4312 int
4313 is_catchpoint (struct breakpoint *ep)
4314 {
4315   return (ep->type == bp_catchpoint);
4316 }
4317
4318 /* Frees any storage that is part of a bpstat.  Does not walk the
4319    'next' chain.  */
4320
4321 static void
4322 bpstat_free (bpstat bs)
4323 {
4324   if (bs->old_val != NULL)
4325     value_free (bs->old_val);
4326   decref_counted_command_line (&bs->commands);
4327   decref_bp_location (&bs->bp_location_at);
4328   xfree (bs);
4329 }
4330
4331 /* Clear a bpstat so that it says we are not at any breakpoint.
4332    Also free any storage that is part of a bpstat.  */
4333
4334 void
4335 bpstat_clear (bpstat *bsp)
4336 {
4337   bpstat p;
4338   bpstat q;
4339
4340   if (bsp == 0)
4341     return;
4342   p = *bsp;
4343   while (p != NULL)
4344     {
4345       q = p->next;
4346       bpstat_free (p);
4347       p = q;
4348     }
4349   *bsp = NULL;
4350 }
4351
4352 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4353    is part of the bpstat is copied as well.  */
4354
4355 bpstat
4356 bpstat_copy (bpstat bs)
4357 {
4358   bpstat p = NULL;
4359   bpstat tmp;
4360   bpstat retval = NULL;
4361
4362   if (bs == NULL)
4363     return bs;
4364
4365   for (; bs != NULL; bs = bs->next)
4366     {
4367       tmp = (bpstat) xmalloc (sizeof (*tmp));
4368       memcpy (tmp, bs, sizeof (*tmp));
4369       incref_counted_command_line (tmp->commands);
4370       incref_bp_location (tmp->bp_location_at);
4371       if (bs->old_val != NULL)
4372         {
4373           tmp->old_val = value_copy (bs->old_val);
4374           release_value (tmp->old_val);
4375         }
4376
4377       if (p == NULL)
4378         /* This is the first thing in the chain.  */
4379         retval = tmp;
4380       else
4381         p->next = tmp;
4382       p = tmp;
4383     }
4384   p->next = NULL;
4385   return retval;
4386 }
4387
4388 /* Find the bpstat associated with this breakpoint.  */
4389
4390 bpstat
4391 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4392 {
4393   if (bsp == NULL)
4394     return NULL;
4395
4396   for (; bsp != NULL; bsp = bsp->next)
4397     {
4398       if (bsp->breakpoint_at == breakpoint)
4399         return bsp;
4400     }
4401   return NULL;
4402 }
4403
4404 /* See breakpoint.h.  */
4405
4406 int
4407 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4408 {
4409   for (; bsp != NULL; bsp = bsp->next)
4410     {
4411       if (bsp->breakpoint_at == NULL)
4412         {
4413           /* A moribund location can never explain a signal other than
4414              GDB_SIGNAL_TRAP.  */
4415           if (sig == GDB_SIGNAL_TRAP)
4416             return 1;
4417         }
4418       else
4419         {
4420           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4421                                                         sig))
4422             return 1;
4423         }
4424     }
4425
4426   return 0;
4427 }
4428
4429 /* Put in *NUM the breakpoint number of the first breakpoint we are
4430    stopped at.  *BSP upon return is a bpstat which points to the
4431    remaining breakpoints stopped at (but which is not guaranteed to be
4432    good for anything but further calls to bpstat_num).
4433
4434    Return 0 if passed a bpstat which does not indicate any breakpoints.
4435    Return -1 if stopped at a breakpoint that has been deleted since
4436    we set it.
4437    Return 1 otherwise.  */
4438
4439 int
4440 bpstat_num (bpstat *bsp, int *num)
4441 {
4442   struct breakpoint *b;
4443
4444   if ((*bsp) == NULL)
4445     return 0;                   /* No more breakpoint values */
4446
4447   /* We assume we'll never have several bpstats that correspond to a
4448      single breakpoint -- otherwise, this function might return the
4449      same number more than once and this will look ugly.  */
4450   b = (*bsp)->breakpoint_at;
4451   *bsp = (*bsp)->next;
4452   if (b == NULL)
4453     return -1;                  /* breakpoint that's been deleted since */
4454
4455   *num = b->number;             /* We have its number */
4456   return 1;
4457 }
4458
4459 /* See breakpoint.h.  */
4460
4461 void
4462 bpstat_clear_actions (void)
4463 {
4464   struct thread_info *tp;
4465   bpstat bs;
4466
4467   if (ptid_equal (inferior_ptid, null_ptid))
4468     return;
4469
4470   tp = find_thread_ptid (inferior_ptid);
4471   if (tp == NULL)
4472     return;
4473
4474   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4475     {
4476       decref_counted_command_line (&bs->commands);
4477
4478       if (bs->old_val != NULL)
4479         {
4480           value_free (bs->old_val);
4481           bs->old_val = NULL;
4482         }
4483     }
4484 }
4485
4486 /* Called when a command is about to proceed the inferior.  */
4487
4488 static void
4489 breakpoint_about_to_proceed (void)
4490 {
4491   if (!ptid_equal (inferior_ptid, null_ptid))
4492     {
4493       struct thread_info *tp = inferior_thread ();
4494
4495       /* Allow inferior function calls in breakpoint commands to not
4496          interrupt the command list.  When the call finishes
4497          successfully, the inferior will be standing at the same
4498          breakpoint as if nothing happened.  */
4499       if (tp->control.in_infcall)
4500         return;
4501     }
4502
4503   breakpoint_proceeded = 1;
4504 }
4505
4506 /* Stub for cleaning up our state if we error-out of a breakpoint
4507    command.  */
4508 static void
4509 cleanup_executing_breakpoints (void *ignore)
4510 {
4511   executing_breakpoint_commands = 0;
4512 }
4513
4514 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4515    or its equivalent.  */
4516
4517 static int
4518 command_line_is_silent (struct command_line *cmd)
4519 {
4520   return cmd && (strcmp ("silent", cmd->line) == 0
4521                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4522 }
4523
4524 /* Execute all the commands associated with all the breakpoints at
4525    this location.  Any of these commands could cause the process to
4526    proceed beyond this point, etc.  We look out for such changes by
4527    checking the global "breakpoint_proceeded" after each command.
4528
4529    Returns true if a breakpoint command resumed the inferior.  In that
4530    case, it is the caller's responsibility to recall it again with the
4531    bpstat of the current thread.  */
4532
4533 static int
4534 bpstat_do_actions_1 (bpstat *bsp)
4535 {
4536   bpstat bs;
4537   struct cleanup *old_chain;
4538   int again = 0;
4539
4540   /* Avoid endless recursion if a `source' command is contained
4541      in bs->commands.  */
4542   if (executing_breakpoint_commands)
4543     return 0;
4544
4545   executing_breakpoint_commands = 1;
4546   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4547
4548   prevent_dont_repeat ();
4549
4550   /* This pointer will iterate over the list of bpstat's.  */
4551   bs = *bsp;
4552
4553   breakpoint_proceeded = 0;
4554   for (; bs != NULL; bs = bs->next)
4555     {
4556       struct counted_command_line *ccmd;
4557       struct command_line *cmd;
4558       struct cleanup *this_cmd_tree_chain;
4559
4560       /* Take ownership of the BSP's command tree, if it has one.
4561
4562          The command tree could legitimately contain commands like
4563          'step' and 'next', which call clear_proceed_status, which
4564          frees stop_bpstat's command tree.  To make sure this doesn't
4565          free the tree we're executing out from under us, we need to
4566          take ownership of the tree ourselves.  Since a given bpstat's
4567          commands are only executed once, we don't need to copy it; we
4568          can clear the pointer in the bpstat, and make sure we free
4569          the tree when we're done.  */
4570       ccmd = bs->commands;
4571       bs->commands = NULL;
4572       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4573       cmd = ccmd ? ccmd->commands : NULL;
4574       if (command_line_is_silent (cmd))
4575         {
4576           /* The action has been already done by bpstat_stop_status.  */
4577           cmd = cmd->next;
4578         }
4579
4580       while (cmd != NULL)
4581         {
4582           execute_control_command (cmd);
4583
4584           if (breakpoint_proceeded)
4585             break;
4586           else
4587             cmd = cmd->next;
4588         }
4589
4590       /* We can free this command tree now.  */
4591       do_cleanups (this_cmd_tree_chain);
4592
4593       if (breakpoint_proceeded)
4594         {
4595           if (target_can_async_p ())
4596             /* If we are in async mode, then the target might be still
4597                running, not stopped at any breakpoint, so nothing for
4598                us to do here -- just return to the event loop.  */
4599             ;
4600           else
4601             /* In sync mode, when execute_control_command returns
4602                we're already standing on the next breakpoint.
4603                Breakpoint commands for that stop were not run, since
4604                execute_command does not run breakpoint commands --
4605                only command_line_handler does, but that one is not
4606                involved in execution of breakpoint commands.  So, we
4607                can now execute breakpoint commands.  It should be
4608                noted that making execute_command do bpstat actions is
4609                not an option -- in this case we'll have recursive
4610                invocation of bpstat for each breakpoint with a
4611                command, and can easily blow up GDB stack.  Instead, we
4612                return true, which will trigger the caller to recall us
4613                with the new stop_bpstat.  */
4614             again = 1;
4615           break;
4616         }
4617     }
4618   do_cleanups (old_chain);
4619   return again;
4620 }
4621
4622 void
4623 bpstat_do_actions (void)
4624 {
4625   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4626
4627   /* Do any commands attached to breakpoint we are stopped at.  */
4628   while (!ptid_equal (inferior_ptid, null_ptid)
4629          && target_has_execution
4630          && !is_exited (inferior_ptid)
4631          && !is_executing (inferior_ptid))
4632     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4633        and only return when it is stopped at the next breakpoint, we
4634        keep doing breakpoint actions until it returns false to
4635        indicate the inferior was not resumed.  */
4636     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4637       break;
4638
4639   discard_cleanups (cleanup_if_error);
4640 }
4641
4642 /* Print out the (old or new) value associated with a watchpoint.  */
4643
4644 static void
4645 watchpoint_value_print (struct value *val, struct ui_file *stream)
4646 {
4647   if (val == NULL)
4648     fprintf_unfiltered (stream, _("<unreadable>"));
4649   else
4650     {
4651       struct value_print_options opts;
4652       get_user_print_options (&opts);
4653       value_print (val, stream, &opts);
4654     }
4655 }
4656
4657 /* Generic routine for printing messages indicating why we
4658    stopped.  The behavior of this function depends on the value
4659    'print_it' in the bpstat structure.  Under some circumstances we
4660    may decide not to print anything here and delegate the task to
4661    normal_stop().  */
4662
4663 static enum print_stop_action
4664 print_bp_stop_message (bpstat bs)
4665 {
4666   switch (bs->print_it)
4667     {
4668     case print_it_noop:
4669       /* Nothing should be printed for this bpstat entry.  */
4670       return PRINT_UNKNOWN;
4671       break;
4672
4673     case print_it_done:
4674       /* We still want to print the frame, but we already printed the
4675          relevant messages.  */
4676       return PRINT_SRC_AND_LOC;
4677       break;
4678
4679     case print_it_normal:
4680       {
4681         struct breakpoint *b = bs->breakpoint_at;
4682
4683         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4684            which has since been deleted.  */
4685         if (b == NULL)
4686           return PRINT_UNKNOWN;
4687
4688         /* Normal case.  Call the breakpoint's print_it method.  */
4689         return b->ops->print_it (bs);
4690       }
4691       break;
4692
4693     default:
4694       internal_error (__FILE__, __LINE__,
4695                       _("print_bp_stop_message: unrecognized enum value"));
4696       break;
4697     }
4698 }
4699
4700 /* A helper function that prints a shared library stopped event.  */
4701
4702 static void
4703 print_solib_event (int is_catchpoint)
4704 {
4705   int any_deleted
4706     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4707   int any_added
4708     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4709
4710   if (!is_catchpoint)
4711     {
4712       if (any_added || any_deleted)
4713         ui_out_text (current_uiout,
4714                      _("Stopped due to shared library event:\n"));
4715       else
4716         ui_out_text (current_uiout,
4717                      _("Stopped due to shared library event (no "
4718                        "libraries added or removed)\n"));
4719     }
4720
4721   if (ui_out_is_mi_like_p (current_uiout))
4722     ui_out_field_string (current_uiout, "reason",
4723                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4724
4725   if (any_deleted)
4726     {
4727       struct cleanup *cleanup;
4728       char *name;
4729       int ix;
4730
4731       ui_out_text (current_uiout, _("  Inferior unloaded "));
4732       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4733                                                     "removed");
4734       for (ix = 0;
4735            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4736                         ix, name);
4737            ++ix)
4738         {
4739           if (ix > 0)
4740             ui_out_text (current_uiout, "    ");
4741           ui_out_field_string (current_uiout, "library", name);
4742           ui_out_text (current_uiout, "\n");
4743         }
4744
4745       do_cleanups (cleanup);
4746     }
4747
4748   if (any_added)
4749     {
4750       struct so_list *iter;
4751       int ix;
4752       struct cleanup *cleanup;
4753
4754       ui_out_text (current_uiout, _("  Inferior loaded "));
4755       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4756                                                     "added");
4757       for (ix = 0;
4758            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4759                         ix, iter);
4760            ++ix)
4761         {
4762           if (ix > 0)
4763             ui_out_text (current_uiout, "    ");
4764           ui_out_field_string (current_uiout, "library", iter->so_name);
4765           ui_out_text (current_uiout, "\n");
4766         }
4767
4768       do_cleanups (cleanup);
4769     }
4770 }
4771
4772 /* Print a message indicating what happened.  This is called from
4773    normal_stop().  The input to this routine is the head of the bpstat
4774    list - a list of the eventpoints that caused this stop.  KIND is
4775    the target_waitkind for the stopping event.  This
4776    routine calls the generic print routine for printing a message
4777    about reasons for stopping.  This will print (for example) the
4778    "Breakpoint n," part of the output.  The return value of this
4779    routine is one of:
4780
4781    PRINT_UNKNOWN: Means we printed nothing.
4782    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4783    code to print the location.  An example is 
4784    "Breakpoint 1, " which should be followed by
4785    the location.
4786    PRINT_SRC_ONLY: Means we printed something, but there is no need
4787    to also print the location part of the message.
4788    An example is the catch/throw messages, which
4789    don't require a location appended to the end.
4790    PRINT_NOTHING: We have done some printing and we don't need any 
4791    further info to be printed.  */
4792
4793 enum print_stop_action
4794 bpstat_print (bpstat bs, int kind)
4795 {
4796   int val;
4797
4798   /* Maybe another breakpoint in the chain caused us to stop.
4799      (Currently all watchpoints go on the bpstat whether hit or not.
4800      That probably could (should) be changed, provided care is taken
4801      with respect to bpstat_explains_signal).  */
4802   for (; bs; bs = bs->next)
4803     {
4804       val = print_bp_stop_message (bs);
4805       if (val == PRINT_SRC_ONLY 
4806           || val == PRINT_SRC_AND_LOC 
4807           || val == PRINT_NOTHING)
4808         return val;
4809     }
4810
4811   /* If we had hit a shared library event breakpoint,
4812      print_bp_stop_message would print out this message.  If we hit an
4813      OS-level shared library event, do the same thing.  */
4814   if (kind == TARGET_WAITKIND_LOADED)
4815     {
4816       print_solib_event (0);
4817       return PRINT_NOTHING;
4818     }
4819
4820   /* We reached the end of the chain, or we got a null BS to start
4821      with and nothing was printed.  */
4822   return PRINT_UNKNOWN;
4823 }
4824
4825 /* Evaluate the expression EXP and return 1 if value is zero.
4826    This returns the inverse of the condition because it is called
4827    from catch_errors which returns 0 if an exception happened, and if an
4828    exception happens we want execution to stop.
4829    The argument is a "struct expression *" that has been cast to a
4830    "void *" to make it pass through catch_errors.  */
4831
4832 static int
4833 breakpoint_cond_eval (void *exp)
4834 {
4835   struct value *mark = value_mark ();
4836   int i = !value_true (evaluate_expression ((struct expression *) exp));
4837
4838   value_free_to_mark (mark);
4839   return i;
4840 }
4841
4842 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4843
4844 static bpstat
4845 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4846 {
4847   bpstat bs;
4848
4849   bs = (bpstat) xmalloc (sizeof (*bs));
4850   bs->next = NULL;
4851   **bs_link_pointer = bs;
4852   *bs_link_pointer = &bs->next;
4853   bs->breakpoint_at = bl->owner;
4854   bs->bp_location_at = bl;
4855   incref_bp_location (bl);
4856   /* If the condition is false, etc., don't do the commands.  */
4857   bs->commands = NULL;
4858   bs->old_val = NULL;
4859   bs->print_it = print_it_normal;
4860   return bs;
4861 }
4862 \f
4863 /* The target has stopped with waitstatus WS.  Check if any hardware
4864    watchpoints have triggered, according to the target.  */
4865
4866 int
4867 watchpoints_triggered (struct target_waitstatus *ws)
4868 {
4869   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4870   CORE_ADDR addr;
4871   struct breakpoint *b;
4872
4873   if (!stopped_by_watchpoint)
4874     {
4875       /* We were not stopped by a watchpoint.  Mark all watchpoints
4876          as not triggered.  */
4877       ALL_BREAKPOINTS (b)
4878         if (is_hardware_watchpoint (b))
4879           {
4880             struct watchpoint *w = (struct watchpoint *) b;
4881
4882             w->watchpoint_triggered = watch_triggered_no;
4883           }
4884
4885       return 0;
4886     }
4887
4888   if (!target_stopped_data_address (&current_target, &addr))
4889     {
4890       /* We were stopped by a watchpoint, but we don't know where.
4891          Mark all watchpoints as unknown.  */
4892       ALL_BREAKPOINTS (b)
4893         if (is_hardware_watchpoint (b))
4894           {
4895             struct watchpoint *w = (struct watchpoint *) b;
4896
4897             w->watchpoint_triggered = watch_triggered_unknown;
4898           }
4899
4900       return 1;
4901     }
4902
4903   /* The target could report the data address.  Mark watchpoints
4904      affected by this data address as triggered, and all others as not
4905      triggered.  */
4906
4907   ALL_BREAKPOINTS (b)
4908     if (is_hardware_watchpoint (b))
4909       {
4910         struct watchpoint *w = (struct watchpoint *) b;
4911         struct bp_location *loc;
4912
4913         w->watchpoint_triggered = watch_triggered_no;
4914         for (loc = b->loc; loc; loc = loc->next)
4915           {
4916             if (is_masked_watchpoint (b))
4917               {
4918                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4919                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4920
4921                 if (newaddr == start)
4922                   {
4923                     w->watchpoint_triggered = watch_triggered_yes;
4924                     break;
4925                   }
4926               }
4927             /* Exact match not required.  Within range is sufficient.  */
4928             else if (target_watchpoint_addr_within_range (&current_target,
4929                                                          addr, loc->address,
4930                                                          loc->length))
4931               {
4932                 w->watchpoint_triggered = watch_triggered_yes;
4933                 break;
4934               }
4935           }
4936       }
4937
4938   return 1;
4939 }
4940
4941 /* Possible return values for watchpoint_check (this can't be an enum
4942    because of check_errors).  */
4943 /* The watchpoint has been deleted.  */
4944 #define WP_DELETED 1
4945 /* The value has changed.  */
4946 #define WP_VALUE_CHANGED 2
4947 /* The value has not changed.  */
4948 #define WP_VALUE_NOT_CHANGED 3
4949 /* Ignore this watchpoint, no matter if the value changed or not.  */
4950 #define WP_IGNORE 4
4951
4952 #define BP_TEMPFLAG 1
4953 #define BP_HARDWAREFLAG 2
4954
4955 /* Evaluate watchpoint condition expression and check if its value
4956    changed.
4957
4958    P should be a pointer to struct bpstat, but is defined as a void *
4959    in order for this function to be usable with catch_errors.  */
4960
4961 static int
4962 watchpoint_check (void *p)
4963 {
4964   bpstat bs = (bpstat) p;
4965   struct watchpoint *b;
4966   struct frame_info *fr;
4967   int within_current_scope;
4968
4969   /* BS is built from an existing struct breakpoint.  */
4970   gdb_assert (bs->breakpoint_at != NULL);
4971   b = (struct watchpoint *) bs->breakpoint_at;
4972
4973   /* If this is a local watchpoint, we only want to check if the
4974      watchpoint frame is in scope if the current thread is the thread
4975      that was used to create the watchpoint.  */
4976   if (!watchpoint_in_thread_scope (b))
4977     return WP_IGNORE;
4978
4979   if (b->exp_valid_block == NULL)
4980     within_current_scope = 1;
4981   else
4982     {
4983       struct frame_info *frame = get_current_frame ();
4984       struct gdbarch *frame_arch = get_frame_arch (frame);
4985       CORE_ADDR frame_pc = get_frame_pc (frame);
4986
4987       /* in_function_epilogue_p() returns a non-zero value if we're
4988          still in the function but the stack frame has already been
4989          invalidated.  Since we can't rely on the values of local
4990          variables after the stack has been destroyed, we are treating
4991          the watchpoint in that state as `not changed' without further
4992          checking.  Don't mark watchpoints as changed if the current
4993          frame is in an epilogue - even if they are in some other
4994          frame, our view of the stack is likely to be wrong and
4995          frame_find_by_id could error out.  */
4996       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4997         return WP_IGNORE;
4998
4999       fr = frame_find_by_id (b->watchpoint_frame);
5000       within_current_scope = (fr != NULL);
5001
5002       /* If we've gotten confused in the unwinder, we might have
5003          returned a frame that can't describe this variable.  */
5004       if (within_current_scope)
5005         {
5006           struct symbol *function;
5007
5008           function = get_frame_function (fr);
5009           if (function == NULL
5010               || !contained_in (b->exp_valid_block,
5011                                 SYMBOL_BLOCK_VALUE (function)))
5012             within_current_scope = 0;
5013         }
5014
5015       if (within_current_scope)
5016         /* If we end up stopping, the current frame will get selected
5017            in normal_stop.  So this call to select_frame won't affect
5018            the user.  */
5019         select_frame (fr);
5020     }
5021
5022   if (within_current_scope)
5023     {
5024       /* We use value_{,free_to_}mark because it could be a *long*
5025          time before we return to the command level and call
5026          free_all_values.  We can't call free_all_values because we
5027          might be in the middle of evaluating a function call.  */
5028
5029       int pc = 0;
5030       struct value *mark;
5031       struct value *new_val;
5032
5033       if (is_masked_watchpoint (&b->base))
5034         /* Since we don't know the exact trigger address (from
5035            stopped_data_address), just tell the user we've triggered
5036            a mask watchpoint.  */
5037         return WP_VALUE_CHANGED;
5038
5039       mark = value_mark ();
5040       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5041
5042       /* We use value_equal_contents instead of value_equal because
5043          the latter coerces an array to a pointer, thus comparing just
5044          the address of the array instead of its contents.  This is
5045          not what we want.  */
5046       if ((b->val != NULL) != (new_val != NULL)
5047           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5048         {
5049           if (new_val != NULL)
5050             {
5051               release_value (new_val);
5052               value_free_to_mark (mark);
5053             }
5054           bs->old_val = b->val;
5055           b->val = new_val;
5056           b->val_valid = 1;
5057           return WP_VALUE_CHANGED;
5058         }
5059       else
5060         {
5061           /* Nothing changed.  */
5062           value_free_to_mark (mark);
5063           return WP_VALUE_NOT_CHANGED;
5064         }
5065     }
5066   else
5067     {
5068       struct ui_out *uiout = current_uiout;
5069
5070       /* This seems like the only logical thing to do because
5071          if we temporarily ignored the watchpoint, then when
5072          we reenter the block in which it is valid it contains
5073          garbage (in the case of a function, it may have two
5074          garbage values, one before and one after the prologue).
5075          So we can't even detect the first assignment to it and
5076          watch after that (since the garbage may or may not equal
5077          the first value assigned).  */
5078       /* We print all the stop information in
5079          breakpoint_ops->print_it, but in this case, by the time we
5080          call breakpoint_ops->print_it this bp will be deleted
5081          already.  So we have no choice but print the information
5082          here.  */
5083       if (ui_out_is_mi_like_p (uiout))
5084         ui_out_field_string
5085           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5086       ui_out_text (uiout, "\nWatchpoint ");
5087       ui_out_field_int (uiout, "wpnum", b->base.number);
5088       ui_out_text (uiout,
5089                    " deleted because the program has left the block in\n\
5090 which its expression is valid.\n");     
5091
5092       /* Make sure the watchpoint's commands aren't executed.  */
5093       decref_counted_command_line (&b->base.commands);
5094       watchpoint_del_at_next_stop (b);
5095
5096       return WP_DELETED;
5097     }
5098 }
5099
5100 /* Return true if it looks like target has stopped due to hitting
5101    breakpoint location BL.  This function does not check if we should
5102    stop, only if BL explains the stop.  */
5103
5104 static int
5105 bpstat_check_location (const struct bp_location *bl,
5106                        struct address_space *aspace, CORE_ADDR bp_addr,
5107                        const struct target_waitstatus *ws)
5108 {
5109   struct breakpoint *b = bl->owner;
5110
5111   /* BL is from an existing breakpoint.  */
5112   gdb_assert (b != NULL);
5113
5114   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5115 }
5116
5117 /* Determine if the watched values have actually changed, and we
5118    should stop.  If not, set BS->stop to 0.  */
5119
5120 static void
5121 bpstat_check_watchpoint (bpstat bs)
5122 {
5123   const struct bp_location *bl;
5124   struct watchpoint *b;
5125
5126   /* BS is built for existing struct breakpoint.  */
5127   bl = bs->bp_location_at;
5128   gdb_assert (bl != NULL);
5129   b = (struct watchpoint *) bs->breakpoint_at;
5130   gdb_assert (b != NULL);
5131
5132     {
5133       int must_check_value = 0;
5134       
5135       if (b->base.type == bp_watchpoint)
5136         /* For a software watchpoint, we must always check the
5137            watched value.  */
5138         must_check_value = 1;
5139       else if (b->watchpoint_triggered == watch_triggered_yes)
5140         /* We have a hardware watchpoint (read, write, or access)
5141            and the target earlier reported an address watched by
5142            this watchpoint.  */
5143         must_check_value = 1;
5144       else if (b->watchpoint_triggered == watch_triggered_unknown
5145                && b->base.type == bp_hardware_watchpoint)
5146         /* We were stopped by a hardware watchpoint, but the target could
5147            not report the data address.  We must check the watchpoint's
5148            value.  Access and read watchpoints are out of luck; without
5149            a data address, we can't figure it out.  */
5150         must_check_value = 1;
5151
5152       if (must_check_value)
5153         {
5154           char *message
5155             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5156                           b->base.number);
5157           struct cleanup *cleanups = make_cleanup (xfree, message);
5158           int e = catch_errors (watchpoint_check, bs, message,
5159                                 RETURN_MASK_ALL);
5160           do_cleanups (cleanups);
5161           switch (e)
5162             {
5163             case WP_DELETED:
5164               /* We've already printed what needs to be printed.  */
5165               bs->print_it = print_it_done;
5166               /* Stop.  */
5167               break;
5168             case WP_IGNORE:
5169               bs->print_it = print_it_noop;
5170               bs->stop = 0;
5171               break;
5172             case WP_VALUE_CHANGED:
5173               if (b->base.type == bp_read_watchpoint)
5174                 {
5175                   /* There are two cases to consider here:
5176
5177                      1. We're watching the triggered memory for reads.
5178                      In that case, trust the target, and always report
5179                      the watchpoint hit to the user.  Even though
5180                      reads don't cause value changes, the value may
5181                      have changed since the last time it was read, and
5182                      since we're not trapping writes, we will not see
5183                      those, and as such we should ignore our notion of
5184                      old value.
5185
5186                      2. We're watching the triggered memory for both
5187                      reads and writes.  There are two ways this may
5188                      happen:
5189
5190                      2.1. This is a target that can't break on data
5191                      reads only, but can break on accesses (reads or
5192                      writes), such as e.g., x86.  We detect this case
5193                      at the time we try to insert read watchpoints.
5194
5195                      2.2. Otherwise, the target supports read
5196                      watchpoints, but, the user set an access or write
5197                      watchpoint watching the same memory as this read
5198                      watchpoint.
5199
5200                      If we're watching memory writes as well as reads,
5201                      ignore watchpoint hits when we find that the
5202                      value hasn't changed, as reads don't cause
5203                      changes.  This still gives false positives when
5204                      the program writes the same value to memory as
5205                      what there was already in memory (we will confuse
5206                      it for a read), but it's much better than
5207                      nothing.  */
5208
5209                   int other_write_watchpoint = 0;
5210
5211                   if (bl->watchpoint_type == hw_read)
5212                     {
5213                       struct breakpoint *other_b;
5214
5215                       ALL_BREAKPOINTS (other_b)
5216                         if (other_b->type == bp_hardware_watchpoint
5217                             || other_b->type == bp_access_watchpoint)
5218                           {
5219                             struct watchpoint *other_w =
5220                               (struct watchpoint *) other_b;
5221
5222                             if (other_w->watchpoint_triggered
5223                                 == watch_triggered_yes)
5224                               {
5225                                 other_write_watchpoint = 1;
5226                                 break;
5227                               }
5228                           }
5229                     }
5230
5231                   if (other_write_watchpoint
5232                       || bl->watchpoint_type == hw_access)
5233                     {
5234                       /* We're watching the same memory for writes,
5235                          and the value changed since the last time we
5236                          updated it, so this trap must be for a write.
5237                          Ignore it.  */
5238                       bs->print_it = print_it_noop;
5239                       bs->stop = 0;
5240                     }
5241                 }
5242               break;
5243             case WP_VALUE_NOT_CHANGED:
5244               if (b->base.type == bp_hardware_watchpoint
5245                   || b->base.type == bp_watchpoint)
5246                 {
5247                   /* Don't stop: write watchpoints shouldn't fire if
5248                      the value hasn't changed.  */
5249                   bs->print_it = print_it_noop;
5250                   bs->stop = 0;
5251                 }
5252               /* Stop.  */
5253               break;
5254             default:
5255               /* Can't happen.  */
5256             case 0:
5257               /* Error from catch_errors.  */
5258               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5259               watchpoint_del_at_next_stop (b);
5260               /* We've already printed what needs to be printed.  */
5261               bs->print_it = print_it_done;
5262               break;
5263             }
5264         }
5265       else      /* must_check_value == 0 */
5266         {
5267           /* This is a case where some watchpoint(s) triggered, but
5268              not at the address of this watchpoint, or else no
5269              watchpoint triggered after all.  So don't print
5270              anything for this watchpoint.  */
5271           bs->print_it = print_it_noop;
5272           bs->stop = 0;
5273         }
5274     }
5275 }
5276
5277 /* For breakpoints that are currently marked as telling gdb to stop,
5278    check conditions (condition proper, frame, thread and ignore count)
5279    of breakpoint referred to by BS.  If we should not stop for this
5280    breakpoint, set BS->stop to 0.  */
5281
5282 static void
5283 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5284 {
5285   const struct bp_location *bl;
5286   struct breakpoint *b;
5287   int value_is_zero = 0;
5288   struct expression *cond;
5289
5290   gdb_assert (bs->stop);
5291
5292   /* BS is built for existing struct breakpoint.  */
5293   bl = bs->bp_location_at;
5294   gdb_assert (bl != NULL);
5295   b = bs->breakpoint_at;
5296   gdb_assert (b != NULL);
5297
5298   /* Even if the target evaluated the condition on its end and notified GDB, we
5299      need to do so again since GDB does not know if we stopped due to a
5300      breakpoint or a single step breakpoint.  */
5301
5302   if (frame_id_p (b->frame_id)
5303       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5304     {
5305       bs->stop = 0;
5306       return;
5307     }
5308
5309   /* If this is a thread/task-specific breakpoint, don't waste cpu
5310      evaluating the condition if this isn't the specified
5311      thread/task.  */
5312   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5313       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5314
5315     {
5316       bs->stop = 0;
5317       return;
5318     }
5319
5320   /* Evaluate extension language breakpoints that have a "stop" method
5321      implemented.  */
5322   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5323
5324   if (is_watchpoint (b))
5325     {
5326       struct watchpoint *w = (struct watchpoint *) b;
5327
5328       cond = w->cond_exp;
5329     }
5330   else
5331     cond = bl->cond;
5332
5333   if (cond && b->disposition != disp_del_at_next_stop)
5334     {
5335       int within_current_scope = 1;
5336       struct watchpoint * w;
5337
5338       /* We use value_mark and value_free_to_mark because it could
5339          be a long time before we return to the command level and
5340          call free_all_values.  We can't call free_all_values
5341          because we might be in the middle of evaluating a
5342          function call.  */
5343       struct value *mark = value_mark ();
5344
5345       if (is_watchpoint (b))
5346         w = (struct watchpoint *) b;
5347       else
5348         w = NULL;
5349
5350       /* Need to select the frame, with all that implies so that
5351          the conditions will have the right context.  Because we
5352          use the frame, we will not see an inlined function's
5353          variables when we arrive at a breakpoint at the start
5354          of the inlined function; the current frame will be the
5355          call site.  */
5356       if (w == NULL || w->cond_exp_valid_block == NULL)
5357         select_frame (get_current_frame ());
5358       else
5359         {
5360           struct frame_info *frame;
5361
5362           /* For local watchpoint expressions, which particular
5363              instance of a local is being watched matters, so we
5364              keep track of the frame to evaluate the expression
5365              in.  To evaluate the condition however, it doesn't
5366              really matter which instantiation of the function
5367              where the condition makes sense triggers the
5368              watchpoint.  This allows an expression like "watch
5369              global if q > 10" set in `func', catch writes to
5370              global on all threads that call `func', or catch
5371              writes on all recursive calls of `func' by a single
5372              thread.  We simply always evaluate the condition in
5373              the innermost frame that's executing where it makes
5374              sense to evaluate the condition.  It seems
5375              intuitive.  */
5376           frame = block_innermost_frame (w->cond_exp_valid_block);
5377           if (frame != NULL)
5378             select_frame (frame);
5379           else
5380             within_current_scope = 0;
5381         }
5382       if (within_current_scope)
5383         value_is_zero
5384           = catch_errors (breakpoint_cond_eval, cond,
5385                           "Error in testing breakpoint condition:\n",
5386                           RETURN_MASK_ALL);
5387       else
5388         {
5389           warning (_("Watchpoint condition cannot be tested "
5390                      "in the current scope"));
5391           /* If we failed to set the right context for this
5392              watchpoint, unconditionally report it.  */
5393           value_is_zero = 0;
5394         }
5395       /* FIXME-someday, should give breakpoint #.  */
5396       value_free_to_mark (mark);
5397     }
5398
5399   if (cond && value_is_zero)
5400     {
5401       bs->stop = 0;
5402     }
5403   else if (b->ignore_count > 0)
5404     {
5405       b->ignore_count--;
5406       bs->stop = 0;
5407       /* Increase the hit count even though we don't stop.  */
5408       ++(b->hit_count);
5409       observer_notify_breakpoint_modified (b);
5410     }   
5411 }
5412
5413
5414 /* Get a bpstat associated with having just stopped at address
5415    BP_ADDR in thread PTID.
5416
5417    Determine whether we stopped at a breakpoint, etc, or whether we
5418    don't understand this stop.  Result is a chain of bpstat's such
5419    that:
5420
5421    if we don't understand the stop, the result is a null pointer.
5422
5423    if we understand why we stopped, the result is not null.
5424
5425    Each element of the chain refers to a particular breakpoint or
5426    watchpoint at which we have stopped.  (We may have stopped for
5427    several reasons concurrently.)
5428
5429    Each element of the chain has valid next, breakpoint_at,
5430    commands, FIXME??? fields.  */
5431
5432 bpstat
5433 bpstat_stop_status (struct address_space *aspace,
5434                     CORE_ADDR bp_addr, ptid_t ptid,
5435                     const struct target_waitstatus *ws)
5436 {
5437   struct breakpoint *b = NULL;
5438   struct bp_location *bl;
5439   struct bp_location *loc;
5440   /* First item of allocated bpstat's.  */
5441   bpstat bs_head = NULL, *bs_link = &bs_head;
5442   /* Pointer to the last thing in the chain currently.  */
5443   bpstat bs;
5444   int ix;
5445   int need_remove_insert;
5446   int removed_any;
5447
5448   /* First, build the bpstat chain with locations that explain a
5449      target stop, while being careful to not set the target running,
5450      as that may invalidate locations (in particular watchpoint
5451      locations are recreated).  Resuming will happen here with
5452      breakpoint conditions or watchpoint expressions that include
5453      inferior function calls.  */
5454
5455   ALL_BREAKPOINTS (b)
5456     {
5457       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5458         continue;
5459
5460       for (bl = b->loc; bl != NULL; bl = bl->next)
5461         {
5462           /* For hardware watchpoints, we look only at the first
5463              location.  The watchpoint_check function will work on the
5464              entire expression, not the individual locations.  For
5465              read watchpoints, the watchpoints_triggered function has
5466              checked all locations already.  */
5467           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5468             break;
5469
5470           if (!bl->enabled || bl->shlib_disabled)
5471             continue;
5472
5473           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5474             continue;
5475
5476           /* Come here if it's a watchpoint, or if the break address
5477              matches.  */
5478
5479           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5480                                                    explain stop.  */
5481
5482           /* Assume we stop.  Should we find a watchpoint that is not
5483              actually triggered, or if the condition of the breakpoint
5484              evaluates as false, we'll reset 'stop' to 0.  */
5485           bs->stop = 1;
5486           bs->print = 1;
5487
5488           /* If this is a scope breakpoint, mark the associated
5489              watchpoint as triggered so that we will handle the
5490              out-of-scope event.  We'll get to the watchpoint next
5491              iteration.  */
5492           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5493             {
5494               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5495
5496               w->watchpoint_triggered = watch_triggered_yes;
5497             }
5498         }
5499     }
5500
5501   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5502     {
5503       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5504         {
5505           bs = bpstat_alloc (loc, &bs_link);
5506           /* For hits of moribund locations, we should just proceed.  */
5507           bs->stop = 0;
5508           bs->print = 0;
5509           bs->print_it = print_it_noop;
5510         }
5511     }
5512
5513   /* A bit of special processing for shlib breakpoints.  We need to
5514      process solib loading here, so that the lists of loaded and
5515      unloaded libraries are correct before we handle "catch load" and
5516      "catch unload".  */
5517   for (bs = bs_head; bs != NULL; bs = bs->next)
5518     {
5519       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5520         {
5521           handle_solib_event ();
5522           break;
5523         }
5524     }
5525
5526   /* Now go through the locations that caused the target to stop, and
5527      check whether we're interested in reporting this stop to higher
5528      layers, or whether we should resume the target transparently.  */
5529
5530   removed_any = 0;
5531
5532   for (bs = bs_head; bs != NULL; bs = bs->next)
5533     {
5534       if (!bs->stop)
5535         continue;
5536
5537       b = bs->breakpoint_at;
5538       b->ops->check_status (bs);
5539       if (bs->stop)
5540         {
5541           bpstat_check_breakpoint_conditions (bs, ptid);
5542
5543           if (bs->stop)
5544             {
5545               ++(b->hit_count);
5546               observer_notify_breakpoint_modified (b);
5547
5548               /* We will stop here.  */
5549               if (b->disposition == disp_disable)
5550                 {
5551                   --(b->enable_count);
5552                   if (b->enable_count <= 0
5553                       && b->enable_state != bp_permanent)
5554                     b->enable_state = bp_disabled;
5555                   removed_any = 1;
5556                 }
5557               if (b->silent)
5558                 bs->print = 0;
5559               bs->commands = b->commands;
5560               incref_counted_command_line (bs->commands);
5561               if (command_line_is_silent (bs->commands
5562                                           ? bs->commands->commands : NULL))
5563                 bs->print = 0;
5564
5565               b->ops->after_condition_true (bs);
5566             }
5567
5568         }
5569
5570       /* Print nothing for this entry if we don't stop or don't
5571          print.  */
5572       if (!bs->stop || !bs->print)
5573         bs->print_it = print_it_noop;
5574     }
5575
5576   /* If we aren't stopping, the value of some hardware watchpoint may
5577      not have changed, but the intermediate memory locations we are
5578      watching may have.  Don't bother if we're stopping; this will get
5579      done later.  */
5580   need_remove_insert = 0;
5581   if (! bpstat_causes_stop (bs_head))
5582     for (bs = bs_head; bs != NULL; bs = bs->next)
5583       if (!bs->stop
5584           && bs->breakpoint_at
5585           && is_hardware_watchpoint (bs->breakpoint_at))
5586         {
5587           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5588
5589           update_watchpoint (w, 0 /* don't reparse.  */);
5590           need_remove_insert = 1;
5591         }
5592
5593   if (need_remove_insert)
5594     update_global_location_list (1);
5595   else if (removed_any)
5596     update_global_location_list (0);
5597
5598   return bs_head;
5599 }
5600
5601 static void
5602 handle_jit_event (void)
5603 {
5604   struct frame_info *frame;
5605   struct gdbarch *gdbarch;
5606
5607   /* Switch terminal for any messages produced by
5608      breakpoint_re_set.  */
5609   target_terminal_ours_for_output ();
5610
5611   frame = get_current_frame ();
5612   gdbarch = get_frame_arch (frame);
5613
5614   jit_event_handler (gdbarch);
5615
5616   target_terminal_inferior ();
5617 }
5618
5619 /* Prepare WHAT final decision for infrun.  */
5620
5621 /* Decide what infrun needs to do with this bpstat.  */
5622
5623 struct bpstat_what
5624 bpstat_what (bpstat bs_head)
5625 {
5626   struct bpstat_what retval;
5627   int jit_event = 0;
5628   bpstat bs;
5629
5630   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5631   retval.call_dummy = STOP_NONE;
5632   retval.is_longjmp = 0;
5633
5634   for (bs = bs_head; bs != NULL; bs = bs->next)
5635     {
5636       /* Extract this BS's action.  After processing each BS, we check
5637          if its action overrides all we've seem so far.  */
5638       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5639       enum bptype bptype;
5640
5641       if (bs->breakpoint_at == NULL)
5642         {
5643           /* I suspect this can happen if it was a momentary
5644              breakpoint which has since been deleted.  */
5645           bptype = bp_none;
5646         }
5647       else
5648         bptype = bs->breakpoint_at->type;
5649
5650       switch (bptype)
5651         {
5652         case bp_none:
5653           break;
5654         case bp_breakpoint:
5655         case bp_hardware_breakpoint:
5656         case bp_until:
5657         case bp_finish:
5658         case bp_shlib_event:
5659           if (bs->stop)
5660             {
5661               if (bs->print)
5662                 this_action = BPSTAT_WHAT_STOP_NOISY;
5663               else
5664                 this_action = BPSTAT_WHAT_STOP_SILENT;
5665             }
5666           else
5667             this_action = BPSTAT_WHAT_SINGLE;
5668           break;
5669         case bp_watchpoint:
5670         case bp_hardware_watchpoint:
5671         case bp_read_watchpoint:
5672         case bp_access_watchpoint:
5673           if (bs->stop)
5674             {
5675               if (bs->print)
5676                 this_action = BPSTAT_WHAT_STOP_NOISY;
5677               else
5678                 this_action = BPSTAT_WHAT_STOP_SILENT;
5679             }
5680           else
5681             {
5682               /* There was a watchpoint, but we're not stopping.
5683                  This requires no further action.  */
5684             }
5685           break;
5686         case bp_longjmp:
5687         case bp_longjmp_call_dummy:
5688         case bp_exception:
5689           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5690           retval.is_longjmp = bptype != bp_exception;
5691           break;
5692         case bp_longjmp_resume:
5693         case bp_exception_resume:
5694           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5695           retval.is_longjmp = bptype == bp_longjmp_resume;
5696           break;
5697         case bp_step_resume:
5698           if (bs->stop)
5699             this_action = BPSTAT_WHAT_STEP_RESUME;
5700           else
5701             {
5702               /* It is for the wrong frame.  */
5703               this_action = BPSTAT_WHAT_SINGLE;
5704             }
5705           break;
5706         case bp_hp_step_resume:
5707           if (bs->stop)
5708             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5709           else
5710             {
5711               /* It is for the wrong frame.  */
5712               this_action = BPSTAT_WHAT_SINGLE;
5713             }
5714           break;
5715         case bp_watchpoint_scope:
5716         case bp_thread_event:
5717         case bp_overlay_event:
5718         case bp_longjmp_master:
5719         case bp_std_terminate_master:
5720         case bp_exception_master:
5721           this_action = BPSTAT_WHAT_SINGLE;
5722           break;
5723         case bp_catchpoint:
5724           if (bs->stop)
5725             {
5726               if (bs->print)
5727                 this_action = BPSTAT_WHAT_STOP_NOISY;
5728               else
5729                 this_action = BPSTAT_WHAT_STOP_SILENT;
5730             }
5731           else
5732             {
5733               /* There was a catchpoint, but we're not stopping.
5734                  This requires no further action.  */
5735             }
5736           break;
5737         case bp_jit_event:
5738           jit_event = 1;
5739           this_action = BPSTAT_WHAT_SINGLE;
5740           break;
5741         case bp_call_dummy:
5742           /* Make sure the action is stop (silent or noisy),
5743              so infrun.c pops the dummy frame.  */
5744           retval.call_dummy = STOP_STACK_DUMMY;
5745           this_action = BPSTAT_WHAT_STOP_SILENT;
5746           break;
5747         case bp_std_terminate:
5748           /* Make sure the action is stop (silent or noisy),
5749              so infrun.c pops the dummy frame.  */
5750           retval.call_dummy = STOP_STD_TERMINATE;
5751           this_action = BPSTAT_WHAT_STOP_SILENT;
5752           break;
5753         case bp_tracepoint:
5754         case bp_fast_tracepoint:
5755         case bp_static_tracepoint:
5756           /* Tracepoint hits should not be reported back to GDB, and
5757              if one got through somehow, it should have been filtered
5758              out already.  */
5759           internal_error (__FILE__, __LINE__,
5760                           _("bpstat_what: tracepoint encountered"));
5761           break;
5762         case bp_gnu_ifunc_resolver:
5763           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5764           this_action = BPSTAT_WHAT_SINGLE;
5765           break;
5766         case bp_gnu_ifunc_resolver_return:
5767           /* The breakpoint will be removed, execution will restart from the
5768              PC of the former breakpoint.  */
5769           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5770           break;
5771
5772         case bp_dprintf:
5773           if (bs->stop)
5774             this_action = BPSTAT_WHAT_STOP_SILENT;
5775           else
5776             this_action = BPSTAT_WHAT_SINGLE;
5777           break;
5778
5779         default:
5780           internal_error (__FILE__, __LINE__,
5781                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5782         }
5783
5784       retval.main_action = max (retval.main_action, this_action);
5785     }
5786
5787   /* These operations may affect the bs->breakpoint_at state so they are
5788      delayed after MAIN_ACTION is decided above.  */
5789
5790   if (jit_event)
5791     {
5792       if (debug_infrun)
5793         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5794
5795       handle_jit_event ();
5796     }
5797
5798   for (bs = bs_head; bs != NULL; bs = bs->next)
5799     {
5800       struct breakpoint *b = bs->breakpoint_at;
5801
5802       if (b == NULL)
5803         continue;
5804       switch (b->type)
5805         {
5806         case bp_gnu_ifunc_resolver:
5807           gnu_ifunc_resolver_stop (b);
5808           break;
5809         case bp_gnu_ifunc_resolver_return:
5810           gnu_ifunc_resolver_return_stop (b);
5811           break;
5812         }
5813     }
5814
5815   return retval;
5816 }
5817
5818 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5819    without hardware support).  This isn't related to a specific bpstat,
5820    just to things like whether watchpoints are set.  */
5821
5822 int
5823 bpstat_should_step (void)
5824 {
5825   struct breakpoint *b;
5826
5827   ALL_BREAKPOINTS (b)
5828     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5829       return 1;
5830   return 0;
5831 }
5832
5833 int
5834 bpstat_causes_stop (bpstat bs)
5835 {
5836   for (; bs != NULL; bs = bs->next)
5837     if (bs->stop)
5838       return 1;
5839
5840   return 0;
5841 }
5842
5843 \f
5844
5845 /* Compute a string of spaces suitable to indent the next line
5846    so it starts at the position corresponding to the table column
5847    named COL_NAME in the currently active table of UIOUT.  */
5848
5849 static char *
5850 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5851 {
5852   static char wrap_indent[80];
5853   int i, total_width, width, align;
5854   char *text;
5855
5856   total_width = 0;
5857   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5858     {
5859       if (strcmp (text, col_name) == 0)
5860         {
5861           gdb_assert (total_width < sizeof wrap_indent);
5862           memset (wrap_indent, ' ', total_width);
5863           wrap_indent[total_width] = 0;
5864
5865           return wrap_indent;
5866         }
5867
5868       total_width += width + 1;
5869     }
5870
5871   return NULL;
5872 }
5873
5874 /* Determine if the locations of this breakpoint will have their conditions
5875    evaluated by the target, host or a mix of both.  Returns the following:
5876
5877     "host": Host evals condition.
5878     "host or target": Host or Target evals condition.
5879     "target": Target evals condition.
5880 */
5881
5882 static const char *
5883 bp_condition_evaluator (struct breakpoint *b)
5884 {
5885   struct bp_location *bl;
5886   char host_evals = 0;
5887   char target_evals = 0;
5888
5889   if (!b)
5890     return NULL;
5891
5892   if (!is_breakpoint (b))
5893     return NULL;
5894
5895   if (gdb_evaluates_breakpoint_condition_p ()
5896       || !target_supports_evaluation_of_breakpoint_conditions ())
5897     return condition_evaluation_host;
5898
5899   for (bl = b->loc; bl; bl = bl->next)
5900     {
5901       if (bl->cond_bytecode)
5902         target_evals++;
5903       else
5904         host_evals++;
5905     }
5906
5907   if (host_evals && target_evals)
5908     return condition_evaluation_both;
5909   else if (target_evals)
5910     return condition_evaluation_target;
5911   else
5912     return condition_evaluation_host;
5913 }
5914
5915 /* Determine the breakpoint location's condition evaluator.  This is
5916    similar to bp_condition_evaluator, but for locations.  */
5917
5918 static const char *
5919 bp_location_condition_evaluator (struct bp_location *bl)
5920 {
5921   if (bl && !is_breakpoint (bl->owner))
5922     return NULL;
5923
5924   if (gdb_evaluates_breakpoint_condition_p ()
5925       || !target_supports_evaluation_of_breakpoint_conditions ())
5926     return condition_evaluation_host;
5927
5928   if (bl && bl->cond_bytecode)
5929     return condition_evaluation_target;
5930   else
5931     return condition_evaluation_host;
5932 }
5933
5934 /* Print the LOC location out of the list of B->LOC locations.  */
5935
5936 static void
5937 print_breakpoint_location (struct breakpoint *b,
5938                            struct bp_location *loc)
5939 {
5940   struct ui_out *uiout = current_uiout;
5941   struct cleanup *old_chain = save_current_program_space ();
5942
5943   if (loc != NULL && loc->shlib_disabled)
5944     loc = NULL;
5945
5946   if (loc != NULL)
5947     set_current_program_space (loc->pspace);
5948
5949   if (b->display_canonical)
5950     ui_out_field_string (uiout, "what", b->addr_string);
5951   else if (loc && loc->symtab)
5952     {
5953       struct symbol *sym 
5954         = find_pc_sect_function (loc->address, loc->section);
5955       if (sym)
5956         {
5957           ui_out_text (uiout, "in ");
5958           ui_out_field_string (uiout, "func",
5959                                SYMBOL_PRINT_NAME (sym));
5960           ui_out_text (uiout, " ");
5961           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5962           ui_out_text (uiout, "at ");
5963         }
5964       ui_out_field_string (uiout, "file",
5965                            symtab_to_filename_for_display (loc->symtab));
5966       ui_out_text (uiout, ":");
5967
5968       if (ui_out_is_mi_like_p (uiout))
5969         ui_out_field_string (uiout, "fullname",
5970                              symtab_to_fullname (loc->symtab));
5971       
5972       ui_out_field_int (uiout, "line", loc->line_number);
5973     }
5974   else if (loc)
5975     {
5976       struct ui_file *stb = mem_fileopen ();
5977       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5978
5979       print_address_symbolic (loc->gdbarch, loc->address, stb,
5980                               demangle, "");
5981       ui_out_field_stream (uiout, "at", stb);
5982
5983       do_cleanups (stb_chain);
5984     }
5985   else
5986     ui_out_field_string (uiout, "pending", b->addr_string);
5987
5988   if (loc && is_breakpoint (b)
5989       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5990       && bp_condition_evaluator (b) == condition_evaluation_both)
5991     {
5992       ui_out_text (uiout, " (");
5993       ui_out_field_string (uiout, "evaluated-by",
5994                            bp_location_condition_evaluator (loc));
5995       ui_out_text (uiout, ")");
5996     }
5997
5998   do_cleanups (old_chain);
5999 }
6000
6001 static const char *
6002 bptype_string (enum bptype type)
6003 {
6004   struct ep_type_description
6005     {
6006       enum bptype type;
6007       char *description;
6008     };
6009   static struct ep_type_description bptypes[] =
6010   {
6011     {bp_none, "?deleted?"},
6012     {bp_breakpoint, "breakpoint"},
6013     {bp_hardware_breakpoint, "hw breakpoint"},
6014     {bp_until, "until"},
6015     {bp_finish, "finish"},
6016     {bp_watchpoint, "watchpoint"},
6017     {bp_hardware_watchpoint, "hw watchpoint"},
6018     {bp_read_watchpoint, "read watchpoint"},
6019     {bp_access_watchpoint, "acc watchpoint"},
6020     {bp_longjmp, "longjmp"},
6021     {bp_longjmp_resume, "longjmp resume"},
6022     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6023     {bp_exception, "exception"},
6024     {bp_exception_resume, "exception resume"},
6025     {bp_step_resume, "step resume"},
6026     {bp_hp_step_resume, "high-priority step resume"},
6027     {bp_watchpoint_scope, "watchpoint scope"},
6028     {bp_call_dummy, "call dummy"},
6029     {bp_std_terminate, "std::terminate"},
6030     {bp_shlib_event, "shlib events"},
6031     {bp_thread_event, "thread events"},
6032     {bp_overlay_event, "overlay events"},
6033     {bp_longjmp_master, "longjmp master"},
6034     {bp_std_terminate_master, "std::terminate master"},
6035     {bp_exception_master, "exception master"},
6036     {bp_catchpoint, "catchpoint"},
6037     {bp_tracepoint, "tracepoint"},
6038     {bp_fast_tracepoint, "fast tracepoint"},
6039     {bp_static_tracepoint, "static tracepoint"},
6040     {bp_dprintf, "dprintf"},
6041     {bp_jit_event, "jit events"},
6042     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6043     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6044   };
6045
6046   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6047       || ((int) type != bptypes[(int) type].type))
6048     internal_error (__FILE__, __LINE__,
6049                     _("bptypes table does not describe type #%d."),
6050                     (int) type);
6051
6052   return bptypes[(int) type].description;
6053 }
6054
6055 /* For MI, output a field named 'thread-groups' with a list as the value.
6056    For CLI, prefix the list with the string 'inf'. */
6057
6058 static void
6059 output_thread_groups (struct ui_out *uiout,
6060                       const char *field_name,
6061                       VEC(int) *inf_num,
6062                       int mi_only)
6063 {
6064   struct cleanup *back_to;
6065   int is_mi = ui_out_is_mi_like_p (uiout);
6066   int inf;
6067   int i;
6068
6069   /* For backward compatibility, don't display inferiors in CLI unless
6070      there are several.  Always display them for MI. */
6071   if (!is_mi && mi_only)
6072     return;
6073
6074   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6075
6076   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6077     {
6078       if (is_mi)
6079         {
6080           char mi_group[10];
6081
6082           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6083           ui_out_field_string (uiout, NULL, mi_group);
6084         }
6085       else
6086         {
6087           if (i == 0)
6088             ui_out_text (uiout, " inf ");
6089           else
6090             ui_out_text (uiout, ", ");
6091         
6092           ui_out_text (uiout, plongest (inf));
6093         }
6094     }
6095
6096   do_cleanups (back_to);
6097 }
6098
6099 /* Print B to gdb_stdout.  */
6100
6101 static void
6102 print_one_breakpoint_location (struct breakpoint *b,
6103                                struct bp_location *loc,
6104                                int loc_number,
6105                                struct bp_location **last_loc,
6106                                int allflag)
6107 {
6108   struct command_line *l;
6109   static char bpenables[] = "nynny";
6110
6111   struct ui_out *uiout = current_uiout;
6112   int header_of_multiple = 0;
6113   int part_of_multiple = (loc != NULL);
6114   struct value_print_options opts;
6115
6116   get_user_print_options (&opts);
6117
6118   gdb_assert (!loc || loc_number != 0);
6119   /* See comment in print_one_breakpoint concerning treatment of
6120      breakpoints with single disabled location.  */
6121   if (loc == NULL 
6122       && (b->loc != NULL 
6123           && (b->loc->next != NULL || !b->loc->enabled)))
6124     header_of_multiple = 1;
6125   if (loc == NULL)
6126     loc = b->loc;
6127
6128   annotate_record ();
6129
6130   /* 1 */
6131   annotate_field (0);
6132   if (part_of_multiple)
6133     {
6134       char *formatted;
6135       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6136       ui_out_field_string (uiout, "number", formatted);
6137       xfree (formatted);
6138     }
6139   else
6140     {
6141       ui_out_field_int (uiout, "number", b->number);
6142     }
6143
6144   /* 2 */
6145   annotate_field (1);
6146   if (part_of_multiple)
6147     ui_out_field_skip (uiout, "type");
6148   else
6149     ui_out_field_string (uiout, "type", bptype_string (b->type));
6150
6151   /* 3 */
6152   annotate_field (2);
6153   if (part_of_multiple)
6154     ui_out_field_skip (uiout, "disp");
6155   else
6156     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6157
6158
6159   /* 4 */
6160   annotate_field (3);
6161   if (part_of_multiple)
6162     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6163   else
6164     ui_out_field_fmt (uiout, "enabled", "%c", 
6165                       bpenables[(int) b->enable_state]);
6166   ui_out_spaces (uiout, 2);
6167
6168   
6169   /* 5 and 6 */
6170   if (b->ops != NULL && b->ops->print_one != NULL)
6171     {
6172       /* Although the print_one can possibly print all locations,
6173          calling it here is not likely to get any nice result.  So,
6174          make sure there's just one location.  */
6175       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6176       b->ops->print_one (b, last_loc);
6177     }
6178   else
6179     switch (b->type)
6180       {
6181       case bp_none:
6182         internal_error (__FILE__, __LINE__,
6183                         _("print_one_breakpoint: bp_none encountered\n"));
6184         break;
6185
6186       case bp_watchpoint:
6187       case bp_hardware_watchpoint:
6188       case bp_read_watchpoint:
6189       case bp_access_watchpoint:
6190         {
6191           struct watchpoint *w = (struct watchpoint *) b;
6192
6193           /* Field 4, the address, is omitted (which makes the columns
6194              not line up too nicely with the headers, but the effect
6195              is relatively readable).  */
6196           if (opts.addressprint)
6197             ui_out_field_skip (uiout, "addr");
6198           annotate_field (5);
6199           ui_out_field_string (uiout, "what", w->exp_string);
6200         }
6201         break;
6202
6203       case bp_breakpoint:
6204       case bp_hardware_breakpoint:
6205       case bp_until:
6206       case bp_finish:
6207       case bp_longjmp:
6208       case bp_longjmp_resume:
6209       case bp_longjmp_call_dummy:
6210       case bp_exception:
6211       case bp_exception_resume:
6212       case bp_step_resume:
6213       case bp_hp_step_resume:
6214       case bp_watchpoint_scope:
6215       case bp_call_dummy:
6216       case bp_std_terminate:
6217       case bp_shlib_event:
6218       case bp_thread_event:
6219       case bp_overlay_event:
6220       case bp_longjmp_master:
6221       case bp_std_terminate_master:
6222       case bp_exception_master:
6223       case bp_tracepoint:
6224       case bp_fast_tracepoint:
6225       case bp_static_tracepoint:
6226       case bp_dprintf:
6227       case bp_jit_event:
6228       case bp_gnu_ifunc_resolver:
6229       case bp_gnu_ifunc_resolver_return:
6230         if (opts.addressprint)
6231           {
6232             annotate_field (4);
6233             if (header_of_multiple)
6234               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6235             else if (b->loc == NULL || loc->shlib_disabled)
6236               ui_out_field_string (uiout, "addr", "<PENDING>");
6237             else
6238               ui_out_field_core_addr (uiout, "addr",
6239                                       loc->gdbarch, loc->address);
6240           }
6241         annotate_field (5);
6242         if (!header_of_multiple)
6243           print_breakpoint_location (b, loc);
6244         if (b->loc)
6245           *last_loc = b->loc;
6246         break;
6247       }
6248
6249
6250   if (loc != NULL && !header_of_multiple)
6251     {
6252       struct inferior *inf;
6253       VEC(int) *inf_num = NULL;
6254       int mi_only = 1;
6255
6256       ALL_INFERIORS (inf)
6257         {
6258           if (inf->pspace == loc->pspace)
6259             VEC_safe_push (int, inf_num, inf->num);
6260         }
6261
6262         /* For backward compatibility, don't display inferiors in CLI unless
6263            there are several.  Always display for MI. */
6264         if (allflag
6265             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6266                 && (number_of_program_spaces () > 1
6267                     || number_of_inferiors () > 1)
6268                 /* LOC is for existing B, it cannot be in
6269                    moribund_locations and thus having NULL OWNER.  */
6270                 && loc->owner->type != bp_catchpoint))
6271         mi_only = 0;
6272       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6273       VEC_free (int, inf_num);
6274     }
6275
6276   if (!part_of_multiple)
6277     {
6278       if (b->thread != -1)
6279         {
6280           /* FIXME: This seems to be redundant and lost here; see the
6281              "stop only in" line a little further down.  */
6282           ui_out_text (uiout, " thread ");
6283           ui_out_field_int (uiout, "thread", b->thread);
6284         }
6285       else if (b->task != 0)
6286         {
6287           ui_out_text (uiout, " task ");
6288           ui_out_field_int (uiout, "task", b->task);
6289         }
6290     }
6291
6292   ui_out_text (uiout, "\n");
6293
6294   if (!part_of_multiple)
6295     b->ops->print_one_detail (b, uiout);
6296
6297   if (part_of_multiple && frame_id_p (b->frame_id))
6298     {
6299       annotate_field (6);
6300       ui_out_text (uiout, "\tstop only in stack frame at ");
6301       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6302          the frame ID.  */
6303       ui_out_field_core_addr (uiout, "frame",
6304                               b->gdbarch, b->frame_id.stack_addr);
6305       ui_out_text (uiout, "\n");
6306     }
6307   
6308   if (!part_of_multiple && b->cond_string)
6309     {
6310       annotate_field (7);
6311       if (is_tracepoint (b))
6312         ui_out_text (uiout, "\ttrace only if ");
6313       else
6314         ui_out_text (uiout, "\tstop only if ");
6315       ui_out_field_string (uiout, "cond", b->cond_string);
6316
6317       /* Print whether the target is doing the breakpoint's condition
6318          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6319       if (is_breakpoint (b)
6320           && breakpoint_condition_evaluation_mode ()
6321           == condition_evaluation_target)
6322         {
6323           ui_out_text (uiout, " (");
6324           ui_out_field_string (uiout, "evaluated-by",
6325                                bp_condition_evaluator (b));
6326           ui_out_text (uiout, " evals)");
6327         }
6328       ui_out_text (uiout, "\n");
6329     }
6330
6331   if (!part_of_multiple && b->thread != -1)
6332     {
6333       /* FIXME should make an annotation for this.  */
6334       ui_out_text (uiout, "\tstop only in thread ");
6335       ui_out_field_int (uiout, "thread", b->thread);
6336       ui_out_text (uiout, "\n");
6337     }
6338   
6339   if (!part_of_multiple)
6340     {
6341       if (b->hit_count)
6342         {
6343           /* FIXME should make an annotation for this.  */
6344           if (is_catchpoint (b))
6345             ui_out_text (uiout, "\tcatchpoint");
6346           else if (is_tracepoint (b))
6347             ui_out_text (uiout, "\ttracepoint");
6348           else
6349             ui_out_text (uiout, "\tbreakpoint");
6350           ui_out_text (uiout, " already hit ");
6351           ui_out_field_int (uiout, "times", b->hit_count);
6352           if (b->hit_count == 1)
6353             ui_out_text (uiout, " time\n");
6354           else
6355             ui_out_text (uiout, " times\n");
6356         }
6357       else
6358         {
6359           /* Output the count also if it is zero, but only if this is mi.  */
6360           if (ui_out_is_mi_like_p (uiout))
6361             ui_out_field_int (uiout, "times", b->hit_count);
6362         }
6363     }
6364
6365   if (!part_of_multiple && b->ignore_count)
6366     {
6367       annotate_field (8);
6368       ui_out_text (uiout, "\tignore next ");
6369       ui_out_field_int (uiout, "ignore", b->ignore_count);
6370       ui_out_text (uiout, " hits\n");
6371     }
6372
6373   /* Note that an enable count of 1 corresponds to "enable once"
6374      behavior, which is reported by the combination of enablement and
6375      disposition, so we don't need to mention it here.  */
6376   if (!part_of_multiple && b->enable_count > 1)
6377     {
6378       annotate_field (8);
6379       ui_out_text (uiout, "\tdisable after ");
6380       /* Tweak the wording to clarify that ignore and enable counts
6381          are distinct, and have additive effect.  */
6382       if (b->ignore_count)
6383         ui_out_text (uiout, "additional ");
6384       else
6385         ui_out_text (uiout, "next ");
6386       ui_out_field_int (uiout, "enable", b->enable_count);
6387       ui_out_text (uiout, " hits\n");
6388     }
6389
6390   if (!part_of_multiple && is_tracepoint (b))
6391     {
6392       struct tracepoint *tp = (struct tracepoint *) b;
6393
6394       if (tp->traceframe_usage)
6395         {
6396           ui_out_text (uiout, "\ttrace buffer usage ");
6397           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6398           ui_out_text (uiout, " bytes\n");
6399         }
6400     }
6401
6402   l = b->commands ? b->commands->commands : NULL;
6403   if (!part_of_multiple && l)
6404     {
6405       struct cleanup *script_chain;
6406
6407       annotate_field (9);
6408       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6409       print_command_lines (uiout, l, 4);
6410       do_cleanups (script_chain);
6411     }
6412
6413   if (is_tracepoint (b))
6414     {
6415       struct tracepoint *t = (struct tracepoint *) b;
6416
6417       if (!part_of_multiple && t->pass_count)
6418         {
6419           annotate_field (10);
6420           ui_out_text (uiout, "\tpass count ");
6421           ui_out_field_int (uiout, "pass", t->pass_count);
6422           ui_out_text (uiout, " \n");
6423         }
6424
6425       /* Don't display it when tracepoint or tracepoint location is
6426          pending.   */
6427       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6428         {
6429           annotate_field (11);
6430
6431           if (ui_out_is_mi_like_p (uiout))
6432             ui_out_field_string (uiout, "installed",
6433                                  loc->inserted ? "y" : "n");
6434           else
6435             {
6436               if (loc->inserted)
6437                 ui_out_text (uiout, "\t");
6438               else
6439                 ui_out_text (uiout, "\tnot ");
6440               ui_out_text (uiout, "installed on target\n");
6441             }
6442         }
6443     }
6444
6445   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6446     {
6447       if (is_watchpoint (b))
6448         {
6449           struct watchpoint *w = (struct watchpoint *) b;
6450
6451           ui_out_field_string (uiout, "original-location", w->exp_string);
6452         }
6453       else if (b->addr_string)
6454         ui_out_field_string (uiout, "original-location", b->addr_string);
6455     }
6456 }
6457
6458 static void
6459 print_one_breakpoint (struct breakpoint *b,
6460                       struct bp_location **last_loc, 
6461                       int allflag)
6462 {
6463   struct cleanup *bkpt_chain;
6464   struct ui_out *uiout = current_uiout;
6465
6466   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6467
6468   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6469   do_cleanups (bkpt_chain);
6470
6471   /* If this breakpoint has custom print function,
6472      it's already printed.  Otherwise, print individual
6473      locations, if any.  */
6474   if (b->ops == NULL || b->ops->print_one == NULL)
6475     {
6476       /* If breakpoint has a single location that is disabled, we
6477          print it as if it had several locations, since otherwise it's
6478          hard to represent "breakpoint enabled, location disabled"
6479          situation.
6480
6481          Note that while hardware watchpoints have several locations
6482          internally, that's not a property exposed to user.  */
6483       if (b->loc 
6484           && !is_hardware_watchpoint (b)
6485           && (b->loc->next || !b->loc->enabled))
6486         {
6487           struct bp_location *loc;
6488           int n = 1;
6489
6490           for (loc = b->loc; loc; loc = loc->next, ++n)
6491             {
6492               struct cleanup *inner2 =
6493                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6494               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6495               do_cleanups (inner2);
6496             }
6497         }
6498     }
6499 }
6500
6501 static int
6502 breakpoint_address_bits (struct breakpoint *b)
6503 {
6504   int print_address_bits = 0;
6505   struct bp_location *loc;
6506
6507   for (loc = b->loc; loc; loc = loc->next)
6508     {
6509       int addr_bit;
6510
6511       /* Software watchpoints that aren't watching memory don't have
6512          an address to print.  */
6513       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6514         continue;
6515
6516       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6517       if (addr_bit > print_address_bits)
6518         print_address_bits = addr_bit;
6519     }
6520
6521   return print_address_bits;
6522 }
6523
6524 struct captured_breakpoint_query_args
6525   {
6526     int bnum;
6527   };
6528
6529 static int
6530 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6531 {
6532   struct captured_breakpoint_query_args *args = data;
6533   struct breakpoint *b;
6534   struct bp_location *dummy_loc = NULL;
6535
6536   ALL_BREAKPOINTS (b)
6537     {
6538       if (args->bnum == b->number)
6539         {
6540           print_one_breakpoint (b, &dummy_loc, 0);
6541           return GDB_RC_OK;
6542         }
6543     }
6544   return GDB_RC_NONE;
6545 }
6546
6547 enum gdb_rc
6548 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6549                       char **error_message)
6550 {
6551   struct captured_breakpoint_query_args args;
6552
6553   args.bnum = bnum;
6554   /* For the moment we don't trust print_one_breakpoint() to not throw
6555      an error.  */
6556   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6557                                  error_message, RETURN_MASK_ALL) < 0)
6558     return GDB_RC_FAIL;
6559   else
6560     return GDB_RC_OK;
6561 }
6562
6563 /* Return true if this breakpoint was set by the user, false if it is
6564    internal or momentary.  */
6565
6566 int
6567 user_breakpoint_p (struct breakpoint *b)
6568 {
6569   return b->number > 0;
6570 }
6571
6572 /* Print information on user settable breakpoint (watchpoint, etc)
6573    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6574    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6575    FILTER is non-NULL, call it on each breakpoint and only include the
6576    ones for which it returns non-zero.  Return the total number of
6577    breakpoints listed.  */
6578
6579 static int
6580 breakpoint_1 (char *args, int allflag, 
6581               int (*filter) (const struct breakpoint *))
6582 {
6583   struct breakpoint *b;
6584   struct bp_location *last_loc = NULL;
6585   int nr_printable_breakpoints;
6586   struct cleanup *bkpttbl_chain;
6587   struct value_print_options opts;
6588   int print_address_bits = 0;
6589   int print_type_col_width = 14;
6590   struct ui_out *uiout = current_uiout;
6591
6592   get_user_print_options (&opts);
6593
6594   /* Compute the number of rows in the table, as well as the size
6595      required for address fields.  */
6596   nr_printable_breakpoints = 0;
6597   ALL_BREAKPOINTS (b)
6598     {
6599       /* If we have a filter, only list the breakpoints it accepts.  */
6600       if (filter && !filter (b))
6601         continue;
6602
6603       /* If we have an "args" string, it is a list of breakpoints to 
6604          accept.  Skip the others.  */
6605       if (args != NULL && *args != '\0')
6606         {
6607           if (allflag && parse_and_eval_long (args) != b->number)
6608             continue;
6609           if (!allflag && !number_is_in_list (args, b->number))
6610             continue;
6611         }
6612
6613       if (allflag || user_breakpoint_p (b))
6614         {
6615           int addr_bit, type_len;
6616
6617           addr_bit = breakpoint_address_bits (b);
6618           if (addr_bit > print_address_bits)
6619             print_address_bits = addr_bit;
6620
6621           type_len = strlen (bptype_string (b->type));
6622           if (type_len > print_type_col_width)
6623             print_type_col_width = type_len;
6624
6625           nr_printable_breakpoints++;
6626         }
6627     }
6628
6629   if (opts.addressprint)
6630     bkpttbl_chain 
6631       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6632                                              nr_printable_breakpoints,
6633                                              "BreakpointTable");
6634   else
6635     bkpttbl_chain 
6636       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6637                                              nr_printable_breakpoints,
6638                                              "BreakpointTable");
6639
6640   if (nr_printable_breakpoints > 0)
6641     annotate_breakpoints_headers ();
6642   if (nr_printable_breakpoints > 0)
6643     annotate_field (0);
6644   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6645   if (nr_printable_breakpoints > 0)
6646     annotate_field (1);
6647   ui_out_table_header (uiout, print_type_col_width, ui_left,
6648                        "type", "Type");                         /* 2 */
6649   if (nr_printable_breakpoints > 0)
6650     annotate_field (2);
6651   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6652   if (nr_printable_breakpoints > 0)
6653     annotate_field (3);
6654   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6655   if (opts.addressprint)
6656     {
6657       if (nr_printable_breakpoints > 0)
6658         annotate_field (4);
6659       if (print_address_bits <= 32)
6660         ui_out_table_header (uiout, 10, ui_left, 
6661                              "addr", "Address");                /* 5 */
6662       else
6663         ui_out_table_header (uiout, 18, ui_left, 
6664                              "addr", "Address");                /* 5 */
6665     }
6666   if (nr_printable_breakpoints > 0)
6667     annotate_field (5);
6668   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6669   ui_out_table_body (uiout);
6670   if (nr_printable_breakpoints > 0)
6671     annotate_breakpoints_table ();
6672
6673   ALL_BREAKPOINTS (b)
6674     {
6675       QUIT;
6676       /* If we have a filter, only list the breakpoints it accepts.  */
6677       if (filter && !filter (b))
6678         continue;
6679
6680       /* If we have an "args" string, it is a list of breakpoints to 
6681          accept.  Skip the others.  */
6682
6683       if (args != NULL && *args != '\0')
6684         {
6685           if (allflag)  /* maintenance info breakpoint */
6686             {
6687               if (parse_and_eval_long (args) != b->number)
6688                 continue;
6689             }
6690           else          /* all others */
6691             {
6692               if (!number_is_in_list (args, b->number))
6693                 continue;
6694             }
6695         }
6696       /* We only print out user settable breakpoints unless the
6697          allflag is set.  */
6698       if (allflag || user_breakpoint_p (b))
6699         print_one_breakpoint (b, &last_loc, allflag);
6700     }
6701
6702   do_cleanups (bkpttbl_chain);
6703
6704   if (nr_printable_breakpoints == 0)
6705     {
6706       /* If there's a filter, let the caller decide how to report
6707          empty list.  */
6708       if (!filter)
6709         {
6710           if (args == NULL || *args == '\0')
6711             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6712           else
6713             ui_out_message (uiout, 0, 
6714                             "No breakpoint or watchpoint matching '%s'.\n",
6715                             args);
6716         }
6717     }
6718   else
6719     {
6720       if (last_loc && !server_command)
6721         set_next_address (last_loc->gdbarch, last_loc->address);
6722     }
6723
6724   /* FIXME?  Should this be moved up so that it is only called when
6725      there have been breakpoints? */
6726   annotate_breakpoints_table_end ();
6727
6728   return nr_printable_breakpoints;
6729 }
6730
6731 /* Display the value of default-collect in a way that is generally
6732    compatible with the breakpoint list.  */
6733
6734 static void
6735 default_collect_info (void)
6736 {
6737   struct ui_out *uiout = current_uiout;
6738
6739   /* If it has no value (which is frequently the case), say nothing; a
6740      message like "No default-collect." gets in user's face when it's
6741      not wanted.  */
6742   if (!*default_collect)
6743     return;
6744
6745   /* The following phrase lines up nicely with per-tracepoint collect
6746      actions.  */
6747   ui_out_text (uiout, "default collect ");
6748   ui_out_field_string (uiout, "default-collect", default_collect);
6749   ui_out_text (uiout, " \n");
6750 }
6751   
6752 static void
6753 breakpoints_info (char *args, int from_tty)
6754 {
6755   breakpoint_1 (args, 0, NULL);
6756
6757   default_collect_info ();
6758 }
6759
6760 static void
6761 watchpoints_info (char *args, int from_tty)
6762 {
6763   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6764   struct ui_out *uiout = current_uiout;
6765
6766   if (num_printed == 0)
6767     {
6768       if (args == NULL || *args == '\0')
6769         ui_out_message (uiout, 0, "No watchpoints.\n");
6770       else
6771         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6772     }
6773 }
6774
6775 static void
6776 maintenance_info_breakpoints (char *args, int from_tty)
6777 {
6778   breakpoint_1 (args, 1, NULL);
6779
6780   default_collect_info ();
6781 }
6782
6783 static int
6784 breakpoint_has_pc (struct breakpoint *b,
6785                    struct program_space *pspace,
6786                    CORE_ADDR pc, struct obj_section *section)
6787 {
6788   struct bp_location *bl = b->loc;
6789
6790   for (; bl; bl = bl->next)
6791     {
6792       if (bl->pspace == pspace
6793           && bl->address == pc
6794           && (!overlay_debugging || bl->section == section))
6795         return 1;         
6796     }
6797   return 0;
6798 }
6799
6800 /* Print a message describing any user-breakpoints set at PC.  This
6801    concerns with logical breakpoints, so we match program spaces, not
6802    address spaces.  */
6803
6804 static void
6805 describe_other_breakpoints (struct gdbarch *gdbarch,
6806                             struct program_space *pspace, CORE_ADDR pc,
6807                             struct obj_section *section, int thread)
6808 {
6809   int others = 0;
6810   struct breakpoint *b;
6811
6812   ALL_BREAKPOINTS (b)
6813     others += (user_breakpoint_p (b)
6814                && breakpoint_has_pc (b, pspace, pc, section));
6815   if (others > 0)
6816     {
6817       if (others == 1)
6818         printf_filtered (_("Note: breakpoint "));
6819       else /* if (others == ???) */
6820         printf_filtered (_("Note: breakpoints "));
6821       ALL_BREAKPOINTS (b)
6822         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6823           {
6824             others--;
6825             printf_filtered ("%d", b->number);
6826             if (b->thread == -1 && thread != -1)
6827               printf_filtered (" (all threads)");
6828             else if (b->thread != -1)
6829               printf_filtered (" (thread %d)", b->thread);
6830             printf_filtered ("%s%s ",
6831                              ((b->enable_state == bp_disabled
6832                                || b->enable_state == bp_call_disabled)
6833                               ? " (disabled)"
6834                               : b->enable_state == bp_permanent 
6835                               ? " (permanent)"
6836                               : ""),
6837                              (others > 1) ? "," 
6838                              : ((others == 1) ? " and" : ""));
6839           }
6840       printf_filtered (_("also set at pc "));
6841       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6842       printf_filtered (".\n");
6843     }
6844 }
6845 \f
6846
6847 /* Return true iff it is meaningful to use the address member of
6848    BPT.  For some breakpoint types, the address member is irrelevant
6849    and it makes no sense to attempt to compare it to other addresses
6850    (or use it for any other purpose either).
6851
6852    More specifically, each of the following breakpoint types will
6853    always have a zero valued address and we don't want to mark
6854    breakpoints of any of these types to be a duplicate of an actual
6855    breakpoint at address zero:
6856
6857       bp_watchpoint
6858       bp_catchpoint
6859
6860 */
6861
6862 static int
6863 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6864 {
6865   enum bptype type = bpt->type;
6866
6867   return (type != bp_watchpoint && type != bp_catchpoint);
6868 }
6869
6870 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6871    true if LOC1 and LOC2 represent the same watchpoint location.  */
6872
6873 static int
6874 watchpoint_locations_match (struct bp_location *loc1, 
6875                             struct bp_location *loc2)
6876 {
6877   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6878   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6879
6880   /* Both of them must exist.  */
6881   gdb_assert (w1 != NULL);
6882   gdb_assert (w2 != NULL);
6883
6884   /* If the target can evaluate the condition expression in hardware,
6885      then we we need to insert both watchpoints even if they are at
6886      the same place.  Otherwise the watchpoint will only trigger when
6887      the condition of whichever watchpoint was inserted evaluates to
6888      true, not giving a chance for GDB to check the condition of the
6889      other watchpoint.  */
6890   if ((w1->cond_exp
6891        && target_can_accel_watchpoint_condition (loc1->address, 
6892                                                  loc1->length,
6893                                                  loc1->watchpoint_type,
6894                                                  w1->cond_exp))
6895       || (w2->cond_exp
6896           && target_can_accel_watchpoint_condition (loc2->address, 
6897                                                     loc2->length,
6898                                                     loc2->watchpoint_type,
6899                                                     w2->cond_exp)))
6900     return 0;
6901
6902   /* Note that this checks the owner's type, not the location's.  In
6903      case the target does not support read watchpoints, but does
6904      support access watchpoints, we'll have bp_read_watchpoint
6905      watchpoints with hw_access locations.  Those should be considered
6906      duplicates of hw_read locations.  The hw_read locations will
6907      become hw_access locations later.  */
6908   return (loc1->owner->type == loc2->owner->type
6909           && loc1->pspace->aspace == loc2->pspace->aspace
6910           && loc1->address == loc2->address
6911           && loc1->length == loc2->length);
6912 }
6913
6914 /* See breakpoint.h.  */
6915
6916 int
6917 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6918                           struct address_space *aspace2, CORE_ADDR addr2)
6919 {
6920   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6921            || aspace1 == aspace2)
6922           && addr1 == addr2);
6923 }
6924
6925 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6926    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6927    matches ASPACE2.  On targets that have global breakpoints, the address
6928    space doesn't really matter.  */
6929
6930 static int
6931 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6932                                 int len1, struct address_space *aspace2,
6933                                 CORE_ADDR addr2)
6934 {
6935   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6936            || aspace1 == aspace2)
6937           && addr2 >= addr1 && addr2 < addr1 + len1);
6938 }
6939
6940 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6941    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6942    matches the breakpoint's address space.  On targets that have global
6943    breakpoints, the address space doesn't really matter.  */
6944
6945 static int
6946 breakpoint_location_address_match (struct bp_location *bl,
6947                                    struct address_space *aspace,
6948                                    CORE_ADDR addr)
6949 {
6950   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6951                                     aspace, addr)
6952           || (bl->length
6953               && breakpoint_address_match_range (bl->pspace->aspace,
6954                                                  bl->address, bl->length,
6955                                                  aspace, addr)));
6956 }
6957
6958 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6959    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6960    true, otherwise returns false.  */
6961
6962 static int
6963 tracepoint_locations_match (struct bp_location *loc1,
6964                             struct bp_location *loc2)
6965 {
6966   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6967     /* Since tracepoint locations are never duplicated with others', tracepoint
6968        locations at the same address of different tracepoints are regarded as
6969        different locations.  */
6970     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6971   else
6972     return 0;
6973 }
6974
6975 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6976    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6977    represent the same location.  */
6978
6979 static int
6980 breakpoint_locations_match (struct bp_location *loc1, 
6981                             struct bp_location *loc2)
6982 {
6983   int hw_point1, hw_point2;
6984
6985   /* Both of them must not be in moribund_locations.  */
6986   gdb_assert (loc1->owner != NULL);
6987   gdb_assert (loc2->owner != NULL);
6988
6989   hw_point1 = is_hardware_watchpoint (loc1->owner);
6990   hw_point2 = is_hardware_watchpoint (loc2->owner);
6991
6992   if (hw_point1 != hw_point2)
6993     return 0;
6994   else if (hw_point1)
6995     return watchpoint_locations_match (loc1, loc2);
6996   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6997     return tracepoint_locations_match (loc1, loc2);
6998   else
6999     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7000     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7001                                      loc2->pspace->aspace, loc2->address)
7002             && loc1->length == loc2->length);
7003 }
7004
7005 static void
7006 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7007                                int bnum, int have_bnum)
7008 {
7009   /* The longest string possibly returned by hex_string_custom
7010      is 50 chars.  These must be at least that big for safety.  */
7011   char astr1[64];
7012   char astr2[64];
7013
7014   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7015   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7016   if (have_bnum)
7017     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7018              bnum, astr1, astr2);
7019   else
7020     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7021 }
7022
7023 /* Adjust a breakpoint's address to account for architectural
7024    constraints on breakpoint placement.  Return the adjusted address.
7025    Note: Very few targets require this kind of adjustment.  For most
7026    targets, this function is simply the identity function.  */
7027
7028 static CORE_ADDR
7029 adjust_breakpoint_address (struct gdbarch *gdbarch,
7030                            CORE_ADDR bpaddr, enum bptype bptype)
7031 {
7032   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7033     {
7034       /* Very few targets need any kind of breakpoint adjustment.  */
7035       return bpaddr;
7036     }
7037   else if (bptype == bp_watchpoint
7038            || bptype == bp_hardware_watchpoint
7039            || bptype == bp_read_watchpoint
7040            || bptype == bp_access_watchpoint
7041            || bptype == bp_catchpoint)
7042     {
7043       /* Watchpoints and the various bp_catch_* eventpoints should not
7044          have their addresses modified.  */
7045       return bpaddr;
7046     }
7047   else
7048     {
7049       CORE_ADDR adjusted_bpaddr;
7050
7051       /* Some targets have architectural constraints on the placement
7052          of breakpoint instructions.  Obtain the adjusted address.  */
7053       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7054
7055       /* An adjusted breakpoint address can significantly alter
7056          a user's expectations.  Print a warning if an adjustment
7057          is required.  */
7058       if (adjusted_bpaddr != bpaddr)
7059         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7060
7061       return adjusted_bpaddr;
7062     }
7063 }
7064
7065 void
7066 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7067                   struct breakpoint *owner)
7068 {
7069   memset (loc, 0, sizeof (*loc));
7070
7071   gdb_assert (ops != NULL);
7072
7073   loc->ops = ops;
7074   loc->owner = owner;
7075   loc->cond = NULL;
7076   loc->cond_bytecode = NULL;
7077   loc->shlib_disabled = 0;
7078   loc->enabled = 1;
7079
7080   switch (owner->type)
7081     {
7082     case bp_breakpoint:
7083     case bp_until:
7084     case bp_finish:
7085     case bp_longjmp:
7086     case bp_longjmp_resume:
7087     case bp_longjmp_call_dummy:
7088     case bp_exception:
7089     case bp_exception_resume:
7090     case bp_step_resume:
7091     case bp_hp_step_resume:
7092     case bp_watchpoint_scope:
7093     case bp_call_dummy:
7094     case bp_std_terminate:
7095     case bp_shlib_event:
7096     case bp_thread_event:
7097     case bp_overlay_event:
7098     case bp_jit_event:
7099     case bp_longjmp_master:
7100     case bp_std_terminate_master:
7101     case bp_exception_master:
7102     case bp_gnu_ifunc_resolver:
7103     case bp_gnu_ifunc_resolver_return:
7104     case bp_dprintf:
7105       loc->loc_type = bp_loc_software_breakpoint;
7106       mark_breakpoint_location_modified (loc);
7107       break;
7108     case bp_hardware_breakpoint:
7109       loc->loc_type = bp_loc_hardware_breakpoint;
7110       mark_breakpoint_location_modified (loc);
7111       break;
7112     case bp_hardware_watchpoint:
7113     case bp_read_watchpoint:
7114     case bp_access_watchpoint:
7115       loc->loc_type = bp_loc_hardware_watchpoint;
7116       break;
7117     case bp_watchpoint:
7118     case bp_catchpoint:
7119     case bp_tracepoint:
7120     case bp_fast_tracepoint:
7121     case bp_static_tracepoint:
7122       loc->loc_type = bp_loc_other;
7123       break;
7124     default:
7125       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7126     }
7127
7128   loc->refc = 1;
7129 }
7130
7131 /* Allocate a struct bp_location.  */
7132
7133 static struct bp_location *
7134 allocate_bp_location (struct breakpoint *bpt)
7135 {
7136   return bpt->ops->allocate_location (bpt);
7137 }
7138
7139 static void
7140 free_bp_location (struct bp_location *loc)
7141 {
7142   loc->ops->dtor (loc);
7143   xfree (loc);
7144 }
7145
7146 /* Increment reference count.  */
7147
7148 static void
7149 incref_bp_location (struct bp_location *bl)
7150 {
7151   ++bl->refc;
7152 }
7153
7154 /* Decrement reference count.  If the reference count reaches 0,
7155    destroy the bp_location.  Sets *BLP to NULL.  */
7156
7157 static void
7158 decref_bp_location (struct bp_location **blp)
7159 {
7160   gdb_assert ((*blp)->refc > 0);
7161
7162   if (--(*blp)->refc == 0)
7163     free_bp_location (*blp);
7164   *blp = NULL;
7165 }
7166
7167 /* Add breakpoint B at the end of the global breakpoint chain.  */
7168
7169 static void
7170 add_to_breakpoint_chain (struct breakpoint *b)
7171 {
7172   struct breakpoint *b1;
7173
7174   /* Add this breakpoint to the end of the chain so that a list of
7175      breakpoints will come out in order of increasing numbers.  */
7176
7177   b1 = breakpoint_chain;
7178   if (b1 == 0)
7179     breakpoint_chain = b;
7180   else
7181     {
7182       while (b1->next)
7183         b1 = b1->next;
7184       b1->next = b;
7185     }
7186 }
7187
7188 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7189
7190 static void
7191 init_raw_breakpoint_without_location (struct breakpoint *b,
7192                                       struct gdbarch *gdbarch,
7193                                       enum bptype bptype,
7194                                       const struct breakpoint_ops *ops)
7195 {
7196   memset (b, 0, sizeof (*b));
7197
7198   gdb_assert (ops != NULL);
7199
7200   b->ops = ops;
7201   b->type = bptype;
7202   b->gdbarch = gdbarch;
7203   b->language = current_language->la_language;
7204   b->input_radix = input_radix;
7205   b->thread = -1;
7206   b->enable_state = bp_enabled;
7207   b->next = 0;
7208   b->silent = 0;
7209   b->ignore_count = 0;
7210   b->commands = NULL;
7211   b->frame_id = null_frame_id;
7212   b->condition_not_parsed = 0;
7213   b->py_bp_object = NULL;
7214   b->related_breakpoint = b;
7215 }
7216
7217 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7218    that has type BPTYPE and has no locations as yet.  */
7219
7220 static struct breakpoint *
7221 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7222                                      enum bptype bptype,
7223                                      const struct breakpoint_ops *ops)
7224 {
7225   struct breakpoint *b = XNEW (struct breakpoint);
7226
7227   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7228   add_to_breakpoint_chain (b);
7229   return b;
7230 }
7231
7232 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7233    resolutions should be made as the user specified the location explicitly
7234    enough.  */
7235
7236 static void
7237 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7238 {
7239   gdb_assert (loc->owner != NULL);
7240
7241   if (loc->owner->type == bp_breakpoint
7242       || loc->owner->type == bp_hardware_breakpoint
7243       || is_tracepoint (loc->owner))
7244     {
7245       int is_gnu_ifunc;
7246       const char *function_name;
7247       CORE_ADDR func_addr;
7248
7249       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7250                                           &func_addr, NULL, &is_gnu_ifunc);
7251
7252       if (is_gnu_ifunc && !explicit_loc)
7253         {
7254           struct breakpoint *b = loc->owner;
7255
7256           gdb_assert (loc->pspace == current_program_space);
7257           if (gnu_ifunc_resolve_name (function_name,
7258                                       &loc->requested_address))
7259             {
7260               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7261               loc->address = adjust_breakpoint_address (loc->gdbarch,
7262                                                         loc->requested_address,
7263                                                         b->type);
7264             }
7265           else if (b->type == bp_breakpoint && b->loc == loc
7266                    && loc->next == NULL && b->related_breakpoint == b)
7267             {
7268               /* Create only the whole new breakpoint of this type but do not
7269                  mess more complicated breakpoints with multiple locations.  */
7270               b->type = bp_gnu_ifunc_resolver;
7271               /* Remember the resolver's address for use by the return
7272                  breakpoint.  */
7273               loc->related_address = func_addr;
7274             }
7275         }
7276
7277       if (function_name)
7278         loc->function_name = xstrdup (function_name);
7279     }
7280 }
7281
7282 /* Attempt to determine architecture of location identified by SAL.  */
7283 struct gdbarch *
7284 get_sal_arch (struct symtab_and_line sal)
7285 {
7286   if (sal.section)
7287     return get_objfile_arch (sal.section->objfile);
7288   if (sal.symtab)
7289     return get_objfile_arch (sal.symtab->objfile);
7290
7291   return NULL;
7292 }
7293
7294 /* Low level routine for partially initializing a breakpoint of type
7295    BPTYPE.  The newly created breakpoint's address, section, source
7296    file name, and line number are provided by SAL.
7297
7298    It is expected that the caller will complete the initialization of
7299    the newly created breakpoint struct as well as output any status
7300    information regarding the creation of a new breakpoint.  */
7301
7302 static void
7303 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7304                      struct symtab_and_line sal, enum bptype bptype,
7305                      const struct breakpoint_ops *ops)
7306 {
7307   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7308
7309   add_location_to_breakpoint (b, &sal);
7310
7311   if (bptype != bp_catchpoint)
7312     gdb_assert (sal.pspace != NULL);
7313
7314   /* Store the program space that was used to set the breakpoint,
7315      except for ordinary breakpoints, which are independent of the
7316      program space.  */
7317   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7318     b->pspace = sal.pspace;
7319 }
7320
7321 /* set_raw_breakpoint is a low level routine for allocating and
7322    partially initializing a breakpoint of type BPTYPE.  The newly
7323    created breakpoint's address, section, source file name, and line
7324    number are provided by SAL.  The newly created and partially
7325    initialized breakpoint is added to the breakpoint chain and
7326    is also returned as the value of this function.
7327
7328    It is expected that the caller will complete the initialization of
7329    the newly created breakpoint struct as well as output any status
7330    information regarding the creation of a new breakpoint.  In
7331    particular, set_raw_breakpoint does NOT set the breakpoint
7332    number!  Care should be taken to not allow an error to occur
7333    prior to completing the initialization of the breakpoint.  If this
7334    should happen, a bogus breakpoint will be left on the chain.  */
7335
7336 struct breakpoint *
7337 set_raw_breakpoint (struct gdbarch *gdbarch,
7338                     struct symtab_and_line sal, enum bptype bptype,
7339                     const struct breakpoint_ops *ops)
7340 {
7341   struct breakpoint *b = XNEW (struct breakpoint);
7342
7343   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7344   add_to_breakpoint_chain (b);
7345   return b;
7346 }
7347
7348
7349 /* Note that the breakpoint object B describes a permanent breakpoint
7350    instruction, hard-wired into the inferior's code.  */
7351 void
7352 make_breakpoint_permanent (struct breakpoint *b)
7353 {
7354   struct bp_location *bl;
7355
7356   b->enable_state = bp_permanent;
7357
7358   /* By definition, permanent breakpoints are already present in the
7359      code.  Mark all locations as inserted.  For now,
7360      make_breakpoint_permanent is called in just one place, so it's
7361      hard to say if it's reasonable to have permanent breakpoint with
7362      multiple locations or not, but it's easy to implement.  */
7363   for (bl = b->loc; bl; bl = bl->next)
7364     bl->inserted = 1;
7365 }
7366
7367 /* Call this routine when stepping and nexting to enable a breakpoint
7368    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7369    initiated the operation.  */
7370
7371 void
7372 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7373 {
7374   struct breakpoint *b, *b_tmp;
7375   int thread = tp->num;
7376
7377   /* To avoid having to rescan all objfile symbols at every step,
7378      we maintain a list of continually-inserted but always disabled
7379      longjmp "master" breakpoints.  Here, we simply create momentary
7380      clones of those and enable them for the requested thread.  */
7381   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7382     if (b->pspace == current_program_space
7383         && (b->type == bp_longjmp_master
7384             || b->type == bp_exception_master))
7385       {
7386         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7387         struct breakpoint *clone;
7388
7389         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7390            after their removal.  */
7391         clone = momentary_breakpoint_from_master (b, type,
7392                                                   &longjmp_breakpoint_ops, 1);
7393         clone->thread = thread;
7394       }
7395
7396   tp->initiating_frame = frame;
7397 }
7398
7399 /* Delete all longjmp breakpoints from THREAD.  */
7400 void
7401 delete_longjmp_breakpoint (int thread)
7402 {
7403   struct breakpoint *b, *b_tmp;
7404
7405   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7406     if (b->type == bp_longjmp || b->type == bp_exception)
7407       {
7408         if (b->thread == thread)
7409           delete_breakpoint (b);
7410       }
7411 }
7412
7413 void
7414 delete_longjmp_breakpoint_at_next_stop (int thread)
7415 {
7416   struct breakpoint *b, *b_tmp;
7417
7418   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7419     if (b->type == bp_longjmp || b->type == bp_exception)
7420       {
7421         if (b->thread == thread)
7422           b->disposition = disp_del_at_next_stop;
7423       }
7424 }
7425
7426 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7427    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7428    pointer to any of them.  Return NULL if this system cannot place longjmp
7429    breakpoints.  */
7430
7431 struct breakpoint *
7432 set_longjmp_breakpoint_for_call_dummy (void)
7433 {
7434   struct breakpoint *b, *retval = NULL;
7435
7436   ALL_BREAKPOINTS (b)
7437     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7438       {
7439         struct breakpoint *new_b;
7440
7441         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7442                                                   &momentary_breakpoint_ops,
7443                                                   1);
7444         new_b->thread = pid_to_thread_id (inferior_ptid);
7445
7446         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7447
7448         gdb_assert (new_b->related_breakpoint == new_b);
7449         if (retval == NULL)
7450           retval = new_b;
7451         new_b->related_breakpoint = retval;
7452         while (retval->related_breakpoint != new_b->related_breakpoint)
7453           retval = retval->related_breakpoint;
7454         retval->related_breakpoint = new_b;
7455       }
7456
7457   return retval;
7458 }
7459
7460 /* Verify all existing dummy frames and their associated breakpoints for
7461    TP.  Remove those which can no longer be found in the current frame
7462    stack.
7463
7464    You should call this function only at places where it is safe to currently
7465    unwind the whole stack.  Failed stack unwind would discard live dummy
7466    frames.  */
7467
7468 void
7469 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7470 {
7471   struct breakpoint *b, *b_tmp;
7472
7473   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7474     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7475       {
7476         struct breakpoint *dummy_b = b->related_breakpoint;
7477
7478         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7479           dummy_b = dummy_b->related_breakpoint;
7480         if (dummy_b->type != bp_call_dummy
7481             || frame_find_by_id (dummy_b->frame_id) != NULL)
7482           continue;
7483         
7484         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7485
7486         while (b->related_breakpoint != b)
7487           {
7488             if (b_tmp == b->related_breakpoint)
7489               b_tmp = b->related_breakpoint->next;
7490             delete_breakpoint (b->related_breakpoint);
7491           }
7492         delete_breakpoint (b);
7493       }
7494 }
7495
7496 void
7497 enable_overlay_breakpoints (void)
7498 {
7499   struct breakpoint *b;
7500
7501   ALL_BREAKPOINTS (b)
7502     if (b->type == bp_overlay_event)
7503     {
7504       b->enable_state = bp_enabled;
7505       update_global_location_list (1);
7506       overlay_events_enabled = 1;
7507     }
7508 }
7509
7510 void
7511 disable_overlay_breakpoints (void)
7512 {
7513   struct breakpoint *b;
7514
7515   ALL_BREAKPOINTS (b)
7516     if (b->type == bp_overlay_event)
7517     {
7518       b->enable_state = bp_disabled;
7519       update_global_location_list (0);
7520       overlay_events_enabled = 0;
7521     }
7522 }
7523
7524 /* Set an active std::terminate breakpoint for each std::terminate
7525    master breakpoint.  */
7526 void
7527 set_std_terminate_breakpoint (void)
7528 {
7529   struct breakpoint *b, *b_tmp;
7530
7531   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7532     if (b->pspace == current_program_space
7533         && b->type == bp_std_terminate_master)
7534       {
7535         momentary_breakpoint_from_master (b, bp_std_terminate,
7536                                           &momentary_breakpoint_ops, 1);
7537       }
7538 }
7539
7540 /* Delete all the std::terminate breakpoints.  */
7541 void
7542 delete_std_terminate_breakpoint (void)
7543 {
7544   struct breakpoint *b, *b_tmp;
7545
7546   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7547     if (b->type == bp_std_terminate)
7548       delete_breakpoint (b);
7549 }
7550
7551 struct breakpoint *
7552 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7553 {
7554   struct breakpoint *b;
7555
7556   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7557                                   &internal_breakpoint_ops);
7558
7559   b->enable_state = bp_enabled;
7560   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7561   b->addr_string
7562     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7563
7564   update_global_location_list_nothrow (1);
7565
7566   return b;
7567 }
7568
7569 void
7570 remove_thread_event_breakpoints (void)
7571 {
7572   struct breakpoint *b, *b_tmp;
7573
7574   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7575     if (b->type == bp_thread_event
7576         && b->loc->pspace == current_program_space)
7577       delete_breakpoint (b);
7578 }
7579
7580 struct lang_and_radix
7581   {
7582     enum language lang;
7583     int radix;
7584   };
7585
7586 /* Create a breakpoint for JIT code registration and unregistration.  */
7587
7588 struct breakpoint *
7589 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7590 {
7591   struct breakpoint *b;
7592
7593   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7594                                   &internal_breakpoint_ops);
7595   update_global_location_list_nothrow (1);
7596   return b;
7597 }
7598
7599 /* Remove JIT code registration and unregistration breakpoint(s).  */
7600
7601 void
7602 remove_jit_event_breakpoints (void)
7603 {
7604   struct breakpoint *b, *b_tmp;
7605
7606   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7607     if (b->type == bp_jit_event
7608         && b->loc->pspace == current_program_space)
7609       delete_breakpoint (b);
7610 }
7611
7612 void
7613 remove_solib_event_breakpoints (void)
7614 {
7615   struct breakpoint *b, *b_tmp;
7616
7617   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7618     if (b->type == bp_shlib_event
7619         && b->loc->pspace == current_program_space)
7620       delete_breakpoint (b);
7621 }
7622
7623 struct breakpoint *
7624 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7625 {
7626   struct breakpoint *b;
7627
7628   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7629                                   &internal_breakpoint_ops);
7630   update_global_location_list_nothrow (1);
7631   return b;
7632 }
7633
7634 /* Disable any breakpoints that are on code in shared libraries.  Only
7635    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7636
7637 void
7638 disable_breakpoints_in_shlibs (void)
7639 {
7640   struct bp_location *loc, **locp_tmp;
7641
7642   ALL_BP_LOCATIONS (loc, locp_tmp)
7643   {
7644     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7645     struct breakpoint *b = loc->owner;
7646
7647     /* We apply the check to all breakpoints, including disabled for
7648        those with loc->duplicate set.  This is so that when breakpoint
7649        becomes enabled, or the duplicate is removed, gdb will try to
7650        insert all breakpoints.  If we don't set shlib_disabled here,
7651        we'll try to insert those breakpoints and fail.  */
7652     if (((b->type == bp_breakpoint)
7653          || (b->type == bp_jit_event)
7654          || (b->type == bp_hardware_breakpoint)
7655          || (is_tracepoint (b)))
7656         && loc->pspace == current_program_space
7657         && !loc->shlib_disabled
7658         && solib_name_from_address (loc->pspace, loc->address)
7659         )
7660       {
7661         loc->shlib_disabled = 1;
7662       }
7663   }
7664 }
7665
7666 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7667    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7668    disabled ones can just stay disabled.  */
7669
7670 static void
7671 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7672 {
7673   struct bp_location *loc, **locp_tmp;
7674   int disabled_shlib_breaks = 0;
7675
7676   /* SunOS a.out shared libraries are always mapped, so do not
7677      disable breakpoints; they will only be reported as unloaded
7678      through clear_solib when GDB discards its shared library
7679      list.  See clear_solib for more information.  */
7680   if (exec_bfd != NULL
7681       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7682     return;
7683
7684   ALL_BP_LOCATIONS (loc, locp_tmp)
7685   {
7686     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7687     struct breakpoint *b = loc->owner;
7688
7689     if (solib->pspace == loc->pspace
7690         && !loc->shlib_disabled
7691         && (((b->type == bp_breakpoint
7692               || b->type == bp_jit_event
7693               || b->type == bp_hardware_breakpoint)
7694              && (loc->loc_type == bp_loc_hardware_breakpoint
7695                  || loc->loc_type == bp_loc_software_breakpoint))
7696             || is_tracepoint (b))
7697         && solib_contains_address_p (solib, loc->address))
7698       {
7699         loc->shlib_disabled = 1;
7700         /* At this point, we cannot rely on remove_breakpoint
7701            succeeding so we must mark the breakpoint as not inserted
7702            to prevent future errors occurring in remove_breakpoints.  */
7703         loc->inserted = 0;
7704
7705         /* This may cause duplicate notifications for the same breakpoint.  */
7706         observer_notify_breakpoint_modified (b);
7707
7708         if (!disabled_shlib_breaks)
7709           {
7710             target_terminal_ours_for_output ();
7711             warning (_("Temporarily disabling breakpoints "
7712                        "for unloaded shared library \"%s\""),
7713                      solib->so_name);
7714           }
7715         disabled_shlib_breaks = 1;
7716       }
7717   }
7718 }
7719
7720 /* Disable any breakpoints and tracepoints in OBJFILE upon
7721    notification of free_objfile.  Only apply to enabled breakpoints,
7722    disabled ones can just stay disabled.  */
7723
7724 static void
7725 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7726 {
7727   struct breakpoint *b;
7728
7729   if (objfile == NULL)
7730     return;
7731
7732   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7733      managed by the user with add-symbol-file/remove-symbol-file.
7734      Similarly to how breakpoints in shared libraries are handled in
7735      response to "nosharedlibrary", mark breakpoints in such modules
7736      shlib_disabled so they end up uninserted on the next global
7737      location list update.  Shared libraries not loaded by the user
7738      aren't handled here -- they're already handled in
7739      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7740      solib_unloaded observer.  We skip objfiles that are not
7741      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7742      main objfile).  */
7743   if ((objfile->flags & OBJF_SHARED) == 0
7744       || (objfile->flags & OBJF_USERLOADED) == 0)
7745     return;
7746
7747   ALL_BREAKPOINTS (b)
7748     {
7749       struct bp_location *loc;
7750       int bp_modified = 0;
7751
7752       if (!is_breakpoint (b) && !is_tracepoint (b))
7753         continue;
7754
7755       for (loc = b->loc; loc != NULL; loc = loc->next)
7756         {
7757           CORE_ADDR loc_addr = loc->address;
7758
7759           if (loc->loc_type != bp_loc_hardware_breakpoint
7760               && loc->loc_type != bp_loc_software_breakpoint)
7761             continue;
7762
7763           if (loc->shlib_disabled != 0)
7764             continue;
7765
7766           if (objfile->pspace != loc->pspace)
7767             continue;
7768
7769           if (loc->loc_type != bp_loc_hardware_breakpoint
7770               && loc->loc_type != bp_loc_software_breakpoint)
7771             continue;
7772
7773           if (is_addr_in_objfile (loc_addr, objfile))
7774             {
7775               loc->shlib_disabled = 1;
7776               /* At this point, we don't know whether the object was
7777                  unmapped from the inferior or not, so leave the
7778                  inserted flag alone.  We'll handle failure to
7779                  uninsert quietly, in case the object was indeed
7780                  unmapped.  */
7781
7782               mark_breakpoint_location_modified (loc);
7783
7784               bp_modified = 1;
7785             }
7786         }
7787
7788       if (bp_modified)
7789         observer_notify_breakpoint_modified (b);
7790     }
7791 }
7792
7793 /* FORK & VFORK catchpoints.  */
7794
7795 /* An instance of this type is used to represent a fork or vfork
7796    catchpoint.  It includes a "struct breakpoint" as a kind of base
7797    class; users downcast to "struct breakpoint *" when needed.  A
7798    breakpoint is really of this type iff its ops pointer points to
7799    CATCH_FORK_BREAKPOINT_OPS.  */
7800
7801 struct fork_catchpoint
7802 {
7803   /* The base class.  */
7804   struct breakpoint base;
7805
7806   /* Process id of a child process whose forking triggered this
7807      catchpoint.  This field is only valid immediately after this
7808      catchpoint has triggered.  */
7809   ptid_t forked_inferior_pid;
7810 };
7811
7812 /* Implement the "insert" breakpoint_ops method for fork
7813    catchpoints.  */
7814
7815 static int
7816 insert_catch_fork (struct bp_location *bl)
7817 {
7818   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7819 }
7820
7821 /* Implement the "remove" breakpoint_ops method for fork
7822    catchpoints.  */
7823
7824 static int
7825 remove_catch_fork (struct bp_location *bl)
7826 {
7827   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7828 }
7829
7830 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7831    catchpoints.  */
7832
7833 static int
7834 breakpoint_hit_catch_fork (const struct bp_location *bl,
7835                            struct address_space *aspace, CORE_ADDR bp_addr,
7836                            const struct target_waitstatus *ws)
7837 {
7838   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7839
7840   if (ws->kind != TARGET_WAITKIND_FORKED)
7841     return 0;
7842
7843   c->forked_inferior_pid = ws->value.related_pid;
7844   return 1;
7845 }
7846
7847 /* Implement the "print_it" breakpoint_ops method for fork
7848    catchpoints.  */
7849
7850 static enum print_stop_action
7851 print_it_catch_fork (bpstat bs)
7852 {
7853   struct ui_out *uiout = current_uiout;
7854   struct breakpoint *b = bs->breakpoint_at;
7855   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7856
7857   annotate_catchpoint (b->number);
7858   if (b->disposition == disp_del)
7859     ui_out_text (uiout, "\nTemporary catchpoint ");
7860   else
7861     ui_out_text (uiout, "\nCatchpoint ");
7862   if (ui_out_is_mi_like_p (uiout))
7863     {
7864       ui_out_field_string (uiout, "reason",
7865                            async_reason_lookup (EXEC_ASYNC_FORK));
7866       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7867     }
7868   ui_out_field_int (uiout, "bkptno", b->number);
7869   ui_out_text (uiout, " (forked process ");
7870   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7871   ui_out_text (uiout, "), ");
7872   return PRINT_SRC_AND_LOC;
7873 }
7874
7875 /* Implement the "print_one" breakpoint_ops method for fork
7876    catchpoints.  */
7877
7878 static void
7879 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7880 {
7881   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7882   struct value_print_options opts;
7883   struct ui_out *uiout = current_uiout;
7884
7885   get_user_print_options (&opts);
7886
7887   /* Field 4, the address, is omitted (which makes the columns not
7888      line up too nicely with the headers, but the effect is relatively
7889      readable).  */
7890   if (opts.addressprint)
7891     ui_out_field_skip (uiout, "addr");
7892   annotate_field (5);
7893   ui_out_text (uiout, "fork");
7894   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7895     {
7896       ui_out_text (uiout, ", process ");
7897       ui_out_field_int (uiout, "what",
7898                         ptid_get_pid (c->forked_inferior_pid));
7899       ui_out_spaces (uiout, 1);
7900     }
7901
7902   if (ui_out_is_mi_like_p (uiout))
7903     ui_out_field_string (uiout, "catch-type", "fork");
7904 }
7905
7906 /* Implement the "print_mention" breakpoint_ops method for fork
7907    catchpoints.  */
7908
7909 static void
7910 print_mention_catch_fork (struct breakpoint *b)
7911 {
7912   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7913 }
7914
7915 /* Implement the "print_recreate" breakpoint_ops method for fork
7916    catchpoints.  */
7917
7918 static void
7919 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7920 {
7921   fprintf_unfiltered (fp, "catch fork");
7922   print_recreate_thread (b, fp);
7923 }
7924
7925 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7926
7927 static struct breakpoint_ops catch_fork_breakpoint_ops;
7928
7929 /* Implement the "insert" breakpoint_ops method for vfork
7930    catchpoints.  */
7931
7932 static int
7933 insert_catch_vfork (struct bp_location *bl)
7934 {
7935   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7936 }
7937
7938 /* Implement the "remove" breakpoint_ops method for vfork
7939    catchpoints.  */
7940
7941 static int
7942 remove_catch_vfork (struct bp_location *bl)
7943 {
7944   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7945 }
7946
7947 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7948    catchpoints.  */
7949
7950 static int
7951 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7952                             struct address_space *aspace, CORE_ADDR bp_addr,
7953                             const struct target_waitstatus *ws)
7954 {
7955   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7956
7957   if (ws->kind != TARGET_WAITKIND_VFORKED)
7958     return 0;
7959
7960   c->forked_inferior_pid = ws->value.related_pid;
7961   return 1;
7962 }
7963
7964 /* Implement the "print_it" breakpoint_ops method for vfork
7965    catchpoints.  */
7966
7967 static enum print_stop_action
7968 print_it_catch_vfork (bpstat bs)
7969 {
7970   struct ui_out *uiout = current_uiout;
7971   struct breakpoint *b = bs->breakpoint_at;
7972   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7973
7974   annotate_catchpoint (b->number);
7975   if (b->disposition == disp_del)
7976     ui_out_text (uiout, "\nTemporary catchpoint ");
7977   else
7978     ui_out_text (uiout, "\nCatchpoint ");
7979   if (ui_out_is_mi_like_p (uiout))
7980     {
7981       ui_out_field_string (uiout, "reason",
7982                            async_reason_lookup (EXEC_ASYNC_VFORK));
7983       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7984     }
7985   ui_out_field_int (uiout, "bkptno", b->number);
7986   ui_out_text (uiout, " (vforked process ");
7987   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7988   ui_out_text (uiout, "), ");
7989   return PRINT_SRC_AND_LOC;
7990 }
7991
7992 /* Implement the "print_one" breakpoint_ops method for vfork
7993    catchpoints.  */
7994
7995 static void
7996 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7997 {
7998   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7999   struct value_print_options opts;
8000   struct ui_out *uiout = current_uiout;
8001
8002   get_user_print_options (&opts);
8003   /* Field 4, the address, is omitted (which makes the columns not
8004      line up too nicely with the headers, but the effect is relatively
8005      readable).  */
8006   if (opts.addressprint)
8007     ui_out_field_skip (uiout, "addr");
8008   annotate_field (5);
8009   ui_out_text (uiout, "vfork");
8010   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8011     {
8012       ui_out_text (uiout, ", process ");
8013       ui_out_field_int (uiout, "what",
8014                         ptid_get_pid (c->forked_inferior_pid));
8015       ui_out_spaces (uiout, 1);
8016     }
8017
8018   if (ui_out_is_mi_like_p (uiout))
8019     ui_out_field_string (uiout, "catch-type", "vfork");
8020 }
8021
8022 /* Implement the "print_mention" breakpoint_ops method for vfork
8023    catchpoints.  */
8024
8025 static void
8026 print_mention_catch_vfork (struct breakpoint *b)
8027 {
8028   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8029 }
8030
8031 /* Implement the "print_recreate" breakpoint_ops method for vfork
8032    catchpoints.  */
8033
8034 static void
8035 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8036 {
8037   fprintf_unfiltered (fp, "catch vfork");
8038   print_recreate_thread (b, fp);
8039 }
8040
8041 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8042
8043 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8044
8045 /* An instance of this type is used to represent an solib catchpoint.
8046    It includes a "struct breakpoint" as a kind of base class; users
8047    downcast to "struct breakpoint *" when needed.  A breakpoint is
8048    really of this type iff its ops pointer points to
8049    CATCH_SOLIB_BREAKPOINT_OPS.  */
8050
8051 struct solib_catchpoint
8052 {
8053   /* The base class.  */
8054   struct breakpoint base;
8055
8056   /* True for "catch load", false for "catch unload".  */
8057   unsigned char is_load;
8058
8059   /* Regular expression to match, if any.  COMPILED is only valid when
8060      REGEX is non-NULL.  */
8061   char *regex;
8062   regex_t compiled;
8063 };
8064
8065 static void
8066 dtor_catch_solib (struct breakpoint *b)
8067 {
8068   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8069
8070   if (self->regex)
8071     regfree (&self->compiled);
8072   xfree (self->regex);
8073
8074   base_breakpoint_ops.dtor (b);
8075 }
8076
8077 static int
8078 insert_catch_solib (struct bp_location *ignore)
8079 {
8080   return 0;
8081 }
8082
8083 static int
8084 remove_catch_solib (struct bp_location *ignore)
8085 {
8086   return 0;
8087 }
8088
8089 static int
8090 breakpoint_hit_catch_solib (const struct bp_location *bl,
8091                             struct address_space *aspace,
8092                             CORE_ADDR bp_addr,
8093                             const struct target_waitstatus *ws)
8094 {
8095   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8096   struct breakpoint *other;
8097
8098   if (ws->kind == TARGET_WAITKIND_LOADED)
8099     return 1;
8100
8101   ALL_BREAKPOINTS (other)
8102   {
8103     struct bp_location *other_bl;
8104
8105     if (other == bl->owner)
8106       continue;
8107
8108     if (other->type != bp_shlib_event)
8109       continue;
8110
8111     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8112       continue;
8113
8114     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8115       {
8116         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8117           return 1;
8118       }
8119   }
8120
8121   return 0;
8122 }
8123
8124 static void
8125 check_status_catch_solib (struct bpstats *bs)
8126 {
8127   struct solib_catchpoint *self
8128     = (struct solib_catchpoint *) bs->breakpoint_at;
8129   int ix;
8130
8131   if (self->is_load)
8132     {
8133       struct so_list *iter;
8134
8135       for (ix = 0;
8136            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8137                         ix, iter);
8138            ++ix)
8139         {
8140           if (!self->regex
8141               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8142             return;
8143         }
8144     }
8145   else
8146     {
8147       char *iter;
8148
8149       for (ix = 0;
8150            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8151                         ix, iter);
8152            ++ix)
8153         {
8154           if (!self->regex
8155               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8156             return;
8157         }
8158     }
8159
8160   bs->stop = 0;
8161   bs->print_it = print_it_noop;
8162 }
8163
8164 static enum print_stop_action
8165 print_it_catch_solib (bpstat bs)
8166 {
8167   struct breakpoint *b = bs->breakpoint_at;
8168   struct ui_out *uiout = current_uiout;
8169
8170   annotate_catchpoint (b->number);
8171   if (b->disposition == disp_del)
8172     ui_out_text (uiout, "\nTemporary catchpoint ");
8173   else
8174     ui_out_text (uiout, "\nCatchpoint ");
8175   ui_out_field_int (uiout, "bkptno", b->number);
8176   ui_out_text (uiout, "\n");
8177   if (ui_out_is_mi_like_p (uiout))
8178     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8179   print_solib_event (1);
8180   return PRINT_SRC_AND_LOC;
8181 }
8182
8183 static void
8184 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8185 {
8186   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8187   struct value_print_options opts;
8188   struct ui_out *uiout = current_uiout;
8189   char *msg;
8190
8191   get_user_print_options (&opts);
8192   /* Field 4, the address, is omitted (which makes the columns not
8193      line up too nicely with the headers, but the effect is relatively
8194      readable).  */
8195   if (opts.addressprint)
8196     {
8197       annotate_field (4);
8198       ui_out_field_skip (uiout, "addr");
8199     }
8200
8201   annotate_field (5);
8202   if (self->is_load)
8203     {
8204       if (self->regex)
8205         msg = xstrprintf (_("load of library matching %s"), self->regex);
8206       else
8207         msg = xstrdup (_("load of library"));
8208     }
8209   else
8210     {
8211       if (self->regex)
8212         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8213       else
8214         msg = xstrdup (_("unload of library"));
8215     }
8216   ui_out_field_string (uiout, "what", msg);
8217   xfree (msg);
8218
8219   if (ui_out_is_mi_like_p (uiout))
8220     ui_out_field_string (uiout, "catch-type",
8221                          self->is_load ? "load" : "unload");
8222 }
8223
8224 static void
8225 print_mention_catch_solib (struct breakpoint *b)
8226 {
8227   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8228
8229   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8230                    self->is_load ? "load" : "unload");
8231 }
8232
8233 static void
8234 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8235 {
8236   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8237
8238   fprintf_unfiltered (fp, "%s %s",
8239                       b->disposition == disp_del ? "tcatch" : "catch",
8240                       self->is_load ? "load" : "unload");
8241   if (self->regex)
8242     fprintf_unfiltered (fp, " %s", self->regex);
8243   fprintf_unfiltered (fp, "\n");
8244 }
8245
8246 static struct breakpoint_ops catch_solib_breakpoint_ops;
8247
8248 /* Shared helper function (MI and CLI) for creating and installing
8249    a shared object event catchpoint.  If IS_LOAD is non-zero then
8250    the events to be caught are load events, otherwise they are
8251    unload events.  If IS_TEMP is non-zero the catchpoint is a
8252    temporary one.  If ENABLED is non-zero the catchpoint is
8253    created in an enabled state.  */
8254
8255 void
8256 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8257 {
8258   struct solib_catchpoint *c;
8259   struct gdbarch *gdbarch = get_current_arch ();
8260   struct cleanup *cleanup;
8261
8262   if (!arg)
8263     arg = "";
8264   arg = skip_spaces (arg);
8265
8266   c = XCNEW (struct solib_catchpoint);
8267   cleanup = make_cleanup (xfree, c);
8268
8269   if (*arg != '\0')
8270     {
8271       int errcode;
8272
8273       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8274       if (errcode != 0)
8275         {
8276           char *err = get_regcomp_error (errcode, &c->compiled);
8277
8278           make_cleanup (xfree, err);
8279           error (_("Invalid regexp (%s): %s"), err, arg);
8280         }
8281       c->regex = xstrdup (arg);
8282     }
8283
8284   c->is_load = is_load;
8285   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8286                    &catch_solib_breakpoint_ops);
8287
8288   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8289
8290   discard_cleanups (cleanup);
8291   install_breakpoint (0, &c->base, 1);
8292 }
8293
8294 /* A helper function that does all the work for "catch load" and
8295    "catch unload".  */
8296
8297 static void
8298 catch_load_or_unload (char *arg, int from_tty, int is_load,
8299                       struct cmd_list_element *command)
8300 {
8301   int tempflag;
8302   const int enabled = 1;
8303
8304   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8305
8306   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8307 }
8308
8309 static void
8310 catch_load_command_1 (char *arg, int from_tty,
8311                       struct cmd_list_element *command)
8312 {
8313   catch_load_or_unload (arg, from_tty, 1, command);
8314 }
8315
8316 static void
8317 catch_unload_command_1 (char *arg, int from_tty,
8318                         struct cmd_list_element *command)
8319 {
8320   catch_load_or_unload (arg, from_tty, 0, command);
8321 }
8322
8323 /* An instance of this type is used to represent a syscall catchpoint.
8324    It includes a "struct breakpoint" as a kind of base class; users
8325    downcast to "struct breakpoint *" when needed.  A breakpoint is
8326    really of this type iff its ops pointer points to
8327    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8328
8329 struct syscall_catchpoint
8330 {
8331   /* The base class.  */
8332   struct breakpoint base;
8333
8334   /* Syscall numbers used for the 'catch syscall' feature.  If no
8335      syscall has been specified for filtering, its value is NULL.
8336      Otherwise, it holds a list of all syscalls to be caught.  The
8337      list elements are allocated with xmalloc.  */
8338   VEC(int) *syscalls_to_be_caught;
8339 };
8340
8341 /* Implement the "dtor" breakpoint_ops method for syscall
8342    catchpoints.  */
8343
8344 static void
8345 dtor_catch_syscall (struct breakpoint *b)
8346 {
8347   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8348
8349   VEC_free (int, c->syscalls_to_be_caught);
8350
8351   base_breakpoint_ops.dtor (b);
8352 }
8353
8354 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8355
8356 struct catch_syscall_inferior_data
8357 {
8358   /* We keep a count of the number of times the user has requested a
8359      particular syscall to be tracked, and pass this information to the
8360      target.  This lets capable targets implement filtering directly.  */
8361
8362   /* Number of times that "any" syscall is requested.  */
8363   int any_syscall_count;
8364
8365   /* Count of each system call.  */
8366   VEC(int) *syscalls_counts;
8367
8368   /* This counts all syscall catch requests, so we can readily determine
8369      if any catching is necessary.  */
8370   int total_syscalls_count;
8371 };
8372
8373 static struct catch_syscall_inferior_data*
8374 get_catch_syscall_inferior_data (struct inferior *inf)
8375 {
8376   struct catch_syscall_inferior_data *inf_data;
8377
8378   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8379   if (inf_data == NULL)
8380     {
8381       inf_data = XCNEW (struct catch_syscall_inferior_data);
8382       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8383     }
8384
8385   return inf_data;
8386 }
8387
8388 static void
8389 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8390 {
8391   xfree (arg);
8392 }
8393
8394
8395 /* Implement the "insert" breakpoint_ops method for syscall
8396    catchpoints.  */
8397
8398 static int
8399 insert_catch_syscall (struct bp_location *bl)
8400 {
8401   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8402   struct inferior *inf = current_inferior ();
8403   struct catch_syscall_inferior_data *inf_data
8404     = get_catch_syscall_inferior_data (inf);
8405
8406   ++inf_data->total_syscalls_count;
8407   if (!c->syscalls_to_be_caught)
8408     ++inf_data->any_syscall_count;
8409   else
8410     {
8411       int i, iter;
8412
8413       for (i = 0;
8414            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8415            i++)
8416         {
8417           int elem;
8418
8419           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8420             {
8421               int old_size = VEC_length (int, inf_data->syscalls_counts);
8422               uintptr_t vec_addr_offset
8423                 = old_size * ((uintptr_t) sizeof (int));
8424               uintptr_t vec_addr;
8425               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8426               vec_addr = ((uintptr_t) VEC_address (int,
8427                                                   inf_data->syscalls_counts)
8428                           + vec_addr_offset);
8429               memset ((void *) vec_addr, 0,
8430                       (iter + 1 - old_size) * sizeof (int));
8431             }
8432           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8433           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8434         }
8435     }
8436
8437   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8438                                         inf_data->total_syscalls_count != 0,
8439                                         inf_data->any_syscall_count,
8440                                         VEC_length (int,
8441                                                     inf_data->syscalls_counts),
8442                                         VEC_address (int,
8443                                                      inf_data->syscalls_counts));
8444 }
8445
8446 /* Implement the "remove" breakpoint_ops method for syscall
8447    catchpoints.  */
8448
8449 static int
8450 remove_catch_syscall (struct bp_location *bl)
8451 {
8452   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8453   struct inferior *inf = current_inferior ();
8454   struct catch_syscall_inferior_data *inf_data
8455     = get_catch_syscall_inferior_data (inf);
8456
8457   --inf_data->total_syscalls_count;
8458   if (!c->syscalls_to_be_caught)
8459     --inf_data->any_syscall_count;
8460   else
8461     {
8462       int i, iter;
8463
8464       for (i = 0;
8465            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8466            i++)
8467         {
8468           int elem;
8469           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8470             /* Shouldn't happen.  */
8471             continue;
8472           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8473           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8474         }
8475     }
8476
8477   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8478                                         inf_data->total_syscalls_count != 0,
8479                                         inf_data->any_syscall_count,
8480                                         VEC_length (int,
8481                                                     inf_data->syscalls_counts),
8482                                         VEC_address (int,
8483                                                      inf_data->syscalls_counts));
8484 }
8485
8486 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8487    catchpoints.  */
8488
8489 static int
8490 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8491                               struct address_space *aspace, CORE_ADDR bp_addr,
8492                               const struct target_waitstatus *ws)
8493 {
8494   /* We must check if we are catching specific syscalls in this
8495      breakpoint.  If we are, then we must guarantee that the called
8496      syscall is the same syscall we are catching.  */
8497   int syscall_number = 0;
8498   const struct syscall_catchpoint *c
8499     = (const struct syscall_catchpoint *) bl->owner;
8500
8501   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8502       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8503     return 0;
8504
8505   syscall_number = ws->value.syscall_number;
8506
8507   /* Now, checking if the syscall is the same.  */
8508   if (c->syscalls_to_be_caught)
8509     {
8510       int i, iter;
8511
8512       for (i = 0;
8513            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8514            i++)
8515         if (syscall_number == iter)
8516           return 1;
8517
8518       return 0;
8519     }
8520
8521   return 1;
8522 }
8523
8524 /* Implement the "print_it" breakpoint_ops method for syscall
8525    catchpoints.  */
8526
8527 static enum print_stop_action
8528 print_it_catch_syscall (bpstat bs)
8529 {
8530   struct ui_out *uiout = current_uiout;
8531   struct breakpoint *b = bs->breakpoint_at;
8532   /* These are needed because we want to know in which state a
8533      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8534      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8535      must print "called syscall" or "returned from syscall".  */
8536   ptid_t ptid;
8537   struct target_waitstatus last;
8538   struct syscall s;
8539
8540   get_last_target_status (&ptid, &last);
8541
8542   get_syscall_by_number (last.value.syscall_number, &s);
8543
8544   annotate_catchpoint (b->number);
8545
8546   if (b->disposition == disp_del)
8547     ui_out_text (uiout, "\nTemporary catchpoint ");
8548   else
8549     ui_out_text (uiout, "\nCatchpoint ");
8550   if (ui_out_is_mi_like_p (uiout))
8551     {
8552       ui_out_field_string (uiout, "reason",
8553                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8554                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8555                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8556       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8557     }
8558   ui_out_field_int (uiout, "bkptno", b->number);
8559
8560   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8561     ui_out_text (uiout, " (call to syscall ");
8562   else
8563     ui_out_text (uiout, " (returned from syscall ");
8564
8565   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8566     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8567   if (s.name != NULL)
8568     ui_out_field_string (uiout, "syscall-name", s.name);
8569
8570   ui_out_text (uiout, "), ");
8571
8572   return PRINT_SRC_AND_LOC;
8573 }
8574
8575 /* Implement the "print_one" breakpoint_ops method for syscall
8576    catchpoints.  */
8577
8578 static void
8579 print_one_catch_syscall (struct breakpoint *b,
8580                          struct bp_location **last_loc)
8581 {
8582   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8583   struct value_print_options opts;
8584   struct ui_out *uiout = current_uiout;
8585
8586   get_user_print_options (&opts);
8587   /* Field 4, the address, is omitted (which makes the columns not
8588      line up too nicely with the headers, but the effect is relatively
8589      readable).  */
8590   if (opts.addressprint)
8591     ui_out_field_skip (uiout, "addr");
8592   annotate_field (5);
8593
8594   if (c->syscalls_to_be_caught
8595       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8596     ui_out_text (uiout, "syscalls \"");
8597   else
8598     ui_out_text (uiout, "syscall \"");
8599
8600   if (c->syscalls_to_be_caught)
8601     {
8602       int i, iter;
8603       char *text = xstrprintf ("%s", "");
8604
8605       for (i = 0;
8606            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8607            i++)
8608         {
8609           char *x = text;
8610           struct syscall s;
8611           get_syscall_by_number (iter, &s);
8612
8613           if (s.name != NULL)
8614             text = xstrprintf ("%s%s, ", text, s.name);
8615           else
8616             text = xstrprintf ("%s%d, ", text, iter);
8617
8618           /* We have to xfree the last 'text' (now stored at 'x')
8619              because xstrprintf dynamically allocates new space for it
8620              on every call.  */
8621           xfree (x);
8622         }
8623       /* Remove the last comma.  */
8624       text[strlen (text) - 2] = '\0';
8625       ui_out_field_string (uiout, "what", text);
8626     }
8627   else
8628     ui_out_field_string (uiout, "what", "<any syscall>");
8629   ui_out_text (uiout, "\" ");
8630
8631   if (ui_out_is_mi_like_p (uiout))
8632     ui_out_field_string (uiout, "catch-type", "syscall");
8633 }
8634
8635 /* Implement the "print_mention" breakpoint_ops method for syscall
8636    catchpoints.  */
8637
8638 static void
8639 print_mention_catch_syscall (struct breakpoint *b)
8640 {
8641   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8642
8643   if (c->syscalls_to_be_caught)
8644     {
8645       int i, iter;
8646
8647       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8648         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8649       else
8650         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8651
8652       for (i = 0;
8653            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8654            i++)
8655         {
8656           struct syscall s;
8657           get_syscall_by_number (iter, &s);
8658
8659           if (s.name)
8660             printf_filtered (" '%s' [%d]", s.name, s.number);
8661           else
8662             printf_filtered (" %d", s.number);
8663         }
8664       printf_filtered (")");
8665     }
8666   else
8667     printf_filtered (_("Catchpoint %d (any syscall)"),
8668                      b->number);
8669 }
8670
8671 /* Implement the "print_recreate" breakpoint_ops method for syscall
8672    catchpoints.  */
8673
8674 static void
8675 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8676 {
8677   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8678
8679   fprintf_unfiltered (fp, "catch syscall");
8680
8681   if (c->syscalls_to_be_caught)
8682     {
8683       int i, iter;
8684
8685       for (i = 0;
8686            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8687            i++)
8688         {
8689           struct syscall s;
8690
8691           get_syscall_by_number (iter, &s);
8692           if (s.name)
8693             fprintf_unfiltered (fp, " %s", s.name);
8694           else
8695             fprintf_unfiltered (fp, " %d", s.number);
8696         }
8697     }
8698   print_recreate_thread (b, fp);
8699 }
8700
8701 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8702
8703 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8704
8705 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8706
8707 static int
8708 syscall_catchpoint_p (struct breakpoint *b)
8709 {
8710   return (b->ops == &catch_syscall_breakpoint_ops);
8711 }
8712
8713 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8714    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8715    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8716    the breakpoint_ops structure associated to the catchpoint.  */
8717
8718 void
8719 init_catchpoint (struct breakpoint *b,
8720                  struct gdbarch *gdbarch, int tempflag,
8721                  char *cond_string,
8722                  const struct breakpoint_ops *ops)
8723 {
8724   struct symtab_and_line sal;
8725
8726   init_sal (&sal);
8727   sal.pspace = current_program_space;
8728
8729   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8730
8731   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8732   b->disposition = tempflag ? disp_del : disp_donttouch;
8733 }
8734
8735 void
8736 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8737 {
8738   add_to_breakpoint_chain (b);
8739   set_breakpoint_number (internal, b);
8740   if (is_tracepoint (b))
8741     set_tracepoint_count (breakpoint_count);
8742   if (!internal)
8743     mention (b);
8744   observer_notify_breakpoint_created (b);
8745
8746   if (update_gll)
8747     update_global_location_list (1);
8748 }
8749
8750 static void
8751 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8752                                     int tempflag, char *cond_string,
8753                                     const struct breakpoint_ops *ops)
8754 {
8755   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8756
8757   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8758
8759   c->forked_inferior_pid = null_ptid;
8760
8761   install_breakpoint (0, &c->base, 1);
8762 }
8763
8764 /* Exec catchpoints.  */
8765
8766 /* An instance of this type is used to represent an exec catchpoint.
8767    It includes a "struct breakpoint" as a kind of base class; users
8768    downcast to "struct breakpoint *" when needed.  A breakpoint is
8769    really of this type iff its ops pointer points to
8770    CATCH_EXEC_BREAKPOINT_OPS.  */
8771
8772 struct exec_catchpoint
8773 {
8774   /* The base class.  */
8775   struct breakpoint base;
8776
8777   /* Filename of a program whose exec triggered this catchpoint.
8778      This field is only valid immediately after this catchpoint has
8779      triggered.  */
8780   char *exec_pathname;
8781 };
8782
8783 /* Implement the "dtor" breakpoint_ops method for exec
8784    catchpoints.  */
8785
8786 static void
8787 dtor_catch_exec (struct breakpoint *b)
8788 {
8789   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8790
8791   xfree (c->exec_pathname);
8792
8793   base_breakpoint_ops.dtor (b);
8794 }
8795
8796 static int
8797 insert_catch_exec (struct bp_location *bl)
8798 {
8799   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8800 }
8801
8802 static int
8803 remove_catch_exec (struct bp_location *bl)
8804 {
8805   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8806 }
8807
8808 static int
8809 breakpoint_hit_catch_exec (const struct bp_location *bl,
8810                            struct address_space *aspace, CORE_ADDR bp_addr,
8811                            const struct target_waitstatus *ws)
8812 {
8813   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8814
8815   if (ws->kind != TARGET_WAITKIND_EXECD)
8816     return 0;
8817
8818   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8819   return 1;
8820 }
8821
8822 static enum print_stop_action
8823 print_it_catch_exec (bpstat bs)
8824 {
8825   struct ui_out *uiout = current_uiout;
8826   struct breakpoint *b = bs->breakpoint_at;
8827   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8828
8829   annotate_catchpoint (b->number);
8830   if (b->disposition == disp_del)
8831     ui_out_text (uiout, "\nTemporary catchpoint ");
8832   else
8833     ui_out_text (uiout, "\nCatchpoint ");
8834   if (ui_out_is_mi_like_p (uiout))
8835     {
8836       ui_out_field_string (uiout, "reason",
8837                            async_reason_lookup (EXEC_ASYNC_EXEC));
8838       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8839     }
8840   ui_out_field_int (uiout, "bkptno", b->number);
8841   ui_out_text (uiout, " (exec'd ");
8842   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8843   ui_out_text (uiout, "), ");
8844
8845   return PRINT_SRC_AND_LOC;
8846 }
8847
8848 static void
8849 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8850 {
8851   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8852   struct value_print_options opts;
8853   struct ui_out *uiout = current_uiout;
8854
8855   get_user_print_options (&opts);
8856
8857   /* Field 4, the address, is omitted (which makes the columns
8858      not line up too nicely with the headers, but the effect
8859      is relatively readable).  */
8860   if (opts.addressprint)
8861     ui_out_field_skip (uiout, "addr");
8862   annotate_field (5);
8863   ui_out_text (uiout, "exec");
8864   if (c->exec_pathname != NULL)
8865     {
8866       ui_out_text (uiout, ", program \"");
8867       ui_out_field_string (uiout, "what", c->exec_pathname);
8868       ui_out_text (uiout, "\" ");
8869     }
8870
8871   if (ui_out_is_mi_like_p (uiout))
8872     ui_out_field_string (uiout, "catch-type", "exec");
8873 }
8874
8875 static void
8876 print_mention_catch_exec (struct breakpoint *b)
8877 {
8878   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8879 }
8880
8881 /* Implement the "print_recreate" breakpoint_ops method for exec
8882    catchpoints.  */
8883
8884 static void
8885 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8886 {
8887   fprintf_unfiltered (fp, "catch exec");
8888   print_recreate_thread (b, fp);
8889 }
8890
8891 static struct breakpoint_ops catch_exec_breakpoint_ops;
8892
8893 static void
8894 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8895                                  const struct breakpoint_ops *ops)
8896 {
8897   struct syscall_catchpoint *c;
8898   struct gdbarch *gdbarch = get_current_arch ();
8899
8900   c = XNEW (struct syscall_catchpoint);
8901   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8902   c->syscalls_to_be_caught = filter;
8903
8904   install_breakpoint (0, &c->base, 1);
8905 }
8906
8907 static int
8908 hw_breakpoint_used_count (void)
8909 {
8910   int i = 0;
8911   struct breakpoint *b;
8912   struct bp_location *bl;
8913
8914   ALL_BREAKPOINTS (b)
8915   {
8916     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8917       for (bl = b->loc; bl; bl = bl->next)
8918         {
8919           /* Special types of hardware breakpoints may use more than
8920              one register.  */
8921           i += b->ops->resources_needed (bl);
8922         }
8923   }
8924
8925   return i;
8926 }
8927
8928 /* Returns the resources B would use if it were a hardware
8929    watchpoint.  */
8930
8931 static int
8932 hw_watchpoint_use_count (struct breakpoint *b)
8933 {
8934   int i = 0;
8935   struct bp_location *bl;
8936
8937   if (!breakpoint_enabled (b))
8938     return 0;
8939
8940   for (bl = b->loc; bl; bl = bl->next)
8941     {
8942       /* Special types of hardware watchpoints may use more than
8943          one register.  */
8944       i += b->ops->resources_needed (bl);
8945     }
8946
8947   return i;
8948 }
8949
8950 /* Returns the sum the used resources of all hardware watchpoints of
8951    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8952    the sum of the used resources of all hardware watchpoints of other
8953    types _not_ TYPE.  */
8954
8955 static int
8956 hw_watchpoint_used_count_others (struct breakpoint *except,
8957                                  enum bptype type, int *other_type_used)
8958 {
8959   int i = 0;
8960   struct breakpoint *b;
8961
8962   *other_type_used = 0;
8963   ALL_BREAKPOINTS (b)
8964     {
8965       if (b == except)
8966         continue;
8967       if (!breakpoint_enabled (b))
8968         continue;
8969
8970       if (b->type == type)
8971         i += hw_watchpoint_use_count (b);
8972       else if (is_hardware_watchpoint (b))
8973         *other_type_used = 1;
8974     }
8975
8976   return i;
8977 }
8978
8979 void
8980 disable_watchpoints_before_interactive_call_start (void)
8981 {
8982   struct breakpoint *b;
8983
8984   ALL_BREAKPOINTS (b)
8985   {
8986     if (is_watchpoint (b) && breakpoint_enabled (b))
8987       {
8988         b->enable_state = bp_call_disabled;
8989         update_global_location_list (0);
8990       }
8991   }
8992 }
8993
8994 void
8995 enable_watchpoints_after_interactive_call_stop (void)
8996 {
8997   struct breakpoint *b;
8998
8999   ALL_BREAKPOINTS (b)
9000   {
9001     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9002       {
9003         b->enable_state = bp_enabled;
9004         update_global_location_list (1);
9005       }
9006   }
9007 }
9008
9009 void
9010 disable_breakpoints_before_startup (void)
9011 {
9012   current_program_space->executing_startup = 1;
9013   update_global_location_list (0);
9014 }
9015
9016 void
9017 enable_breakpoints_after_startup (void)
9018 {
9019   current_program_space->executing_startup = 0;
9020   breakpoint_re_set ();
9021 }
9022
9023
9024 /* Set a breakpoint that will evaporate an end of command
9025    at address specified by SAL.
9026    Restrict it to frame FRAME if FRAME is nonzero.  */
9027
9028 struct breakpoint *
9029 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9030                           struct frame_id frame_id, enum bptype type)
9031 {
9032   struct breakpoint *b;
9033
9034   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9035      tail-called one.  */
9036   gdb_assert (!frame_id_artificial_p (frame_id));
9037
9038   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9039   b->enable_state = bp_enabled;
9040   b->disposition = disp_donttouch;
9041   b->frame_id = frame_id;
9042
9043   /* If we're debugging a multi-threaded program, then we want
9044      momentary breakpoints to be active in only a single thread of
9045      control.  */
9046   if (in_thread_list (inferior_ptid))
9047     b->thread = pid_to_thread_id (inferior_ptid);
9048
9049   update_global_location_list_nothrow (1);
9050
9051   return b;
9052 }
9053
9054 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9055    The new breakpoint will have type TYPE, use OPS as its
9056    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9057
9058 static struct breakpoint *
9059 momentary_breakpoint_from_master (struct breakpoint *orig,
9060                                   enum bptype type,
9061                                   const struct breakpoint_ops *ops,
9062                                   int loc_enabled)
9063 {
9064   struct breakpoint *copy;
9065
9066   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9067   copy->loc = allocate_bp_location (copy);
9068   set_breakpoint_location_function (copy->loc, 1);
9069
9070   copy->loc->gdbarch = orig->loc->gdbarch;
9071   copy->loc->requested_address = orig->loc->requested_address;
9072   copy->loc->address = orig->loc->address;
9073   copy->loc->section = orig->loc->section;
9074   copy->loc->pspace = orig->loc->pspace;
9075   copy->loc->probe = orig->loc->probe;
9076   copy->loc->line_number = orig->loc->line_number;
9077   copy->loc->symtab = orig->loc->symtab;
9078   copy->loc->enabled = loc_enabled;
9079   copy->frame_id = orig->frame_id;
9080   copy->thread = orig->thread;
9081   copy->pspace = orig->pspace;
9082
9083   copy->enable_state = bp_enabled;
9084   copy->disposition = disp_donttouch;
9085   copy->number = internal_breakpoint_number--;
9086
9087   update_global_location_list_nothrow (0);
9088   return copy;
9089 }
9090
9091 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9092    ORIG is NULL.  */
9093
9094 struct breakpoint *
9095 clone_momentary_breakpoint (struct breakpoint *orig)
9096 {
9097   /* If there's nothing to clone, then return nothing.  */
9098   if (orig == NULL)
9099     return NULL;
9100
9101   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9102 }
9103
9104 struct breakpoint *
9105 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9106                                 enum bptype type)
9107 {
9108   struct symtab_and_line sal;
9109
9110   sal = find_pc_line (pc, 0);
9111   sal.pc = pc;
9112   sal.section = find_pc_overlay (pc);
9113   sal.explicit_pc = 1;
9114
9115   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9116 }
9117 \f
9118
9119 /* Tell the user we have just set a breakpoint B.  */
9120
9121 static void
9122 mention (struct breakpoint *b)
9123 {
9124   b->ops->print_mention (b);
9125   if (ui_out_is_mi_like_p (current_uiout))
9126     return;
9127   printf_filtered ("\n");
9128 }
9129 \f
9130
9131 static struct bp_location *
9132 add_location_to_breakpoint (struct breakpoint *b,
9133                             const struct symtab_and_line *sal)
9134 {
9135   struct bp_location *loc, **tmp;
9136   CORE_ADDR adjusted_address;
9137   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9138
9139   if (loc_gdbarch == NULL)
9140     loc_gdbarch = b->gdbarch;
9141
9142   /* Adjust the breakpoint's address prior to allocating a location.
9143      Once we call allocate_bp_location(), that mostly uninitialized
9144      location will be placed on the location chain.  Adjustment of the
9145      breakpoint may cause target_read_memory() to be called and we do
9146      not want its scan of the location chain to find a breakpoint and
9147      location that's only been partially initialized.  */
9148   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9149                                                 sal->pc, b->type);
9150
9151   /* Sort the locations by their ADDRESS.  */
9152   loc = allocate_bp_location (b);
9153   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9154        tmp = &((*tmp)->next))
9155     ;
9156   loc->next = *tmp;
9157   *tmp = loc;
9158
9159   loc->requested_address = sal->pc;
9160   loc->address = adjusted_address;
9161   loc->pspace = sal->pspace;
9162   loc->probe.probe = sal->probe;
9163   loc->probe.objfile = sal->objfile;
9164   gdb_assert (loc->pspace != NULL);
9165   loc->section = sal->section;
9166   loc->gdbarch = loc_gdbarch;
9167   loc->line_number = sal->line;
9168   loc->symtab = sal->symtab;
9169
9170   set_breakpoint_location_function (loc,
9171                                     sal->explicit_pc || sal->explicit_line);
9172   return loc;
9173 }
9174 \f
9175
9176 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9177    return 0 otherwise.  */
9178
9179 static int
9180 bp_loc_is_permanent (struct bp_location *loc)
9181 {
9182   int len;
9183   CORE_ADDR addr;
9184   const gdb_byte *bpoint;
9185   gdb_byte *target_mem;
9186   struct cleanup *cleanup;
9187   int retval = 0;
9188
9189   gdb_assert (loc != NULL);
9190
9191   addr = loc->address;
9192   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9193
9194   /* Software breakpoints unsupported?  */
9195   if (bpoint == NULL)
9196     return 0;
9197
9198   target_mem = alloca (len);
9199
9200   /* Enable the automatic memory restoration from breakpoints while
9201      we read the memory.  Otherwise we could say about our temporary
9202      breakpoints they are permanent.  */
9203   cleanup = save_current_space_and_thread ();
9204
9205   switch_to_program_space_and_thread (loc->pspace);
9206   make_show_memory_breakpoints_cleanup (0);
9207
9208   if (target_read_memory (loc->address, target_mem, len) == 0
9209       && memcmp (target_mem, bpoint, len) == 0)
9210     retval = 1;
9211
9212   do_cleanups (cleanup);
9213
9214   return retval;
9215 }
9216
9217 /* Build a command list for the dprintf corresponding to the current
9218    settings of the dprintf style options.  */
9219
9220 static void
9221 update_dprintf_command_list (struct breakpoint *b)
9222 {
9223   char *dprintf_args = b->extra_string;
9224   char *printf_line = NULL;
9225
9226   if (!dprintf_args)
9227     return;
9228
9229   dprintf_args = skip_spaces (dprintf_args);
9230
9231   /* Allow a comma, as it may have terminated a location, but don't
9232      insist on it.  */
9233   if (*dprintf_args == ',')
9234     ++dprintf_args;
9235   dprintf_args = skip_spaces (dprintf_args);
9236
9237   if (*dprintf_args != '"')
9238     error (_("Bad format string, missing '\"'."));
9239
9240   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9241     printf_line = xstrprintf ("printf %s", dprintf_args);
9242   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9243     {
9244       if (!dprintf_function)
9245         error (_("No function supplied for dprintf call"));
9246
9247       if (dprintf_channel && strlen (dprintf_channel) > 0)
9248         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9249                                   dprintf_function,
9250                                   dprintf_channel,
9251                                   dprintf_args);
9252       else
9253         printf_line = xstrprintf ("call (void) %s (%s)",
9254                                   dprintf_function,
9255                                   dprintf_args);
9256     }
9257   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9258     {
9259       if (target_can_run_breakpoint_commands ())
9260         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9261       else
9262         {
9263           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9264           printf_line = xstrprintf ("printf %s", dprintf_args);
9265         }
9266     }
9267   else
9268     internal_error (__FILE__, __LINE__,
9269                     _("Invalid dprintf style."));
9270
9271   gdb_assert (printf_line != NULL);
9272   /* Manufacture a printf sequence.  */
9273   {
9274     struct command_line *printf_cmd_line
9275       = xmalloc (sizeof (struct command_line));
9276
9277     printf_cmd_line = xmalloc (sizeof (struct command_line));
9278     printf_cmd_line->control_type = simple_control;
9279     printf_cmd_line->body_count = 0;
9280     printf_cmd_line->body_list = NULL;
9281     printf_cmd_line->next = NULL;
9282     printf_cmd_line->line = printf_line;
9283
9284     breakpoint_set_commands (b, printf_cmd_line);
9285   }
9286 }
9287
9288 /* Update all dprintf commands, making their command lists reflect
9289    current style settings.  */
9290
9291 static void
9292 update_dprintf_commands (char *args, int from_tty,
9293                          struct cmd_list_element *c)
9294 {
9295   struct breakpoint *b;
9296
9297   ALL_BREAKPOINTS (b)
9298     {
9299       if (b->type == bp_dprintf)
9300         update_dprintf_command_list (b);
9301     }
9302 }
9303
9304 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9305    as textual description of the location, and COND_STRING
9306    as condition expression.  */
9307
9308 static void
9309 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9310                      struct symtabs_and_lines sals, char *addr_string,
9311                      char *filter, char *cond_string,
9312                      char *extra_string,
9313                      enum bptype type, enum bpdisp disposition,
9314                      int thread, int task, int ignore_count,
9315                      const struct breakpoint_ops *ops, int from_tty,
9316                      int enabled, int internal, unsigned flags,
9317                      int display_canonical)
9318 {
9319   int i;
9320
9321   if (type == bp_hardware_breakpoint)
9322     {
9323       int target_resources_ok;
9324
9325       i = hw_breakpoint_used_count ();
9326       target_resources_ok =
9327         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9328                                             i + 1, 0);
9329       if (target_resources_ok == 0)
9330         error (_("No hardware breakpoint support in the target."));
9331       else if (target_resources_ok < 0)
9332         error (_("Hardware breakpoints used exceeds limit."));
9333     }
9334
9335   gdb_assert (sals.nelts > 0);
9336
9337   for (i = 0; i < sals.nelts; ++i)
9338     {
9339       struct symtab_and_line sal = sals.sals[i];
9340       struct bp_location *loc;
9341
9342       if (from_tty)
9343         {
9344           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9345           if (!loc_gdbarch)
9346             loc_gdbarch = gdbarch;
9347
9348           describe_other_breakpoints (loc_gdbarch,
9349                                       sal.pspace, sal.pc, sal.section, thread);
9350         }
9351
9352       if (i == 0)
9353         {
9354           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9355           b->thread = thread;
9356           b->task = task;
9357
9358           b->cond_string = cond_string;
9359           b->extra_string = extra_string;
9360           b->ignore_count = ignore_count;
9361           b->enable_state = enabled ? bp_enabled : bp_disabled;
9362           b->disposition = disposition;
9363
9364           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9365             b->loc->inserted = 1;
9366
9367           if (type == bp_static_tracepoint)
9368             {
9369               struct tracepoint *t = (struct tracepoint *) b;
9370               struct static_tracepoint_marker marker;
9371
9372               if (strace_marker_p (b))
9373                 {
9374                   /* We already know the marker exists, otherwise, we
9375                      wouldn't see a sal for it.  */
9376                   char *p = &addr_string[3];
9377                   char *endp;
9378                   char *marker_str;
9379
9380                   p = skip_spaces (p);
9381
9382                   endp = skip_to_space (p);
9383
9384                   marker_str = savestring (p, endp - p);
9385                   t->static_trace_marker_id = marker_str;
9386
9387                   printf_filtered (_("Probed static tracepoint "
9388                                      "marker \"%s\"\n"),
9389                                    t->static_trace_marker_id);
9390                 }
9391               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9392                 {
9393                   t->static_trace_marker_id = xstrdup (marker.str_id);
9394                   release_static_tracepoint_marker (&marker);
9395
9396                   printf_filtered (_("Probed static tracepoint "
9397                                      "marker \"%s\"\n"),
9398                                    t->static_trace_marker_id);
9399                 }
9400               else
9401                 warning (_("Couldn't determine the static "
9402                            "tracepoint marker to probe"));
9403             }
9404
9405           loc = b->loc;
9406         }
9407       else
9408         {
9409           loc = add_location_to_breakpoint (b, &sal);
9410           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9411             loc->inserted = 1;
9412         }
9413
9414       if (bp_loc_is_permanent (loc))
9415         make_breakpoint_permanent (b);
9416
9417       if (b->cond_string)
9418         {
9419           const char *arg = b->cond_string;
9420
9421           loc->cond = parse_exp_1 (&arg, loc->address,
9422                                    block_for_pc (loc->address), 0);
9423           if (*arg)
9424               error (_("Garbage '%s' follows condition"), arg);
9425         }
9426
9427       /* Dynamic printf requires and uses additional arguments on the
9428          command line, otherwise it's an error.  */
9429       if (type == bp_dprintf)
9430         {
9431           if (b->extra_string)
9432             update_dprintf_command_list (b);
9433           else
9434             error (_("Format string required"));
9435         }
9436       else if (b->extra_string)
9437         error (_("Garbage '%s' at end of command"), b->extra_string);
9438     }
9439
9440   b->display_canonical = display_canonical;
9441   if (addr_string)
9442     b->addr_string = addr_string;
9443   else
9444     /* addr_string has to be used or breakpoint_re_set will delete
9445        me.  */
9446     b->addr_string
9447       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9448   b->filter = filter;
9449 }
9450
9451 static void
9452 create_breakpoint_sal (struct gdbarch *gdbarch,
9453                        struct symtabs_and_lines sals, char *addr_string,
9454                        char *filter, char *cond_string,
9455                        char *extra_string,
9456                        enum bptype type, enum bpdisp disposition,
9457                        int thread, int task, int ignore_count,
9458                        const struct breakpoint_ops *ops, int from_tty,
9459                        int enabled, int internal, unsigned flags,
9460                        int display_canonical)
9461 {
9462   struct breakpoint *b;
9463   struct cleanup *old_chain;
9464
9465   if (is_tracepoint_type (type))
9466     {
9467       struct tracepoint *t;
9468
9469       t = XCNEW (struct tracepoint);
9470       b = &t->base;
9471     }
9472   else
9473     b = XNEW (struct breakpoint);
9474
9475   old_chain = make_cleanup (xfree, b);
9476
9477   init_breakpoint_sal (b, gdbarch,
9478                        sals, addr_string,
9479                        filter, cond_string, extra_string,
9480                        type, disposition,
9481                        thread, task, ignore_count,
9482                        ops, from_tty,
9483                        enabled, internal, flags,
9484                        display_canonical);
9485   discard_cleanups (old_chain);
9486
9487   install_breakpoint (internal, b, 0);
9488 }
9489
9490 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9491    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9492    value.  COND_STRING, if not NULL, specified the condition to be
9493    used for all breakpoints.  Essentially the only case where
9494    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9495    function.  In that case, it's still not possible to specify
9496    separate conditions for different overloaded functions, so
9497    we take just a single condition string.
9498    
9499    NOTE: If the function succeeds, the caller is expected to cleanup
9500    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9501    array contents).  If the function fails (error() is called), the
9502    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9503    COND and SALS arrays and each of those arrays contents.  */
9504
9505 static void
9506 create_breakpoints_sal (struct gdbarch *gdbarch,
9507                         struct linespec_result *canonical,
9508                         char *cond_string, char *extra_string,
9509                         enum bptype type, enum bpdisp disposition,
9510                         int thread, int task, int ignore_count,
9511                         const struct breakpoint_ops *ops, int from_tty,
9512                         int enabled, int internal, unsigned flags)
9513 {
9514   int i;
9515   struct linespec_sals *lsal;
9516
9517   if (canonical->pre_expanded)
9518     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9519
9520   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9521     {
9522       /* Note that 'addr_string' can be NULL in the case of a plain
9523          'break', without arguments.  */
9524       char *addr_string = (canonical->addr_string
9525                            ? xstrdup (canonical->addr_string)
9526                            : NULL);
9527       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9528       struct cleanup *inner = make_cleanup (xfree, addr_string);
9529
9530       make_cleanup (xfree, filter_string);
9531       create_breakpoint_sal (gdbarch, lsal->sals,
9532                              addr_string,
9533                              filter_string,
9534                              cond_string, extra_string,
9535                              type, disposition,
9536                              thread, task, ignore_count, ops,
9537                              from_tty, enabled, internal, flags,
9538                              canonical->special_display);
9539       discard_cleanups (inner);
9540     }
9541 }
9542
9543 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9544    followed by conditionals.  On return, SALS contains an array of SAL
9545    addresses found.  ADDR_STRING contains a vector of (canonical)
9546    address strings.  ADDRESS points to the end of the SAL.
9547
9548    The array and the line spec strings are allocated on the heap, it is
9549    the caller's responsibility to free them.  */
9550
9551 static void
9552 parse_breakpoint_sals (char **address,
9553                        struct linespec_result *canonical)
9554 {
9555   /* If no arg given, or if first arg is 'if ', use the default
9556      breakpoint.  */
9557   if ((*address) == NULL
9558       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9559     {
9560       /* The last displayed codepoint, if it's valid, is our default breakpoint
9561          address.  */
9562       if (last_displayed_sal_is_valid ())
9563         {
9564           struct linespec_sals lsal;
9565           struct symtab_and_line sal;
9566           CORE_ADDR pc;
9567
9568           init_sal (&sal);              /* Initialize to zeroes.  */
9569           lsal.sals.sals = (struct symtab_and_line *)
9570             xmalloc (sizeof (struct symtab_and_line));
9571
9572           /* Set sal's pspace, pc, symtab, and line to the values
9573              corresponding to the last call to print_frame_info.
9574              Be sure to reinitialize LINE with NOTCURRENT == 0
9575              as the breakpoint line number is inappropriate otherwise.
9576              find_pc_line would adjust PC, re-set it back.  */
9577           get_last_displayed_sal (&sal);
9578           pc = sal.pc;
9579           sal = find_pc_line (pc, 0);
9580
9581           /* "break" without arguments is equivalent to "break *PC"
9582              where PC is the last displayed codepoint's address.  So
9583              make sure to set sal.explicit_pc to prevent GDB from
9584              trying to expand the list of sals to include all other
9585              instances with the same symtab and line.  */
9586           sal.pc = pc;
9587           sal.explicit_pc = 1;
9588
9589           lsal.sals.sals[0] = sal;
9590           lsal.sals.nelts = 1;
9591           lsal.canonical = NULL;
9592
9593           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9594         }
9595       else
9596         error (_("No default breakpoint address now."));
9597     }
9598   else
9599     {
9600       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9601
9602       /* Force almost all breakpoints to be in terms of the
9603          current_source_symtab (which is decode_line_1's default).
9604          This should produce the results we want almost all of the
9605          time while leaving default_breakpoint_* alone.
9606
9607          ObjC: However, don't match an Objective-C method name which
9608          may have a '+' or '-' succeeded by a '['.  */
9609       if (last_displayed_sal_is_valid ()
9610           && (!cursal.symtab
9611               || ((strchr ("+-", (*address)[0]) != NULL)
9612                   && ((*address)[1] != '['))))
9613         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9614                           get_last_displayed_symtab (),
9615                           get_last_displayed_line (),
9616                           canonical, NULL, NULL);
9617       else
9618         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9619                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9620     }
9621 }
9622
9623
9624 /* Convert each SAL into a real PC.  Verify that the PC can be
9625    inserted as a breakpoint.  If it can't throw an error.  */
9626
9627 static void
9628 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9629 {    
9630   int i;
9631
9632   for (i = 0; i < sals->nelts; i++)
9633     resolve_sal_pc (&sals->sals[i]);
9634 }
9635
9636 /* Fast tracepoints may have restrictions on valid locations.  For
9637    instance, a fast tracepoint using a jump instead of a trap will
9638    likely have to overwrite more bytes than a trap would, and so can
9639    only be placed where the instruction is longer than the jump, or a
9640    multi-instruction sequence does not have a jump into the middle of
9641    it, etc.  */
9642
9643 static void
9644 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9645                             struct symtabs_and_lines *sals)
9646 {
9647   int i, rslt;
9648   struct symtab_and_line *sal;
9649   char *msg;
9650   struct cleanup *old_chain;
9651
9652   for (i = 0; i < sals->nelts; i++)
9653     {
9654       struct gdbarch *sarch;
9655
9656       sal = &sals->sals[i];
9657
9658       sarch = get_sal_arch (*sal);
9659       /* We fall back to GDBARCH if there is no architecture
9660          associated with SAL.  */
9661       if (sarch == NULL)
9662         sarch = gdbarch;
9663       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9664                                                NULL, &msg);
9665       old_chain = make_cleanup (xfree, msg);
9666
9667       if (!rslt)
9668         error (_("May not have a fast tracepoint at 0x%s%s"),
9669                paddress (sarch, sal->pc), (msg ? msg : ""));
9670
9671       do_cleanups (old_chain);
9672     }
9673 }
9674
9675 /* Issue an invalid thread ID error.  */
9676
9677 static void ATTRIBUTE_NORETURN
9678 invalid_thread_id_error (int id)
9679 {
9680   error (_("Unknown thread %d."), id);
9681 }
9682
9683 /* Given TOK, a string specification of condition and thread, as
9684    accepted by the 'break' command, extract the condition
9685    string and thread number and set *COND_STRING and *THREAD.
9686    PC identifies the context at which the condition should be parsed.
9687    If no condition is found, *COND_STRING is set to NULL.
9688    If no thread is found, *THREAD is set to -1.  */
9689
9690 static void
9691 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9692                            char **cond_string, int *thread, int *task,
9693                            char **rest)
9694 {
9695   *cond_string = NULL;
9696   *thread = -1;
9697   *task = 0;
9698   *rest = NULL;
9699
9700   while (tok && *tok)
9701     {
9702       const char *end_tok;
9703       int toklen;
9704       const char *cond_start = NULL;
9705       const char *cond_end = NULL;
9706
9707       tok = skip_spaces_const (tok);
9708
9709       if ((*tok == '"' || *tok == ',') && rest)
9710         {
9711           *rest = savestring (tok, strlen (tok));
9712           return;
9713         }
9714
9715       end_tok = skip_to_space_const (tok);
9716
9717       toklen = end_tok - tok;
9718
9719       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9720         {
9721           struct expression *expr;
9722
9723           tok = cond_start = end_tok + 1;
9724           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9725           xfree (expr);
9726           cond_end = tok;
9727           *cond_string = savestring (cond_start, cond_end - cond_start);
9728         }
9729       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9730         {
9731           char *tmptok;
9732
9733           tok = end_tok + 1;
9734           *thread = strtol (tok, &tmptok, 0);
9735           if (tok == tmptok)
9736             error (_("Junk after thread keyword."));
9737           if (!valid_thread_id (*thread))
9738             invalid_thread_id_error (*thread);
9739           tok = tmptok;
9740         }
9741       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9742         {
9743           char *tmptok;
9744
9745           tok = end_tok + 1;
9746           *task = strtol (tok, &tmptok, 0);
9747           if (tok == tmptok)
9748             error (_("Junk after task keyword."));
9749           if (!valid_task_id (*task))
9750             error (_("Unknown task %d."), *task);
9751           tok = tmptok;
9752         }
9753       else if (rest)
9754         {
9755           *rest = savestring (tok, strlen (tok));
9756           return;
9757         }
9758       else
9759         error (_("Junk at end of arguments."));
9760     }
9761 }
9762
9763 /* Decode a static tracepoint marker spec.  */
9764
9765 static struct symtabs_and_lines
9766 decode_static_tracepoint_spec (char **arg_p)
9767 {
9768   VEC(static_tracepoint_marker_p) *markers = NULL;
9769   struct symtabs_and_lines sals;
9770   struct cleanup *old_chain;
9771   char *p = &(*arg_p)[3];
9772   char *endp;
9773   char *marker_str;
9774   int i;
9775
9776   p = skip_spaces (p);
9777
9778   endp = skip_to_space (p);
9779
9780   marker_str = savestring (p, endp - p);
9781   old_chain = make_cleanup (xfree, marker_str);
9782
9783   markers = target_static_tracepoint_markers_by_strid (marker_str);
9784   if (VEC_empty(static_tracepoint_marker_p, markers))
9785     error (_("No known static tracepoint marker named %s"), marker_str);
9786
9787   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9788   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9789
9790   for (i = 0; i < sals.nelts; i++)
9791     {
9792       struct static_tracepoint_marker *marker;
9793
9794       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9795
9796       init_sal (&sals.sals[i]);
9797
9798       sals.sals[i] = find_pc_line (marker->address, 0);
9799       sals.sals[i].pc = marker->address;
9800
9801       release_static_tracepoint_marker (marker);
9802     }
9803
9804   do_cleanups (old_chain);
9805
9806   *arg_p = endp;
9807   return sals;
9808 }
9809
9810 /* Set a breakpoint.  This function is shared between CLI and MI
9811    functions for setting a breakpoint.  This function has two major
9812    modes of operations, selected by the PARSE_ARG parameter.  If
9813    non-zero, the function will parse ARG, extracting location,
9814    condition, thread and extra string.  Otherwise, ARG is just the
9815    breakpoint's location, with condition, thread, and extra string
9816    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9817    If INTERNAL is non-zero, the breakpoint number will be allocated
9818    from the internal breakpoint count.  Returns true if any breakpoint
9819    was created; false otherwise.  */
9820
9821 int
9822 create_breakpoint (struct gdbarch *gdbarch,
9823                    char *arg, char *cond_string,
9824                    int thread, char *extra_string,
9825                    int parse_arg,
9826                    int tempflag, enum bptype type_wanted,
9827                    int ignore_count,
9828                    enum auto_boolean pending_break_support,
9829                    const struct breakpoint_ops *ops,
9830                    int from_tty, int enabled, int internal,
9831                    unsigned flags)
9832 {
9833   volatile struct gdb_exception e;
9834   char *copy_arg = NULL;
9835   char *addr_start = arg;
9836   struct linespec_result canonical;
9837   struct cleanup *old_chain;
9838   struct cleanup *bkpt_chain = NULL;
9839   int pending = 0;
9840   int task = 0;
9841   int prev_bkpt_count = breakpoint_count;
9842
9843   gdb_assert (ops != NULL);
9844
9845   init_linespec_result (&canonical);
9846
9847   TRY_CATCH (e, RETURN_MASK_ALL)
9848     {
9849       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9850                                      addr_start, &copy_arg);
9851     }
9852
9853   /* If caller is interested in rc value from parse, set value.  */
9854   switch (e.reason)
9855     {
9856     case GDB_NO_ERROR:
9857       if (VEC_empty (linespec_sals, canonical.sals))
9858         return 0;
9859       break;
9860     case RETURN_ERROR:
9861       switch (e.error)
9862         {
9863         case NOT_FOUND_ERROR:
9864
9865           /* If pending breakpoint support is turned off, throw
9866              error.  */
9867
9868           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9869             throw_exception (e);
9870
9871           exception_print (gdb_stderr, e);
9872
9873           /* If pending breakpoint support is auto query and the user
9874              selects no, then simply return the error code.  */
9875           if (pending_break_support == AUTO_BOOLEAN_AUTO
9876               && !nquery (_("Make %s pending on future shared library load? "),
9877                           bptype_string (type_wanted)))
9878             return 0;
9879
9880           /* At this point, either the user was queried about setting
9881              a pending breakpoint and selected yes, or pending
9882              breakpoint behavior is on and thus a pending breakpoint
9883              is defaulted on behalf of the user.  */
9884           {
9885             struct linespec_sals lsal;
9886
9887             copy_arg = xstrdup (addr_start);
9888             lsal.canonical = xstrdup (copy_arg);
9889             lsal.sals.nelts = 1;
9890             lsal.sals.sals = XNEW (struct symtab_and_line);
9891             init_sal (&lsal.sals.sals[0]);
9892             pending = 1;
9893             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9894           }
9895           break;
9896         default:
9897           throw_exception (e);
9898         }
9899       break;
9900     default:
9901       throw_exception (e);
9902     }
9903
9904   /* Create a chain of things that always need to be cleaned up.  */
9905   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9906
9907   /* ----------------------------- SNIP -----------------------------
9908      Anything added to the cleanup chain beyond this point is assumed
9909      to be part of a breakpoint.  If the breakpoint create succeeds
9910      then the memory is not reclaimed.  */
9911   bkpt_chain = make_cleanup (null_cleanup, 0);
9912
9913   /* Resolve all line numbers to PC's and verify that the addresses
9914      are ok for the target.  */
9915   if (!pending)
9916     {
9917       int ix;
9918       struct linespec_sals *iter;
9919
9920       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9921         breakpoint_sals_to_pc (&iter->sals);
9922     }
9923
9924   /* Fast tracepoints may have additional restrictions on location.  */
9925   if (!pending && type_wanted == bp_fast_tracepoint)
9926     {
9927       int ix;
9928       struct linespec_sals *iter;
9929
9930       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9931         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9932     }
9933
9934   /* Verify that condition can be parsed, before setting any
9935      breakpoints.  Allocate a separate condition expression for each
9936      breakpoint.  */
9937   if (!pending)
9938     {
9939       if (parse_arg)
9940         {
9941           char *rest;
9942           struct linespec_sals *lsal;
9943
9944           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9945
9946           /* Here we only parse 'arg' to separate condition
9947              from thread number, so parsing in context of first
9948              sal is OK.  When setting the breakpoint we'll
9949              re-parse it in context of each sal.  */
9950
9951           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9952                                      &thread, &task, &rest);
9953           if (cond_string)
9954             make_cleanup (xfree, cond_string);
9955           if (rest)
9956             make_cleanup (xfree, rest);
9957           if (rest)
9958             extra_string = rest;
9959         }
9960       else
9961         {
9962           if (*arg != '\0')
9963             error (_("Garbage '%s' at end of location"), arg);
9964
9965           /* Create a private copy of condition string.  */
9966           if (cond_string)
9967             {
9968               cond_string = xstrdup (cond_string);
9969               make_cleanup (xfree, cond_string);
9970             }
9971           /* Create a private copy of any extra string.  */
9972           if (extra_string)
9973             {
9974               extra_string = xstrdup (extra_string);
9975               make_cleanup (xfree, extra_string);
9976             }
9977         }
9978
9979       ops->create_breakpoints_sal (gdbarch, &canonical,
9980                                    cond_string, extra_string, type_wanted,
9981                                    tempflag ? disp_del : disp_donttouch,
9982                                    thread, task, ignore_count, ops,
9983                                    from_tty, enabled, internal, flags);
9984     }
9985   else
9986     {
9987       struct breakpoint *b;
9988
9989       make_cleanup (xfree, copy_arg);
9990
9991       if (is_tracepoint_type (type_wanted))
9992         {
9993           struct tracepoint *t;
9994
9995           t = XCNEW (struct tracepoint);
9996           b = &t->base;
9997         }
9998       else
9999         b = XNEW (struct breakpoint);
10000
10001       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10002
10003       b->addr_string = copy_arg;
10004       if (parse_arg)
10005         b->cond_string = NULL;
10006       else
10007         {
10008           /* Create a private copy of condition string.  */
10009           if (cond_string)
10010             {
10011               cond_string = xstrdup (cond_string);
10012               make_cleanup (xfree, cond_string);
10013             }
10014           b->cond_string = cond_string;
10015         }
10016       b->extra_string = NULL;
10017       b->ignore_count = ignore_count;
10018       b->disposition = tempflag ? disp_del : disp_donttouch;
10019       b->condition_not_parsed = 1;
10020       b->enable_state = enabled ? bp_enabled : bp_disabled;
10021       if ((type_wanted != bp_breakpoint
10022            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10023         b->pspace = current_program_space;
10024
10025       install_breakpoint (internal, b, 0);
10026     }
10027   
10028   if (VEC_length (linespec_sals, canonical.sals) > 1)
10029     {
10030       warning (_("Multiple breakpoints were set.\nUse the "
10031                  "\"delete\" command to delete unwanted breakpoints."));
10032       prev_breakpoint_count = prev_bkpt_count;
10033     }
10034
10035   /* That's it.  Discard the cleanups for data inserted into the
10036      breakpoint.  */
10037   discard_cleanups (bkpt_chain);
10038   /* But cleanup everything else.  */
10039   do_cleanups (old_chain);
10040
10041   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10042   update_global_location_list (1);
10043
10044   return 1;
10045 }
10046
10047 /* Set a breakpoint.
10048    ARG is a string describing breakpoint address,
10049    condition, and thread.
10050    FLAG specifies if a breakpoint is hardware on,
10051    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10052    and BP_TEMPFLAG.  */
10053
10054 static void
10055 break_command_1 (char *arg, int flag, int from_tty)
10056 {
10057   int tempflag = flag & BP_TEMPFLAG;
10058   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10059                              ? bp_hardware_breakpoint
10060                              : bp_breakpoint);
10061   struct breakpoint_ops *ops;
10062   const char *arg_cp = arg;
10063
10064   /* Matching breakpoints on probes.  */
10065   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10066     ops = &bkpt_probe_breakpoint_ops;
10067   else
10068     ops = &bkpt_breakpoint_ops;
10069
10070   create_breakpoint (get_current_arch (),
10071                      arg,
10072                      NULL, 0, NULL, 1 /* parse arg */,
10073                      tempflag, type_wanted,
10074                      0 /* Ignore count */,
10075                      pending_break_support,
10076                      ops,
10077                      from_tty,
10078                      1 /* enabled */,
10079                      0 /* internal */,
10080                      0);
10081 }
10082
10083 /* Helper function for break_command_1 and disassemble_command.  */
10084
10085 void
10086 resolve_sal_pc (struct symtab_and_line *sal)
10087 {
10088   CORE_ADDR pc;
10089
10090   if (sal->pc == 0 && sal->symtab != NULL)
10091     {
10092       if (!find_line_pc (sal->symtab, sal->line, &pc))
10093         error (_("No line %d in file \"%s\"."),
10094                sal->line, symtab_to_filename_for_display (sal->symtab));
10095       sal->pc = pc;
10096
10097       /* If this SAL corresponds to a breakpoint inserted using a line
10098          number, then skip the function prologue if necessary.  */
10099       if (sal->explicit_line)
10100         skip_prologue_sal (sal);
10101     }
10102
10103   if (sal->section == 0 && sal->symtab != NULL)
10104     {
10105       const struct blockvector *bv;
10106       const struct block *b;
10107       struct symbol *sym;
10108
10109       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10110       if (bv != NULL)
10111         {
10112           sym = block_linkage_function (b);
10113           if (sym != NULL)
10114             {
10115               fixup_symbol_section (sym, sal->symtab->objfile);
10116               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10117             }
10118           else
10119             {
10120               /* It really is worthwhile to have the section, so we'll
10121                  just have to look harder. This case can be executed
10122                  if we have line numbers but no functions (as can
10123                  happen in assembly source).  */
10124
10125               struct bound_minimal_symbol msym;
10126               struct cleanup *old_chain = save_current_space_and_thread ();
10127
10128               switch_to_program_space_and_thread (sal->pspace);
10129
10130               msym = lookup_minimal_symbol_by_pc (sal->pc);
10131               if (msym.minsym)
10132                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10133
10134               do_cleanups (old_chain);
10135             }
10136         }
10137     }
10138 }
10139
10140 void
10141 break_command (char *arg, int from_tty)
10142 {
10143   break_command_1 (arg, 0, from_tty);
10144 }
10145
10146 void
10147 tbreak_command (char *arg, int from_tty)
10148 {
10149   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10150 }
10151
10152 static void
10153 hbreak_command (char *arg, int from_tty)
10154 {
10155   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10156 }
10157
10158 static void
10159 thbreak_command (char *arg, int from_tty)
10160 {
10161   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10162 }
10163
10164 static void
10165 stop_command (char *arg, int from_tty)
10166 {
10167   printf_filtered (_("Specify the type of breakpoint to set.\n\
10168 Usage: stop in <function | address>\n\
10169        stop at <line>\n"));
10170 }
10171
10172 static void
10173 stopin_command (char *arg, int from_tty)
10174 {
10175   int badInput = 0;
10176
10177   if (arg == (char *) NULL)
10178     badInput = 1;
10179   else if (*arg != '*')
10180     {
10181       char *argptr = arg;
10182       int hasColon = 0;
10183
10184       /* Look for a ':'.  If this is a line number specification, then
10185          say it is bad, otherwise, it should be an address or
10186          function/method name.  */
10187       while (*argptr && !hasColon)
10188         {
10189           hasColon = (*argptr == ':');
10190           argptr++;
10191         }
10192
10193       if (hasColon)
10194         badInput = (*argptr != ':');    /* Not a class::method */
10195       else
10196         badInput = isdigit (*arg);      /* a simple line number */
10197     }
10198
10199   if (badInput)
10200     printf_filtered (_("Usage: stop in <function | address>\n"));
10201   else
10202     break_command_1 (arg, 0, from_tty);
10203 }
10204
10205 static void
10206 stopat_command (char *arg, int from_tty)
10207 {
10208   int badInput = 0;
10209
10210   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10211     badInput = 1;
10212   else
10213     {
10214       char *argptr = arg;
10215       int hasColon = 0;
10216
10217       /* Look for a ':'.  If there is a '::' then get out, otherwise
10218          it is probably a line number.  */
10219       while (*argptr && !hasColon)
10220         {
10221           hasColon = (*argptr == ':');
10222           argptr++;
10223         }
10224
10225       if (hasColon)
10226         badInput = (*argptr == ':');    /* we have class::method */
10227       else
10228         badInput = !isdigit (*arg);     /* not a line number */
10229     }
10230
10231   if (badInput)
10232     printf_filtered (_("Usage: stop at <line>\n"));
10233   else
10234     break_command_1 (arg, 0, from_tty);
10235 }
10236
10237 /* The dynamic printf command is mostly like a regular breakpoint, but
10238    with a prewired command list consisting of a single output command,
10239    built from extra arguments supplied on the dprintf command
10240    line.  */
10241
10242 static void
10243 dprintf_command (char *arg, int from_tty)
10244 {
10245   create_breakpoint (get_current_arch (),
10246                      arg,
10247                      NULL, 0, NULL, 1 /* parse arg */,
10248                      0, bp_dprintf,
10249                      0 /* Ignore count */,
10250                      pending_break_support,
10251                      &dprintf_breakpoint_ops,
10252                      from_tty,
10253                      1 /* enabled */,
10254                      0 /* internal */,
10255                      0);
10256 }
10257
10258 static void
10259 agent_printf_command (char *arg, int from_tty)
10260 {
10261   error (_("May only run agent-printf on the target"));
10262 }
10263
10264 /* Implement the "breakpoint_hit" breakpoint_ops method for
10265    ranged breakpoints.  */
10266
10267 static int
10268 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10269                                   struct address_space *aspace,
10270                                   CORE_ADDR bp_addr,
10271                                   const struct target_waitstatus *ws)
10272 {
10273   if (ws->kind != TARGET_WAITKIND_STOPPED
10274       || ws->value.sig != GDB_SIGNAL_TRAP)
10275     return 0;
10276
10277   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10278                                          bl->length, aspace, bp_addr);
10279 }
10280
10281 /* Implement the "resources_needed" breakpoint_ops method for
10282    ranged breakpoints.  */
10283
10284 static int
10285 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10286 {
10287   return target_ranged_break_num_registers ();
10288 }
10289
10290 /* Implement the "print_it" breakpoint_ops method for
10291    ranged breakpoints.  */
10292
10293 static enum print_stop_action
10294 print_it_ranged_breakpoint (bpstat bs)
10295 {
10296   struct breakpoint *b = bs->breakpoint_at;
10297   struct bp_location *bl = b->loc;
10298   struct ui_out *uiout = current_uiout;
10299
10300   gdb_assert (b->type == bp_hardware_breakpoint);
10301
10302   /* Ranged breakpoints have only one location.  */
10303   gdb_assert (bl && bl->next == NULL);
10304
10305   annotate_breakpoint (b->number);
10306   if (b->disposition == disp_del)
10307     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10308   else
10309     ui_out_text (uiout, "\nRanged breakpoint ");
10310   if (ui_out_is_mi_like_p (uiout))
10311     {
10312       ui_out_field_string (uiout, "reason",
10313                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10314       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10315     }
10316   ui_out_field_int (uiout, "bkptno", b->number);
10317   ui_out_text (uiout, ", ");
10318
10319   return PRINT_SRC_AND_LOC;
10320 }
10321
10322 /* Implement the "print_one" breakpoint_ops method for
10323    ranged breakpoints.  */
10324
10325 static void
10326 print_one_ranged_breakpoint (struct breakpoint *b,
10327                              struct bp_location **last_loc)
10328 {
10329   struct bp_location *bl = b->loc;
10330   struct value_print_options opts;
10331   struct ui_out *uiout = current_uiout;
10332
10333   /* Ranged breakpoints have only one location.  */
10334   gdb_assert (bl && bl->next == NULL);
10335
10336   get_user_print_options (&opts);
10337
10338   if (opts.addressprint)
10339     /* We don't print the address range here, it will be printed later
10340        by print_one_detail_ranged_breakpoint.  */
10341     ui_out_field_skip (uiout, "addr");
10342   annotate_field (5);
10343   print_breakpoint_location (b, bl);
10344   *last_loc = bl;
10345 }
10346
10347 /* Implement the "print_one_detail" breakpoint_ops method for
10348    ranged breakpoints.  */
10349
10350 static void
10351 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10352                                     struct ui_out *uiout)
10353 {
10354   CORE_ADDR address_start, address_end;
10355   struct bp_location *bl = b->loc;
10356   struct ui_file *stb = mem_fileopen ();
10357   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10358
10359   gdb_assert (bl);
10360
10361   address_start = bl->address;
10362   address_end = address_start + bl->length - 1;
10363
10364   ui_out_text (uiout, "\taddress range: ");
10365   fprintf_unfiltered (stb, "[%s, %s]",
10366                       print_core_address (bl->gdbarch, address_start),
10367                       print_core_address (bl->gdbarch, address_end));
10368   ui_out_field_stream (uiout, "addr", stb);
10369   ui_out_text (uiout, "\n");
10370
10371   do_cleanups (cleanup);
10372 }
10373
10374 /* Implement the "print_mention" breakpoint_ops method for
10375    ranged breakpoints.  */
10376
10377 static void
10378 print_mention_ranged_breakpoint (struct breakpoint *b)
10379 {
10380   struct bp_location *bl = b->loc;
10381   struct ui_out *uiout = current_uiout;
10382
10383   gdb_assert (bl);
10384   gdb_assert (b->type == bp_hardware_breakpoint);
10385
10386   if (ui_out_is_mi_like_p (uiout))
10387     return;
10388
10389   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10390                    b->number, paddress (bl->gdbarch, bl->address),
10391                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10392 }
10393
10394 /* Implement the "print_recreate" breakpoint_ops method for
10395    ranged breakpoints.  */
10396
10397 static void
10398 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10399 {
10400   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10401                       b->addr_string_range_end);
10402   print_recreate_thread (b, fp);
10403 }
10404
10405 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10406
10407 static struct breakpoint_ops ranged_breakpoint_ops;
10408
10409 /* Find the address where the end of the breakpoint range should be
10410    placed, given the SAL of the end of the range.  This is so that if
10411    the user provides a line number, the end of the range is set to the
10412    last instruction of the given line.  */
10413
10414 static CORE_ADDR
10415 find_breakpoint_range_end (struct symtab_and_line sal)
10416 {
10417   CORE_ADDR end;
10418
10419   /* If the user provided a PC value, use it.  Otherwise,
10420      find the address of the end of the given location.  */
10421   if (sal.explicit_pc)
10422     end = sal.pc;
10423   else
10424     {
10425       int ret;
10426       CORE_ADDR start;
10427
10428       ret = find_line_pc_range (sal, &start, &end);
10429       if (!ret)
10430         error (_("Could not find location of the end of the range."));
10431
10432       /* find_line_pc_range returns the start of the next line.  */
10433       end--;
10434     }
10435
10436   return end;
10437 }
10438
10439 /* Implement the "break-range" CLI command.  */
10440
10441 static void
10442 break_range_command (char *arg, int from_tty)
10443 {
10444   char *arg_start, *addr_string_start, *addr_string_end;
10445   struct linespec_result canonical_start, canonical_end;
10446   int bp_count, can_use_bp, length;
10447   CORE_ADDR end;
10448   struct breakpoint *b;
10449   struct symtab_and_line sal_start, sal_end;
10450   struct cleanup *cleanup_bkpt;
10451   struct linespec_sals *lsal_start, *lsal_end;
10452
10453   /* We don't support software ranged breakpoints.  */
10454   if (target_ranged_break_num_registers () < 0)
10455     error (_("This target does not support hardware ranged breakpoints."));
10456
10457   bp_count = hw_breakpoint_used_count ();
10458   bp_count += target_ranged_break_num_registers ();
10459   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10460                                                    bp_count, 0);
10461   if (can_use_bp < 0)
10462     error (_("Hardware breakpoints used exceeds limit."));
10463
10464   arg = skip_spaces (arg);
10465   if (arg == NULL || arg[0] == '\0')
10466     error(_("No address range specified."));
10467
10468   init_linespec_result (&canonical_start);
10469
10470   arg_start = arg;
10471   parse_breakpoint_sals (&arg, &canonical_start);
10472
10473   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10474
10475   if (arg[0] != ',')
10476     error (_("Too few arguments."));
10477   else if (VEC_empty (linespec_sals, canonical_start.sals))
10478     error (_("Could not find location of the beginning of the range."));
10479
10480   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10481
10482   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10483       || lsal_start->sals.nelts != 1)
10484     error (_("Cannot create a ranged breakpoint with multiple locations."));
10485
10486   sal_start = lsal_start->sals.sals[0];
10487   addr_string_start = savestring (arg_start, arg - arg_start);
10488   make_cleanup (xfree, addr_string_start);
10489
10490   arg++;        /* Skip the comma.  */
10491   arg = skip_spaces (arg);
10492
10493   /* Parse the end location.  */
10494
10495   init_linespec_result (&canonical_end);
10496   arg_start = arg;
10497
10498   /* We call decode_line_full directly here instead of using
10499      parse_breakpoint_sals because we need to specify the start location's
10500      symtab and line as the default symtab and line for the end of the
10501      range.  This makes it possible to have ranges like "foo.c:27, +14",
10502      where +14 means 14 lines from the start location.  */
10503   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10504                     sal_start.symtab, sal_start.line,
10505                     &canonical_end, NULL, NULL);
10506
10507   make_cleanup_destroy_linespec_result (&canonical_end);
10508
10509   if (VEC_empty (linespec_sals, canonical_end.sals))
10510     error (_("Could not find location of the end of the range."));
10511
10512   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10513   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10514       || lsal_end->sals.nelts != 1)
10515     error (_("Cannot create a ranged breakpoint with multiple locations."));
10516
10517   sal_end = lsal_end->sals.sals[0];
10518   addr_string_end = savestring (arg_start, arg - arg_start);
10519   make_cleanup (xfree, addr_string_end);
10520
10521   end = find_breakpoint_range_end (sal_end);
10522   if (sal_start.pc > end)
10523     error (_("Invalid address range, end precedes start."));
10524
10525   length = end - sal_start.pc + 1;
10526   if (length < 0)
10527     /* Length overflowed.  */
10528     error (_("Address range too large."));
10529   else if (length == 1)
10530     {
10531       /* This range is simple enough to be handled by
10532          the `hbreak' command.  */
10533       hbreak_command (addr_string_start, 1);
10534
10535       do_cleanups (cleanup_bkpt);
10536
10537       return;
10538     }
10539
10540   /* Now set up the breakpoint.  */
10541   b = set_raw_breakpoint (get_current_arch (), sal_start,
10542                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10543   set_breakpoint_count (breakpoint_count + 1);
10544   b->number = breakpoint_count;
10545   b->disposition = disp_donttouch;
10546   b->addr_string = xstrdup (addr_string_start);
10547   b->addr_string_range_end = xstrdup (addr_string_end);
10548   b->loc->length = length;
10549
10550   do_cleanups (cleanup_bkpt);
10551
10552   mention (b);
10553   observer_notify_breakpoint_created (b);
10554   update_global_location_list (1);
10555 }
10556
10557 /*  Return non-zero if EXP is verified as constant.  Returned zero
10558     means EXP is variable.  Also the constant detection may fail for
10559     some constant expressions and in such case still falsely return
10560     zero.  */
10561
10562 static int
10563 watchpoint_exp_is_const (const struct expression *exp)
10564 {
10565   int i = exp->nelts;
10566
10567   while (i > 0)
10568     {
10569       int oplenp, argsp;
10570
10571       /* We are only interested in the descriptor of each element.  */
10572       operator_length (exp, i, &oplenp, &argsp);
10573       i -= oplenp;
10574
10575       switch (exp->elts[i].opcode)
10576         {
10577         case BINOP_ADD:
10578         case BINOP_SUB:
10579         case BINOP_MUL:
10580         case BINOP_DIV:
10581         case BINOP_REM:
10582         case BINOP_MOD:
10583         case BINOP_LSH:
10584         case BINOP_RSH:
10585         case BINOP_LOGICAL_AND:
10586         case BINOP_LOGICAL_OR:
10587         case BINOP_BITWISE_AND:
10588         case BINOP_BITWISE_IOR:
10589         case BINOP_BITWISE_XOR:
10590         case BINOP_EQUAL:
10591         case BINOP_NOTEQUAL:
10592         case BINOP_LESS:
10593         case BINOP_GTR:
10594         case BINOP_LEQ:
10595         case BINOP_GEQ:
10596         case BINOP_REPEAT:
10597         case BINOP_COMMA:
10598         case BINOP_EXP:
10599         case BINOP_MIN:
10600         case BINOP_MAX:
10601         case BINOP_INTDIV:
10602         case BINOP_CONCAT:
10603         case TERNOP_COND:
10604         case TERNOP_SLICE:
10605
10606         case OP_LONG:
10607         case OP_DOUBLE:
10608         case OP_DECFLOAT:
10609         case OP_LAST:
10610         case OP_COMPLEX:
10611         case OP_STRING:
10612         case OP_ARRAY:
10613         case OP_TYPE:
10614         case OP_TYPEOF:
10615         case OP_DECLTYPE:
10616         case OP_TYPEID:
10617         case OP_NAME:
10618         case OP_OBJC_NSSTRING:
10619
10620         case UNOP_NEG:
10621         case UNOP_LOGICAL_NOT:
10622         case UNOP_COMPLEMENT:
10623         case UNOP_ADDR:
10624         case UNOP_HIGH:
10625         case UNOP_CAST:
10626
10627         case UNOP_CAST_TYPE:
10628         case UNOP_REINTERPRET_CAST:
10629         case UNOP_DYNAMIC_CAST:
10630           /* Unary, binary and ternary operators: We have to check
10631              their operands.  If they are constant, then so is the
10632              result of that operation.  For instance, if A and B are
10633              determined to be constants, then so is "A + B".
10634
10635              UNOP_IND is one exception to the rule above, because the
10636              value of *ADDR is not necessarily a constant, even when
10637              ADDR is.  */
10638           break;
10639
10640         case OP_VAR_VALUE:
10641           /* Check whether the associated symbol is a constant.
10642
10643              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10644              possible that a buggy compiler could mark a variable as
10645              constant even when it is not, and TYPE_CONST would return
10646              true in this case, while SYMBOL_CLASS wouldn't.
10647
10648              We also have to check for function symbols because they
10649              are always constant.  */
10650           {
10651             struct symbol *s = exp->elts[i + 2].symbol;
10652
10653             if (SYMBOL_CLASS (s) != LOC_BLOCK
10654                 && SYMBOL_CLASS (s) != LOC_CONST
10655                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10656               return 0;
10657             break;
10658           }
10659
10660         /* The default action is to return 0 because we are using
10661            the optimistic approach here: If we don't know something,
10662            then it is not a constant.  */
10663         default:
10664           return 0;
10665         }
10666     }
10667
10668   return 1;
10669 }
10670
10671 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10672
10673 static void
10674 dtor_watchpoint (struct breakpoint *self)
10675 {
10676   struct watchpoint *w = (struct watchpoint *) self;
10677
10678   xfree (w->cond_exp);
10679   xfree (w->exp);
10680   xfree (w->exp_string);
10681   xfree (w->exp_string_reparse);
10682   value_free (w->val);
10683
10684   base_breakpoint_ops.dtor (self);
10685 }
10686
10687 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10688
10689 static void
10690 re_set_watchpoint (struct breakpoint *b)
10691 {
10692   struct watchpoint *w = (struct watchpoint *) b;
10693
10694   /* Watchpoint can be either on expression using entirely global
10695      variables, or it can be on local variables.
10696
10697      Watchpoints of the first kind are never auto-deleted, and even
10698      persist across program restarts.  Since they can use variables
10699      from shared libraries, we need to reparse expression as libraries
10700      are loaded and unloaded.
10701
10702      Watchpoints on local variables can also change meaning as result
10703      of solib event.  For example, if a watchpoint uses both a local
10704      and a global variables in expression, it's a local watchpoint,
10705      but unloading of a shared library will make the expression
10706      invalid.  This is not a very common use case, but we still
10707      re-evaluate expression, to avoid surprises to the user.
10708
10709      Note that for local watchpoints, we re-evaluate it only if
10710      watchpoints frame id is still valid.  If it's not, it means the
10711      watchpoint is out of scope and will be deleted soon.  In fact,
10712      I'm not sure we'll ever be called in this case.
10713
10714      If a local watchpoint's frame id is still valid, then
10715      w->exp_valid_block is likewise valid, and we can safely use it.
10716
10717      Don't do anything about disabled watchpoints, since they will be
10718      reevaluated again when enabled.  */
10719   update_watchpoint (w, 1 /* reparse */);
10720 }
10721
10722 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10723
10724 static int
10725 insert_watchpoint (struct bp_location *bl)
10726 {
10727   struct watchpoint *w = (struct watchpoint *) bl->owner;
10728   int length = w->exact ? 1 : bl->length;
10729
10730   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10731                                    w->cond_exp);
10732 }
10733
10734 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10735
10736 static int
10737 remove_watchpoint (struct bp_location *bl)
10738 {
10739   struct watchpoint *w = (struct watchpoint *) bl->owner;
10740   int length = w->exact ? 1 : bl->length;
10741
10742   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10743                                    w->cond_exp);
10744 }
10745
10746 static int
10747 breakpoint_hit_watchpoint (const struct bp_location *bl,
10748                            struct address_space *aspace, CORE_ADDR bp_addr,
10749                            const struct target_waitstatus *ws)
10750 {
10751   struct breakpoint *b = bl->owner;
10752   struct watchpoint *w = (struct watchpoint *) b;
10753
10754   /* Continuable hardware watchpoints are treated as non-existent if the
10755      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10756      some data address).  Otherwise gdb won't stop on a break instruction
10757      in the code (not from a breakpoint) when a hardware watchpoint has
10758      been defined.  Also skip watchpoints which we know did not trigger
10759      (did not match the data address).  */
10760   if (is_hardware_watchpoint (b)
10761       && w->watchpoint_triggered == watch_triggered_no)
10762     return 0;
10763
10764   return 1;
10765 }
10766
10767 static void
10768 check_status_watchpoint (bpstat bs)
10769 {
10770   gdb_assert (is_watchpoint (bs->breakpoint_at));
10771
10772   bpstat_check_watchpoint (bs);
10773 }
10774
10775 /* Implement the "resources_needed" breakpoint_ops method for
10776    hardware watchpoints.  */
10777
10778 static int
10779 resources_needed_watchpoint (const struct bp_location *bl)
10780 {
10781   struct watchpoint *w = (struct watchpoint *) bl->owner;
10782   int length = w->exact? 1 : bl->length;
10783
10784   return target_region_ok_for_hw_watchpoint (bl->address, length);
10785 }
10786
10787 /* Implement the "works_in_software_mode" breakpoint_ops method for
10788    hardware watchpoints.  */
10789
10790 static int
10791 works_in_software_mode_watchpoint (const struct breakpoint *b)
10792 {
10793   /* Read and access watchpoints only work with hardware support.  */
10794   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10795 }
10796
10797 static enum print_stop_action
10798 print_it_watchpoint (bpstat bs)
10799 {
10800   struct cleanup *old_chain;
10801   struct breakpoint *b;
10802   struct ui_file *stb;
10803   enum print_stop_action result;
10804   struct watchpoint *w;
10805   struct ui_out *uiout = current_uiout;
10806
10807   gdb_assert (bs->bp_location_at != NULL);
10808
10809   b = bs->breakpoint_at;
10810   w = (struct watchpoint *) b;
10811
10812   stb = mem_fileopen ();
10813   old_chain = make_cleanup_ui_file_delete (stb);
10814
10815   switch (b->type)
10816     {
10817     case bp_watchpoint:
10818     case bp_hardware_watchpoint:
10819       annotate_watchpoint (b->number);
10820       if (ui_out_is_mi_like_p (uiout))
10821         ui_out_field_string
10822           (uiout, "reason",
10823            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10824       mention (b);
10825       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10826       ui_out_text (uiout, "\nOld value = ");
10827       watchpoint_value_print (bs->old_val, stb);
10828       ui_out_field_stream (uiout, "old", stb);
10829       ui_out_text (uiout, "\nNew value = ");
10830       watchpoint_value_print (w->val, stb);
10831       ui_out_field_stream (uiout, "new", stb);
10832       ui_out_text (uiout, "\n");
10833       /* More than one watchpoint may have been triggered.  */
10834       result = PRINT_UNKNOWN;
10835       break;
10836
10837     case bp_read_watchpoint:
10838       if (ui_out_is_mi_like_p (uiout))
10839         ui_out_field_string
10840           (uiout, "reason",
10841            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10842       mention (b);
10843       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10844       ui_out_text (uiout, "\nValue = ");
10845       watchpoint_value_print (w->val, stb);
10846       ui_out_field_stream (uiout, "value", stb);
10847       ui_out_text (uiout, "\n");
10848       result = PRINT_UNKNOWN;
10849       break;
10850
10851     case bp_access_watchpoint:
10852       if (bs->old_val != NULL)
10853         {
10854           annotate_watchpoint (b->number);
10855           if (ui_out_is_mi_like_p (uiout))
10856             ui_out_field_string
10857               (uiout, "reason",
10858                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10859           mention (b);
10860           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10861           ui_out_text (uiout, "\nOld value = ");
10862           watchpoint_value_print (bs->old_val, stb);
10863           ui_out_field_stream (uiout, "old", stb);
10864           ui_out_text (uiout, "\nNew value = ");
10865         }
10866       else
10867         {
10868           mention (b);
10869           if (ui_out_is_mi_like_p (uiout))
10870             ui_out_field_string
10871               (uiout, "reason",
10872                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10873           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10874           ui_out_text (uiout, "\nValue = ");
10875         }
10876       watchpoint_value_print (w->val, stb);
10877       ui_out_field_stream (uiout, "new", stb);
10878       ui_out_text (uiout, "\n");
10879       result = PRINT_UNKNOWN;
10880       break;
10881     default:
10882       result = PRINT_UNKNOWN;
10883     }
10884
10885   do_cleanups (old_chain);
10886   return result;
10887 }
10888
10889 /* Implement the "print_mention" breakpoint_ops method for hardware
10890    watchpoints.  */
10891
10892 static void
10893 print_mention_watchpoint (struct breakpoint *b)
10894 {
10895   struct cleanup *ui_out_chain;
10896   struct watchpoint *w = (struct watchpoint *) b;
10897   struct ui_out *uiout = current_uiout;
10898
10899   switch (b->type)
10900     {
10901     case bp_watchpoint:
10902       ui_out_text (uiout, "Watchpoint ");
10903       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10904       break;
10905     case bp_hardware_watchpoint:
10906       ui_out_text (uiout, "Hardware watchpoint ");
10907       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10908       break;
10909     case bp_read_watchpoint:
10910       ui_out_text (uiout, "Hardware read watchpoint ");
10911       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10912       break;
10913     case bp_access_watchpoint:
10914       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10915       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10916       break;
10917     default:
10918       internal_error (__FILE__, __LINE__,
10919                       _("Invalid hardware watchpoint type."));
10920     }
10921
10922   ui_out_field_int (uiout, "number", b->number);
10923   ui_out_text (uiout, ": ");
10924   ui_out_field_string (uiout, "exp", w->exp_string);
10925   do_cleanups (ui_out_chain);
10926 }
10927
10928 /* Implement the "print_recreate" breakpoint_ops method for
10929    watchpoints.  */
10930
10931 static void
10932 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10933 {
10934   struct watchpoint *w = (struct watchpoint *) b;
10935
10936   switch (b->type)
10937     {
10938     case bp_watchpoint:
10939     case bp_hardware_watchpoint:
10940       fprintf_unfiltered (fp, "watch");
10941       break;
10942     case bp_read_watchpoint:
10943       fprintf_unfiltered (fp, "rwatch");
10944       break;
10945     case bp_access_watchpoint:
10946       fprintf_unfiltered (fp, "awatch");
10947       break;
10948     default:
10949       internal_error (__FILE__, __LINE__,
10950                       _("Invalid watchpoint type."));
10951     }
10952
10953   fprintf_unfiltered (fp, " %s", w->exp_string);
10954   print_recreate_thread (b, fp);
10955 }
10956
10957 /* Implement the "explains_signal" breakpoint_ops method for
10958    watchpoints.  */
10959
10960 static int
10961 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10962 {
10963   /* A software watchpoint cannot cause a signal other than
10964      GDB_SIGNAL_TRAP.  */
10965   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10966     return 0;
10967
10968   return 1;
10969 }
10970
10971 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10972
10973 static struct breakpoint_ops watchpoint_breakpoint_ops;
10974
10975 /* Implement the "insert" breakpoint_ops method for
10976    masked hardware watchpoints.  */
10977
10978 static int
10979 insert_masked_watchpoint (struct bp_location *bl)
10980 {
10981   struct watchpoint *w = (struct watchpoint *) bl->owner;
10982
10983   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10984                                         bl->watchpoint_type);
10985 }
10986
10987 /* Implement the "remove" breakpoint_ops method for
10988    masked hardware watchpoints.  */
10989
10990 static int
10991 remove_masked_watchpoint (struct bp_location *bl)
10992 {
10993   struct watchpoint *w = (struct watchpoint *) bl->owner;
10994
10995   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10996                                         bl->watchpoint_type);
10997 }
10998
10999 /* Implement the "resources_needed" breakpoint_ops method for
11000    masked hardware watchpoints.  */
11001
11002 static int
11003 resources_needed_masked_watchpoint (const struct bp_location *bl)
11004 {
11005   struct watchpoint *w = (struct watchpoint *) bl->owner;
11006
11007   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11008 }
11009
11010 /* Implement the "works_in_software_mode" breakpoint_ops method for
11011    masked hardware watchpoints.  */
11012
11013 static int
11014 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11015 {
11016   return 0;
11017 }
11018
11019 /* Implement the "print_it" breakpoint_ops method for
11020    masked hardware watchpoints.  */
11021
11022 static enum print_stop_action
11023 print_it_masked_watchpoint (bpstat bs)
11024 {
11025   struct breakpoint *b = bs->breakpoint_at;
11026   struct ui_out *uiout = current_uiout;
11027
11028   /* Masked watchpoints have only one location.  */
11029   gdb_assert (b->loc && b->loc->next == NULL);
11030
11031   switch (b->type)
11032     {
11033     case bp_hardware_watchpoint:
11034       annotate_watchpoint (b->number);
11035       if (ui_out_is_mi_like_p (uiout))
11036         ui_out_field_string
11037           (uiout, "reason",
11038            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11039       break;
11040
11041     case bp_read_watchpoint:
11042       if (ui_out_is_mi_like_p (uiout))
11043         ui_out_field_string
11044           (uiout, "reason",
11045            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11046       break;
11047
11048     case bp_access_watchpoint:
11049       if (ui_out_is_mi_like_p (uiout))
11050         ui_out_field_string
11051           (uiout, "reason",
11052            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11053       break;
11054     default:
11055       internal_error (__FILE__, __LINE__,
11056                       _("Invalid hardware watchpoint type."));
11057     }
11058
11059   mention (b);
11060   ui_out_text (uiout, _("\n\
11061 Check the underlying instruction at PC for the memory\n\
11062 address and value which triggered this watchpoint.\n"));
11063   ui_out_text (uiout, "\n");
11064
11065   /* More than one watchpoint may have been triggered.  */
11066   return PRINT_UNKNOWN;
11067 }
11068
11069 /* Implement the "print_one_detail" breakpoint_ops method for
11070    masked hardware watchpoints.  */
11071
11072 static void
11073 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11074                                     struct ui_out *uiout)
11075 {
11076   struct watchpoint *w = (struct watchpoint *) b;
11077
11078   /* Masked watchpoints have only one location.  */
11079   gdb_assert (b->loc && b->loc->next == NULL);
11080
11081   ui_out_text (uiout, "\tmask ");
11082   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11083   ui_out_text (uiout, "\n");
11084 }
11085
11086 /* Implement the "print_mention" breakpoint_ops method for
11087    masked hardware watchpoints.  */
11088
11089 static void
11090 print_mention_masked_watchpoint (struct breakpoint *b)
11091 {
11092   struct watchpoint *w = (struct watchpoint *) b;
11093   struct ui_out *uiout = current_uiout;
11094   struct cleanup *ui_out_chain;
11095
11096   switch (b->type)
11097     {
11098     case bp_hardware_watchpoint:
11099       ui_out_text (uiout, "Masked hardware watchpoint ");
11100       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11101       break;
11102     case bp_read_watchpoint:
11103       ui_out_text (uiout, "Masked hardware read watchpoint ");
11104       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11105       break;
11106     case bp_access_watchpoint:
11107       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11108       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11109       break;
11110     default:
11111       internal_error (__FILE__, __LINE__,
11112                       _("Invalid hardware watchpoint type."));
11113     }
11114
11115   ui_out_field_int (uiout, "number", b->number);
11116   ui_out_text (uiout, ": ");
11117   ui_out_field_string (uiout, "exp", w->exp_string);
11118   do_cleanups (ui_out_chain);
11119 }
11120
11121 /* Implement the "print_recreate" breakpoint_ops method for
11122    masked hardware watchpoints.  */
11123
11124 static void
11125 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11126 {
11127   struct watchpoint *w = (struct watchpoint *) b;
11128   char tmp[40];
11129
11130   switch (b->type)
11131     {
11132     case bp_hardware_watchpoint:
11133       fprintf_unfiltered (fp, "watch");
11134       break;
11135     case bp_read_watchpoint:
11136       fprintf_unfiltered (fp, "rwatch");
11137       break;
11138     case bp_access_watchpoint:
11139       fprintf_unfiltered (fp, "awatch");
11140       break;
11141     default:
11142       internal_error (__FILE__, __LINE__,
11143                       _("Invalid hardware watchpoint type."));
11144     }
11145
11146   sprintf_vma (tmp, w->hw_wp_mask);
11147   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11148   print_recreate_thread (b, fp);
11149 }
11150
11151 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11152
11153 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11154
11155 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11156
11157 static int
11158 is_masked_watchpoint (const struct breakpoint *b)
11159 {
11160   return b->ops == &masked_watchpoint_breakpoint_ops;
11161 }
11162
11163 /* accessflag:  hw_write:  watch write, 
11164                 hw_read:   watch read, 
11165                 hw_access: watch access (read or write) */
11166 static void
11167 watch_command_1 (const char *arg, int accessflag, int from_tty,
11168                  int just_location, int internal)
11169 {
11170   volatile struct gdb_exception e;
11171   struct breakpoint *b, *scope_breakpoint = NULL;
11172   struct expression *exp;
11173   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11174   struct value *val, *mark, *result;
11175   struct frame_info *frame;
11176   const char *exp_start = NULL;
11177   const char *exp_end = NULL;
11178   const char *tok, *end_tok;
11179   int toklen = -1;
11180   const char *cond_start = NULL;
11181   const char *cond_end = NULL;
11182   enum bptype bp_type;
11183   int thread = -1;
11184   int pc = 0;
11185   /* Flag to indicate whether we are going to use masks for
11186      the hardware watchpoint.  */
11187   int use_mask = 0;
11188   CORE_ADDR mask = 0;
11189   struct watchpoint *w;
11190   char *expression;
11191   struct cleanup *back_to;
11192
11193   /* Make sure that we actually have parameters to parse.  */
11194   if (arg != NULL && arg[0] != '\0')
11195     {
11196       const char *value_start;
11197
11198       exp_end = arg + strlen (arg);
11199
11200       /* Look for "parameter value" pairs at the end
11201          of the arguments string.  */
11202       for (tok = exp_end - 1; tok > arg; tok--)
11203         {
11204           /* Skip whitespace at the end of the argument list.  */
11205           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11206             tok--;
11207
11208           /* Find the beginning of the last token.
11209              This is the value of the parameter.  */
11210           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11211             tok--;
11212           value_start = tok + 1;
11213
11214           /* Skip whitespace.  */
11215           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11216             tok--;
11217
11218           end_tok = tok;
11219
11220           /* Find the beginning of the second to last token.
11221              This is the parameter itself.  */
11222           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11223             tok--;
11224           tok++;
11225           toklen = end_tok - tok + 1;
11226
11227           if (toklen == 6 && !strncmp (tok, "thread", 6))
11228             {
11229               /* At this point we've found a "thread" token, which means
11230                  the user is trying to set a watchpoint that triggers
11231                  only in a specific thread.  */
11232               char *endp;
11233
11234               if (thread != -1)
11235                 error(_("You can specify only one thread."));
11236
11237               /* Extract the thread ID from the next token.  */
11238               thread = strtol (value_start, &endp, 0);
11239
11240               /* Check if the user provided a valid numeric value for the
11241                  thread ID.  */
11242               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11243                 error (_("Invalid thread ID specification %s."), value_start);
11244
11245               /* Check if the thread actually exists.  */
11246               if (!valid_thread_id (thread))
11247                 invalid_thread_id_error (thread);
11248             }
11249           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11250             {
11251               /* We've found a "mask" token, which means the user wants to
11252                  create a hardware watchpoint that is going to have the mask
11253                  facility.  */
11254               struct value *mask_value, *mark;
11255
11256               if (use_mask)
11257                 error(_("You can specify only one mask."));
11258
11259               use_mask = just_location = 1;
11260
11261               mark = value_mark ();
11262               mask_value = parse_to_comma_and_eval (&value_start);
11263               mask = value_as_address (mask_value);
11264               value_free_to_mark (mark);
11265             }
11266           else
11267             /* We didn't recognize what we found.  We should stop here.  */
11268             break;
11269
11270           /* Truncate the string and get rid of the "parameter value" pair before
11271              the arguments string is parsed by the parse_exp_1 function.  */
11272           exp_end = tok;
11273         }
11274     }
11275   else
11276     exp_end = arg;
11277
11278   /* Parse the rest of the arguments.  From here on out, everything
11279      is in terms of a newly allocated string instead of the original
11280      ARG.  */
11281   innermost_block = NULL;
11282   expression = savestring (arg, exp_end - arg);
11283   back_to = make_cleanup (xfree, expression);
11284   exp_start = arg = expression;
11285   exp = parse_exp_1 (&arg, 0, 0, 0);
11286   exp_end = arg;
11287   /* Remove trailing whitespace from the expression before saving it.
11288      This makes the eventual display of the expression string a bit
11289      prettier.  */
11290   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11291     --exp_end;
11292
11293   /* Checking if the expression is not constant.  */
11294   if (watchpoint_exp_is_const (exp))
11295     {
11296       int len;
11297
11298       len = exp_end - exp_start;
11299       while (len > 0 && isspace (exp_start[len - 1]))
11300         len--;
11301       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11302     }
11303
11304   exp_valid_block = innermost_block;
11305   mark = value_mark ();
11306   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11307
11308   if (just_location)
11309     {
11310       int ret;
11311
11312       exp_valid_block = NULL;
11313       val = value_addr (result);
11314       release_value (val);
11315       value_free_to_mark (mark);
11316
11317       if (use_mask)
11318         {
11319           ret = target_masked_watch_num_registers (value_as_address (val),
11320                                                    mask);
11321           if (ret == -1)
11322             error (_("This target does not support masked watchpoints."));
11323           else if (ret == -2)
11324             error (_("Invalid mask or memory region."));
11325         }
11326     }
11327   else if (val != NULL)
11328     release_value (val);
11329
11330   tok = skip_spaces_const (arg);
11331   end_tok = skip_to_space_const (tok);
11332
11333   toklen = end_tok - tok;
11334   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11335     {
11336       struct expression *cond;
11337
11338       innermost_block = NULL;
11339       tok = cond_start = end_tok + 1;
11340       cond = parse_exp_1 (&tok, 0, 0, 0);
11341
11342       /* The watchpoint expression may not be local, but the condition
11343          may still be.  E.g.: `watch global if local > 0'.  */
11344       cond_exp_valid_block = innermost_block;
11345
11346       xfree (cond);
11347       cond_end = tok;
11348     }
11349   if (*tok)
11350     error (_("Junk at end of command."));
11351
11352   frame = block_innermost_frame (exp_valid_block);
11353
11354   /* If the expression is "local", then set up a "watchpoint scope"
11355      breakpoint at the point where we've left the scope of the watchpoint
11356      expression.  Create the scope breakpoint before the watchpoint, so
11357      that we will encounter it first in bpstat_stop_status.  */
11358   if (exp_valid_block && frame)
11359     {
11360       if (frame_id_p (frame_unwind_caller_id (frame)))
11361         {
11362           scope_breakpoint
11363             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11364                                           frame_unwind_caller_pc (frame),
11365                                           bp_watchpoint_scope,
11366                                           &momentary_breakpoint_ops);
11367
11368           scope_breakpoint->enable_state = bp_enabled;
11369
11370           /* Automatically delete the breakpoint when it hits.  */
11371           scope_breakpoint->disposition = disp_del;
11372
11373           /* Only break in the proper frame (help with recursion).  */
11374           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11375
11376           /* Set the address at which we will stop.  */
11377           scope_breakpoint->loc->gdbarch
11378             = frame_unwind_caller_arch (frame);
11379           scope_breakpoint->loc->requested_address
11380             = frame_unwind_caller_pc (frame);
11381           scope_breakpoint->loc->address
11382             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11383                                          scope_breakpoint->loc->requested_address,
11384                                          scope_breakpoint->type);
11385         }
11386     }
11387
11388   /* Now set up the breakpoint.  We create all watchpoints as hardware
11389      watchpoints here even if hardware watchpoints are turned off, a call
11390      to update_watchpoint later in this function will cause the type to
11391      drop back to bp_watchpoint (software watchpoint) if required.  */
11392
11393   if (accessflag == hw_read)
11394     bp_type = bp_read_watchpoint;
11395   else if (accessflag == hw_access)
11396     bp_type = bp_access_watchpoint;
11397   else
11398     bp_type = bp_hardware_watchpoint;
11399
11400   w = XCNEW (struct watchpoint);
11401   b = &w->base;
11402   if (use_mask)
11403     init_raw_breakpoint_without_location (b, NULL, bp_type,
11404                                           &masked_watchpoint_breakpoint_ops);
11405   else
11406     init_raw_breakpoint_without_location (b, NULL, bp_type,
11407                                           &watchpoint_breakpoint_ops);
11408   b->thread = thread;
11409   b->disposition = disp_donttouch;
11410   b->pspace = current_program_space;
11411   w->exp = exp;
11412   w->exp_valid_block = exp_valid_block;
11413   w->cond_exp_valid_block = cond_exp_valid_block;
11414   if (just_location)
11415     {
11416       struct type *t = value_type (val);
11417       CORE_ADDR addr = value_as_address (val);
11418       char *name;
11419
11420       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11421       name = type_to_string (t);
11422
11423       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11424                                           core_addr_to_string (addr));
11425       xfree (name);
11426
11427       w->exp_string = xstrprintf ("-location %.*s",
11428                                   (int) (exp_end - exp_start), exp_start);
11429
11430       /* The above expression is in C.  */
11431       b->language = language_c;
11432     }
11433   else
11434     w->exp_string = savestring (exp_start, exp_end - exp_start);
11435
11436   if (use_mask)
11437     {
11438       w->hw_wp_mask = mask;
11439     }
11440   else
11441     {
11442       w->val = val;
11443       w->val_valid = 1;
11444     }
11445
11446   if (cond_start)
11447     b->cond_string = savestring (cond_start, cond_end - cond_start);
11448   else
11449     b->cond_string = 0;
11450
11451   if (frame)
11452     {
11453       w->watchpoint_frame = get_frame_id (frame);
11454       w->watchpoint_thread = inferior_ptid;
11455     }
11456   else
11457     {
11458       w->watchpoint_frame = null_frame_id;
11459       w->watchpoint_thread = null_ptid;
11460     }
11461
11462   if (scope_breakpoint != NULL)
11463     {
11464       /* The scope breakpoint is related to the watchpoint.  We will
11465          need to act on them together.  */
11466       b->related_breakpoint = scope_breakpoint;
11467       scope_breakpoint->related_breakpoint = b;
11468     }
11469
11470   if (!just_location)
11471     value_free_to_mark (mark);
11472
11473   TRY_CATCH (e, RETURN_MASK_ALL)
11474     {
11475       /* Finally update the new watchpoint.  This creates the locations
11476          that should be inserted.  */
11477       update_watchpoint (w, 1);
11478     }
11479   if (e.reason < 0)
11480     {
11481       delete_breakpoint (b);
11482       throw_exception (e);
11483     }
11484
11485   install_breakpoint (internal, b, 1);
11486   do_cleanups (back_to);
11487 }
11488
11489 /* Return count of debug registers needed to watch the given expression.
11490    If the watchpoint cannot be handled in hardware return zero.  */
11491
11492 static int
11493 can_use_hardware_watchpoint (struct value *v)
11494 {
11495   int found_memory_cnt = 0;
11496   struct value *head = v;
11497
11498   /* Did the user specifically forbid us to use hardware watchpoints? */
11499   if (!can_use_hw_watchpoints)
11500     return 0;
11501
11502   /* Make sure that the value of the expression depends only upon
11503      memory contents, and values computed from them within GDB.  If we
11504      find any register references or function calls, we can't use a
11505      hardware watchpoint.
11506
11507      The idea here is that evaluating an expression generates a series
11508      of values, one holding the value of every subexpression.  (The
11509      expression a*b+c has five subexpressions: a, b, a*b, c, and
11510      a*b+c.)  GDB's values hold almost enough information to establish
11511      the criteria given above --- they identify memory lvalues,
11512      register lvalues, computed values, etcetera.  So we can evaluate
11513      the expression, and then scan the chain of values that leaves
11514      behind to decide whether we can detect any possible change to the
11515      expression's final value using only hardware watchpoints.
11516
11517      However, I don't think that the values returned by inferior
11518      function calls are special in any way.  So this function may not
11519      notice that an expression involving an inferior function call
11520      can't be watched with hardware watchpoints.  FIXME.  */
11521   for (; v; v = value_next (v))
11522     {
11523       if (VALUE_LVAL (v) == lval_memory)
11524         {
11525           if (v != head && value_lazy (v))
11526             /* A lazy memory lvalue in the chain is one that GDB never
11527                needed to fetch; we either just used its address (e.g.,
11528                `a' in `a.b') or we never needed it at all (e.g., `a'
11529                in `a,b').  This doesn't apply to HEAD; if that is
11530                lazy then it was not readable, but watch it anyway.  */
11531             ;
11532           else
11533             {
11534               /* Ahh, memory we actually used!  Check if we can cover
11535                  it with hardware watchpoints.  */
11536               struct type *vtype = check_typedef (value_type (v));
11537
11538               /* We only watch structs and arrays if user asked for it
11539                  explicitly, never if they just happen to appear in a
11540                  middle of some value chain.  */
11541               if (v == head
11542                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11543                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11544                 {
11545                   CORE_ADDR vaddr = value_address (v);
11546                   int len;
11547                   int num_regs;
11548
11549                   len = (target_exact_watchpoints
11550                          && is_scalar_type_recursive (vtype))?
11551                     1 : TYPE_LENGTH (value_type (v));
11552
11553                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11554                   if (!num_regs)
11555                     return 0;
11556                   else
11557                     found_memory_cnt += num_regs;
11558                 }
11559             }
11560         }
11561       else if (VALUE_LVAL (v) != not_lval
11562                && deprecated_value_modifiable (v) == 0)
11563         return 0;       /* These are values from the history (e.g., $1).  */
11564       else if (VALUE_LVAL (v) == lval_register)
11565         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11566     }
11567
11568   /* The expression itself looks suitable for using a hardware
11569      watchpoint, but give the target machine a chance to reject it.  */
11570   return found_memory_cnt;
11571 }
11572
11573 void
11574 watch_command_wrapper (char *arg, int from_tty, int internal)
11575 {
11576   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11577 }
11578
11579 /* A helper function that looks for the "-location" argument and then
11580    calls watch_command_1.  */
11581
11582 static void
11583 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11584 {
11585   int just_location = 0;
11586
11587   if (arg
11588       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11589           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11590     {
11591       arg = skip_spaces (arg);
11592       just_location = 1;
11593     }
11594
11595   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11596 }
11597
11598 static void
11599 watch_command (char *arg, int from_tty)
11600 {
11601   watch_maybe_just_location (arg, hw_write, from_tty);
11602 }
11603
11604 void
11605 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11606 {
11607   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11608 }
11609
11610 static void
11611 rwatch_command (char *arg, int from_tty)
11612 {
11613   watch_maybe_just_location (arg, hw_read, from_tty);
11614 }
11615
11616 void
11617 awatch_command_wrapper (char *arg, int from_tty, int internal)
11618 {
11619   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11620 }
11621
11622 static void
11623 awatch_command (char *arg, int from_tty)
11624 {
11625   watch_maybe_just_location (arg, hw_access, from_tty);
11626 }
11627 \f
11628
11629 /* Helper routines for the until_command routine in infcmd.c.  Here
11630    because it uses the mechanisms of breakpoints.  */
11631
11632 struct until_break_command_continuation_args
11633 {
11634   struct breakpoint *breakpoint;
11635   struct breakpoint *breakpoint2;
11636   int thread_num;
11637 };
11638
11639 /* This function is called by fetch_inferior_event via the
11640    cmd_continuation pointer, to complete the until command.  It takes
11641    care of cleaning up the temporary breakpoints set up by the until
11642    command.  */
11643 static void
11644 until_break_command_continuation (void *arg, int err)
11645 {
11646   struct until_break_command_continuation_args *a = arg;
11647
11648   delete_breakpoint (a->breakpoint);
11649   if (a->breakpoint2)
11650     delete_breakpoint (a->breakpoint2);
11651   delete_longjmp_breakpoint (a->thread_num);
11652 }
11653
11654 void
11655 until_break_command (char *arg, int from_tty, int anywhere)
11656 {
11657   struct symtabs_and_lines sals;
11658   struct symtab_and_line sal;
11659   struct frame_info *frame;
11660   struct gdbarch *frame_gdbarch;
11661   struct frame_id stack_frame_id;
11662   struct frame_id caller_frame_id;
11663   struct breakpoint *breakpoint;
11664   struct breakpoint *breakpoint2 = NULL;
11665   struct cleanup *old_chain;
11666   int thread;
11667   struct thread_info *tp;
11668
11669   clear_proceed_status (0);
11670
11671   /* Set a breakpoint where the user wants it and at return from
11672      this function.  */
11673
11674   if (last_displayed_sal_is_valid ())
11675     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11676                           get_last_displayed_symtab (),
11677                           get_last_displayed_line ());
11678   else
11679     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11680                           (struct symtab *) NULL, 0);
11681
11682   if (sals.nelts != 1)
11683     error (_("Couldn't get information on specified line."));
11684
11685   sal = sals.sals[0];
11686   xfree (sals.sals);    /* malloc'd, so freed.  */
11687
11688   if (*arg)
11689     error (_("Junk at end of arguments."));
11690
11691   resolve_sal_pc (&sal);
11692
11693   tp = inferior_thread ();
11694   thread = tp->num;
11695
11696   old_chain = make_cleanup (null_cleanup, NULL);
11697
11698   /* Note linespec handling above invalidates the frame chain.
11699      Installing a breakpoint also invalidates the frame chain (as it
11700      may need to switch threads), so do any frame handling before
11701      that.  */
11702
11703   frame = get_selected_frame (NULL);
11704   frame_gdbarch = get_frame_arch (frame);
11705   stack_frame_id = get_stack_frame_id (frame);
11706   caller_frame_id = frame_unwind_caller_id (frame);
11707
11708   /* Keep within the current frame, or in frames called by the current
11709      one.  */
11710
11711   if (frame_id_p (caller_frame_id))
11712     {
11713       struct symtab_and_line sal2;
11714
11715       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11716       sal2.pc = frame_unwind_caller_pc (frame);
11717       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11718                                               sal2,
11719                                               caller_frame_id,
11720                                               bp_until);
11721       make_cleanup_delete_breakpoint (breakpoint2);
11722
11723       set_longjmp_breakpoint (tp, caller_frame_id);
11724       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11725     }
11726
11727   /* set_momentary_breakpoint could invalidate FRAME.  */
11728   frame = NULL;
11729
11730   if (anywhere)
11731     /* If the user told us to continue until a specified location,
11732        we don't specify a frame at which we need to stop.  */
11733     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11734                                            null_frame_id, bp_until);
11735   else
11736     /* Otherwise, specify the selected frame, because we want to stop
11737        only at the very same frame.  */
11738     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11739                                            stack_frame_id, bp_until);
11740   make_cleanup_delete_breakpoint (breakpoint);
11741
11742   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11743
11744   /* If we are running asynchronously, and proceed call above has
11745      actually managed to start the target, arrange for breakpoints to
11746      be deleted when the target stops.  Otherwise, we're already
11747      stopped and delete breakpoints via cleanup chain.  */
11748
11749   if (target_can_async_p () && is_running (inferior_ptid))
11750     {
11751       struct until_break_command_continuation_args *args;
11752       args = xmalloc (sizeof (*args));
11753
11754       args->breakpoint = breakpoint;
11755       args->breakpoint2 = breakpoint2;
11756       args->thread_num = thread;
11757
11758       discard_cleanups (old_chain);
11759       add_continuation (inferior_thread (),
11760                         until_break_command_continuation, args,
11761                         xfree);
11762     }
11763   else
11764     do_cleanups (old_chain);
11765 }
11766
11767 /* This function attempts to parse an optional "if <cond>" clause
11768    from the arg string.  If one is not found, it returns NULL.
11769
11770    Else, it returns a pointer to the condition string.  (It does not
11771    attempt to evaluate the string against a particular block.)  And,
11772    it updates arg to point to the first character following the parsed
11773    if clause in the arg string.  */
11774
11775 char *
11776 ep_parse_optional_if_clause (char **arg)
11777 {
11778   char *cond_string;
11779
11780   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11781     return NULL;
11782
11783   /* Skip the "if" keyword.  */
11784   (*arg) += 2;
11785
11786   /* Skip any extra leading whitespace, and record the start of the
11787      condition string.  */
11788   *arg = skip_spaces (*arg);
11789   cond_string = *arg;
11790
11791   /* Assume that the condition occupies the remainder of the arg
11792      string.  */
11793   (*arg) += strlen (cond_string);
11794
11795   return cond_string;
11796 }
11797
11798 /* Commands to deal with catching events, such as signals, exceptions,
11799    process start/exit, etc.  */
11800
11801 typedef enum
11802 {
11803   catch_fork_temporary, catch_vfork_temporary,
11804   catch_fork_permanent, catch_vfork_permanent
11805 }
11806 catch_fork_kind;
11807
11808 static void
11809 catch_fork_command_1 (char *arg, int from_tty, 
11810                       struct cmd_list_element *command)
11811 {
11812   struct gdbarch *gdbarch = get_current_arch ();
11813   char *cond_string = NULL;
11814   catch_fork_kind fork_kind;
11815   int tempflag;
11816
11817   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11818   tempflag = (fork_kind == catch_fork_temporary
11819               || fork_kind == catch_vfork_temporary);
11820
11821   if (!arg)
11822     arg = "";
11823   arg = skip_spaces (arg);
11824
11825   /* The allowed syntax is:
11826      catch [v]fork
11827      catch [v]fork if <cond>
11828
11829      First, check if there's an if clause.  */
11830   cond_string = ep_parse_optional_if_clause (&arg);
11831
11832   if ((*arg != '\0') && !isspace (*arg))
11833     error (_("Junk at end of arguments."));
11834
11835   /* If this target supports it, create a fork or vfork catchpoint
11836      and enable reporting of such events.  */
11837   switch (fork_kind)
11838     {
11839     case catch_fork_temporary:
11840     case catch_fork_permanent:
11841       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11842                                           &catch_fork_breakpoint_ops);
11843       break;
11844     case catch_vfork_temporary:
11845     case catch_vfork_permanent:
11846       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11847                                           &catch_vfork_breakpoint_ops);
11848       break;
11849     default:
11850       error (_("unsupported or unknown fork kind; cannot catch it"));
11851       break;
11852     }
11853 }
11854
11855 static void
11856 catch_exec_command_1 (char *arg, int from_tty, 
11857                       struct cmd_list_element *command)
11858 {
11859   struct exec_catchpoint *c;
11860   struct gdbarch *gdbarch = get_current_arch ();
11861   int tempflag;
11862   char *cond_string = NULL;
11863
11864   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11865
11866   if (!arg)
11867     arg = "";
11868   arg = skip_spaces (arg);
11869
11870   /* The allowed syntax is:
11871      catch exec
11872      catch exec if <cond>
11873
11874      First, check if there's an if clause.  */
11875   cond_string = ep_parse_optional_if_clause (&arg);
11876
11877   if ((*arg != '\0') && !isspace (*arg))
11878     error (_("Junk at end of arguments."));
11879
11880   c = XNEW (struct exec_catchpoint);
11881   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11882                    &catch_exec_breakpoint_ops);
11883   c->exec_pathname = NULL;
11884
11885   install_breakpoint (0, &c->base, 1);
11886 }
11887
11888 void
11889 init_ada_exception_breakpoint (struct breakpoint *b,
11890                                struct gdbarch *gdbarch,
11891                                struct symtab_and_line sal,
11892                                char *addr_string,
11893                                const struct breakpoint_ops *ops,
11894                                int tempflag,
11895                                int enabled,
11896                                int from_tty)
11897 {
11898   if (from_tty)
11899     {
11900       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11901       if (!loc_gdbarch)
11902         loc_gdbarch = gdbarch;
11903
11904       describe_other_breakpoints (loc_gdbarch,
11905                                   sal.pspace, sal.pc, sal.section, -1);
11906       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11907          version for exception catchpoints, because two catchpoints
11908          used for different exception names will use the same address.
11909          In this case, a "breakpoint ... also set at..." warning is
11910          unproductive.  Besides, the warning phrasing is also a bit
11911          inappropriate, we should use the word catchpoint, and tell
11912          the user what type of catchpoint it is.  The above is good
11913          enough for now, though.  */
11914     }
11915
11916   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11917
11918   b->enable_state = enabled ? bp_enabled : bp_disabled;
11919   b->disposition = tempflag ? disp_del : disp_donttouch;
11920   b->addr_string = addr_string;
11921   b->language = language_ada;
11922 }
11923
11924 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11925    filter list, or NULL if no filtering is required.  */
11926 static VEC(int) *
11927 catch_syscall_split_args (char *arg)
11928 {
11929   VEC(int) *result = NULL;
11930   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11931
11932   while (*arg != '\0')
11933     {
11934       int i, syscall_number;
11935       char *endptr;
11936       char cur_name[128];
11937       struct syscall s;
11938
11939       /* Skip whitespace.  */
11940       arg = skip_spaces (arg);
11941
11942       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11943         cur_name[i] = arg[i];
11944       cur_name[i] = '\0';
11945       arg += i;
11946
11947       /* Check if the user provided a syscall name or a number.  */
11948       syscall_number = (int) strtol (cur_name, &endptr, 0);
11949       if (*endptr == '\0')
11950         get_syscall_by_number (syscall_number, &s);
11951       else
11952         {
11953           /* We have a name.  Let's check if it's valid and convert it
11954              to a number.  */
11955           get_syscall_by_name (cur_name, &s);
11956
11957           if (s.number == UNKNOWN_SYSCALL)
11958             /* Here we have to issue an error instead of a warning,
11959                because GDB cannot do anything useful if there's no
11960                syscall number to be caught.  */
11961             error (_("Unknown syscall name '%s'."), cur_name);
11962         }
11963
11964       /* Ok, it's valid.  */
11965       VEC_safe_push (int, result, s.number);
11966     }
11967
11968   discard_cleanups (cleanup);
11969   return result;
11970 }
11971
11972 /* Implement the "catch syscall" command.  */
11973
11974 static void
11975 catch_syscall_command_1 (char *arg, int from_tty, 
11976                          struct cmd_list_element *command)
11977 {
11978   int tempflag;
11979   VEC(int) *filter;
11980   struct syscall s;
11981   struct gdbarch *gdbarch = get_current_arch ();
11982
11983   /* Checking if the feature if supported.  */
11984   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11985     error (_("The feature 'catch syscall' is not supported on \
11986 this architecture yet."));
11987
11988   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11989
11990   arg = skip_spaces (arg);
11991
11992   /* We need to do this first "dummy" translation in order
11993      to get the syscall XML file loaded or, most important,
11994      to display a warning to the user if there's no XML file
11995      for his/her architecture.  */
11996   get_syscall_by_number (0, &s);
11997
11998   /* The allowed syntax is:
11999      catch syscall
12000      catch syscall <name | number> [<name | number> ... <name | number>]
12001
12002      Let's check if there's a syscall name.  */
12003
12004   if (arg != NULL)
12005     filter = catch_syscall_split_args (arg);
12006   else
12007     filter = NULL;
12008
12009   create_syscall_event_catchpoint (tempflag, filter,
12010                                    &catch_syscall_breakpoint_ops);
12011 }
12012
12013 static void
12014 catch_command (char *arg, int from_tty)
12015 {
12016   error (_("Catch requires an event name."));
12017 }
12018 \f
12019
12020 static void
12021 tcatch_command (char *arg, int from_tty)
12022 {
12023   error (_("Catch requires an event name."));
12024 }
12025
12026 /* A qsort comparison function that sorts breakpoints in order.  */
12027
12028 static int
12029 compare_breakpoints (const void *a, const void *b)
12030 {
12031   const breakpoint_p *ba = a;
12032   uintptr_t ua = (uintptr_t) *ba;
12033   const breakpoint_p *bb = b;
12034   uintptr_t ub = (uintptr_t) *bb;
12035
12036   if ((*ba)->number < (*bb)->number)
12037     return -1;
12038   else if ((*ba)->number > (*bb)->number)
12039     return 1;
12040
12041   /* Now sort by address, in case we see, e..g, two breakpoints with
12042      the number 0.  */
12043   if (ua < ub)
12044     return -1;
12045   return ua > ub ? 1 : 0;
12046 }
12047
12048 /* Delete breakpoints by address or line.  */
12049
12050 static void
12051 clear_command (char *arg, int from_tty)
12052 {
12053   struct breakpoint *b, *prev;
12054   VEC(breakpoint_p) *found = 0;
12055   int ix;
12056   int default_match;
12057   struct symtabs_and_lines sals;
12058   struct symtab_and_line sal;
12059   int i;
12060   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12061
12062   if (arg)
12063     {
12064       sals = decode_line_with_current_source (arg,
12065                                               (DECODE_LINE_FUNFIRSTLINE
12066                                                | DECODE_LINE_LIST_MODE));
12067       make_cleanup (xfree, sals.sals);
12068       default_match = 0;
12069     }
12070   else
12071     {
12072       sals.sals = (struct symtab_and_line *)
12073         xmalloc (sizeof (struct symtab_and_line));
12074       make_cleanup (xfree, sals.sals);
12075       init_sal (&sal);          /* Initialize to zeroes.  */
12076
12077       /* Set sal's line, symtab, pc, and pspace to the values
12078          corresponding to the last call to print_frame_info.  If the
12079          codepoint is not valid, this will set all the fields to 0.  */
12080       get_last_displayed_sal (&sal);
12081       if (sal.symtab == 0)
12082         error (_("No source file specified."));
12083
12084       sals.sals[0] = sal;
12085       sals.nelts = 1;
12086
12087       default_match = 1;
12088     }
12089
12090   /* We don't call resolve_sal_pc here.  That's not as bad as it
12091      seems, because all existing breakpoints typically have both
12092      file/line and pc set.  So, if clear is given file/line, we can
12093      match this to existing breakpoint without obtaining pc at all.
12094
12095      We only support clearing given the address explicitly 
12096      present in breakpoint table.  Say, we've set breakpoint 
12097      at file:line.  There were several PC values for that file:line,
12098      due to optimization, all in one block.
12099
12100      We've picked one PC value.  If "clear" is issued with another
12101      PC corresponding to the same file:line, the breakpoint won't
12102      be cleared.  We probably can still clear the breakpoint, but 
12103      since the other PC value is never presented to user, user
12104      can only find it by guessing, and it does not seem important
12105      to support that.  */
12106
12107   /* For each line spec given, delete bps which correspond to it.  Do
12108      it in two passes, solely to preserve the current behavior that
12109      from_tty is forced true if we delete more than one
12110      breakpoint.  */
12111
12112   found = NULL;
12113   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12114   for (i = 0; i < sals.nelts; i++)
12115     {
12116       const char *sal_fullname;
12117
12118       /* If exact pc given, clear bpts at that pc.
12119          If line given (pc == 0), clear all bpts on specified line.
12120          If defaulting, clear all bpts on default line
12121          or at default pc.
12122
12123          defaulting    sal.pc != 0    tests to do
12124
12125          0              1             pc
12126          1              1             pc _and_ line
12127          0              0             line
12128          1              0             <can't happen> */
12129
12130       sal = sals.sals[i];
12131       sal_fullname = (sal.symtab == NULL
12132                       ? NULL : symtab_to_fullname (sal.symtab));
12133
12134       /* Find all matching breakpoints and add them to 'found'.  */
12135       ALL_BREAKPOINTS (b)
12136         {
12137           int match = 0;
12138           /* Are we going to delete b?  */
12139           if (b->type != bp_none && !is_watchpoint (b))
12140             {
12141               struct bp_location *loc = b->loc;
12142               for (; loc; loc = loc->next)
12143                 {
12144                   /* If the user specified file:line, don't allow a PC
12145                      match.  This matches historical gdb behavior.  */
12146                   int pc_match = (!sal.explicit_line
12147                                   && sal.pc
12148                                   && (loc->pspace == sal.pspace)
12149                                   && (loc->address == sal.pc)
12150                                   && (!section_is_overlay (loc->section)
12151                                       || loc->section == sal.section));
12152                   int line_match = 0;
12153
12154                   if ((default_match || sal.explicit_line)
12155                       && loc->symtab != NULL
12156                       && sal_fullname != NULL
12157                       && sal.pspace == loc->pspace
12158                       && loc->line_number == sal.line
12159                       && filename_cmp (symtab_to_fullname (loc->symtab),
12160                                        sal_fullname) == 0)
12161                     line_match = 1;
12162
12163                   if (pc_match || line_match)
12164                     {
12165                       match = 1;
12166                       break;
12167                     }
12168                 }
12169             }
12170
12171           if (match)
12172             VEC_safe_push(breakpoint_p, found, b);
12173         }
12174     }
12175
12176   /* Now go thru the 'found' chain and delete them.  */
12177   if (VEC_empty(breakpoint_p, found))
12178     {
12179       if (arg)
12180         error (_("No breakpoint at %s."), arg);
12181       else
12182         error (_("No breakpoint at this line."));
12183     }
12184
12185   /* Remove duplicates from the vec.  */
12186   qsort (VEC_address (breakpoint_p, found),
12187          VEC_length (breakpoint_p, found),
12188          sizeof (breakpoint_p),
12189          compare_breakpoints);
12190   prev = VEC_index (breakpoint_p, found, 0);
12191   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12192     {
12193       if (b == prev)
12194         {
12195           VEC_ordered_remove (breakpoint_p, found, ix);
12196           --ix;
12197         }
12198     }
12199
12200   if (VEC_length(breakpoint_p, found) > 1)
12201     from_tty = 1;       /* Always report if deleted more than one.  */
12202   if (from_tty)
12203     {
12204       if (VEC_length(breakpoint_p, found) == 1)
12205         printf_unfiltered (_("Deleted breakpoint "));
12206       else
12207         printf_unfiltered (_("Deleted breakpoints "));
12208     }
12209
12210   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12211     {
12212       if (from_tty)
12213         printf_unfiltered ("%d ", b->number);
12214       delete_breakpoint (b);
12215     }
12216   if (from_tty)
12217     putchar_unfiltered ('\n');
12218
12219   do_cleanups (cleanups);
12220 }
12221 \f
12222 /* Delete breakpoint in BS if they are `delete' breakpoints and
12223    all breakpoints that are marked for deletion, whether hit or not.
12224    This is called after any breakpoint is hit, or after errors.  */
12225
12226 void
12227 breakpoint_auto_delete (bpstat bs)
12228 {
12229   struct breakpoint *b, *b_tmp;
12230
12231   for (; bs; bs = bs->next)
12232     if (bs->breakpoint_at
12233         && bs->breakpoint_at->disposition == disp_del
12234         && bs->stop)
12235       delete_breakpoint (bs->breakpoint_at);
12236
12237   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12238   {
12239     if (b->disposition == disp_del_at_next_stop)
12240       delete_breakpoint (b);
12241   }
12242 }
12243
12244 /* A comparison function for bp_location AP and BP being interfaced to
12245    qsort.  Sort elements primarily by their ADDRESS (no matter what
12246    does breakpoint_address_is_meaningful say for its OWNER),
12247    secondarily by ordering first bp_permanent OWNERed elements and
12248    terciarily just ensuring the array is sorted stable way despite
12249    qsort being an unstable algorithm.  */
12250
12251 static int
12252 bp_location_compare (const void *ap, const void *bp)
12253 {
12254   struct bp_location *a = *(void **) ap;
12255   struct bp_location *b = *(void **) bp;
12256   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12257   int a_perm = a->owner->enable_state == bp_permanent;
12258   int b_perm = b->owner->enable_state == bp_permanent;
12259
12260   if (a->address != b->address)
12261     return (a->address > b->address) - (a->address < b->address);
12262
12263   /* Sort locations at the same address by their pspace number, keeping
12264      locations of the same inferior (in a multi-inferior environment)
12265      grouped.  */
12266
12267   if (a->pspace->num != b->pspace->num)
12268     return ((a->pspace->num > b->pspace->num)
12269             - (a->pspace->num < b->pspace->num));
12270
12271   /* Sort permanent breakpoints first.  */
12272   if (a_perm != b_perm)
12273     return (a_perm < b_perm) - (a_perm > b_perm);
12274
12275   /* Make the internal GDB representation stable across GDB runs
12276      where A and B memory inside GDB can differ.  Breakpoint locations of
12277      the same type at the same address can be sorted in arbitrary order.  */
12278
12279   if (a->owner->number != b->owner->number)
12280     return ((a->owner->number > b->owner->number)
12281             - (a->owner->number < b->owner->number));
12282
12283   return (a > b) - (a < b);
12284 }
12285
12286 /* Set bp_location_placed_address_before_address_max and
12287    bp_location_shadow_len_after_address_max according to the current
12288    content of the bp_location array.  */
12289
12290 static void
12291 bp_location_target_extensions_update (void)
12292 {
12293   struct bp_location *bl, **blp_tmp;
12294
12295   bp_location_placed_address_before_address_max = 0;
12296   bp_location_shadow_len_after_address_max = 0;
12297
12298   ALL_BP_LOCATIONS (bl, blp_tmp)
12299     {
12300       CORE_ADDR start, end, addr;
12301
12302       if (!bp_location_has_shadow (bl))
12303         continue;
12304
12305       start = bl->target_info.placed_address;
12306       end = start + bl->target_info.shadow_len;
12307
12308       gdb_assert (bl->address >= start);
12309       addr = bl->address - start;
12310       if (addr > bp_location_placed_address_before_address_max)
12311         bp_location_placed_address_before_address_max = addr;
12312
12313       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12314
12315       gdb_assert (bl->address < end);
12316       addr = end - bl->address;
12317       if (addr > bp_location_shadow_len_after_address_max)
12318         bp_location_shadow_len_after_address_max = addr;
12319     }
12320 }
12321
12322 /* Download tracepoint locations if they haven't been.  */
12323
12324 static void
12325 download_tracepoint_locations (void)
12326 {
12327   struct breakpoint *b;
12328   struct cleanup *old_chain;
12329
12330   if (!target_can_download_tracepoint ())
12331     return;
12332
12333   old_chain = save_current_space_and_thread ();
12334
12335   ALL_TRACEPOINTS (b)
12336     {
12337       struct bp_location *bl;
12338       struct tracepoint *t;
12339       int bp_location_downloaded = 0;
12340
12341       if ((b->type == bp_fast_tracepoint
12342            ? !may_insert_fast_tracepoints
12343            : !may_insert_tracepoints))
12344         continue;
12345
12346       for (bl = b->loc; bl; bl = bl->next)
12347         {
12348           /* In tracepoint, locations are _never_ duplicated, so
12349              should_be_inserted is equivalent to
12350              unduplicated_should_be_inserted.  */
12351           if (!should_be_inserted (bl) || bl->inserted)
12352             continue;
12353
12354           switch_to_program_space_and_thread (bl->pspace);
12355
12356           target_download_tracepoint (bl);
12357
12358           bl->inserted = 1;
12359           bp_location_downloaded = 1;
12360         }
12361       t = (struct tracepoint *) b;
12362       t->number_on_target = b->number;
12363       if (bp_location_downloaded)
12364         observer_notify_breakpoint_modified (b);
12365     }
12366
12367   do_cleanups (old_chain);
12368 }
12369
12370 /* Swap the insertion/duplication state between two locations.  */
12371
12372 static void
12373 swap_insertion (struct bp_location *left, struct bp_location *right)
12374 {
12375   const int left_inserted = left->inserted;
12376   const int left_duplicate = left->duplicate;
12377   const int left_needs_update = left->needs_update;
12378   const struct bp_target_info left_target_info = left->target_info;
12379
12380   /* Locations of tracepoints can never be duplicated.  */
12381   if (is_tracepoint (left->owner))
12382     gdb_assert (!left->duplicate);
12383   if (is_tracepoint (right->owner))
12384     gdb_assert (!right->duplicate);
12385
12386   left->inserted = right->inserted;
12387   left->duplicate = right->duplicate;
12388   left->needs_update = right->needs_update;
12389   left->target_info = right->target_info;
12390   right->inserted = left_inserted;
12391   right->duplicate = left_duplicate;
12392   right->needs_update = left_needs_update;
12393   right->target_info = left_target_info;
12394 }
12395
12396 /* Force the re-insertion of the locations at ADDRESS.  This is called
12397    once a new/deleted/modified duplicate location is found and we are evaluating
12398    conditions on the target's side.  Such conditions need to be updated on
12399    the target.  */
12400
12401 static void
12402 force_breakpoint_reinsertion (struct bp_location *bl)
12403 {
12404   struct bp_location **locp = NULL, **loc2p;
12405   struct bp_location *loc;
12406   CORE_ADDR address = 0;
12407   int pspace_num;
12408
12409   address = bl->address;
12410   pspace_num = bl->pspace->num;
12411
12412   /* This is only meaningful if the target is
12413      evaluating conditions and if the user has
12414      opted for condition evaluation on the target's
12415      side.  */
12416   if (gdb_evaluates_breakpoint_condition_p ()
12417       || !target_supports_evaluation_of_breakpoint_conditions ())
12418     return;
12419
12420   /* Flag all breakpoint locations with this address and
12421      the same program space as the location
12422      as "its condition has changed".  We need to
12423      update the conditions on the target's side.  */
12424   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12425     {
12426       loc = *loc2p;
12427
12428       if (!is_breakpoint (loc->owner)
12429           || pspace_num != loc->pspace->num)
12430         continue;
12431
12432       /* Flag the location appropriately.  We use a different state to
12433          let everyone know that we already updated the set of locations
12434          with addr bl->address and program space bl->pspace.  This is so
12435          we don't have to keep calling these functions just to mark locations
12436          that have already been marked.  */
12437       loc->condition_changed = condition_updated;
12438
12439       /* Free the agent expression bytecode as well.  We will compute
12440          it later on.  */
12441       if (loc->cond_bytecode)
12442         {
12443           free_agent_expr (loc->cond_bytecode);
12444           loc->cond_bytecode = NULL;
12445         }
12446     }
12447 }
12448
12449 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12450    into the inferior, only remove already-inserted locations that no
12451    longer should be inserted.  Functions that delete a breakpoint or
12452    breakpoints should pass false, so that deleting a breakpoint
12453    doesn't have the side effect of inserting the locations of other
12454    breakpoints that are marked not-inserted, but should_be_inserted
12455    returns true on them.
12456
12457    This behaviour is useful is situations close to tear-down -- e.g.,
12458    after an exec, while the target still has execution, but breakpoint
12459    shadows of the previous executable image should *NOT* be restored
12460    to the new image; or before detaching, where the target still has
12461    execution and wants to delete breakpoints from GDB's lists, and all
12462    breakpoints had already been removed from the inferior.  */
12463
12464 static void
12465 update_global_location_list (int should_insert)
12466 {
12467   struct breakpoint *b;
12468   struct bp_location **locp, *loc;
12469   struct cleanup *cleanups;
12470   /* Last breakpoint location address that was marked for update.  */
12471   CORE_ADDR last_addr = 0;
12472   /* Last breakpoint location program space that was marked for update.  */
12473   int last_pspace_num = -1;
12474
12475   /* Used in the duplicates detection below.  When iterating over all
12476      bp_locations, points to the first bp_location of a given address.
12477      Breakpoints and watchpoints of different types are never
12478      duplicates of each other.  Keep one pointer for each type of
12479      breakpoint/watchpoint, so we only need to loop over all locations
12480      once.  */
12481   struct bp_location *bp_loc_first;  /* breakpoint */
12482   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12483   struct bp_location *awp_loc_first; /* access watchpoint */
12484   struct bp_location *rwp_loc_first; /* read watchpoint */
12485
12486   /* Saved former bp_location array which we compare against the newly
12487      built bp_location from the current state of ALL_BREAKPOINTS.  */
12488   struct bp_location **old_location, **old_locp;
12489   unsigned old_location_count;
12490
12491   old_location = bp_location;
12492   old_location_count = bp_location_count;
12493   bp_location = NULL;
12494   bp_location_count = 0;
12495   cleanups = make_cleanup (xfree, old_location);
12496
12497   ALL_BREAKPOINTS (b)
12498     for (loc = b->loc; loc; loc = loc->next)
12499       bp_location_count++;
12500
12501   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12502   locp = bp_location;
12503   ALL_BREAKPOINTS (b)
12504     for (loc = b->loc; loc; loc = loc->next)
12505       *locp++ = loc;
12506   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12507          bp_location_compare);
12508
12509   bp_location_target_extensions_update ();
12510
12511   /* Identify bp_location instances that are no longer present in the
12512      new list, and therefore should be freed.  Note that it's not
12513      necessary that those locations should be removed from inferior --
12514      if there's another location at the same address (previously
12515      marked as duplicate), we don't need to remove/insert the
12516      location.
12517      
12518      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12519      and former bp_location array state respectively.  */
12520
12521   locp = bp_location;
12522   for (old_locp = old_location; old_locp < old_location + old_location_count;
12523        old_locp++)
12524     {
12525       struct bp_location *old_loc = *old_locp;
12526       struct bp_location **loc2p;
12527
12528       /* Tells if 'old_loc' is found among the new locations.  If
12529          not, we have to free it.  */
12530       int found_object = 0;
12531       /* Tells if the location should remain inserted in the target.  */
12532       int keep_in_target = 0;
12533       int removed = 0;
12534
12535       /* Skip LOCP entries which will definitely never be needed.
12536          Stop either at or being the one matching OLD_LOC.  */
12537       while (locp < bp_location + bp_location_count
12538              && (*locp)->address < old_loc->address)
12539         locp++;
12540
12541       for (loc2p = locp;
12542            (loc2p < bp_location + bp_location_count
12543             && (*loc2p)->address == old_loc->address);
12544            loc2p++)
12545         {
12546           /* Check if this is a new/duplicated location or a duplicated
12547              location that had its condition modified.  If so, we want to send
12548              its condition to the target if evaluation of conditions is taking
12549              place there.  */
12550           if ((*loc2p)->condition_changed == condition_modified
12551               && (last_addr != old_loc->address
12552                   || last_pspace_num != old_loc->pspace->num))
12553             {
12554               force_breakpoint_reinsertion (*loc2p);
12555               last_pspace_num = old_loc->pspace->num;
12556             }
12557
12558           if (*loc2p == old_loc)
12559             found_object = 1;
12560         }
12561
12562       /* We have already handled this address, update it so that we don't
12563          have to go through updates again.  */
12564       last_addr = old_loc->address;
12565
12566       /* Target-side condition evaluation: Handle deleted locations.  */
12567       if (!found_object)
12568         force_breakpoint_reinsertion (old_loc);
12569
12570       /* If this location is no longer present, and inserted, look if
12571          there's maybe a new location at the same address.  If so,
12572          mark that one inserted, and don't remove this one.  This is
12573          needed so that we don't have a time window where a breakpoint
12574          at certain location is not inserted.  */
12575
12576       if (old_loc->inserted)
12577         {
12578           /* If the location is inserted now, we might have to remove
12579              it.  */
12580
12581           if (found_object && should_be_inserted (old_loc))
12582             {
12583               /* The location is still present in the location list,
12584                  and still should be inserted.  Don't do anything.  */
12585               keep_in_target = 1;
12586             }
12587           else
12588             {
12589               /* This location still exists, but it won't be kept in the
12590                  target since it may have been disabled.  We proceed to
12591                  remove its target-side condition.  */
12592
12593               /* The location is either no longer present, or got
12594                  disabled.  See if there's another location at the
12595                  same address, in which case we don't need to remove
12596                  this one from the target.  */
12597
12598               /* OLD_LOC comes from existing struct breakpoint.  */
12599               if (breakpoint_address_is_meaningful (old_loc->owner))
12600                 {
12601                   for (loc2p = locp;
12602                        (loc2p < bp_location + bp_location_count
12603                         && (*loc2p)->address == old_loc->address);
12604                        loc2p++)
12605                     {
12606                       struct bp_location *loc2 = *loc2p;
12607
12608                       if (breakpoint_locations_match (loc2, old_loc))
12609                         {
12610                           /* Read watchpoint locations are switched to
12611                              access watchpoints, if the former are not
12612                              supported, but the latter are.  */
12613                           if (is_hardware_watchpoint (old_loc->owner))
12614                             {
12615                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12616                               loc2->watchpoint_type = old_loc->watchpoint_type;
12617                             }
12618
12619                           /* loc2 is a duplicated location. We need to check
12620                              if it should be inserted in case it will be
12621                              unduplicated.  */
12622                           if (loc2 != old_loc
12623                               && unduplicated_should_be_inserted (loc2))
12624                             {
12625                               swap_insertion (old_loc, loc2);
12626                               keep_in_target = 1;
12627                               break;
12628                             }
12629                         }
12630                     }
12631                 }
12632             }
12633
12634           if (!keep_in_target)
12635             {
12636               if (remove_breakpoint (old_loc, mark_uninserted))
12637                 {
12638                   /* This is just about all we can do.  We could keep
12639                      this location on the global list, and try to
12640                      remove it next time, but there's no particular
12641                      reason why we will succeed next time.
12642                      
12643                      Note that at this point, old_loc->owner is still
12644                      valid, as delete_breakpoint frees the breakpoint
12645                      only after calling us.  */
12646                   printf_filtered (_("warning: Error removing "
12647                                      "breakpoint %d\n"), 
12648                                    old_loc->owner->number);
12649                 }
12650               removed = 1;
12651             }
12652         }
12653
12654       if (!found_object)
12655         {
12656           if (removed && non_stop
12657               && breakpoint_address_is_meaningful (old_loc->owner)
12658               && !is_hardware_watchpoint (old_loc->owner))
12659             {
12660               /* This location was removed from the target.  In
12661                  non-stop mode, a race condition is possible where
12662                  we've removed a breakpoint, but stop events for that
12663                  breakpoint are already queued and will arrive later.
12664                  We apply an heuristic to be able to distinguish such
12665                  SIGTRAPs from other random SIGTRAPs: we keep this
12666                  breakpoint location for a bit, and will retire it
12667                  after we see some number of events.  The theory here
12668                  is that reporting of events should, "on the average",
12669                  be fair, so after a while we'll see events from all
12670                  threads that have anything of interest, and no longer
12671                  need to keep this breakpoint location around.  We
12672                  don't hold locations forever so to reduce chances of
12673                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12674                  SIGTRAP.
12675
12676                  The heuristic failing can be disastrous on
12677                  decr_pc_after_break targets.
12678
12679                  On decr_pc_after_break targets, like e.g., x86-linux,
12680                  if we fail to recognize a late breakpoint SIGTRAP,
12681                  because events_till_retirement has reached 0 too
12682                  soon, we'll fail to do the PC adjustment, and report
12683                  a random SIGTRAP to the user.  When the user resumes
12684                  the inferior, it will most likely immediately crash
12685                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12686                  corrupted, because of being resumed e.g., in the
12687                  middle of a multi-byte instruction, or skipped a
12688                  one-byte instruction.  This was actually seen happen
12689                  on native x86-linux, and should be less rare on
12690                  targets that do not support new thread events, like
12691                  remote, due to the heuristic depending on
12692                  thread_count.
12693
12694                  Mistaking a random SIGTRAP for a breakpoint trap
12695                  causes similar symptoms (PC adjustment applied when
12696                  it shouldn't), but then again, playing with SIGTRAPs
12697                  behind the debugger's back is asking for trouble.
12698
12699                  Since hardware watchpoint traps are always
12700                  distinguishable from other traps, so we don't need to
12701                  apply keep hardware watchpoint moribund locations
12702                  around.  We simply always ignore hardware watchpoint
12703                  traps we can no longer explain.  */
12704
12705               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12706               old_loc->owner = NULL;
12707
12708               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12709             }
12710           else
12711             {
12712               old_loc->owner = NULL;
12713               decref_bp_location (&old_loc);
12714             }
12715         }
12716     }
12717
12718   /* Rescan breakpoints at the same address and section, marking the
12719      first one as "first" and any others as "duplicates".  This is so
12720      that the bpt instruction is only inserted once.  If we have a
12721      permanent breakpoint at the same place as BPT, make that one the
12722      official one, and the rest as duplicates.  Permanent breakpoints
12723      are sorted first for the same address.
12724
12725      Do the same for hardware watchpoints, but also considering the
12726      watchpoint's type (regular/access/read) and length.  */
12727
12728   bp_loc_first = NULL;
12729   wp_loc_first = NULL;
12730   awp_loc_first = NULL;
12731   rwp_loc_first = NULL;
12732   ALL_BP_LOCATIONS (loc, locp)
12733     {
12734       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12735          non-NULL.  */
12736       struct bp_location **loc_first_p;
12737       b = loc->owner;
12738
12739       if (!unduplicated_should_be_inserted (loc)
12740           || !breakpoint_address_is_meaningful (b)
12741           /* Don't detect duplicate for tracepoint locations because they are
12742            never duplicated.  See the comments in field `duplicate' of
12743            `struct bp_location'.  */
12744           || is_tracepoint (b))
12745         {
12746           /* Clear the condition modification flag.  */
12747           loc->condition_changed = condition_unchanged;
12748           continue;
12749         }
12750
12751       /* Permanent breakpoint should always be inserted.  */
12752       if (b->enable_state == bp_permanent && ! loc->inserted)
12753         internal_error (__FILE__, __LINE__,
12754                         _("allegedly permanent breakpoint is not "
12755                         "actually inserted"));
12756
12757       if (b->type == bp_hardware_watchpoint)
12758         loc_first_p = &wp_loc_first;
12759       else if (b->type == bp_read_watchpoint)
12760         loc_first_p = &rwp_loc_first;
12761       else if (b->type == bp_access_watchpoint)
12762         loc_first_p = &awp_loc_first;
12763       else
12764         loc_first_p = &bp_loc_first;
12765
12766       if (*loc_first_p == NULL
12767           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12768           || !breakpoint_locations_match (loc, *loc_first_p))
12769         {
12770           *loc_first_p = loc;
12771           loc->duplicate = 0;
12772
12773           if (is_breakpoint (loc->owner) && loc->condition_changed)
12774             {
12775               loc->needs_update = 1;
12776               /* Clear the condition modification flag.  */
12777               loc->condition_changed = condition_unchanged;
12778             }
12779           continue;
12780         }
12781
12782
12783       /* This and the above ensure the invariant that the first location
12784          is not duplicated, and is the inserted one.
12785          All following are marked as duplicated, and are not inserted.  */
12786       if (loc->inserted)
12787         swap_insertion (loc, *loc_first_p);
12788       loc->duplicate = 1;
12789
12790       /* Clear the condition modification flag.  */
12791       loc->condition_changed = condition_unchanged;
12792
12793       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12794           && b->enable_state != bp_permanent)
12795         internal_error (__FILE__, __LINE__,
12796                         _("another breakpoint was inserted on top of "
12797                         "a permanent breakpoint"));
12798     }
12799
12800   if (breakpoints_always_inserted_mode ()
12801       && (have_live_inferiors ()
12802           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12803     {
12804       if (should_insert)
12805         insert_breakpoint_locations ();
12806       else
12807         {
12808           /* Though should_insert is false, we may need to update conditions
12809              on the target's side if it is evaluating such conditions.  We
12810              only update conditions for locations that are marked
12811              "needs_update".  */
12812           update_inserted_breakpoint_locations ();
12813         }
12814     }
12815
12816   if (should_insert)
12817     download_tracepoint_locations ();
12818
12819   do_cleanups (cleanups);
12820 }
12821
12822 void
12823 breakpoint_retire_moribund (void)
12824 {
12825   struct bp_location *loc;
12826   int ix;
12827
12828   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12829     if (--(loc->events_till_retirement) == 0)
12830       {
12831         decref_bp_location (&loc);
12832         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12833         --ix;
12834       }
12835 }
12836
12837 static void
12838 update_global_location_list_nothrow (int inserting)
12839 {
12840   volatile struct gdb_exception e;
12841
12842   TRY_CATCH (e, RETURN_MASK_ERROR)
12843     update_global_location_list (inserting);
12844 }
12845
12846 /* Clear BKP from a BPS.  */
12847
12848 static void
12849 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12850 {
12851   bpstat bs;
12852
12853   for (bs = bps; bs; bs = bs->next)
12854     if (bs->breakpoint_at == bpt)
12855       {
12856         bs->breakpoint_at = NULL;
12857         bs->old_val = NULL;
12858         /* bs->commands will be freed later.  */
12859       }
12860 }
12861
12862 /* Callback for iterate_over_threads.  */
12863 static int
12864 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12865 {
12866   struct breakpoint *bpt = data;
12867
12868   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12869   return 0;
12870 }
12871
12872 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12873    callbacks.  */
12874
12875 static void
12876 say_where (struct breakpoint *b)
12877 {
12878   struct value_print_options opts;
12879
12880   get_user_print_options (&opts);
12881
12882   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12883      single string.  */
12884   if (b->loc == NULL)
12885     {
12886       printf_filtered (_(" (%s) pending."), b->addr_string);
12887     }
12888   else
12889     {
12890       if (opts.addressprint || b->loc->symtab == NULL)
12891         {
12892           printf_filtered (" at ");
12893           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12894                           gdb_stdout);
12895         }
12896       if (b->loc->symtab != NULL)
12897         {
12898           /* If there is a single location, we can print the location
12899              more nicely.  */
12900           if (b->loc->next == NULL)
12901             printf_filtered (": file %s, line %d.",
12902                              symtab_to_filename_for_display (b->loc->symtab),
12903                              b->loc->line_number);
12904           else
12905             /* This is not ideal, but each location may have a
12906                different file name, and this at least reflects the
12907                real situation somewhat.  */
12908             printf_filtered (": %s.", b->addr_string);
12909         }
12910
12911       if (b->loc->next)
12912         {
12913           struct bp_location *loc = b->loc;
12914           int n = 0;
12915           for (; loc; loc = loc->next)
12916             ++n;
12917           printf_filtered (" (%d locations)", n);
12918         }
12919     }
12920 }
12921
12922 /* Default bp_location_ops methods.  */
12923
12924 static void
12925 bp_location_dtor (struct bp_location *self)
12926 {
12927   xfree (self->cond);
12928   if (self->cond_bytecode)
12929     free_agent_expr (self->cond_bytecode);
12930   xfree (self->function_name);
12931
12932   VEC_free (agent_expr_p, self->target_info.conditions);
12933   VEC_free (agent_expr_p, self->target_info.tcommands);
12934 }
12935
12936 static const struct bp_location_ops bp_location_ops =
12937 {
12938   bp_location_dtor
12939 };
12940
12941 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12942    inherit from.  */
12943
12944 static void
12945 base_breakpoint_dtor (struct breakpoint *self)
12946 {
12947   decref_counted_command_line (&self->commands);
12948   xfree (self->cond_string);
12949   xfree (self->extra_string);
12950   xfree (self->addr_string);
12951   xfree (self->filter);
12952   xfree (self->addr_string_range_end);
12953 }
12954
12955 static struct bp_location *
12956 base_breakpoint_allocate_location (struct breakpoint *self)
12957 {
12958   struct bp_location *loc;
12959
12960   loc = XNEW (struct bp_location);
12961   init_bp_location (loc, &bp_location_ops, self);
12962   return loc;
12963 }
12964
12965 static void
12966 base_breakpoint_re_set (struct breakpoint *b)
12967 {
12968   /* Nothing to re-set. */
12969 }
12970
12971 #define internal_error_pure_virtual_called() \
12972   gdb_assert_not_reached ("pure virtual function called")
12973
12974 static int
12975 base_breakpoint_insert_location (struct bp_location *bl)
12976 {
12977   internal_error_pure_virtual_called ();
12978 }
12979
12980 static int
12981 base_breakpoint_remove_location (struct bp_location *bl)
12982 {
12983   internal_error_pure_virtual_called ();
12984 }
12985
12986 static int
12987 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12988                                 struct address_space *aspace,
12989                                 CORE_ADDR bp_addr,
12990                                 const struct target_waitstatus *ws)
12991 {
12992   internal_error_pure_virtual_called ();
12993 }
12994
12995 static void
12996 base_breakpoint_check_status (bpstat bs)
12997 {
12998   /* Always stop.   */
12999 }
13000
13001 /* A "works_in_software_mode" breakpoint_ops method that just internal
13002    errors.  */
13003
13004 static int
13005 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13006 {
13007   internal_error_pure_virtual_called ();
13008 }
13009
13010 /* A "resources_needed" breakpoint_ops method that just internal
13011    errors.  */
13012
13013 static int
13014 base_breakpoint_resources_needed (const struct bp_location *bl)
13015 {
13016   internal_error_pure_virtual_called ();
13017 }
13018
13019 static enum print_stop_action
13020 base_breakpoint_print_it (bpstat bs)
13021 {
13022   internal_error_pure_virtual_called ();
13023 }
13024
13025 static void
13026 base_breakpoint_print_one_detail (const struct breakpoint *self,
13027                                   struct ui_out *uiout)
13028 {
13029   /* nothing */
13030 }
13031
13032 static void
13033 base_breakpoint_print_mention (struct breakpoint *b)
13034 {
13035   internal_error_pure_virtual_called ();
13036 }
13037
13038 static void
13039 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13040 {
13041   internal_error_pure_virtual_called ();
13042 }
13043
13044 static void
13045 base_breakpoint_create_sals_from_address (char **arg,
13046                                           struct linespec_result *canonical,
13047                                           enum bptype type_wanted,
13048                                           char *addr_start,
13049                                           char **copy_arg)
13050 {
13051   internal_error_pure_virtual_called ();
13052 }
13053
13054 static void
13055 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13056                                         struct linespec_result *c,
13057                                         char *cond_string,
13058                                         char *extra_string,
13059                                         enum bptype type_wanted,
13060                                         enum bpdisp disposition,
13061                                         int thread,
13062                                         int task, int ignore_count,
13063                                         const struct breakpoint_ops *o,
13064                                         int from_tty, int enabled,
13065                                         int internal, unsigned flags)
13066 {
13067   internal_error_pure_virtual_called ();
13068 }
13069
13070 static void
13071 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13072                                  struct symtabs_and_lines *sals)
13073 {
13074   internal_error_pure_virtual_called ();
13075 }
13076
13077 /* The default 'explains_signal' method.  */
13078
13079 static int
13080 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13081 {
13082   return 1;
13083 }
13084
13085 /* The default "after_condition_true" method.  */
13086
13087 static void
13088 base_breakpoint_after_condition_true (struct bpstats *bs)
13089 {
13090   /* Nothing to do.   */
13091 }
13092
13093 struct breakpoint_ops base_breakpoint_ops =
13094 {
13095   base_breakpoint_dtor,
13096   base_breakpoint_allocate_location,
13097   base_breakpoint_re_set,
13098   base_breakpoint_insert_location,
13099   base_breakpoint_remove_location,
13100   base_breakpoint_breakpoint_hit,
13101   base_breakpoint_check_status,
13102   base_breakpoint_resources_needed,
13103   base_breakpoint_works_in_software_mode,
13104   base_breakpoint_print_it,
13105   NULL,
13106   base_breakpoint_print_one_detail,
13107   base_breakpoint_print_mention,
13108   base_breakpoint_print_recreate,
13109   base_breakpoint_create_sals_from_address,
13110   base_breakpoint_create_breakpoints_sal,
13111   base_breakpoint_decode_linespec,
13112   base_breakpoint_explains_signal,
13113   base_breakpoint_after_condition_true,
13114 };
13115
13116 /* Default breakpoint_ops methods.  */
13117
13118 static void
13119 bkpt_re_set (struct breakpoint *b)
13120 {
13121   /* FIXME: is this still reachable?  */
13122   if (b->addr_string == NULL)
13123     {
13124       /* Anything without a string can't be re-set.  */
13125       delete_breakpoint (b);
13126       return;
13127     }
13128
13129   breakpoint_re_set_default (b);
13130 }
13131
13132 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13133    inserted DEST, so we can remove it later, in case SRC is removed
13134    first.  */
13135
13136 static void
13137 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13138                                      const struct bp_target_info *src)
13139 {
13140   dest->shadow_len = src->shadow_len;
13141   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13142   dest->placed_size = src->placed_size;
13143 }
13144
13145 static int
13146 bkpt_insert_location (struct bp_location *bl)
13147 {
13148   if (bl->loc_type == bp_loc_hardware_breakpoint)
13149     return target_insert_hw_breakpoint (bl->gdbarch,
13150                                         &bl->target_info);
13151   else
13152     {
13153       struct bp_target_info *bp_tgt = &bl->target_info;
13154       int ret;
13155       int sss_slot;
13156
13157       /* There is no need to insert a breakpoint if an unconditional
13158          raw/sss breakpoint is already inserted at that location.  */
13159       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13160                                               bp_tgt->placed_address);
13161       if (sss_slot >= 0)
13162         {
13163           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13164
13165           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13166           return 0;
13167         }
13168
13169       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13170     }
13171 }
13172
13173 static int
13174 bkpt_remove_location (struct bp_location *bl)
13175 {
13176   if (bl->loc_type == bp_loc_hardware_breakpoint)
13177     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13178   else
13179     {
13180       struct bp_target_info *bp_tgt = &bl->target_info;
13181       struct address_space *aspace = bp_tgt->placed_address_space;
13182       CORE_ADDR address = bp_tgt->placed_address;
13183
13184       /* Only remove the breakpoint if there is no raw/sss breakpoint
13185          still inserted at this location.  Otherwise, we would be
13186          effectively disabling the raw/sss breakpoint.  */
13187       if (single_step_breakpoint_inserted_here_p (aspace, address))
13188         return 0;
13189
13190       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13191     }
13192 }
13193
13194 static int
13195 bkpt_breakpoint_hit (const struct bp_location *bl,
13196                      struct address_space *aspace, CORE_ADDR bp_addr,
13197                      const struct target_waitstatus *ws)
13198 {
13199   if (ws->kind != TARGET_WAITKIND_STOPPED
13200       || ws->value.sig != GDB_SIGNAL_TRAP)
13201     return 0;
13202
13203   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13204                                  aspace, bp_addr))
13205     return 0;
13206
13207   if (overlay_debugging         /* unmapped overlay section */
13208       && section_is_overlay (bl->section)
13209       && !section_is_mapped (bl->section))
13210     return 0;
13211
13212   return 1;
13213 }
13214
13215 static int
13216 dprintf_breakpoint_hit (const struct bp_location *bl,
13217                         struct address_space *aspace, CORE_ADDR bp_addr,
13218                         const struct target_waitstatus *ws)
13219 {
13220   if (dprintf_style == dprintf_style_agent
13221       && target_can_run_breakpoint_commands ())
13222     {
13223       /* An agent-style dprintf never causes a stop.  If we see a trap
13224          for this address it must be for a breakpoint that happens to
13225          be set at the same address.  */
13226       return 0;
13227     }
13228
13229   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13230 }
13231
13232 static int
13233 bkpt_resources_needed (const struct bp_location *bl)
13234 {
13235   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13236
13237   return 1;
13238 }
13239
13240 static enum print_stop_action
13241 bkpt_print_it (bpstat bs)
13242 {
13243   struct breakpoint *b;
13244   const struct bp_location *bl;
13245   int bp_temp;
13246   struct ui_out *uiout = current_uiout;
13247
13248   gdb_assert (bs->bp_location_at != NULL);
13249
13250   bl = bs->bp_location_at;
13251   b = bs->breakpoint_at;
13252
13253   bp_temp = b->disposition == disp_del;
13254   if (bl->address != bl->requested_address)
13255     breakpoint_adjustment_warning (bl->requested_address,
13256                                    bl->address,
13257                                    b->number, 1);
13258   annotate_breakpoint (b->number);
13259   if (bp_temp)
13260     ui_out_text (uiout, "\nTemporary breakpoint ");
13261   else
13262     ui_out_text (uiout, "\nBreakpoint ");
13263   if (ui_out_is_mi_like_p (uiout))
13264     {
13265       ui_out_field_string (uiout, "reason",
13266                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13267       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13268     }
13269   ui_out_field_int (uiout, "bkptno", b->number);
13270   ui_out_text (uiout, ", ");
13271
13272   return PRINT_SRC_AND_LOC;
13273 }
13274
13275 static void
13276 bkpt_print_mention (struct breakpoint *b)
13277 {
13278   if (ui_out_is_mi_like_p (current_uiout))
13279     return;
13280
13281   switch (b->type)
13282     {
13283     case bp_breakpoint:
13284     case bp_gnu_ifunc_resolver:
13285       if (b->disposition == disp_del)
13286         printf_filtered (_("Temporary breakpoint"));
13287       else
13288         printf_filtered (_("Breakpoint"));
13289       printf_filtered (_(" %d"), b->number);
13290       if (b->type == bp_gnu_ifunc_resolver)
13291         printf_filtered (_(" at gnu-indirect-function resolver"));
13292       break;
13293     case bp_hardware_breakpoint:
13294       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13295       break;
13296     case bp_dprintf:
13297       printf_filtered (_("Dprintf %d"), b->number);
13298       break;
13299     }
13300
13301   say_where (b);
13302 }
13303
13304 static void
13305 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13306 {
13307   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13308     fprintf_unfiltered (fp, "tbreak");
13309   else if (tp->type == bp_breakpoint)
13310     fprintf_unfiltered (fp, "break");
13311   else if (tp->type == bp_hardware_breakpoint
13312            && tp->disposition == disp_del)
13313     fprintf_unfiltered (fp, "thbreak");
13314   else if (tp->type == bp_hardware_breakpoint)
13315     fprintf_unfiltered (fp, "hbreak");
13316   else
13317     internal_error (__FILE__, __LINE__,
13318                     _("unhandled breakpoint type %d"), (int) tp->type);
13319
13320   fprintf_unfiltered (fp, " %s", tp->addr_string);
13321   print_recreate_thread (tp, fp);
13322 }
13323
13324 static void
13325 bkpt_create_sals_from_address (char **arg,
13326                                struct linespec_result *canonical,
13327                                enum bptype type_wanted,
13328                                char *addr_start, char **copy_arg)
13329 {
13330   create_sals_from_address_default (arg, canonical, type_wanted,
13331                                     addr_start, copy_arg);
13332 }
13333
13334 static void
13335 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13336                              struct linespec_result *canonical,
13337                              char *cond_string,
13338                              char *extra_string,
13339                              enum bptype type_wanted,
13340                              enum bpdisp disposition,
13341                              int thread,
13342                              int task, int ignore_count,
13343                              const struct breakpoint_ops *ops,
13344                              int from_tty, int enabled,
13345                              int internal, unsigned flags)
13346 {
13347   create_breakpoints_sal_default (gdbarch, canonical,
13348                                   cond_string, extra_string,
13349                                   type_wanted,
13350                                   disposition, thread, task,
13351                                   ignore_count, ops, from_tty,
13352                                   enabled, internal, flags);
13353 }
13354
13355 static void
13356 bkpt_decode_linespec (struct breakpoint *b, char **s,
13357                       struct symtabs_and_lines *sals)
13358 {
13359   decode_linespec_default (b, s, sals);
13360 }
13361
13362 /* Virtual table for internal breakpoints.  */
13363
13364 static void
13365 internal_bkpt_re_set (struct breakpoint *b)
13366 {
13367   switch (b->type)
13368     {
13369       /* Delete overlay event and longjmp master breakpoints; they
13370          will be reset later by breakpoint_re_set.  */
13371     case bp_overlay_event:
13372     case bp_longjmp_master:
13373     case bp_std_terminate_master:
13374     case bp_exception_master:
13375       delete_breakpoint (b);
13376       break;
13377
13378       /* This breakpoint is special, it's set up when the inferior
13379          starts and we really don't want to touch it.  */
13380     case bp_shlib_event:
13381
13382       /* Like bp_shlib_event, this breakpoint type is special.  Once
13383          it is set up, we do not want to touch it.  */
13384     case bp_thread_event:
13385       break;
13386     }
13387 }
13388
13389 static void
13390 internal_bkpt_check_status (bpstat bs)
13391 {
13392   if (bs->breakpoint_at->type == bp_shlib_event)
13393     {
13394       /* If requested, stop when the dynamic linker notifies GDB of
13395          events.  This allows the user to get control and place
13396          breakpoints in initializer routines for dynamically loaded
13397          objects (among other things).  */
13398       bs->stop = stop_on_solib_events;
13399       bs->print = stop_on_solib_events;
13400     }
13401   else
13402     bs->stop = 0;
13403 }
13404
13405 static enum print_stop_action
13406 internal_bkpt_print_it (bpstat bs)
13407 {
13408   struct breakpoint *b;
13409
13410   b = bs->breakpoint_at;
13411
13412   switch (b->type)
13413     {
13414     case bp_shlib_event:
13415       /* Did we stop because the user set the stop_on_solib_events
13416          variable?  (If so, we report this as a generic, "Stopped due
13417          to shlib event" message.) */
13418       print_solib_event (0);
13419       break;
13420
13421     case bp_thread_event:
13422       /* Not sure how we will get here.
13423          GDB should not stop for these breakpoints.  */
13424       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13425       break;
13426
13427     case bp_overlay_event:
13428       /* By analogy with the thread event, GDB should not stop for these.  */
13429       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13430       break;
13431
13432     case bp_longjmp_master:
13433       /* These should never be enabled.  */
13434       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13435       break;
13436
13437     case bp_std_terminate_master:
13438       /* These should never be enabled.  */
13439       printf_filtered (_("std::terminate Master Breakpoint: "
13440                          "gdb should not stop!\n"));
13441       break;
13442
13443     case bp_exception_master:
13444       /* These should never be enabled.  */
13445       printf_filtered (_("Exception Master Breakpoint: "
13446                          "gdb should not stop!\n"));
13447       break;
13448     }
13449
13450   return PRINT_NOTHING;
13451 }
13452
13453 static void
13454 internal_bkpt_print_mention (struct breakpoint *b)
13455 {
13456   /* Nothing to mention.  These breakpoints are internal.  */
13457 }
13458
13459 /* Virtual table for momentary breakpoints  */
13460
13461 static void
13462 momentary_bkpt_re_set (struct breakpoint *b)
13463 {
13464   /* Keep temporary breakpoints, which can be encountered when we step
13465      over a dlopen call and solib_add is resetting the breakpoints.
13466      Otherwise these should have been blown away via the cleanup chain
13467      or by breakpoint_init_inferior when we rerun the executable.  */
13468 }
13469
13470 static void
13471 momentary_bkpt_check_status (bpstat bs)
13472 {
13473   /* Nothing.  The point of these breakpoints is causing a stop.  */
13474 }
13475
13476 static enum print_stop_action
13477 momentary_bkpt_print_it (bpstat bs)
13478 {
13479   struct ui_out *uiout = current_uiout;
13480
13481   if (ui_out_is_mi_like_p (uiout))
13482     {
13483       struct breakpoint *b = bs->breakpoint_at;
13484
13485       switch (b->type)
13486         {
13487         case bp_finish:
13488           ui_out_field_string
13489             (uiout, "reason",
13490              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13491           break;
13492
13493         case bp_until:
13494           ui_out_field_string
13495             (uiout, "reason",
13496              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13497           break;
13498         }
13499     }
13500
13501   return PRINT_UNKNOWN;
13502 }
13503
13504 static void
13505 momentary_bkpt_print_mention (struct breakpoint *b)
13506 {
13507   /* Nothing to mention.  These breakpoints are internal.  */
13508 }
13509
13510 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13511
13512    It gets cleared already on the removal of the first one of such placed
13513    breakpoints.  This is OK as they get all removed altogether.  */
13514
13515 static void
13516 longjmp_bkpt_dtor (struct breakpoint *self)
13517 {
13518   struct thread_info *tp = find_thread_id (self->thread);
13519
13520   if (tp)
13521     tp->initiating_frame = null_frame_id;
13522
13523   momentary_breakpoint_ops.dtor (self);
13524 }
13525
13526 /* Specific methods for probe breakpoints.  */
13527
13528 static int
13529 bkpt_probe_insert_location (struct bp_location *bl)
13530 {
13531   int v = bkpt_insert_location (bl);
13532
13533   if (v == 0)
13534     {
13535       /* The insertion was successful, now let's set the probe's semaphore
13536          if needed.  */
13537       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13538                                             bl->probe.objfile,
13539                                             bl->gdbarch);
13540     }
13541
13542   return v;
13543 }
13544
13545 static int
13546 bkpt_probe_remove_location (struct bp_location *bl)
13547 {
13548   /* Let's clear the semaphore before removing the location.  */
13549   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13550                                           bl->probe.objfile,
13551                                           bl->gdbarch);
13552
13553   return bkpt_remove_location (bl);
13554 }
13555
13556 static void
13557 bkpt_probe_create_sals_from_address (char **arg,
13558                                      struct linespec_result *canonical,
13559                                      enum bptype type_wanted,
13560                                      char *addr_start, char **copy_arg)
13561 {
13562   struct linespec_sals lsal;
13563
13564   lsal.sals = parse_probes (arg, canonical);
13565
13566   *copy_arg = xstrdup (canonical->addr_string);
13567   lsal.canonical = xstrdup (*copy_arg);
13568
13569   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13570 }
13571
13572 static void
13573 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13574                             struct symtabs_and_lines *sals)
13575 {
13576   *sals = parse_probes (s, NULL);
13577   if (!sals->sals)
13578     error (_("probe not found"));
13579 }
13580
13581 /* The breakpoint_ops structure to be used in tracepoints.  */
13582
13583 static void
13584 tracepoint_re_set (struct breakpoint *b)
13585 {
13586   breakpoint_re_set_default (b);
13587 }
13588
13589 static int
13590 tracepoint_breakpoint_hit (const struct bp_location *bl,
13591                            struct address_space *aspace, CORE_ADDR bp_addr,
13592                            const struct target_waitstatus *ws)
13593 {
13594   /* By definition, the inferior does not report stops at
13595      tracepoints.  */
13596   return 0;
13597 }
13598
13599 static void
13600 tracepoint_print_one_detail (const struct breakpoint *self,
13601                              struct ui_out *uiout)
13602 {
13603   struct tracepoint *tp = (struct tracepoint *) self;
13604   if (tp->static_trace_marker_id)
13605     {
13606       gdb_assert (self->type == bp_static_tracepoint);
13607
13608       ui_out_text (uiout, "\tmarker id is ");
13609       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13610                            tp->static_trace_marker_id);
13611       ui_out_text (uiout, "\n");
13612     }
13613 }
13614
13615 static void
13616 tracepoint_print_mention (struct breakpoint *b)
13617 {
13618   if (ui_out_is_mi_like_p (current_uiout))
13619     return;
13620
13621   switch (b->type)
13622     {
13623     case bp_tracepoint:
13624       printf_filtered (_("Tracepoint"));
13625       printf_filtered (_(" %d"), b->number);
13626       break;
13627     case bp_fast_tracepoint:
13628       printf_filtered (_("Fast tracepoint"));
13629       printf_filtered (_(" %d"), b->number);
13630       break;
13631     case bp_static_tracepoint:
13632       printf_filtered (_("Static tracepoint"));
13633       printf_filtered (_(" %d"), b->number);
13634       break;
13635     default:
13636       internal_error (__FILE__, __LINE__,
13637                       _("unhandled tracepoint type %d"), (int) b->type);
13638     }
13639
13640   say_where (b);
13641 }
13642
13643 static void
13644 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13645 {
13646   struct tracepoint *tp = (struct tracepoint *) self;
13647
13648   if (self->type == bp_fast_tracepoint)
13649     fprintf_unfiltered (fp, "ftrace");
13650   if (self->type == bp_static_tracepoint)
13651     fprintf_unfiltered (fp, "strace");
13652   else if (self->type == bp_tracepoint)
13653     fprintf_unfiltered (fp, "trace");
13654   else
13655     internal_error (__FILE__, __LINE__,
13656                     _("unhandled tracepoint type %d"), (int) self->type);
13657
13658   fprintf_unfiltered (fp, " %s", self->addr_string);
13659   print_recreate_thread (self, fp);
13660
13661   if (tp->pass_count)
13662     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13663 }
13664
13665 static void
13666 tracepoint_create_sals_from_address (char **arg,
13667                                      struct linespec_result *canonical,
13668                                      enum bptype type_wanted,
13669                                      char *addr_start, char **copy_arg)
13670 {
13671   create_sals_from_address_default (arg, canonical, type_wanted,
13672                                     addr_start, copy_arg);
13673 }
13674
13675 static void
13676 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13677                                    struct linespec_result *canonical,
13678                                    char *cond_string,
13679                                    char *extra_string,
13680                                    enum bptype type_wanted,
13681                                    enum bpdisp disposition,
13682                                    int thread,
13683                                    int task, int ignore_count,
13684                                    const struct breakpoint_ops *ops,
13685                                    int from_tty, int enabled,
13686                                    int internal, unsigned flags)
13687 {
13688   create_breakpoints_sal_default (gdbarch, canonical,
13689                                   cond_string, extra_string,
13690                                   type_wanted,
13691                                   disposition, thread, task,
13692                                   ignore_count, ops, from_tty,
13693                                   enabled, internal, flags);
13694 }
13695
13696 static void
13697 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13698                             struct symtabs_and_lines *sals)
13699 {
13700   decode_linespec_default (b, s, sals);
13701 }
13702
13703 struct breakpoint_ops tracepoint_breakpoint_ops;
13704
13705 /* The breakpoint_ops structure to be use on tracepoints placed in a
13706    static probe.  */
13707
13708 static void
13709 tracepoint_probe_create_sals_from_address (char **arg,
13710                                            struct linespec_result *canonical,
13711                                            enum bptype type_wanted,
13712                                            char *addr_start, char **copy_arg)
13713 {
13714   /* We use the same method for breakpoint on probes.  */
13715   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13716                                        addr_start, copy_arg);
13717 }
13718
13719 static void
13720 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13721                                   struct symtabs_and_lines *sals)
13722 {
13723   /* We use the same method for breakpoint on probes.  */
13724   bkpt_probe_decode_linespec (b, s, sals);
13725 }
13726
13727 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13728
13729 /* Dprintf breakpoint_ops methods.  */
13730
13731 static void
13732 dprintf_re_set (struct breakpoint *b)
13733 {
13734   breakpoint_re_set_default (b);
13735
13736   /* This breakpoint could have been pending, and be resolved now, and
13737      if so, we should now have the extra string.  If we don't, the
13738      dprintf was malformed when created, but we couldn't tell because
13739      we can't extract the extra string until the location is
13740      resolved.  */
13741   if (b->loc != NULL && b->extra_string == NULL)
13742     error (_("Format string required"));
13743
13744   /* 1 - connect to target 1, that can run breakpoint commands.
13745      2 - create a dprintf, which resolves fine.
13746      3 - disconnect from target 1
13747      4 - connect to target 2, that can NOT run breakpoint commands.
13748
13749      After steps #3/#4, you'll want the dprintf command list to
13750      be updated, because target 1 and 2 may well return different
13751      answers for target_can_run_breakpoint_commands().
13752      Given absence of finer grained resetting, we get to do
13753      it all the time.  */
13754   if (b->extra_string != NULL)
13755     update_dprintf_command_list (b);
13756 }
13757
13758 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13759
13760 static void
13761 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13762 {
13763   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13764                       tp->extra_string);
13765   print_recreate_thread (tp, fp);
13766 }
13767
13768 /* Implement the "after_condition_true" breakpoint_ops method for
13769    dprintf.
13770
13771    dprintf's are implemented with regular commands in their command
13772    list, but we run the commands here instead of before presenting the
13773    stop to the user, as dprintf's don't actually cause a stop.  This
13774    also makes it so that the commands of multiple dprintfs at the same
13775    address are all handled.  */
13776
13777 static void
13778 dprintf_after_condition_true (struct bpstats *bs)
13779 {
13780   struct cleanup *old_chain;
13781   struct bpstats tmp_bs = { NULL };
13782   struct bpstats *tmp_bs_p = &tmp_bs;
13783
13784   /* dprintf's never cause a stop.  This wasn't set in the
13785      check_status hook instead because that would make the dprintf's
13786      condition not be evaluated.  */
13787   bs->stop = 0;
13788
13789   /* Run the command list here.  Take ownership of it instead of
13790      copying.  We never want these commands to run later in
13791      bpstat_do_actions, if a breakpoint that causes a stop happens to
13792      be set at same address as this dprintf, or even if running the
13793      commands here throws.  */
13794   tmp_bs.commands = bs->commands;
13795   bs->commands = NULL;
13796   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13797
13798   bpstat_do_actions_1 (&tmp_bs_p);
13799
13800   /* 'tmp_bs.commands' will usually be NULL by now, but
13801      bpstat_do_actions_1 may return early without processing the whole
13802      list.  */
13803   do_cleanups (old_chain);
13804 }
13805
13806 /* The breakpoint_ops structure to be used on static tracepoints with
13807    markers (`-m').  */
13808
13809 static void
13810 strace_marker_create_sals_from_address (char **arg,
13811                                         struct linespec_result *canonical,
13812                                         enum bptype type_wanted,
13813                                         char *addr_start, char **copy_arg)
13814 {
13815   struct linespec_sals lsal;
13816
13817   lsal.sals = decode_static_tracepoint_spec (arg);
13818
13819   *copy_arg = savestring (addr_start, *arg - addr_start);
13820
13821   canonical->addr_string = xstrdup (*copy_arg);
13822   lsal.canonical = xstrdup (*copy_arg);
13823   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13824 }
13825
13826 static void
13827 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13828                                       struct linespec_result *canonical,
13829                                       char *cond_string,
13830                                       char *extra_string,
13831                                       enum bptype type_wanted,
13832                                       enum bpdisp disposition,
13833                                       int thread,
13834                                       int task, int ignore_count,
13835                                       const struct breakpoint_ops *ops,
13836                                       int from_tty, int enabled,
13837                                       int internal, unsigned flags)
13838 {
13839   int i;
13840   struct linespec_sals *lsal = VEC_index (linespec_sals,
13841                                           canonical->sals, 0);
13842
13843   /* If the user is creating a static tracepoint by marker id
13844      (strace -m MARKER_ID), then store the sals index, so that
13845      breakpoint_re_set can try to match up which of the newly
13846      found markers corresponds to this one, and, don't try to
13847      expand multiple locations for each sal, given than SALS
13848      already should contain all sals for MARKER_ID.  */
13849
13850   for (i = 0; i < lsal->sals.nelts; ++i)
13851     {
13852       struct symtabs_and_lines expanded;
13853       struct tracepoint *tp;
13854       struct cleanup *old_chain;
13855       char *addr_string;
13856
13857       expanded.nelts = 1;
13858       expanded.sals = &lsal->sals.sals[i];
13859
13860       addr_string = xstrdup (canonical->addr_string);
13861       old_chain = make_cleanup (xfree, addr_string);
13862
13863       tp = XCNEW (struct tracepoint);
13864       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13865                            addr_string, NULL,
13866                            cond_string, extra_string,
13867                            type_wanted, disposition,
13868                            thread, task, ignore_count, ops,
13869                            from_tty, enabled, internal, flags,
13870                            canonical->special_display);
13871       /* Given that its possible to have multiple markers with
13872          the same string id, if the user is creating a static
13873          tracepoint by marker id ("strace -m MARKER_ID"), then
13874          store the sals index, so that breakpoint_re_set can
13875          try to match up which of the newly found markers
13876          corresponds to this one  */
13877       tp->static_trace_marker_id_idx = i;
13878
13879       install_breakpoint (internal, &tp->base, 0);
13880
13881       discard_cleanups (old_chain);
13882     }
13883 }
13884
13885 static void
13886 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13887                                struct symtabs_and_lines *sals)
13888 {
13889   struct tracepoint *tp = (struct tracepoint *) b;
13890
13891   *sals = decode_static_tracepoint_spec (s);
13892   if (sals->nelts > tp->static_trace_marker_id_idx)
13893     {
13894       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13895       sals->nelts = 1;
13896     }
13897   else
13898     error (_("marker %s not found"), tp->static_trace_marker_id);
13899 }
13900
13901 static struct breakpoint_ops strace_marker_breakpoint_ops;
13902
13903 static int
13904 strace_marker_p (struct breakpoint *b)
13905 {
13906   return b->ops == &strace_marker_breakpoint_ops;
13907 }
13908
13909 /* Delete a breakpoint and clean up all traces of it in the data
13910    structures.  */
13911
13912 void
13913 delete_breakpoint (struct breakpoint *bpt)
13914 {
13915   struct breakpoint *b;
13916
13917   gdb_assert (bpt != NULL);
13918
13919   /* Has this bp already been deleted?  This can happen because
13920      multiple lists can hold pointers to bp's.  bpstat lists are
13921      especial culprits.
13922
13923      One example of this happening is a watchpoint's scope bp.  When
13924      the scope bp triggers, we notice that the watchpoint is out of
13925      scope, and delete it.  We also delete its scope bp.  But the
13926      scope bp is marked "auto-deleting", and is already on a bpstat.
13927      That bpstat is then checked for auto-deleting bp's, which are
13928      deleted.
13929
13930      A real solution to this problem might involve reference counts in
13931      bp's, and/or giving them pointers back to their referencing
13932      bpstat's, and teaching delete_breakpoint to only free a bp's
13933      storage when no more references were extent.  A cheaper bandaid
13934      was chosen.  */
13935   if (bpt->type == bp_none)
13936     return;
13937
13938   /* At least avoid this stale reference until the reference counting
13939      of breakpoints gets resolved.  */
13940   if (bpt->related_breakpoint != bpt)
13941     {
13942       struct breakpoint *related;
13943       struct watchpoint *w;
13944
13945       if (bpt->type == bp_watchpoint_scope)
13946         w = (struct watchpoint *) bpt->related_breakpoint;
13947       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13948         w = (struct watchpoint *) bpt;
13949       else
13950         w = NULL;
13951       if (w != NULL)
13952         watchpoint_del_at_next_stop (w);
13953
13954       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13955       for (related = bpt; related->related_breakpoint != bpt;
13956            related = related->related_breakpoint);
13957       related->related_breakpoint = bpt->related_breakpoint;
13958       bpt->related_breakpoint = bpt;
13959     }
13960
13961   /* watch_command_1 creates a watchpoint but only sets its number if
13962      update_watchpoint succeeds in creating its bp_locations.  If there's
13963      a problem in that process, we'll be asked to delete the half-created
13964      watchpoint.  In that case, don't announce the deletion.  */
13965   if (bpt->number)
13966     observer_notify_breakpoint_deleted (bpt);
13967
13968   if (breakpoint_chain == bpt)
13969     breakpoint_chain = bpt->next;
13970
13971   ALL_BREAKPOINTS (b)
13972     if (b->next == bpt)
13973     {
13974       b->next = bpt->next;
13975       break;
13976     }
13977
13978   /* Be sure no bpstat's are pointing at the breakpoint after it's
13979      been freed.  */
13980   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13981      in all threads for now.  Note that we cannot just remove bpstats
13982      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13983      commands are associated with the bpstat; if we remove it here,
13984      then the later call to bpstat_do_actions (&stop_bpstat); in
13985      event-top.c won't do anything, and temporary breakpoints with
13986      commands won't work.  */
13987
13988   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13989
13990   /* Now that breakpoint is removed from breakpoint list, update the
13991      global location list.  This will remove locations that used to
13992      belong to this breakpoint.  Do this before freeing the breakpoint
13993      itself, since remove_breakpoint looks at location's owner.  It
13994      might be better design to have location completely
13995      self-contained, but it's not the case now.  */
13996   update_global_location_list (0);
13997
13998   bpt->ops->dtor (bpt);
13999   /* On the chance that someone will soon try again to delete this
14000      same bp, we mark it as deleted before freeing its storage.  */
14001   bpt->type = bp_none;
14002   xfree (bpt);
14003 }
14004
14005 static void
14006 do_delete_breakpoint_cleanup (void *b)
14007 {
14008   delete_breakpoint (b);
14009 }
14010
14011 struct cleanup *
14012 make_cleanup_delete_breakpoint (struct breakpoint *b)
14013 {
14014   return make_cleanup (do_delete_breakpoint_cleanup, b);
14015 }
14016
14017 /* Iterator function to call a user-provided callback function once
14018    for each of B and its related breakpoints.  */
14019
14020 static void
14021 iterate_over_related_breakpoints (struct breakpoint *b,
14022                                   void (*function) (struct breakpoint *,
14023                                                     void *),
14024                                   void *data)
14025 {
14026   struct breakpoint *related;
14027
14028   related = b;
14029   do
14030     {
14031       struct breakpoint *next;
14032
14033       /* FUNCTION may delete RELATED.  */
14034       next = related->related_breakpoint;
14035
14036       if (next == related)
14037         {
14038           /* RELATED is the last ring entry.  */
14039           function (related, data);
14040
14041           /* FUNCTION may have deleted it, so we'd never reach back to
14042              B.  There's nothing left to do anyway, so just break
14043              out.  */
14044           break;
14045         }
14046       else
14047         function (related, data);
14048
14049       related = next;
14050     }
14051   while (related != b);
14052 }
14053
14054 static void
14055 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14056 {
14057   delete_breakpoint (b);
14058 }
14059
14060 /* A callback for map_breakpoint_numbers that calls
14061    delete_breakpoint.  */
14062
14063 static void
14064 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14065 {
14066   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14067 }
14068
14069 void
14070 delete_command (char *arg, int from_tty)
14071 {
14072   struct breakpoint *b, *b_tmp;
14073
14074   dont_repeat ();
14075
14076   if (arg == 0)
14077     {
14078       int breaks_to_delete = 0;
14079
14080       /* Delete all breakpoints if no argument.  Do not delete
14081          internal breakpoints, these have to be deleted with an
14082          explicit breakpoint number argument.  */
14083       ALL_BREAKPOINTS (b)
14084         if (user_breakpoint_p (b))
14085           {
14086             breaks_to_delete = 1;
14087             break;
14088           }
14089
14090       /* Ask user only if there are some breakpoints to delete.  */
14091       if (!from_tty
14092           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14093         {
14094           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14095             if (user_breakpoint_p (b))
14096               delete_breakpoint (b);
14097         }
14098     }
14099   else
14100     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14101 }
14102
14103 static int
14104 all_locations_are_pending (struct bp_location *loc)
14105 {
14106   for (; loc; loc = loc->next)
14107     if (!loc->shlib_disabled
14108         && !loc->pspace->executing_startup)
14109       return 0;
14110   return 1;
14111 }
14112
14113 /* Subroutine of update_breakpoint_locations to simplify it.
14114    Return non-zero if multiple fns in list LOC have the same name.
14115    Null names are ignored.  */
14116
14117 static int
14118 ambiguous_names_p (struct bp_location *loc)
14119 {
14120   struct bp_location *l;
14121   htab_t htab = htab_create_alloc (13, htab_hash_string,
14122                                    (int (*) (const void *, 
14123                                              const void *)) streq,
14124                                    NULL, xcalloc, xfree);
14125
14126   for (l = loc; l != NULL; l = l->next)
14127     {
14128       const char **slot;
14129       const char *name = l->function_name;
14130
14131       /* Allow for some names to be NULL, ignore them.  */
14132       if (name == NULL)
14133         continue;
14134
14135       slot = (const char **) htab_find_slot (htab, (const void *) name,
14136                                              INSERT);
14137       /* NOTE: We can assume slot != NULL here because xcalloc never
14138          returns NULL.  */
14139       if (*slot != NULL)
14140         {
14141           htab_delete (htab);
14142           return 1;
14143         }
14144       *slot = name;
14145     }
14146
14147   htab_delete (htab);
14148   return 0;
14149 }
14150
14151 /* When symbols change, it probably means the sources changed as well,
14152    and it might mean the static tracepoint markers are no longer at
14153    the same address or line numbers they used to be at last we
14154    checked.  Losing your static tracepoints whenever you rebuild is
14155    undesirable.  This function tries to resync/rematch gdb static
14156    tracepoints with the markers on the target, for static tracepoints
14157    that have not been set by marker id.  Static tracepoint that have
14158    been set by marker id are reset by marker id in breakpoint_re_set.
14159    The heuristic is:
14160
14161    1) For a tracepoint set at a specific address, look for a marker at
14162    the old PC.  If one is found there, assume to be the same marker.
14163    If the name / string id of the marker found is different from the
14164    previous known name, assume that means the user renamed the marker
14165    in the sources, and output a warning.
14166
14167    2) For a tracepoint set at a given line number, look for a marker
14168    at the new address of the old line number.  If one is found there,
14169    assume to be the same marker.  If the name / string id of the
14170    marker found is different from the previous known name, assume that
14171    means the user renamed the marker in the sources, and output a
14172    warning.
14173
14174    3) If a marker is no longer found at the same address or line, it
14175    may mean the marker no longer exists.  But it may also just mean
14176    the code changed a bit.  Maybe the user added a few lines of code
14177    that made the marker move up or down (in line number terms).  Ask
14178    the target for info about the marker with the string id as we knew
14179    it.  If found, update line number and address in the matching
14180    static tracepoint.  This will get confused if there's more than one
14181    marker with the same ID (possible in UST, although unadvised
14182    precisely because it confuses tools).  */
14183
14184 static struct symtab_and_line
14185 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14186 {
14187   struct tracepoint *tp = (struct tracepoint *) b;
14188   struct static_tracepoint_marker marker;
14189   CORE_ADDR pc;
14190
14191   pc = sal.pc;
14192   if (sal.line)
14193     find_line_pc (sal.symtab, sal.line, &pc);
14194
14195   if (target_static_tracepoint_marker_at (pc, &marker))
14196     {
14197       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14198         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14199                  b->number,
14200                  tp->static_trace_marker_id, marker.str_id);
14201
14202       xfree (tp->static_trace_marker_id);
14203       tp->static_trace_marker_id = xstrdup (marker.str_id);
14204       release_static_tracepoint_marker (&marker);
14205
14206       return sal;
14207     }
14208
14209   /* Old marker wasn't found on target at lineno.  Try looking it up
14210      by string ID.  */
14211   if (!sal.explicit_pc
14212       && sal.line != 0
14213       && sal.symtab != NULL
14214       && tp->static_trace_marker_id != NULL)
14215     {
14216       VEC(static_tracepoint_marker_p) *markers;
14217
14218       markers
14219         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14220
14221       if (!VEC_empty(static_tracepoint_marker_p, markers))
14222         {
14223           struct symtab_and_line sal2;
14224           struct symbol *sym;
14225           struct static_tracepoint_marker *tpmarker;
14226           struct ui_out *uiout = current_uiout;
14227
14228           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14229
14230           xfree (tp->static_trace_marker_id);
14231           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14232
14233           warning (_("marker for static tracepoint %d (%s) not "
14234                      "found at previous line number"),
14235                    b->number, tp->static_trace_marker_id);
14236
14237           init_sal (&sal2);
14238
14239           sal2.pc = tpmarker->address;
14240
14241           sal2 = find_pc_line (tpmarker->address, 0);
14242           sym = find_pc_sect_function (tpmarker->address, NULL);
14243           ui_out_text (uiout, "Now in ");
14244           if (sym)
14245             {
14246               ui_out_field_string (uiout, "func",
14247                                    SYMBOL_PRINT_NAME (sym));
14248               ui_out_text (uiout, " at ");
14249             }
14250           ui_out_field_string (uiout, "file",
14251                                symtab_to_filename_for_display (sal2.symtab));
14252           ui_out_text (uiout, ":");
14253
14254           if (ui_out_is_mi_like_p (uiout))
14255             {
14256               const char *fullname = symtab_to_fullname (sal2.symtab);
14257
14258               ui_out_field_string (uiout, "fullname", fullname);
14259             }
14260
14261           ui_out_field_int (uiout, "line", sal2.line);
14262           ui_out_text (uiout, "\n");
14263
14264           b->loc->line_number = sal2.line;
14265           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14266
14267           xfree (b->addr_string);
14268           b->addr_string = xstrprintf ("%s:%d",
14269                                    symtab_to_filename_for_display (sal2.symtab),
14270                                        b->loc->line_number);
14271
14272           /* Might be nice to check if function changed, and warn if
14273              so.  */
14274
14275           release_static_tracepoint_marker (tpmarker);
14276         }
14277     }
14278   return sal;
14279 }
14280
14281 /* Returns 1 iff locations A and B are sufficiently same that
14282    we don't need to report breakpoint as changed.  */
14283
14284 static int
14285 locations_are_equal (struct bp_location *a, struct bp_location *b)
14286 {
14287   while (a && b)
14288     {
14289       if (a->address != b->address)
14290         return 0;
14291
14292       if (a->shlib_disabled != b->shlib_disabled)
14293         return 0;
14294
14295       if (a->enabled != b->enabled)
14296         return 0;
14297
14298       a = a->next;
14299       b = b->next;
14300     }
14301
14302   if ((a == NULL) != (b == NULL))
14303     return 0;
14304
14305   return 1;
14306 }
14307
14308 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14309    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14310    a ranged breakpoint.  */
14311
14312 void
14313 update_breakpoint_locations (struct breakpoint *b,
14314                              struct symtabs_and_lines sals,
14315                              struct symtabs_and_lines sals_end)
14316 {
14317   int i;
14318   struct bp_location *existing_locations = b->loc;
14319
14320   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14321     {
14322       /* Ranged breakpoints have only one start location and one end
14323          location.  */
14324       b->enable_state = bp_disabled;
14325       update_global_location_list (1);
14326       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14327                            "multiple locations found\n"),
14328                          b->number);
14329       return;
14330     }
14331
14332   /* If there's no new locations, and all existing locations are
14333      pending, don't do anything.  This optimizes the common case where
14334      all locations are in the same shared library, that was unloaded.
14335      We'd like to retain the location, so that when the library is
14336      loaded again, we don't loose the enabled/disabled status of the
14337      individual locations.  */
14338   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14339     return;
14340
14341   b->loc = NULL;
14342
14343   for (i = 0; i < sals.nelts; ++i)
14344     {
14345       struct bp_location *new_loc;
14346
14347       switch_to_program_space_and_thread (sals.sals[i].pspace);
14348
14349       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14350
14351       /* Reparse conditions, they might contain references to the
14352          old symtab.  */
14353       if (b->cond_string != NULL)
14354         {
14355           const char *s;
14356           volatile struct gdb_exception e;
14357
14358           s = b->cond_string;
14359           TRY_CATCH (e, RETURN_MASK_ERROR)
14360             {
14361               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14362                                            block_for_pc (sals.sals[i].pc), 
14363                                            0);
14364             }
14365           if (e.reason < 0)
14366             {
14367               warning (_("failed to reevaluate condition "
14368                          "for breakpoint %d: %s"), 
14369                        b->number, e.message);
14370               new_loc->enabled = 0;
14371             }
14372         }
14373
14374       if (sals_end.nelts)
14375         {
14376           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14377
14378           new_loc->length = end - sals.sals[0].pc + 1;
14379         }
14380     }
14381
14382   /* Update locations of permanent breakpoints.  */
14383   if (b->enable_state == bp_permanent)
14384     make_breakpoint_permanent (b);
14385
14386   /* If possible, carry over 'disable' status from existing
14387      breakpoints.  */
14388   {
14389     struct bp_location *e = existing_locations;
14390     /* If there are multiple breakpoints with the same function name,
14391        e.g. for inline functions, comparing function names won't work.
14392        Instead compare pc addresses; this is just a heuristic as things
14393        may have moved, but in practice it gives the correct answer
14394        often enough until a better solution is found.  */
14395     int have_ambiguous_names = ambiguous_names_p (b->loc);
14396
14397     for (; e; e = e->next)
14398       {
14399         if (!e->enabled && e->function_name)
14400           {
14401             struct bp_location *l = b->loc;
14402             if (have_ambiguous_names)
14403               {
14404                 for (; l; l = l->next)
14405                   if (breakpoint_locations_match (e, l))
14406                     {
14407                       l->enabled = 0;
14408                       break;
14409                     }
14410               }
14411             else
14412               {
14413                 for (; l; l = l->next)
14414                   if (l->function_name
14415                       && strcmp (e->function_name, l->function_name) == 0)
14416                     {
14417                       l->enabled = 0;
14418                       break;
14419                     }
14420               }
14421           }
14422       }
14423   }
14424
14425   if (!locations_are_equal (existing_locations, b->loc))
14426     observer_notify_breakpoint_modified (b);
14427
14428   update_global_location_list (1);
14429 }
14430
14431 /* Find the SaL locations corresponding to the given ADDR_STRING.
14432    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14433
14434 static struct symtabs_and_lines
14435 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14436 {
14437   char *s;
14438   struct symtabs_and_lines sals = {0};
14439   volatile struct gdb_exception e;
14440
14441   gdb_assert (b->ops != NULL);
14442   s = addr_string;
14443
14444   TRY_CATCH (e, RETURN_MASK_ERROR)
14445     {
14446       b->ops->decode_linespec (b, &s, &sals);
14447     }
14448   if (e.reason < 0)
14449     {
14450       int not_found_and_ok = 0;
14451       /* For pending breakpoints, it's expected that parsing will
14452          fail until the right shared library is loaded.  User has
14453          already told to create pending breakpoints and don't need
14454          extra messages.  If breakpoint is in bp_shlib_disabled
14455          state, then user already saw the message about that
14456          breakpoint being disabled, and don't want to see more
14457          errors.  */
14458       if (e.error == NOT_FOUND_ERROR
14459           && (b->condition_not_parsed 
14460               || (b->loc && b->loc->shlib_disabled)
14461               || (b->loc && b->loc->pspace->executing_startup)
14462               || b->enable_state == bp_disabled))
14463         not_found_and_ok = 1;
14464
14465       if (!not_found_and_ok)
14466         {
14467           /* We surely don't want to warn about the same breakpoint
14468              10 times.  One solution, implemented here, is disable
14469              the breakpoint on error.  Another solution would be to
14470              have separate 'warning emitted' flag.  Since this
14471              happens only when a binary has changed, I don't know
14472              which approach is better.  */
14473           b->enable_state = bp_disabled;
14474           throw_exception (e);
14475         }
14476     }
14477
14478   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14479     {
14480       int i;
14481
14482       for (i = 0; i < sals.nelts; ++i)
14483         resolve_sal_pc (&sals.sals[i]);
14484       if (b->condition_not_parsed && s && s[0])
14485         {
14486           char *cond_string, *extra_string;
14487           int thread, task;
14488
14489           find_condition_and_thread (s, sals.sals[0].pc,
14490                                      &cond_string, &thread, &task,
14491                                      &extra_string);
14492           if (cond_string)
14493             b->cond_string = cond_string;
14494           b->thread = thread;
14495           b->task = task;
14496           if (extra_string)
14497             b->extra_string = extra_string;
14498           b->condition_not_parsed = 0;
14499         }
14500
14501       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14502         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14503
14504       *found = 1;
14505     }
14506   else
14507     *found = 0;
14508
14509   return sals;
14510 }
14511
14512 /* The default re_set method, for typical hardware or software
14513    breakpoints.  Reevaluate the breakpoint and recreate its
14514    locations.  */
14515
14516 static void
14517 breakpoint_re_set_default (struct breakpoint *b)
14518 {
14519   int found;
14520   struct symtabs_and_lines sals, sals_end;
14521   struct symtabs_and_lines expanded = {0};
14522   struct symtabs_and_lines expanded_end = {0};
14523
14524   sals = addr_string_to_sals (b, b->addr_string, &found);
14525   if (found)
14526     {
14527       make_cleanup (xfree, sals.sals);
14528       expanded = sals;
14529     }
14530
14531   if (b->addr_string_range_end)
14532     {
14533       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14534       if (found)
14535         {
14536           make_cleanup (xfree, sals_end.sals);
14537           expanded_end = sals_end;
14538         }
14539     }
14540
14541   update_breakpoint_locations (b, expanded, expanded_end);
14542 }
14543
14544 /* Default method for creating SALs from an address string.  It basically
14545    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14546
14547 static void
14548 create_sals_from_address_default (char **arg,
14549                                   struct linespec_result *canonical,
14550                                   enum bptype type_wanted,
14551                                   char *addr_start, char **copy_arg)
14552 {
14553   parse_breakpoint_sals (arg, canonical);
14554 }
14555
14556 /* Call create_breakpoints_sal for the given arguments.  This is the default
14557    function for the `create_breakpoints_sal' method of
14558    breakpoint_ops.  */
14559
14560 static void
14561 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14562                                 struct linespec_result *canonical,
14563                                 char *cond_string,
14564                                 char *extra_string,
14565                                 enum bptype type_wanted,
14566                                 enum bpdisp disposition,
14567                                 int thread,
14568                                 int task, int ignore_count,
14569                                 const struct breakpoint_ops *ops,
14570                                 int from_tty, int enabled,
14571                                 int internal, unsigned flags)
14572 {
14573   create_breakpoints_sal (gdbarch, canonical, cond_string,
14574                           extra_string,
14575                           type_wanted, disposition,
14576                           thread, task, ignore_count, ops, from_tty,
14577                           enabled, internal, flags);
14578 }
14579
14580 /* Decode the line represented by S by calling decode_line_full.  This is the
14581    default function for the `decode_linespec' method of breakpoint_ops.  */
14582
14583 static void
14584 decode_linespec_default (struct breakpoint *b, char **s,
14585                          struct symtabs_and_lines *sals)
14586 {
14587   struct linespec_result canonical;
14588
14589   init_linespec_result (&canonical);
14590   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14591                     (struct symtab *) NULL, 0,
14592                     &canonical, multiple_symbols_all,
14593                     b->filter);
14594
14595   /* We should get 0 or 1 resulting SALs.  */
14596   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14597
14598   if (VEC_length (linespec_sals, canonical.sals) > 0)
14599     {
14600       struct linespec_sals *lsal;
14601
14602       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14603       *sals = lsal->sals;
14604       /* Arrange it so the destructor does not free the
14605          contents.  */
14606       lsal->sals.sals = NULL;
14607     }
14608
14609   destroy_linespec_result (&canonical);
14610 }
14611
14612 /* Prepare the global context for a re-set of breakpoint B.  */
14613
14614 static struct cleanup *
14615 prepare_re_set_context (struct breakpoint *b)
14616 {
14617   struct cleanup *cleanups;
14618
14619   input_radix = b->input_radix;
14620   cleanups = save_current_space_and_thread ();
14621   if (b->pspace != NULL)
14622     switch_to_program_space_and_thread (b->pspace);
14623   set_language (b->language);
14624
14625   return cleanups;
14626 }
14627
14628 /* Reset a breakpoint given it's struct breakpoint * BINT.
14629    The value we return ends up being the return value from catch_errors.
14630    Unused in this case.  */
14631
14632 static int
14633 breakpoint_re_set_one (void *bint)
14634 {
14635   /* Get past catch_errs.  */
14636   struct breakpoint *b = (struct breakpoint *) bint;
14637   struct cleanup *cleanups;
14638
14639   cleanups = prepare_re_set_context (b);
14640   b->ops->re_set (b);
14641   do_cleanups (cleanups);
14642   return 0;
14643 }
14644
14645 /* Re-set all breakpoints after symbols have been re-loaded.  */
14646 void
14647 breakpoint_re_set (void)
14648 {
14649   struct breakpoint *b, *b_tmp;
14650   enum language save_language;
14651   int save_input_radix;
14652   struct cleanup *old_chain;
14653
14654   save_language = current_language->la_language;
14655   save_input_radix = input_radix;
14656   old_chain = save_current_program_space ();
14657
14658   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14659   {
14660     /* Format possible error msg.  */
14661     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14662                                 b->number);
14663     struct cleanup *cleanups = make_cleanup (xfree, message);
14664     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14665     do_cleanups (cleanups);
14666   }
14667   set_language (save_language);
14668   input_radix = save_input_radix;
14669
14670   jit_breakpoint_re_set ();
14671
14672   do_cleanups (old_chain);
14673
14674   create_overlay_event_breakpoint ();
14675   create_longjmp_master_breakpoint ();
14676   create_std_terminate_master_breakpoint ();
14677   create_exception_master_breakpoint ();
14678 }
14679 \f
14680 /* Reset the thread number of this breakpoint:
14681
14682    - If the breakpoint is for all threads, leave it as-is.
14683    - Else, reset it to the current thread for inferior_ptid.  */
14684 void
14685 breakpoint_re_set_thread (struct breakpoint *b)
14686 {
14687   if (b->thread != -1)
14688     {
14689       if (in_thread_list (inferior_ptid))
14690         b->thread = pid_to_thread_id (inferior_ptid);
14691
14692       /* We're being called after following a fork.  The new fork is
14693          selected as current, and unless this was a vfork will have a
14694          different program space from the original thread.  Reset that
14695          as well.  */
14696       b->loc->pspace = current_program_space;
14697     }
14698 }
14699
14700 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14701    If from_tty is nonzero, it prints a message to that effect,
14702    which ends with a period (no newline).  */
14703
14704 void
14705 set_ignore_count (int bptnum, int count, int from_tty)
14706 {
14707   struct breakpoint *b;
14708
14709   if (count < 0)
14710     count = 0;
14711
14712   ALL_BREAKPOINTS (b)
14713     if (b->number == bptnum)
14714     {
14715       if (is_tracepoint (b))
14716         {
14717           if (from_tty && count != 0)
14718             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14719                              bptnum);
14720           return;
14721         }
14722       
14723       b->ignore_count = count;
14724       if (from_tty)
14725         {
14726           if (count == 0)
14727             printf_filtered (_("Will stop next time "
14728                                "breakpoint %d is reached."),
14729                              bptnum);
14730           else if (count == 1)
14731             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14732                              bptnum);
14733           else
14734             printf_filtered (_("Will ignore next %d "
14735                                "crossings of breakpoint %d."),
14736                              count, bptnum);
14737         }
14738       observer_notify_breakpoint_modified (b);
14739       return;
14740     }
14741
14742   error (_("No breakpoint number %d."), bptnum);
14743 }
14744
14745 /* Command to set ignore-count of breakpoint N to COUNT.  */
14746
14747 static void
14748 ignore_command (char *args, int from_tty)
14749 {
14750   char *p = args;
14751   int num;
14752
14753   if (p == 0)
14754     error_no_arg (_("a breakpoint number"));
14755
14756   num = get_number (&p);
14757   if (num == 0)
14758     error (_("bad breakpoint number: '%s'"), args);
14759   if (*p == 0)
14760     error (_("Second argument (specified ignore-count) is missing."));
14761
14762   set_ignore_count (num,
14763                     longest_to_int (value_as_long (parse_and_eval (p))),
14764                     from_tty);
14765   if (from_tty)
14766     printf_filtered ("\n");
14767 }
14768 \f
14769 /* Call FUNCTION on each of the breakpoints
14770    whose numbers are given in ARGS.  */
14771
14772 static void
14773 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14774                                                       void *),
14775                         void *data)
14776 {
14777   int num;
14778   struct breakpoint *b, *tmp;
14779   int match;
14780   struct get_number_or_range_state state;
14781
14782   if (args == 0)
14783     error_no_arg (_("one or more breakpoint numbers"));
14784
14785   init_number_or_range (&state, args);
14786
14787   while (!state.finished)
14788     {
14789       const char *p = state.string;
14790
14791       match = 0;
14792
14793       num = get_number_or_range (&state);
14794       if (num == 0)
14795         {
14796           warning (_("bad breakpoint number at or near '%s'"), p);
14797         }
14798       else
14799         {
14800           ALL_BREAKPOINTS_SAFE (b, tmp)
14801             if (b->number == num)
14802               {
14803                 match = 1;
14804                 function (b, data);
14805                 break;
14806               }
14807           if (match == 0)
14808             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14809         }
14810     }
14811 }
14812
14813 static struct bp_location *
14814 find_location_by_number (char *number)
14815 {
14816   char *dot = strchr (number, '.');
14817   char *p1;
14818   int bp_num;
14819   int loc_num;
14820   struct breakpoint *b;
14821   struct bp_location *loc;  
14822
14823   *dot = '\0';
14824
14825   p1 = number;
14826   bp_num = get_number (&p1);
14827   if (bp_num == 0)
14828     error (_("Bad breakpoint number '%s'"), number);
14829
14830   ALL_BREAKPOINTS (b)
14831     if (b->number == bp_num)
14832       {
14833         break;
14834       }
14835
14836   if (!b || b->number != bp_num)
14837     error (_("Bad breakpoint number '%s'"), number);
14838   
14839   p1 = dot+1;
14840   loc_num = get_number (&p1);
14841   if (loc_num == 0)
14842     error (_("Bad breakpoint location number '%s'"), number);
14843
14844   --loc_num;
14845   loc = b->loc;
14846   for (;loc_num && loc; --loc_num, loc = loc->next)
14847     ;
14848   if (!loc)
14849     error (_("Bad breakpoint location number '%s'"), dot+1);
14850     
14851   return loc;  
14852 }
14853
14854
14855 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14856    If from_tty is nonzero, it prints a message to that effect,
14857    which ends with a period (no newline).  */
14858
14859 void
14860 disable_breakpoint (struct breakpoint *bpt)
14861 {
14862   /* Never disable a watchpoint scope breakpoint; we want to
14863      hit them when we leave scope so we can delete both the
14864      watchpoint and its scope breakpoint at that time.  */
14865   if (bpt->type == bp_watchpoint_scope)
14866     return;
14867
14868   /* You can't disable permanent breakpoints.  */
14869   if (bpt->enable_state == bp_permanent)
14870     return;
14871
14872   bpt->enable_state = bp_disabled;
14873
14874   /* Mark breakpoint locations modified.  */
14875   mark_breakpoint_modified (bpt);
14876
14877   if (target_supports_enable_disable_tracepoint ()
14878       && current_trace_status ()->running && is_tracepoint (bpt))
14879     {
14880       struct bp_location *location;
14881      
14882       for (location = bpt->loc; location; location = location->next)
14883         target_disable_tracepoint (location);
14884     }
14885
14886   update_global_location_list (0);
14887
14888   observer_notify_breakpoint_modified (bpt);
14889 }
14890
14891 /* A callback for iterate_over_related_breakpoints.  */
14892
14893 static void
14894 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14895 {
14896   disable_breakpoint (b);
14897 }
14898
14899 /* A callback for map_breakpoint_numbers that calls
14900    disable_breakpoint.  */
14901
14902 static void
14903 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14904 {
14905   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14906 }
14907
14908 static void
14909 disable_command (char *args, int from_tty)
14910 {
14911   if (args == 0)
14912     {
14913       struct breakpoint *bpt;
14914
14915       ALL_BREAKPOINTS (bpt)
14916         if (user_breakpoint_p (bpt))
14917           disable_breakpoint (bpt);
14918     }
14919   else
14920     {
14921       char *num = extract_arg (&args);
14922
14923       while (num)
14924         {
14925           if (strchr (num, '.'))
14926             {
14927               struct bp_location *loc = find_location_by_number (num);
14928
14929               if (loc)
14930                 {
14931                   if (loc->enabled)
14932                     {
14933                       loc->enabled = 0;
14934                       mark_breakpoint_location_modified (loc);
14935                     }
14936                   if (target_supports_enable_disable_tracepoint ()
14937                       && current_trace_status ()->running && loc->owner
14938                       && is_tracepoint (loc->owner))
14939                     target_disable_tracepoint (loc);
14940                 }
14941               update_global_location_list (0);
14942             }
14943           else
14944             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14945           num = extract_arg (&args);
14946         }
14947     }
14948 }
14949
14950 static void
14951 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14952                         int count)
14953 {
14954   int target_resources_ok;
14955
14956   if (bpt->type == bp_hardware_breakpoint)
14957     {
14958       int i;
14959       i = hw_breakpoint_used_count ();
14960       target_resources_ok = 
14961         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14962                                             i + 1, 0);
14963       if (target_resources_ok == 0)
14964         error (_("No hardware breakpoint support in the target."));
14965       else if (target_resources_ok < 0)
14966         error (_("Hardware breakpoints used exceeds limit."));
14967     }
14968
14969   if (is_watchpoint (bpt))
14970     {
14971       /* Initialize it just to avoid a GCC false warning.  */
14972       enum enable_state orig_enable_state = 0;
14973       volatile struct gdb_exception e;
14974
14975       TRY_CATCH (e, RETURN_MASK_ALL)
14976         {
14977           struct watchpoint *w = (struct watchpoint *) bpt;
14978
14979           orig_enable_state = bpt->enable_state;
14980           bpt->enable_state = bp_enabled;
14981           update_watchpoint (w, 1 /* reparse */);
14982         }
14983       if (e.reason < 0)
14984         {
14985           bpt->enable_state = orig_enable_state;
14986           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14987                              bpt->number);
14988           return;
14989         }
14990     }
14991
14992   if (bpt->enable_state != bp_permanent)
14993     bpt->enable_state = bp_enabled;
14994
14995   bpt->enable_state = bp_enabled;
14996
14997   /* Mark breakpoint locations modified.  */
14998   mark_breakpoint_modified (bpt);
14999
15000   if (target_supports_enable_disable_tracepoint ()
15001       && current_trace_status ()->running && is_tracepoint (bpt))
15002     {
15003       struct bp_location *location;
15004
15005       for (location = bpt->loc; location; location = location->next)
15006         target_enable_tracepoint (location);
15007     }
15008
15009   bpt->disposition = disposition;
15010   bpt->enable_count = count;
15011   update_global_location_list (1);
15012
15013   observer_notify_breakpoint_modified (bpt);
15014 }
15015
15016
15017 void
15018 enable_breakpoint (struct breakpoint *bpt)
15019 {
15020   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15021 }
15022
15023 static void
15024 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15025 {
15026   enable_breakpoint (bpt);
15027 }
15028
15029 /* A callback for map_breakpoint_numbers that calls
15030    enable_breakpoint.  */
15031
15032 static void
15033 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15034 {
15035   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15036 }
15037
15038 /* The enable command enables the specified breakpoints (or all defined
15039    breakpoints) so they once again become (or continue to be) effective
15040    in stopping the inferior.  */
15041
15042 static void
15043 enable_command (char *args, int from_tty)
15044 {
15045   if (args == 0)
15046     {
15047       struct breakpoint *bpt;
15048
15049       ALL_BREAKPOINTS (bpt)
15050         if (user_breakpoint_p (bpt))
15051           enable_breakpoint (bpt);
15052     }
15053   else
15054     {
15055       char *num = extract_arg (&args);
15056
15057       while (num)
15058         {
15059           if (strchr (num, '.'))
15060             {
15061               struct bp_location *loc = find_location_by_number (num);
15062
15063               if (loc)
15064                 {
15065                   if (!loc->enabled)
15066                     {
15067                       loc->enabled = 1;
15068                       mark_breakpoint_location_modified (loc);
15069                     }
15070                   if (target_supports_enable_disable_tracepoint ()
15071                       && current_trace_status ()->running && loc->owner
15072                       && is_tracepoint (loc->owner))
15073                     target_enable_tracepoint (loc);
15074                 }
15075               update_global_location_list (1);
15076             }
15077           else
15078             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15079           num = extract_arg (&args);
15080         }
15081     }
15082 }
15083
15084 /* This struct packages up disposition data for application to multiple
15085    breakpoints.  */
15086
15087 struct disp_data
15088 {
15089   enum bpdisp disp;
15090   int count;
15091 };
15092
15093 static void
15094 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15095 {
15096   struct disp_data disp_data = *(struct disp_data *) arg;
15097
15098   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15099 }
15100
15101 static void
15102 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15103 {
15104   struct disp_data disp = { disp_disable, 1 };
15105
15106   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15107 }
15108
15109 static void
15110 enable_once_command (char *args, int from_tty)
15111 {
15112   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15113 }
15114
15115 static void
15116 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15117 {
15118   struct disp_data disp = { disp_disable, *(int *) countptr };
15119
15120   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15121 }
15122
15123 static void
15124 enable_count_command (char *args, int from_tty)
15125 {
15126   int count = get_number (&args);
15127
15128   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15129 }
15130
15131 static void
15132 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15133 {
15134   struct disp_data disp = { disp_del, 1 };
15135
15136   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15137 }
15138
15139 static void
15140 enable_delete_command (char *args, int from_tty)
15141 {
15142   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15143 }
15144 \f
15145 static void
15146 set_breakpoint_cmd (char *args, int from_tty)
15147 {
15148 }
15149
15150 static void
15151 show_breakpoint_cmd (char *args, int from_tty)
15152 {
15153 }
15154
15155 /* Invalidate last known value of any hardware watchpoint if
15156    the memory which that value represents has been written to by
15157    GDB itself.  */
15158
15159 static void
15160 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15161                                       CORE_ADDR addr, ssize_t len,
15162                                       const bfd_byte *data)
15163 {
15164   struct breakpoint *bp;
15165
15166   ALL_BREAKPOINTS (bp)
15167     if (bp->enable_state == bp_enabled
15168         && bp->type == bp_hardware_watchpoint)
15169       {
15170         struct watchpoint *wp = (struct watchpoint *) bp;
15171
15172         if (wp->val_valid && wp->val)
15173           {
15174             struct bp_location *loc;
15175
15176             for (loc = bp->loc; loc != NULL; loc = loc->next)
15177               if (loc->loc_type == bp_loc_hardware_watchpoint
15178                   && loc->address + loc->length > addr
15179                   && addr + len > loc->address)
15180                 {
15181                   value_free (wp->val);
15182                   wp->val = NULL;
15183                   wp->val_valid = 0;
15184                 }
15185           }
15186       }
15187 }
15188
15189 /* Create and insert a raw software breakpoint at PC.  Return an
15190    identifier, which should be used to remove the breakpoint later.
15191    In general, places which call this should be using something on the
15192    breakpoint chain instead; this function should be eliminated
15193    someday.  */
15194
15195 void *
15196 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15197                                   struct address_space *aspace, CORE_ADDR pc)
15198 {
15199   struct bp_target_info *bp_tgt;
15200   struct bp_location *bl;
15201
15202   bp_tgt = XCNEW (struct bp_target_info);
15203
15204   bp_tgt->placed_address_space = aspace;
15205   bp_tgt->placed_address = pc;
15206
15207   /* If an unconditional non-raw breakpoint is already inserted at
15208      that location, there's no need to insert another.  However, with
15209      target-side evaluation of breakpoint conditions, if the
15210      breakpoint that is currently inserted on the target is
15211      conditional, we need to make it unconditional.  Note that a
15212      breakpoint with target-side commands is not reported even if
15213      unconditional, so we need to remove the commands from the target
15214      as well.  */
15215   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15216   if (bl != NULL
15217       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15218       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15219     {
15220       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15221       return bp_tgt;
15222     }
15223
15224   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15225     {
15226       /* Could not insert the breakpoint.  */
15227       xfree (bp_tgt);
15228       return NULL;
15229     }
15230
15231   return bp_tgt;
15232 }
15233
15234 /* Remove a breakpoint BP inserted by
15235    deprecated_insert_raw_breakpoint.  */
15236
15237 int
15238 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15239 {
15240   struct bp_target_info *bp_tgt = bp;
15241   struct address_space *aspace = bp_tgt->placed_address_space;
15242   CORE_ADDR address = bp_tgt->placed_address;
15243   struct bp_location *bl;
15244   int ret;
15245
15246   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15247
15248   /* Only remove the raw breakpoint if there are no other non-raw
15249      breakpoints still inserted at this location.  Otherwise, we would
15250      be effectively disabling those breakpoints.  */
15251   if (bl == NULL)
15252     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15253   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15254            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15255     {
15256       /* The target is evaluating conditions, and when we inserted the
15257          software single-step breakpoint, we had made the breakpoint
15258          unconditional and command-less on the target side.  Reinsert
15259          to restore the conditions/commands.  */
15260       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15261     }
15262   else
15263     ret = 0;
15264
15265   xfree (bp_tgt);
15266
15267   return ret;
15268 }
15269
15270 /* Create and insert a breakpoint for software single step.  */
15271
15272 void
15273 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15274                                struct address_space *aspace, 
15275                                CORE_ADDR next_pc)
15276 {
15277   void **bpt_p;
15278
15279   if (single_step_breakpoints[0] == NULL)
15280     {
15281       bpt_p = &single_step_breakpoints[0];
15282       single_step_gdbarch[0] = gdbarch;
15283     }
15284   else
15285     {
15286       gdb_assert (single_step_breakpoints[1] == NULL);
15287       bpt_p = &single_step_breakpoints[1];
15288       single_step_gdbarch[1] = gdbarch;
15289     }
15290
15291   /* NOTE drow/2006-04-11: A future improvement to this function would
15292      be to only create the breakpoints once, and actually put them on
15293      the breakpoint chain.  That would let us use set_raw_breakpoint.
15294      We could adjust the addresses each time they were needed.  Doing
15295      this requires corresponding changes elsewhere where single step
15296      breakpoints are handled, however.  So, for now, we use this.  */
15297
15298   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15299   if (*bpt_p == NULL)
15300     error (_("Could not insert single-step breakpoint at %s"),
15301              paddress (gdbarch, next_pc));
15302 }
15303
15304 /* Check if the breakpoints used for software single stepping
15305    were inserted or not.  */
15306
15307 int
15308 single_step_breakpoints_inserted (void)
15309 {
15310   return (single_step_breakpoints[0] != NULL
15311           || single_step_breakpoints[1] != NULL);
15312 }
15313
15314 /* Remove and delete any breakpoints used for software single step.  */
15315
15316 void
15317 remove_single_step_breakpoints (void)
15318 {
15319   gdb_assert (single_step_breakpoints[0] != NULL);
15320
15321   /* See insert_single_step_breakpoint for more about this deprecated
15322      call.  */
15323   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15324                                     single_step_breakpoints[0]);
15325   single_step_gdbarch[0] = NULL;
15326   single_step_breakpoints[0] = NULL;
15327
15328   if (single_step_breakpoints[1] != NULL)
15329     {
15330       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15331                                         single_step_breakpoints[1]);
15332       single_step_gdbarch[1] = NULL;
15333       single_step_breakpoints[1] = NULL;
15334     }
15335 }
15336
15337 /* Delete software single step breakpoints without removing them from
15338    the inferior.  This is intended to be used if the inferior's address
15339    space where they were inserted is already gone, e.g. after exit or
15340    exec.  */
15341
15342 void
15343 cancel_single_step_breakpoints (void)
15344 {
15345   int i;
15346
15347   for (i = 0; i < 2; i++)
15348     if (single_step_breakpoints[i])
15349       {
15350         xfree (single_step_breakpoints[i]);
15351         single_step_breakpoints[i] = NULL;
15352         single_step_gdbarch[i] = NULL;
15353       }
15354 }
15355
15356 /* Detach software single-step breakpoints from INFERIOR_PTID without
15357    removing them.  */
15358
15359 static void
15360 detach_single_step_breakpoints (void)
15361 {
15362   int i;
15363
15364   for (i = 0; i < 2; i++)
15365     if (single_step_breakpoints[i])
15366       target_remove_breakpoint (single_step_gdbarch[i],
15367                                 single_step_breakpoints[i]);
15368 }
15369
15370 /* Find the software single-step breakpoint that inserted at PC.
15371    Returns its slot if found, and -1 if not found.  */
15372
15373 static int
15374 find_single_step_breakpoint (struct address_space *aspace,
15375                              CORE_ADDR pc)
15376 {
15377   int i;
15378
15379   for (i = 0; i < 2; i++)
15380     {
15381       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15382       if (bp_tgt
15383           && breakpoint_address_match (bp_tgt->placed_address_space,
15384                                        bp_tgt->placed_address,
15385                                        aspace, pc))
15386         return i;
15387     }
15388
15389   return -1;
15390 }
15391
15392 /* Check whether a software single-step breakpoint is inserted at
15393    PC.  */
15394
15395 int
15396 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15397                                         CORE_ADDR pc)
15398 {
15399   return find_single_step_breakpoint (aspace, pc) >= 0;
15400 }
15401
15402 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15403    non-zero otherwise.  */
15404 static int
15405 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15406 {
15407   if (syscall_catchpoint_p (bp)
15408       && bp->enable_state != bp_disabled
15409       && bp->enable_state != bp_call_disabled)
15410     return 1;
15411   else
15412     return 0;
15413 }
15414
15415 int
15416 catch_syscall_enabled (void)
15417 {
15418   struct catch_syscall_inferior_data *inf_data
15419     = get_catch_syscall_inferior_data (current_inferior ());
15420
15421   return inf_data->total_syscalls_count != 0;
15422 }
15423
15424 int
15425 catching_syscall_number (int syscall_number)
15426 {
15427   struct breakpoint *bp;
15428
15429   ALL_BREAKPOINTS (bp)
15430     if (is_syscall_catchpoint_enabled (bp))
15431       {
15432         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15433
15434         if (c->syscalls_to_be_caught)
15435           {
15436             int i, iter;
15437             for (i = 0;
15438                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15439                  i++)
15440               if (syscall_number == iter)
15441                 return 1;
15442           }
15443         else
15444           return 1;
15445       }
15446
15447   return 0;
15448 }
15449
15450 /* Complete syscall names.  Used by "catch syscall".  */
15451 static VEC (char_ptr) *
15452 catch_syscall_completer (struct cmd_list_element *cmd,
15453                          const char *text, const char *word)
15454 {
15455   const char **list = get_syscall_names ();
15456   VEC (char_ptr) *retlist
15457     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15458
15459   xfree (list);
15460   return retlist;
15461 }
15462
15463 /* Tracepoint-specific operations.  */
15464
15465 /* Set tracepoint count to NUM.  */
15466 static void
15467 set_tracepoint_count (int num)
15468 {
15469   tracepoint_count = num;
15470   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15471 }
15472
15473 static void
15474 trace_command (char *arg, int from_tty)
15475 {
15476   struct breakpoint_ops *ops;
15477   const char *arg_cp = arg;
15478
15479   if (arg && probe_linespec_to_ops (&arg_cp))
15480     ops = &tracepoint_probe_breakpoint_ops;
15481   else
15482     ops = &tracepoint_breakpoint_ops;
15483
15484   create_breakpoint (get_current_arch (),
15485                      arg,
15486                      NULL, 0, NULL, 1 /* parse arg */,
15487                      0 /* tempflag */,
15488                      bp_tracepoint /* type_wanted */,
15489                      0 /* Ignore count */,
15490                      pending_break_support,
15491                      ops,
15492                      from_tty,
15493                      1 /* enabled */,
15494                      0 /* internal */, 0);
15495 }
15496
15497 static void
15498 ftrace_command (char *arg, int from_tty)
15499 {
15500   create_breakpoint (get_current_arch (),
15501                      arg,
15502                      NULL, 0, NULL, 1 /* parse arg */,
15503                      0 /* tempflag */,
15504                      bp_fast_tracepoint /* type_wanted */,
15505                      0 /* Ignore count */,
15506                      pending_break_support,
15507                      &tracepoint_breakpoint_ops,
15508                      from_tty,
15509                      1 /* enabled */,
15510                      0 /* internal */, 0);
15511 }
15512
15513 /* strace command implementation.  Creates a static tracepoint.  */
15514
15515 static void
15516 strace_command (char *arg, int from_tty)
15517 {
15518   struct breakpoint_ops *ops;
15519
15520   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15521      or with a normal static tracepoint.  */
15522   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15523     ops = &strace_marker_breakpoint_ops;
15524   else
15525     ops = &tracepoint_breakpoint_ops;
15526
15527   create_breakpoint (get_current_arch (),
15528                      arg,
15529                      NULL, 0, NULL, 1 /* parse arg */,
15530                      0 /* tempflag */,
15531                      bp_static_tracepoint /* type_wanted */,
15532                      0 /* Ignore count */,
15533                      pending_break_support,
15534                      ops,
15535                      from_tty,
15536                      1 /* enabled */,
15537                      0 /* internal */, 0);
15538 }
15539
15540 /* Set up a fake reader function that gets command lines from a linked
15541    list that was acquired during tracepoint uploading.  */
15542
15543 static struct uploaded_tp *this_utp;
15544 static int next_cmd;
15545
15546 static char *
15547 read_uploaded_action (void)
15548 {
15549   char *rslt;
15550
15551   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15552
15553   next_cmd++;
15554
15555   return rslt;
15556 }
15557
15558 /* Given information about a tracepoint as recorded on a target (which
15559    can be either a live system or a trace file), attempt to create an
15560    equivalent GDB tracepoint.  This is not a reliable process, since
15561    the target does not necessarily have all the information used when
15562    the tracepoint was originally defined.  */
15563   
15564 struct tracepoint *
15565 create_tracepoint_from_upload (struct uploaded_tp *utp)
15566 {
15567   char *addr_str, small_buf[100];
15568   struct tracepoint *tp;
15569
15570   if (utp->at_string)
15571     addr_str = utp->at_string;
15572   else
15573     {
15574       /* In the absence of a source location, fall back to raw
15575          address.  Since there is no way to confirm that the address
15576          means the same thing as when the trace was started, warn the
15577          user.  */
15578       warning (_("Uploaded tracepoint %d has no "
15579                  "source location, using raw address"),
15580                utp->number);
15581       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15582       addr_str = small_buf;
15583     }
15584
15585   /* There's not much we can do with a sequence of bytecodes.  */
15586   if (utp->cond && !utp->cond_string)
15587     warning (_("Uploaded tracepoint %d condition "
15588                "has no source form, ignoring it"),
15589              utp->number);
15590
15591   if (!create_breakpoint (get_current_arch (),
15592                           addr_str,
15593                           utp->cond_string, -1, NULL,
15594                           0 /* parse cond/thread */,
15595                           0 /* tempflag */,
15596                           utp->type /* type_wanted */,
15597                           0 /* Ignore count */,
15598                           pending_break_support,
15599                           &tracepoint_breakpoint_ops,
15600                           0 /* from_tty */,
15601                           utp->enabled /* enabled */,
15602                           0 /* internal */,
15603                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15604     return NULL;
15605
15606   /* Get the tracepoint we just created.  */
15607   tp = get_tracepoint (tracepoint_count);
15608   gdb_assert (tp != NULL);
15609
15610   if (utp->pass > 0)
15611     {
15612       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15613                  tp->base.number);
15614
15615       trace_pass_command (small_buf, 0);
15616     }
15617
15618   /* If we have uploaded versions of the original commands, set up a
15619      special-purpose "reader" function and call the usual command line
15620      reader, then pass the result to the breakpoint command-setting
15621      function.  */
15622   if (!VEC_empty (char_ptr, utp->cmd_strings))
15623     {
15624       struct command_line *cmd_list;
15625
15626       this_utp = utp;
15627       next_cmd = 0;
15628
15629       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15630
15631       breakpoint_set_commands (&tp->base, cmd_list);
15632     }
15633   else if (!VEC_empty (char_ptr, utp->actions)
15634            || !VEC_empty (char_ptr, utp->step_actions))
15635     warning (_("Uploaded tracepoint %d actions "
15636                "have no source form, ignoring them"),
15637              utp->number);
15638
15639   /* Copy any status information that might be available.  */
15640   tp->base.hit_count = utp->hit_count;
15641   tp->traceframe_usage = utp->traceframe_usage;
15642
15643   return tp;
15644 }
15645   
15646 /* Print information on tracepoint number TPNUM_EXP, or all if
15647    omitted.  */
15648
15649 static void
15650 tracepoints_info (char *args, int from_tty)
15651 {
15652   struct ui_out *uiout = current_uiout;
15653   int num_printed;
15654
15655   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15656
15657   if (num_printed == 0)
15658     {
15659       if (args == NULL || *args == '\0')
15660         ui_out_message (uiout, 0, "No tracepoints.\n");
15661       else
15662         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15663     }
15664
15665   default_collect_info ();
15666 }
15667
15668 /* The 'enable trace' command enables tracepoints.
15669    Not supported by all targets.  */
15670 static void
15671 enable_trace_command (char *args, int from_tty)
15672 {
15673   enable_command (args, from_tty);
15674 }
15675
15676 /* The 'disable trace' command disables tracepoints.
15677    Not supported by all targets.  */
15678 static void
15679 disable_trace_command (char *args, int from_tty)
15680 {
15681   disable_command (args, from_tty);
15682 }
15683
15684 /* Remove a tracepoint (or all if no argument).  */
15685 static void
15686 delete_trace_command (char *arg, int from_tty)
15687 {
15688   struct breakpoint *b, *b_tmp;
15689
15690   dont_repeat ();
15691
15692   if (arg == 0)
15693     {
15694       int breaks_to_delete = 0;
15695
15696       /* Delete all breakpoints if no argument.
15697          Do not delete internal or call-dummy breakpoints, these
15698          have to be deleted with an explicit breakpoint number 
15699          argument.  */
15700       ALL_TRACEPOINTS (b)
15701         if (is_tracepoint (b) && user_breakpoint_p (b))
15702           {
15703             breaks_to_delete = 1;
15704             break;
15705           }
15706
15707       /* Ask user only if there are some breakpoints to delete.  */
15708       if (!from_tty
15709           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15710         {
15711           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15712             if (is_tracepoint (b) && user_breakpoint_p (b))
15713               delete_breakpoint (b);
15714         }
15715     }
15716   else
15717     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15718 }
15719
15720 /* Helper function for trace_pass_command.  */
15721
15722 static void
15723 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15724 {
15725   tp->pass_count = count;
15726   observer_notify_breakpoint_modified (&tp->base);
15727   if (from_tty)
15728     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15729                      tp->base.number, count);
15730 }
15731
15732 /* Set passcount for tracepoint.
15733
15734    First command argument is passcount, second is tracepoint number.
15735    If tracepoint number omitted, apply to most recently defined.
15736    Also accepts special argument "all".  */
15737
15738 static void
15739 trace_pass_command (char *args, int from_tty)
15740 {
15741   struct tracepoint *t1;
15742   unsigned int count;
15743
15744   if (args == 0 || *args == 0)
15745     error (_("passcount command requires an "
15746              "argument (count + optional TP num)"));
15747
15748   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15749
15750   args = skip_spaces (args);
15751   if (*args && strncasecmp (args, "all", 3) == 0)
15752     {
15753       struct breakpoint *b;
15754
15755       args += 3;                        /* Skip special argument "all".  */
15756       if (*args)
15757         error (_("Junk at end of arguments."));
15758
15759       ALL_TRACEPOINTS (b)
15760       {
15761         t1 = (struct tracepoint *) b;
15762         trace_pass_set_count (t1, count, from_tty);
15763       }
15764     }
15765   else if (*args == '\0')
15766     {
15767       t1 = get_tracepoint_by_number (&args, NULL);
15768       if (t1)
15769         trace_pass_set_count (t1, count, from_tty);
15770     }
15771   else
15772     {
15773       struct get_number_or_range_state state;
15774
15775       init_number_or_range (&state, args);
15776       while (!state.finished)
15777         {
15778           t1 = get_tracepoint_by_number (&args, &state);
15779           if (t1)
15780             trace_pass_set_count (t1, count, from_tty);
15781         }
15782     }
15783 }
15784
15785 struct tracepoint *
15786 get_tracepoint (int num)
15787 {
15788   struct breakpoint *t;
15789
15790   ALL_TRACEPOINTS (t)
15791     if (t->number == num)
15792       return (struct tracepoint *) t;
15793
15794   return NULL;
15795 }
15796
15797 /* Find the tracepoint with the given target-side number (which may be
15798    different from the tracepoint number after disconnecting and
15799    reconnecting).  */
15800
15801 struct tracepoint *
15802 get_tracepoint_by_number_on_target (int num)
15803 {
15804   struct breakpoint *b;
15805
15806   ALL_TRACEPOINTS (b)
15807     {
15808       struct tracepoint *t = (struct tracepoint *) b;
15809
15810       if (t->number_on_target == num)
15811         return t;
15812     }
15813
15814   return NULL;
15815 }
15816
15817 /* Utility: parse a tracepoint number and look it up in the list.
15818    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15819    If the argument is missing, the most recent tracepoint
15820    (tracepoint_count) is returned.  */
15821
15822 struct tracepoint *
15823 get_tracepoint_by_number (char **arg,
15824                           struct get_number_or_range_state *state)
15825 {
15826   struct breakpoint *t;
15827   int tpnum;
15828   char *instring = arg == NULL ? NULL : *arg;
15829
15830   if (state)
15831     {
15832       gdb_assert (!state->finished);
15833       tpnum = get_number_or_range (state);
15834     }
15835   else if (arg == NULL || *arg == NULL || ! **arg)
15836     tpnum = tracepoint_count;
15837   else
15838     tpnum = get_number (arg);
15839
15840   if (tpnum <= 0)
15841     {
15842       if (instring && *instring)
15843         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15844                          instring);
15845       else
15846         printf_filtered (_("No previous tracepoint\n"));
15847       return NULL;
15848     }
15849
15850   ALL_TRACEPOINTS (t)
15851     if (t->number == tpnum)
15852     {
15853       return (struct tracepoint *) t;
15854     }
15855
15856   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15857   return NULL;
15858 }
15859
15860 void
15861 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15862 {
15863   if (b->thread != -1)
15864     fprintf_unfiltered (fp, " thread %d", b->thread);
15865
15866   if (b->task != 0)
15867     fprintf_unfiltered (fp, " task %d", b->task);
15868
15869   fprintf_unfiltered (fp, "\n");
15870 }
15871
15872 /* Save information on user settable breakpoints (watchpoints, etc) to
15873    a new script file named FILENAME.  If FILTER is non-NULL, call it
15874    on each breakpoint and only include the ones for which it returns
15875    non-zero.  */
15876
15877 static void
15878 save_breakpoints (char *filename, int from_tty,
15879                   int (*filter) (const struct breakpoint *))
15880 {
15881   struct breakpoint *tp;
15882   int any = 0;
15883   struct cleanup *cleanup;
15884   struct ui_file *fp;
15885   int extra_trace_bits = 0;
15886
15887   if (filename == 0 || *filename == 0)
15888     error (_("Argument required (file name in which to save)"));
15889
15890   /* See if we have anything to save.  */
15891   ALL_BREAKPOINTS (tp)
15892   {
15893     /* Skip internal and momentary breakpoints.  */
15894     if (!user_breakpoint_p (tp))
15895       continue;
15896
15897     /* If we have a filter, only save the breakpoints it accepts.  */
15898     if (filter && !filter (tp))
15899       continue;
15900
15901     any = 1;
15902
15903     if (is_tracepoint (tp))
15904       {
15905         extra_trace_bits = 1;
15906
15907         /* We can stop searching.  */
15908         break;
15909       }
15910   }
15911
15912   if (!any)
15913     {
15914       warning (_("Nothing to save."));
15915       return;
15916     }
15917
15918   filename = tilde_expand (filename);
15919   cleanup = make_cleanup (xfree, filename);
15920   fp = gdb_fopen (filename, "w");
15921   if (!fp)
15922     error (_("Unable to open file '%s' for saving (%s)"),
15923            filename, safe_strerror (errno));
15924   make_cleanup_ui_file_delete (fp);
15925
15926   if (extra_trace_bits)
15927     save_trace_state_variables (fp);
15928
15929   ALL_BREAKPOINTS (tp)
15930   {
15931     /* Skip internal and momentary breakpoints.  */
15932     if (!user_breakpoint_p (tp))
15933       continue;
15934
15935     /* If we have a filter, only save the breakpoints it accepts.  */
15936     if (filter && !filter (tp))
15937       continue;
15938
15939     tp->ops->print_recreate (tp, fp);
15940
15941     /* Note, we can't rely on tp->number for anything, as we can't
15942        assume the recreated breakpoint numbers will match.  Use $bpnum
15943        instead.  */
15944
15945     if (tp->cond_string)
15946       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15947
15948     if (tp->ignore_count)
15949       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15950
15951     if (tp->type != bp_dprintf && tp->commands)
15952       {
15953         volatile struct gdb_exception ex;       
15954
15955         fprintf_unfiltered (fp, "  commands\n");
15956         
15957         ui_out_redirect (current_uiout, fp);
15958         TRY_CATCH (ex, RETURN_MASK_ALL)
15959           {
15960             print_command_lines (current_uiout, tp->commands->commands, 2);
15961           }
15962         ui_out_redirect (current_uiout, NULL);
15963
15964         if (ex.reason < 0)
15965           throw_exception (ex);
15966
15967         fprintf_unfiltered (fp, "  end\n");
15968       }
15969
15970     if (tp->enable_state == bp_disabled)
15971       fprintf_unfiltered (fp, "disable\n");
15972
15973     /* If this is a multi-location breakpoint, check if the locations
15974        should be individually disabled.  Watchpoint locations are
15975        special, and not user visible.  */
15976     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15977       {
15978         struct bp_location *loc;
15979         int n = 1;
15980
15981         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15982           if (!loc->enabled)
15983             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15984       }
15985   }
15986
15987   if (extra_trace_bits && *default_collect)
15988     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15989
15990   if (from_tty)
15991     printf_filtered (_("Saved to file '%s'.\n"), filename);
15992   do_cleanups (cleanup);
15993 }
15994
15995 /* The `save breakpoints' command.  */
15996
15997 static void
15998 save_breakpoints_command (char *args, int from_tty)
15999 {
16000   save_breakpoints (args, from_tty, NULL);
16001 }
16002
16003 /* The `save tracepoints' command.  */
16004
16005 static void
16006 save_tracepoints_command (char *args, int from_tty)
16007 {
16008   save_breakpoints (args, from_tty, is_tracepoint);
16009 }
16010
16011 /* Create a vector of all tracepoints.  */
16012
16013 VEC(breakpoint_p) *
16014 all_tracepoints (void)
16015 {
16016   VEC(breakpoint_p) *tp_vec = 0;
16017   struct breakpoint *tp;
16018
16019   ALL_TRACEPOINTS (tp)
16020   {
16021     VEC_safe_push (breakpoint_p, tp_vec, tp);
16022   }
16023
16024   return tp_vec;
16025 }
16026
16027 \f
16028 /* This help string is used for the break, hbreak, tbreak and thbreak
16029    commands.  It is defined as a macro to prevent duplication.
16030    COMMAND should be a string constant containing the name of the
16031    command.  */
16032 #define BREAK_ARGS_HELP(command) \
16033 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16034 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16035 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16036 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16037 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16038 If a line number is specified, break at start of code for that line.\n\
16039 If a function is specified, break at start of code for that function.\n\
16040 If an address is specified, break at that exact address.\n\
16041 With no LOCATION, uses current execution address of the selected\n\
16042 stack frame.  This is useful for breaking on return to a stack frame.\n\
16043 \n\
16044 THREADNUM is the number from \"info threads\".\n\
16045 CONDITION is a boolean expression.\n\
16046 \n\
16047 Multiple breakpoints at one place are permitted, and useful if their\n\
16048 conditions are different.\n\
16049 \n\
16050 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16051
16052 /* List of subcommands for "catch".  */
16053 static struct cmd_list_element *catch_cmdlist;
16054
16055 /* List of subcommands for "tcatch".  */
16056 static struct cmd_list_element *tcatch_cmdlist;
16057
16058 void
16059 add_catch_command (char *name, char *docstring,
16060                    cmd_sfunc_ftype *sfunc,
16061                    completer_ftype *completer,
16062                    void *user_data_catch,
16063                    void *user_data_tcatch)
16064 {
16065   struct cmd_list_element *command;
16066
16067   command = add_cmd (name, class_breakpoint, NULL, docstring,
16068                      &catch_cmdlist);
16069   set_cmd_sfunc (command, sfunc);
16070   set_cmd_context (command, user_data_catch);
16071   set_cmd_completer (command, completer);
16072
16073   command = add_cmd (name, class_breakpoint, NULL, docstring,
16074                      &tcatch_cmdlist);
16075   set_cmd_sfunc (command, sfunc);
16076   set_cmd_context (command, user_data_tcatch);
16077   set_cmd_completer (command, completer);
16078 }
16079
16080 static void
16081 clear_syscall_counts (struct inferior *inf)
16082 {
16083   struct catch_syscall_inferior_data *inf_data
16084     = get_catch_syscall_inferior_data (inf);
16085
16086   inf_data->total_syscalls_count = 0;
16087   inf_data->any_syscall_count = 0;
16088   VEC_free (int, inf_data->syscalls_counts);
16089 }
16090
16091 static void
16092 save_command (char *arg, int from_tty)
16093 {
16094   printf_unfiltered (_("\"save\" must be followed by "
16095                        "the name of a save subcommand.\n"));
16096   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16097 }
16098
16099 struct breakpoint *
16100 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16101                           void *data)
16102 {
16103   struct breakpoint *b, *b_tmp;
16104
16105   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16106     {
16107       if ((*callback) (b, data))
16108         return b;
16109     }
16110
16111   return NULL;
16112 }
16113
16114 /* Zero if any of the breakpoint's locations could be a location where
16115    functions have been inlined, nonzero otherwise.  */
16116
16117 static int
16118 is_non_inline_function (struct breakpoint *b)
16119 {
16120   /* The shared library event breakpoint is set on the address of a
16121      non-inline function.  */
16122   if (b->type == bp_shlib_event)
16123     return 1;
16124
16125   return 0;
16126 }
16127
16128 /* Nonzero if the specified PC cannot be a location where functions
16129    have been inlined.  */
16130
16131 int
16132 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16133                            const struct target_waitstatus *ws)
16134 {
16135   struct breakpoint *b;
16136   struct bp_location *bl;
16137
16138   ALL_BREAKPOINTS (b)
16139     {
16140       if (!is_non_inline_function (b))
16141         continue;
16142
16143       for (bl = b->loc; bl != NULL; bl = bl->next)
16144         {
16145           if (!bl->shlib_disabled
16146               && bpstat_check_location (bl, aspace, pc, ws))
16147             return 1;
16148         }
16149     }
16150
16151   return 0;
16152 }
16153
16154 /* Remove any references to OBJFILE which is going to be freed.  */
16155
16156 void
16157 breakpoint_free_objfile (struct objfile *objfile)
16158 {
16159   struct bp_location **locp, *loc;
16160
16161   ALL_BP_LOCATIONS (loc, locp)
16162     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16163       loc->symtab = NULL;
16164 }
16165
16166 void
16167 initialize_breakpoint_ops (void)
16168 {
16169   static int initialized = 0;
16170
16171   struct breakpoint_ops *ops;
16172
16173   if (initialized)
16174     return;
16175   initialized = 1;
16176
16177   /* The breakpoint_ops structure to be inherit by all kinds of
16178      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16179      internal and momentary breakpoints, etc.).  */
16180   ops = &bkpt_base_breakpoint_ops;
16181   *ops = base_breakpoint_ops;
16182   ops->re_set = bkpt_re_set;
16183   ops->insert_location = bkpt_insert_location;
16184   ops->remove_location = bkpt_remove_location;
16185   ops->breakpoint_hit = bkpt_breakpoint_hit;
16186   ops->create_sals_from_address = bkpt_create_sals_from_address;
16187   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16188   ops->decode_linespec = bkpt_decode_linespec;
16189
16190   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16191   ops = &bkpt_breakpoint_ops;
16192   *ops = bkpt_base_breakpoint_ops;
16193   ops->re_set = bkpt_re_set;
16194   ops->resources_needed = bkpt_resources_needed;
16195   ops->print_it = bkpt_print_it;
16196   ops->print_mention = bkpt_print_mention;
16197   ops->print_recreate = bkpt_print_recreate;
16198
16199   /* Ranged breakpoints.  */
16200   ops = &ranged_breakpoint_ops;
16201   *ops = bkpt_breakpoint_ops;
16202   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16203   ops->resources_needed = resources_needed_ranged_breakpoint;
16204   ops->print_it = print_it_ranged_breakpoint;
16205   ops->print_one = print_one_ranged_breakpoint;
16206   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16207   ops->print_mention = print_mention_ranged_breakpoint;
16208   ops->print_recreate = print_recreate_ranged_breakpoint;
16209
16210   /* Internal breakpoints.  */
16211   ops = &internal_breakpoint_ops;
16212   *ops = bkpt_base_breakpoint_ops;
16213   ops->re_set = internal_bkpt_re_set;
16214   ops->check_status = internal_bkpt_check_status;
16215   ops->print_it = internal_bkpt_print_it;
16216   ops->print_mention = internal_bkpt_print_mention;
16217
16218   /* Momentary breakpoints.  */
16219   ops = &momentary_breakpoint_ops;
16220   *ops = bkpt_base_breakpoint_ops;
16221   ops->re_set = momentary_bkpt_re_set;
16222   ops->check_status = momentary_bkpt_check_status;
16223   ops->print_it = momentary_bkpt_print_it;
16224   ops->print_mention = momentary_bkpt_print_mention;
16225
16226   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16227   ops = &longjmp_breakpoint_ops;
16228   *ops = momentary_breakpoint_ops;
16229   ops->dtor = longjmp_bkpt_dtor;
16230
16231   /* Probe breakpoints.  */
16232   ops = &bkpt_probe_breakpoint_ops;
16233   *ops = bkpt_breakpoint_ops;
16234   ops->insert_location = bkpt_probe_insert_location;
16235   ops->remove_location = bkpt_probe_remove_location;
16236   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16237   ops->decode_linespec = bkpt_probe_decode_linespec;
16238
16239   /* Watchpoints.  */
16240   ops = &watchpoint_breakpoint_ops;
16241   *ops = base_breakpoint_ops;
16242   ops->dtor = dtor_watchpoint;
16243   ops->re_set = re_set_watchpoint;
16244   ops->insert_location = insert_watchpoint;
16245   ops->remove_location = remove_watchpoint;
16246   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16247   ops->check_status = check_status_watchpoint;
16248   ops->resources_needed = resources_needed_watchpoint;
16249   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16250   ops->print_it = print_it_watchpoint;
16251   ops->print_mention = print_mention_watchpoint;
16252   ops->print_recreate = print_recreate_watchpoint;
16253   ops->explains_signal = explains_signal_watchpoint;
16254
16255   /* Masked watchpoints.  */
16256   ops = &masked_watchpoint_breakpoint_ops;
16257   *ops = watchpoint_breakpoint_ops;
16258   ops->insert_location = insert_masked_watchpoint;
16259   ops->remove_location = remove_masked_watchpoint;
16260   ops->resources_needed = resources_needed_masked_watchpoint;
16261   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16262   ops->print_it = print_it_masked_watchpoint;
16263   ops->print_one_detail = print_one_detail_masked_watchpoint;
16264   ops->print_mention = print_mention_masked_watchpoint;
16265   ops->print_recreate = print_recreate_masked_watchpoint;
16266
16267   /* Tracepoints.  */
16268   ops = &tracepoint_breakpoint_ops;
16269   *ops = base_breakpoint_ops;
16270   ops->re_set = tracepoint_re_set;
16271   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16272   ops->print_one_detail = tracepoint_print_one_detail;
16273   ops->print_mention = tracepoint_print_mention;
16274   ops->print_recreate = tracepoint_print_recreate;
16275   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16276   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16277   ops->decode_linespec = tracepoint_decode_linespec;
16278
16279   /* Probe tracepoints.  */
16280   ops = &tracepoint_probe_breakpoint_ops;
16281   *ops = tracepoint_breakpoint_ops;
16282   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16283   ops->decode_linespec = tracepoint_probe_decode_linespec;
16284
16285   /* Static tracepoints with marker (`-m').  */
16286   ops = &strace_marker_breakpoint_ops;
16287   *ops = tracepoint_breakpoint_ops;
16288   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16289   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16290   ops->decode_linespec = strace_marker_decode_linespec;
16291
16292   /* Fork catchpoints.  */
16293   ops = &catch_fork_breakpoint_ops;
16294   *ops = base_breakpoint_ops;
16295   ops->insert_location = insert_catch_fork;
16296   ops->remove_location = remove_catch_fork;
16297   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16298   ops->print_it = print_it_catch_fork;
16299   ops->print_one = print_one_catch_fork;
16300   ops->print_mention = print_mention_catch_fork;
16301   ops->print_recreate = print_recreate_catch_fork;
16302
16303   /* Vfork catchpoints.  */
16304   ops = &catch_vfork_breakpoint_ops;
16305   *ops = base_breakpoint_ops;
16306   ops->insert_location = insert_catch_vfork;
16307   ops->remove_location = remove_catch_vfork;
16308   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16309   ops->print_it = print_it_catch_vfork;
16310   ops->print_one = print_one_catch_vfork;
16311   ops->print_mention = print_mention_catch_vfork;
16312   ops->print_recreate = print_recreate_catch_vfork;
16313
16314   /* Exec catchpoints.  */
16315   ops = &catch_exec_breakpoint_ops;
16316   *ops = base_breakpoint_ops;
16317   ops->dtor = dtor_catch_exec;
16318   ops->insert_location = insert_catch_exec;
16319   ops->remove_location = remove_catch_exec;
16320   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16321   ops->print_it = print_it_catch_exec;
16322   ops->print_one = print_one_catch_exec;
16323   ops->print_mention = print_mention_catch_exec;
16324   ops->print_recreate = print_recreate_catch_exec;
16325
16326   /* Syscall catchpoints.  */
16327   ops = &catch_syscall_breakpoint_ops;
16328   *ops = base_breakpoint_ops;
16329   ops->dtor = dtor_catch_syscall;
16330   ops->insert_location = insert_catch_syscall;
16331   ops->remove_location = remove_catch_syscall;
16332   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16333   ops->print_it = print_it_catch_syscall;
16334   ops->print_one = print_one_catch_syscall;
16335   ops->print_mention = print_mention_catch_syscall;
16336   ops->print_recreate = print_recreate_catch_syscall;
16337
16338   /* Solib-related catchpoints.  */
16339   ops = &catch_solib_breakpoint_ops;
16340   *ops = base_breakpoint_ops;
16341   ops->dtor = dtor_catch_solib;
16342   ops->insert_location = insert_catch_solib;
16343   ops->remove_location = remove_catch_solib;
16344   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16345   ops->check_status = check_status_catch_solib;
16346   ops->print_it = print_it_catch_solib;
16347   ops->print_one = print_one_catch_solib;
16348   ops->print_mention = print_mention_catch_solib;
16349   ops->print_recreate = print_recreate_catch_solib;
16350
16351   ops = &dprintf_breakpoint_ops;
16352   *ops = bkpt_base_breakpoint_ops;
16353   ops->re_set = dprintf_re_set;
16354   ops->resources_needed = bkpt_resources_needed;
16355   ops->print_it = bkpt_print_it;
16356   ops->print_mention = bkpt_print_mention;
16357   ops->print_recreate = dprintf_print_recreate;
16358   ops->after_condition_true = dprintf_after_condition_true;
16359   ops->breakpoint_hit = dprintf_breakpoint_hit;
16360 }
16361
16362 /* Chain containing all defined "enable breakpoint" subcommands.  */
16363
16364 static struct cmd_list_element *enablebreaklist = NULL;
16365
16366 void
16367 _initialize_breakpoint (void)
16368 {
16369   struct cmd_list_element *c;
16370
16371   initialize_breakpoint_ops ();
16372
16373   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16374   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16375   observer_attach_inferior_exit (clear_syscall_counts);
16376   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16377
16378   breakpoint_objfile_key
16379     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16380
16381   catch_syscall_inferior_data
16382     = register_inferior_data_with_cleanup (NULL,
16383                                            catch_syscall_inferior_data_cleanup);
16384
16385   breakpoint_chain = 0;
16386   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16387      before a breakpoint is set.  */
16388   breakpoint_count = 0;
16389
16390   tracepoint_count = 0;
16391
16392   add_com ("ignore", class_breakpoint, ignore_command, _("\
16393 Set ignore-count of breakpoint number N to COUNT.\n\
16394 Usage is `ignore N COUNT'."));
16395   if (xdb_commands)
16396     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16397
16398   add_com ("commands", class_breakpoint, commands_command, _("\
16399 Set commands to be executed when a breakpoint is hit.\n\
16400 Give breakpoint number as argument after \"commands\".\n\
16401 With no argument, the targeted breakpoint is the last one set.\n\
16402 The commands themselves follow starting on the next line.\n\
16403 Type a line containing \"end\" to indicate the end of them.\n\
16404 Give \"silent\" as the first line to make the breakpoint silent;\n\
16405 then no output is printed when it is hit, except what the commands print."));
16406
16407   c = add_com ("condition", class_breakpoint, condition_command, _("\
16408 Specify breakpoint number N to break only if COND is true.\n\
16409 Usage is `condition N COND', where N is an integer and COND is an\n\
16410 expression to be evaluated whenever breakpoint N is reached."));
16411   set_cmd_completer (c, condition_completer);
16412
16413   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16414 Set a temporary breakpoint.\n\
16415 Like \"break\" except the breakpoint is only temporary,\n\
16416 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16417 by using \"enable delete\" on the breakpoint number.\n\
16418 \n"
16419 BREAK_ARGS_HELP ("tbreak")));
16420   set_cmd_completer (c, location_completer);
16421
16422   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16423 Set a hardware assisted breakpoint.\n\
16424 Like \"break\" except the breakpoint requires hardware support,\n\
16425 some target hardware may not have this support.\n\
16426 \n"
16427 BREAK_ARGS_HELP ("hbreak")));
16428   set_cmd_completer (c, location_completer);
16429
16430   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16431 Set a temporary hardware assisted breakpoint.\n\
16432 Like \"hbreak\" except the breakpoint is only temporary,\n\
16433 so it will be deleted when hit.\n\
16434 \n"
16435 BREAK_ARGS_HELP ("thbreak")));
16436   set_cmd_completer (c, location_completer);
16437
16438   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16439 Enable some breakpoints.\n\
16440 Give breakpoint numbers (separated by spaces) as arguments.\n\
16441 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16442 This is used to cancel the effect of the \"disable\" command.\n\
16443 With a subcommand you can enable temporarily."),
16444                   &enablelist, "enable ", 1, &cmdlist);
16445   if (xdb_commands)
16446     add_com ("ab", class_breakpoint, enable_command, _("\
16447 Enable some breakpoints.\n\
16448 Give breakpoint numbers (separated by spaces) as arguments.\n\
16449 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16450 This is used to cancel the effect of the \"disable\" command.\n\
16451 With a subcommand you can enable temporarily."));
16452
16453   add_com_alias ("en", "enable", class_breakpoint, 1);
16454
16455   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16456 Enable some breakpoints.\n\
16457 Give breakpoint numbers (separated by spaces) as arguments.\n\
16458 This is used to cancel the effect of the \"disable\" command.\n\
16459 May be abbreviated to simply \"enable\".\n"),
16460                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16461
16462   add_cmd ("once", no_class, enable_once_command, _("\
16463 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16464 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16465            &enablebreaklist);
16466
16467   add_cmd ("delete", no_class, enable_delete_command, _("\
16468 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16469 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16470            &enablebreaklist);
16471
16472   add_cmd ("count", no_class, enable_count_command, _("\
16473 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16474 If a breakpoint is hit while enabled in this fashion,\n\
16475 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16476            &enablebreaklist);
16477
16478   add_cmd ("delete", no_class, enable_delete_command, _("\
16479 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16480 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16481            &enablelist);
16482
16483   add_cmd ("once", no_class, enable_once_command, _("\
16484 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16485 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16486            &enablelist);
16487
16488   add_cmd ("count", no_class, enable_count_command, _("\
16489 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16490 If a breakpoint is hit while enabled in this fashion,\n\
16491 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16492            &enablelist);
16493
16494   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16495 Disable some breakpoints.\n\
16496 Arguments are breakpoint numbers with spaces in between.\n\
16497 To disable all breakpoints, give no argument.\n\
16498 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16499                   &disablelist, "disable ", 1, &cmdlist);
16500   add_com_alias ("dis", "disable", class_breakpoint, 1);
16501   add_com_alias ("disa", "disable", class_breakpoint, 1);
16502   if (xdb_commands)
16503     add_com ("sb", class_breakpoint, disable_command, _("\
16504 Disable some breakpoints.\n\
16505 Arguments are breakpoint numbers with spaces in between.\n\
16506 To disable all breakpoints, give no argument.\n\
16507 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16508
16509   add_cmd ("breakpoints", class_alias, disable_command, _("\
16510 Disable some breakpoints.\n\
16511 Arguments are breakpoint numbers with spaces in between.\n\
16512 To disable all breakpoints, give no argument.\n\
16513 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16514 This command may be abbreviated \"disable\"."),
16515            &disablelist);
16516
16517   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16518 Delete some breakpoints or auto-display expressions.\n\
16519 Arguments are breakpoint numbers with spaces in between.\n\
16520 To delete all breakpoints, give no argument.\n\
16521 \n\
16522 Also a prefix command for deletion of other GDB objects.\n\
16523 The \"unset\" command is also an alias for \"delete\"."),
16524                   &deletelist, "delete ", 1, &cmdlist);
16525   add_com_alias ("d", "delete", class_breakpoint, 1);
16526   add_com_alias ("del", "delete", class_breakpoint, 1);
16527   if (xdb_commands)
16528     add_com ("db", class_breakpoint, delete_command, _("\
16529 Delete some breakpoints.\n\
16530 Arguments are breakpoint numbers with spaces in between.\n\
16531 To delete all breakpoints, give no argument.\n"));
16532
16533   add_cmd ("breakpoints", class_alias, delete_command, _("\
16534 Delete some breakpoints or auto-display expressions.\n\
16535 Arguments are breakpoint numbers with spaces in between.\n\
16536 To delete all breakpoints, give no argument.\n\
16537 This command may be abbreviated \"delete\"."),
16538            &deletelist);
16539
16540   add_com ("clear", class_breakpoint, clear_command, _("\
16541 Clear breakpoint at specified line or function.\n\
16542 Argument may be line number, function name, or \"*\" and an address.\n\
16543 If line number is specified, all breakpoints in that line are cleared.\n\
16544 If function is specified, breakpoints at beginning of function are cleared.\n\
16545 If an address is specified, breakpoints at that address are cleared.\n\
16546 \n\
16547 With no argument, clears all breakpoints in the line that the selected frame\n\
16548 is executing in.\n\
16549 \n\
16550 See also the \"delete\" command which clears breakpoints by number."));
16551   add_com_alias ("cl", "clear", class_breakpoint, 1);
16552
16553   c = add_com ("break", class_breakpoint, break_command, _("\
16554 Set breakpoint at specified line or function.\n"
16555 BREAK_ARGS_HELP ("break")));
16556   set_cmd_completer (c, location_completer);
16557
16558   add_com_alias ("b", "break", class_run, 1);
16559   add_com_alias ("br", "break", class_run, 1);
16560   add_com_alias ("bre", "break", class_run, 1);
16561   add_com_alias ("brea", "break", class_run, 1);
16562
16563   if (xdb_commands)
16564    add_com_alias ("ba", "break", class_breakpoint, 1);
16565
16566   if (dbx_commands)
16567     {
16568       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16569 Break in function/address or break at a line in the current file."),
16570                              &stoplist, "stop ", 1, &cmdlist);
16571       add_cmd ("in", class_breakpoint, stopin_command,
16572                _("Break in function or address."), &stoplist);
16573       add_cmd ("at", class_breakpoint, stopat_command,
16574                _("Break at a line in the current file."), &stoplist);
16575       add_com ("status", class_info, breakpoints_info, _("\
16576 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16577 The \"Type\" column indicates one of:\n\
16578 \tbreakpoint     - normal breakpoint\n\
16579 \twatchpoint     - watchpoint\n\
16580 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16581 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16582 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16583 address and file/line number respectively.\n\
16584 \n\
16585 Convenience variable \"$_\" and default examine address for \"x\"\n\
16586 are set to the address of the last breakpoint listed unless the command\n\
16587 is prefixed with \"server \".\n\n\
16588 Convenience variable \"$bpnum\" contains the number of the last\n\
16589 breakpoint set."));
16590     }
16591
16592   add_info ("breakpoints", breakpoints_info, _("\
16593 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16594 The \"Type\" column indicates one of:\n\
16595 \tbreakpoint     - normal breakpoint\n\
16596 \twatchpoint     - watchpoint\n\
16597 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16598 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16599 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16600 address and file/line number respectively.\n\
16601 \n\
16602 Convenience variable \"$_\" and default examine address for \"x\"\n\
16603 are set to the address of the last breakpoint listed unless the command\n\
16604 is prefixed with \"server \".\n\n\
16605 Convenience variable \"$bpnum\" contains the number of the last\n\
16606 breakpoint set."));
16607
16608   add_info_alias ("b", "breakpoints", 1);
16609
16610   if (xdb_commands)
16611     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16612 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16613 The \"Type\" column indicates one of:\n\
16614 \tbreakpoint     - normal breakpoint\n\
16615 \twatchpoint     - watchpoint\n\
16616 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16617 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16618 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16619 address and file/line number respectively.\n\
16620 \n\
16621 Convenience variable \"$_\" and default examine address for \"x\"\n\
16622 are set to the address of the last breakpoint listed unless the command\n\
16623 is prefixed with \"server \".\n\n\
16624 Convenience variable \"$bpnum\" contains the number of the last\n\
16625 breakpoint set."));
16626
16627   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16628 Status of all breakpoints, or breakpoint number NUMBER.\n\
16629 The \"Type\" column indicates one of:\n\
16630 \tbreakpoint     - normal breakpoint\n\
16631 \twatchpoint     - watchpoint\n\
16632 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16633 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16634 \tuntil          - internal breakpoint used by the \"until\" command\n\
16635 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16636 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16637 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16638 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16639 address and file/line number respectively.\n\
16640 \n\
16641 Convenience variable \"$_\" and default examine address for \"x\"\n\
16642 are set to the address of the last breakpoint listed unless the command\n\
16643 is prefixed with \"server \".\n\n\
16644 Convenience variable \"$bpnum\" contains the number of the last\n\
16645 breakpoint set."),
16646            &maintenanceinfolist);
16647
16648   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16649 Set catchpoints to catch events."),
16650                   &catch_cmdlist, "catch ",
16651                   0/*allow-unknown*/, &cmdlist);
16652
16653   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16654 Set temporary catchpoints to catch events."),
16655                   &tcatch_cmdlist, "tcatch ",
16656                   0/*allow-unknown*/, &cmdlist);
16657
16658   add_catch_command ("fork", _("Catch calls to fork."),
16659                      catch_fork_command_1,
16660                      NULL,
16661                      (void *) (uintptr_t) catch_fork_permanent,
16662                      (void *) (uintptr_t) catch_fork_temporary);
16663   add_catch_command ("vfork", _("Catch calls to vfork."),
16664                      catch_fork_command_1,
16665                      NULL,
16666                      (void *) (uintptr_t) catch_vfork_permanent,
16667                      (void *) (uintptr_t) catch_vfork_temporary);
16668   add_catch_command ("exec", _("Catch calls to exec."),
16669                      catch_exec_command_1,
16670                      NULL,
16671                      CATCH_PERMANENT,
16672                      CATCH_TEMPORARY);
16673   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16674 Usage: catch load [REGEX]\n\
16675 If REGEX is given, only stop for libraries matching the regular expression."),
16676                      catch_load_command_1,
16677                      NULL,
16678                      CATCH_PERMANENT,
16679                      CATCH_TEMPORARY);
16680   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16681 Usage: catch unload [REGEX]\n\
16682 If REGEX is given, only stop for libraries matching the regular expression."),
16683                      catch_unload_command_1,
16684                      NULL,
16685                      CATCH_PERMANENT,
16686                      CATCH_TEMPORARY);
16687   add_catch_command ("syscall", _("\
16688 Catch system calls by their names and/or numbers.\n\
16689 Arguments say which system calls to catch.  If no arguments\n\
16690 are given, every system call will be caught.\n\
16691 Arguments, if given, should be one or more system call names\n\
16692 (if your system supports that), or system call numbers."),
16693                      catch_syscall_command_1,
16694                      catch_syscall_completer,
16695                      CATCH_PERMANENT,
16696                      CATCH_TEMPORARY);
16697
16698   c = add_com ("watch", class_breakpoint, watch_command, _("\
16699 Set a watchpoint for an expression.\n\
16700 Usage: watch [-l|-location] EXPRESSION\n\
16701 A watchpoint stops execution of your program whenever the value of\n\
16702 an expression changes.\n\
16703 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16704 the memory to which it refers."));
16705   set_cmd_completer (c, expression_completer);
16706
16707   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16708 Set a read watchpoint for an expression.\n\
16709 Usage: rwatch [-l|-location] EXPRESSION\n\
16710 A watchpoint stops execution of your program whenever the value of\n\
16711 an expression is read.\n\
16712 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16713 the memory to which it refers."));
16714   set_cmd_completer (c, expression_completer);
16715
16716   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16717 Set a watchpoint for an expression.\n\
16718 Usage: awatch [-l|-location] EXPRESSION\n\
16719 A watchpoint stops execution of your program whenever the value of\n\
16720 an expression is either read or written.\n\
16721 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16722 the memory to which it refers."));
16723   set_cmd_completer (c, expression_completer);
16724
16725   add_info ("watchpoints", watchpoints_info, _("\
16726 Status of specified watchpoints (all watchpoints if no argument)."));
16727
16728   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16729      respond to changes - contrary to the description.  */
16730   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16731                             &can_use_hw_watchpoints, _("\
16732 Set debugger's willingness to use watchpoint hardware."), _("\
16733 Show debugger's willingness to use watchpoint hardware."), _("\
16734 If zero, gdb will not use hardware for new watchpoints, even if\n\
16735 such is available.  (However, any hardware watchpoints that were\n\
16736 created before setting this to nonzero, will continue to use watchpoint\n\
16737 hardware.)"),
16738                             NULL,
16739                             show_can_use_hw_watchpoints,
16740                             &setlist, &showlist);
16741
16742   can_use_hw_watchpoints = 1;
16743
16744   /* Tracepoint manipulation commands.  */
16745
16746   c = add_com ("trace", class_breakpoint, trace_command, _("\
16747 Set a tracepoint at specified line or function.\n\
16748 \n"
16749 BREAK_ARGS_HELP ("trace") "\n\
16750 Do \"help tracepoints\" for info on other tracepoint commands."));
16751   set_cmd_completer (c, location_completer);
16752
16753   add_com_alias ("tp", "trace", class_alias, 0);
16754   add_com_alias ("tr", "trace", class_alias, 1);
16755   add_com_alias ("tra", "trace", class_alias, 1);
16756   add_com_alias ("trac", "trace", class_alias, 1);
16757
16758   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16759 Set a fast tracepoint at specified line or function.\n\
16760 \n"
16761 BREAK_ARGS_HELP ("ftrace") "\n\
16762 Do \"help tracepoints\" for info on other tracepoint commands."));
16763   set_cmd_completer (c, location_completer);
16764
16765   c = add_com ("strace", class_breakpoint, strace_command, _("\
16766 Set a static tracepoint at specified line, function or marker.\n\
16767 \n\
16768 strace [LOCATION] [if CONDITION]\n\
16769 LOCATION may be a line number, function name, \"*\" and an address,\n\
16770 or -m MARKER_ID.\n\
16771 If a line number is specified, probe the marker at start of code\n\
16772 for that line.  If a function is specified, probe the marker at start\n\
16773 of code for that function.  If an address is specified, probe the marker\n\
16774 at that exact address.  If a marker id is specified, probe the marker\n\
16775 with that name.  With no LOCATION, uses current execution address of\n\
16776 the selected stack frame.\n\
16777 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16778 This collects arbitrary user data passed in the probe point call to the\n\
16779 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16780 by printing the $_sdata variable like any other convenience variable.\n\
16781 \n\
16782 CONDITION is a boolean expression.\n\
16783 \n\
16784 Multiple tracepoints at one place are permitted, and useful if their\n\
16785 conditions are different.\n\
16786 \n\
16787 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16788 Do \"help tracepoints\" for info on other tracepoint commands."));
16789   set_cmd_completer (c, location_completer);
16790
16791   add_info ("tracepoints", tracepoints_info, _("\
16792 Status of specified tracepoints (all tracepoints if no argument).\n\
16793 Convenience variable \"$tpnum\" contains the number of the\n\
16794 last tracepoint set."));
16795
16796   add_info_alias ("tp", "tracepoints", 1);
16797
16798   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16799 Delete specified tracepoints.\n\
16800 Arguments are tracepoint numbers, separated by spaces.\n\
16801 No argument means delete all tracepoints."),
16802            &deletelist);
16803   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16804
16805   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16806 Disable specified tracepoints.\n\
16807 Arguments are tracepoint numbers, separated by spaces.\n\
16808 No argument means disable all tracepoints."),
16809            &disablelist);
16810   deprecate_cmd (c, "disable");
16811
16812   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16813 Enable specified tracepoints.\n\
16814 Arguments are tracepoint numbers, separated by spaces.\n\
16815 No argument means enable all tracepoints."),
16816            &enablelist);
16817   deprecate_cmd (c, "enable");
16818
16819   add_com ("passcount", class_trace, trace_pass_command, _("\
16820 Set the passcount for a tracepoint.\n\
16821 The trace will end when the tracepoint has been passed 'count' times.\n\
16822 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16823 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16824
16825   add_prefix_cmd ("save", class_breakpoint, save_command,
16826                   _("Save breakpoint definitions as a script."),
16827                   &save_cmdlist, "save ",
16828                   0/*allow-unknown*/, &cmdlist);
16829
16830   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16831 Save current breakpoint definitions as a script.\n\
16832 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16833 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16834 session to restore them."),
16835                &save_cmdlist);
16836   set_cmd_completer (c, filename_completer);
16837
16838   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16839 Save current tracepoint definitions as a script.\n\
16840 Use the 'source' command in another debug session to restore them."),
16841                &save_cmdlist);
16842   set_cmd_completer (c, filename_completer);
16843
16844   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16845   deprecate_cmd (c, "save tracepoints");
16846
16847   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16848 Breakpoint specific settings\n\
16849 Configure various breakpoint-specific variables such as\n\
16850 pending breakpoint behavior"),
16851                   &breakpoint_set_cmdlist, "set breakpoint ",
16852                   0/*allow-unknown*/, &setlist);
16853   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16854 Breakpoint specific settings\n\
16855 Configure various breakpoint-specific variables such as\n\
16856 pending breakpoint behavior"),
16857                   &breakpoint_show_cmdlist, "show breakpoint ",
16858                   0/*allow-unknown*/, &showlist);
16859
16860   add_setshow_auto_boolean_cmd ("pending", no_class,
16861                                 &pending_break_support, _("\
16862 Set debugger's behavior regarding pending breakpoints."), _("\
16863 Show debugger's behavior regarding pending breakpoints."), _("\
16864 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16865 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16866 an error.  If auto, an unrecognized breakpoint location results in a\n\
16867 user-query to see if a pending breakpoint should be created."),
16868                                 NULL,
16869                                 show_pending_break_support,
16870                                 &breakpoint_set_cmdlist,
16871                                 &breakpoint_show_cmdlist);
16872
16873   pending_break_support = AUTO_BOOLEAN_AUTO;
16874
16875   add_setshow_boolean_cmd ("auto-hw", no_class,
16876                            &automatic_hardware_breakpoints, _("\
16877 Set automatic usage of hardware breakpoints."), _("\
16878 Show automatic usage of hardware breakpoints."), _("\
16879 If set, the debugger will automatically use hardware breakpoints for\n\
16880 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16881 a warning will be emitted for such breakpoints."),
16882                            NULL,
16883                            show_automatic_hardware_breakpoints,
16884                            &breakpoint_set_cmdlist,
16885                            &breakpoint_show_cmdlist);
16886
16887   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16888                                 &always_inserted_mode, _("\
16889 Set mode for inserting breakpoints."), _("\
16890 Show mode for inserting breakpoints."), _("\
16891 When this mode is off, breakpoints are inserted in inferior when it is\n\
16892 resumed, and removed when execution stops.  When this mode is on,\n\
16893 breakpoints are inserted immediately and removed only when the user\n\
16894 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16895 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16896 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16897 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16898 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16899                                 NULL,
16900                                 &show_always_inserted_mode,
16901                                 &breakpoint_set_cmdlist,
16902                                 &breakpoint_show_cmdlist);
16903
16904   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16905                         condition_evaluation_enums,
16906                         &condition_evaluation_mode_1, _("\
16907 Set mode of breakpoint condition evaluation."), _("\
16908 Show mode of breakpoint condition evaluation."), _("\
16909 When this is set to \"host\", breakpoint conditions will be\n\
16910 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16911 breakpoint conditions will be downloaded to the target (if the target\n\
16912 supports such feature) and conditions will be evaluated on the target's side.\n\
16913 If this is set to \"auto\" (default), this will be automatically set to\n\
16914 \"target\" if it supports condition evaluation, otherwise it will\n\
16915 be set to \"gdb\""),
16916                            &set_condition_evaluation_mode,
16917                            &show_condition_evaluation_mode,
16918                            &breakpoint_set_cmdlist,
16919                            &breakpoint_show_cmdlist);
16920
16921   add_com ("break-range", class_breakpoint, break_range_command, _("\
16922 Set a breakpoint for an address range.\n\
16923 break-range START-LOCATION, END-LOCATION\n\
16924 where START-LOCATION and END-LOCATION can be one of the following:\n\
16925   LINENUM, for that line in the current file,\n\
16926   FILE:LINENUM, for that line in that file,\n\
16927   +OFFSET, for that number of lines after the current line\n\
16928            or the start of the range\n\
16929   FUNCTION, for the first line in that function,\n\
16930   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16931   *ADDRESS, for the instruction at that address.\n\
16932 \n\
16933 The breakpoint will stop execution of the inferior whenever it executes\n\
16934 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16935 range (including START-LOCATION and END-LOCATION)."));
16936
16937   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16938 Set a dynamic printf at specified line or function.\n\
16939 dprintf location,format string,arg1,arg2,...\n\
16940 location may be a line number, function name, or \"*\" and an address.\n\
16941 If a line number is specified, break at start of code for that line.\n\
16942 If a function is specified, break at start of code for that function."));
16943   set_cmd_completer (c, location_completer);
16944
16945   add_setshow_enum_cmd ("dprintf-style", class_support,
16946                         dprintf_style_enums, &dprintf_style, _("\
16947 Set the style of usage for dynamic printf."), _("\
16948 Show the style of usage for dynamic printf."), _("\
16949 This setting chooses how GDB will do a dynamic printf.\n\
16950 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16951 console, as with the \"printf\" command.\n\
16952 If the value is \"call\", the print is done by calling a function in your\n\
16953 program; by default printf(), but you can choose a different function or\n\
16954 output stream by setting dprintf-function and dprintf-channel."),
16955                         update_dprintf_commands, NULL,
16956                         &setlist, &showlist);
16957
16958   dprintf_function = xstrdup ("printf");
16959   add_setshow_string_cmd ("dprintf-function", class_support,
16960                           &dprintf_function, _("\
16961 Set the function to use for dynamic printf"), _("\
16962 Show the function to use for dynamic printf"), NULL,
16963                           update_dprintf_commands, NULL,
16964                           &setlist, &showlist);
16965
16966   dprintf_channel = xstrdup ("");
16967   add_setshow_string_cmd ("dprintf-channel", class_support,
16968                           &dprintf_channel, _("\
16969 Set the channel to use for dynamic printf"), _("\
16970 Show the channel to use for dynamic printf"), NULL,
16971                           update_dprintf_commands, NULL,
16972                           &setlist, &showlist);
16973
16974   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16975                            &disconnected_dprintf, _("\
16976 Set whether dprintf continues after GDB disconnects."), _("\
16977 Show whether dprintf continues after GDB disconnects."), _("\
16978 Use this to let dprintf commands continue to hit and produce output\n\
16979 even if GDB disconnects or detaches from the target."),
16980                            NULL,
16981                            NULL,
16982                            &setlist, &showlist);
16983
16984   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16985 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16986 (target agent only) This is useful for formatted output in user-defined commands."));
16987
16988   automatic_hardware_breakpoints = 1;
16989
16990   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16991   observer_attach_thread_exit (remove_threaded_breakpoints);
16992 }