gdb/
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "gdb_regex.h"
70 #include "ax-gdb.h"
71 #include "dummy-frame.h"
72
73 #include "format.h"
74
75 /* readline include files */
76 #include "readline/readline.h"
77 #include "readline/history.h"
78
79 /* readline defines this.  */
80 #undef savestring
81
82 #include "mi/mi-common.h"
83 #include "python/python.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_RETHROW,
90   EX_EVENT_CATCH
91 };
92
93 /* Prototypes for local functions.  */
94
95 static void enable_delete_command (char *, int);
96
97 static void enable_once_command (char *, int);
98
99 static void enable_count_command (char *, int);
100
101 static void disable_command (char *, int);
102
103 static void enable_command (char *, int);
104
105 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
106                                                       void *),
107                                     void *);
108
109 static void ignore_command (char *, int);
110
111 static int breakpoint_re_set_one (void *);
112
113 static void breakpoint_re_set_default (struct breakpoint *);
114
115 static void create_sals_from_address_default (char **,
116                                               struct linespec_result *,
117                                               enum bptype, char *,
118                                               char **);
119
120 static void create_breakpoints_sal_default (struct gdbarch *,
121                                             struct linespec_result *,
122                                             char *, char *, enum bptype,
123                                             enum bpdisp, int, int,
124                                             int,
125                                             const struct breakpoint_ops *,
126                                             int, int, int, unsigned);
127
128 static void decode_linespec_default (struct breakpoint *, char **,
129                                      struct symtabs_and_lines *);
130
131 static void clear_command (char *, int);
132
133 static void catch_command (char *, int);
134
135 static int can_use_hardware_watchpoint (struct value *);
136
137 static void break_command_1 (char *, int, int);
138
139 static void mention (struct breakpoint *);
140
141 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
142                                                                enum bptype,
143                                                                const struct breakpoint_ops *);
144 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
145                                                        const struct symtab_and_line *);
146
147 /* This function is used in gdbtk sources and thus can not be made
148    static.  */
149 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
150                                        struct symtab_and_line,
151                                        enum bptype,
152                                        const struct breakpoint_ops *);
153
154 static struct breakpoint *
155   momentary_breakpoint_from_master (struct breakpoint *orig,
156                                     enum bptype type,
157                                     const struct breakpoint_ops *ops);
158
159 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
160
161 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
162                                             CORE_ADDR bpaddr,
163                                             enum bptype bptype);
164
165 static void describe_other_breakpoints (struct gdbarch *,
166                                         struct program_space *, CORE_ADDR,
167                                         struct obj_section *, int);
168
169 static int breakpoint_address_match (struct address_space *aspace1,
170                                      CORE_ADDR addr1,
171                                      struct address_space *aspace2,
172                                      CORE_ADDR addr2);
173
174 static int watchpoint_locations_match (struct bp_location *loc1,
175                                        struct bp_location *loc2);
176
177 static int breakpoint_location_address_match (struct bp_location *bl,
178                                               struct address_space *aspace,
179                                               CORE_ADDR addr);
180
181 static void breakpoints_info (char *, int);
182
183 static void watchpoints_info (char *, int);
184
185 static int breakpoint_1 (char *, int, 
186                          int (*) (const struct breakpoint *));
187
188 static int breakpoint_cond_eval (void *);
189
190 static void cleanup_executing_breakpoints (void *);
191
192 static void commands_command (char *, int);
193
194 static void condition_command (char *, int);
195
196 typedef enum
197   {
198     mark_inserted,
199     mark_uninserted
200   }
201 insertion_state_t;
202
203 static int remove_breakpoint (struct bp_location *, insertion_state_t);
204 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
205
206 static enum print_stop_action print_bp_stop_message (bpstat bs);
207
208 static int watchpoint_check (void *);
209
210 static void maintenance_info_breakpoints (char *, int);
211
212 static int hw_breakpoint_used_count (void);
213
214 static int hw_watchpoint_use_count (struct breakpoint *);
215
216 static int hw_watchpoint_used_count_others (struct breakpoint *except,
217                                             enum bptype type,
218                                             int *other_type_used);
219
220 static void hbreak_command (char *, int);
221
222 static void thbreak_command (char *, int);
223
224 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
225                                     int count);
226
227 static void stop_command (char *arg, int from_tty);
228
229 static void stopin_command (char *arg, int from_tty);
230
231 static void stopat_command (char *arg, int from_tty);
232
233 static void tcatch_command (char *arg, int from_tty);
234
235 static void detach_single_step_breakpoints (void);
236
237 static int single_step_breakpoint_inserted_here_p (struct address_space *,
238                                                    CORE_ADDR pc);
239
240 static void free_bp_location (struct bp_location *loc);
241 static void incref_bp_location (struct bp_location *loc);
242 static void decref_bp_location (struct bp_location **loc);
243
244 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
245
246 static void update_global_location_list (int);
247
248 static void update_global_location_list_nothrow (int);
249
250 static int is_hardware_watchpoint (const struct breakpoint *bpt);
251
252 static void insert_breakpoint_locations (void);
253
254 static int syscall_catchpoint_p (struct breakpoint *b);
255
256 static void tracepoints_info (char *, int);
257
258 static void delete_trace_command (char *, int);
259
260 static void enable_trace_command (char *, int);
261
262 static void disable_trace_command (char *, int);
263
264 static void trace_pass_command (char *, int);
265
266 static void set_tracepoint_count (int num);
267
268 static int is_masked_watchpoint (const struct breakpoint *b);
269
270 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
271
272 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
273    otherwise.  */
274
275 static int strace_marker_p (struct breakpoint *b);
276
277 /* The abstract base class all breakpoint_ops structures inherit
278    from.  */
279 struct breakpoint_ops base_breakpoint_ops;
280
281 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
282    that are implemented on top of software or hardware breakpoints
283    (user breakpoints, internal and momentary breakpoints, etc.).  */
284 static struct breakpoint_ops bkpt_base_breakpoint_ops;
285
286 /* Internal breakpoints class type.  */
287 static struct breakpoint_ops internal_breakpoint_ops;
288
289 /* Momentary breakpoints class type.  */
290 static struct breakpoint_ops momentary_breakpoint_ops;
291
292 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
293 static struct breakpoint_ops longjmp_breakpoint_ops;
294
295 /* The breakpoint_ops structure to be used in regular user created
296    breakpoints.  */
297 struct breakpoint_ops bkpt_breakpoint_ops;
298
299 /* Breakpoints set on probes.  */
300 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
301
302 /* Dynamic printf class type.  */
303 struct breakpoint_ops dprintf_breakpoint_ops;
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 Python object assigned to
1052            it, and if it has a definition of the "stop"
1053            method.  This method and conditions entered into GDB from
1054            the CLI are mutually exclusive.  */
1055         if (b->py_bp_object
1056             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1057           error (_("Cannot set a condition where a Python 'stop' "
1058                    "method has been defined in the breakpoint."));
1059         set_breakpoint_condition (b, p, from_tty);
1060
1061         if (is_breakpoint (b))
1062           update_global_location_list (1);
1063
1064         return;
1065       }
1066
1067   error (_("No breakpoint number %d."), bnum);
1068 }
1069
1070 /* Check that COMMAND do not contain commands that are suitable
1071    only for tracepoints and not suitable for ordinary breakpoints.
1072    Throw if any such commands is found.  */
1073
1074 static void
1075 check_no_tracepoint_commands (struct command_line *commands)
1076 {
1077   struct command_line *c;
1078
1079   for (c = commands; c; c = c->next)
1080     {
1081       int i;
1082
1083       if (c->control_type == while_stepping_control)
1084         error (_("The 'while-stepping' command can "
1085                  "only be used for tracepoints"));
1086
1087       for (i = 0; i < c->body_count; ++i)
1088         check_no_tracepoint_commands ((c->body_list)[i]);
1089
1090       /* Not that command parsing removes leading whitespace and comment
1091          lines and also empty lines.  So, we only need to check for
1092          command directly.  */
1093       if (strstr (c->line, "collect ") == c->line)
1094         error (_("The 'collect' command can only be used for tracepoints"));
1095
1096       if (strstr (c->line, "teval ") == c->line)
1097         error (_("The 'teval' command can only be used for tracepoints"));
1098     }
1099 }
1100
1101 /* Encapsulate tests for different types of tracepoints.  */
1102
1103 static int
1104 is_tracepoint_type (enum bptype type)
1105 {
1106   return (type == bp_tracepoint
1107           || type == bp_fast_tracepoint
1108           || type == bp_static_tracepoint);
1109 }
1110
1111 int
1112 is_tracepoint (const struct breakpoint *b)
1113 {
1114   return is_tracepoint_type (b->type);
1115 }
1116
1117 /* A helper function that validates that COMMANDS are valid for a
1118    breakpoint.  This function will throw an exception if a problem is
1119    found.  */
1120
1121 static void
1122 validate_commands_for_breakpoint (struct breakpoint *b,
1123                                   struct command_line *commands)
1124 {
1125   if (is_tracepoint (b))
1126     {
1127       struct tracepoint *t = (struct tracepoint *) b;
1128       struct command_line *c;
1129       struct command_line *while_stepping = 0;
1130
1131       /* Reset the while-stepping step count.  The previous commands
1132          might have included a while-stepping action, while the new
1133          ones might not.  */
1134       t->step_count = 0;
1135
1136       /* We need to verify that each top-level element of commands is
1137          valid for tracepoints, that there's at most one
1138          while-stepping element, and that the while-stepping's body
1139          has valid tracing commands excluding nested while-stepping.
1140          We also need to validate the tracepoint action line in the
1141          context of the tracepoint --- validate_actionline actually
1142          has side effects, like setting the tracepoint's
1143          while-stepping STEP_COUNT, in addition to checking if the
1144          collect/teval actions parse and make sense in the
1145          tracepoint's context.  */
1146       for (c = commands; c; c = c->next)
1147         {
1148           if (c->control_type == while_stepping_control)
1149             {
1150               if (b->type == bp_fast_tracepoint)
1151                 error (_("The 'while-stepping' command "
1152                          "cannot be used for fast tracepoint"));
1153               else if (b->type == bp_static_tracepoint)
1154                 error (_("The 'while-stepping' command "
1155                          "cannot be used for static tracepoint"));
1156
1157               if (while_stepping)
1158                 error (_("The 'while-stepping' command "
1159                          "can be used only once"));
1160               else
1161                 while_stepping = c;
1162             }
1163
1164           validate_actionline (c->line, b);
1165         }
1166       if (while_stepping)
1167         {
1168           struct command_line *c2;
1169
1170           gdb_assert (while_stepping->body_count == 1);
1171           c2 = while_stepping->body_list[0];
1172           for (; c2; c2 = c2->next)
1173             {
1174               if (c2->control_type == while_stepping_control)
1175                 error (_("The 'while-stepping' command cannot be nested"));
1176             }
1177         }
1178     }
1179   else
1180     {
1181       check_no_tracepoint_commands (commands);
1182     }
1183 }
1184
1185 /* Return a vector of all the static tracepoints set at ADDR.  The
1186    caller is responsible for releasing the vector.  */
1187
1188 VEC(breakpoint_p) *
1189 static_tracepoints_here (CORE_ADDR addr)
1190 {
1191   struct breakpoint *b;
1192   VEC(breakpoint_p) *found = 0;
1193   struct bp_location *loc;
1194
1195   ALL_BREAKPOINTS (b)
1196     if (b->type == bp_static_tracepoint)
1197       {
1198         for (loc = b->loc; loc; loc = loc->next)
1199           if (loc->address == addr)
1200             VEC_safe_push(breakpoint_p, found, b);
1201       }
1202
1203   return found;
1204 }
1205
1206 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1207    validate that only allowed commands are included.  */
1208
1209 void
1210 breakpoint_set_commands (struct breakpoint *b, 
1211                          struct command_line *commands)
1212 {
1213   validate_commands_for_breakpoint (b, commands);
1214
1215   decref_counted_command_line (&b->commands);
1216   b->commands = alloc_counted_command_line (commands);
1217   observer_notify_breakpoint_modified (b);
1218 }
1219
1220 /* Set the internal `silent' flag on the breakpoint.  Note that this
1221    is not the same as the "silent" that may appear in the breakpoint's
1222    commands.  */
1223
1224 void
1225 breakpoint_set_silent (struct breakpoint *b, int silent)
1226 {
1227   int old_silent = b->silent;
1228
1229   b->silent = silent;
1230   if (old_silent != silent)
1231     observer_notify_breakpoint_modified (b);
1232 }
1233
1234 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1235    breakpoint work for any thread.  */
1236
1237 void
1238 breakpoint_set_thread (struct breakpoint *b, int thread)
1239 {
1240   int old_thread = b->thread;
1241
1242   b->thread = thread;
1243   if (old_thread != thread)
1244     observer_notify_breakpoint_modified (b);
1245 }
1246
1247 /* Set the task for this breakpoint.  If TASK is 0, make the
1248    breakpoint work for any task.  */
1249
1250 void
1251 breakpoint_set_task (struct breakpoint *b, int task)
1252 {
1253   int old_task = b->task;
1254
1255   b->task = task;
1256   if (old_task != task)
1257     observer_notify_breakpoint_modified (b);
1258 }
1259
1260 void
1261 check_tracepoint_command (char *line, void *closure)
1262 {
1263   struct breakpoint *b = closure;
1264
1265   validate_actionline (line, b);
1266 }
1267
1268 /* A structure used to pass information through
1269    map_breakpoint_numbers.  */
1270
1271 struct commands_info
1272 {
1273   /* True if the command was typed at a tty.  */
1274   int from_tty;
1275
1276   /* The breakpoint range spec.  */
1277   char *arg;
1278
1279   /* Non-NULL if the body of the commands are being read from this
1280      already-parsed command.  */
1281   struct command_line *control;
1282
1283   /* The command lines read from the user, or NULL if they have not
1284      yet been read.  */
1285   struct counted_command_line *cmd;
1286 };
1287
1288 /* A callback for map_breakpoint_numbers that sets the commands for
1289    commands_command.  */
1290
1291 static void
1292 do_map_commands_command (struct breakpoint *b, void *data)
1293 {
1294   struct commands_info *info = data;
1295
1296   if (info->cmd == NULL)
1297     {
1298       struct command_line *l;
1299
1300       if (info->control != NULL)
1301         l = copy_command_lines (info->control->body_list[0]);
1302       else
1303         {
1304           struct cleanup *old_chain;
1305           char *str;
1306
1307           str = xstrprintf (_("Type commands for breakpoint(s) "
1308                               "%s, one per line."),
1309                             info->arg);
1310
1311           old_chain = make_cleanup (xfree, str);
1312
1313           l = read_command_lines (str,
1314                                   info->from_tty, 1,
1315                                   (is_tracepoint (b)
1316                                    ? check_tracepoint_command : 0),
1317                                   b);
1318
1319           do_cleanups (old_chain);
1320         }
1321
1322       info->cmd = alloc_counted_command_line (l);
1323     }
1324
1325   /* If a breakpoint was on the list more than once, we don't need to
1326      do anything.  */
1327   if (b->commands != info->cmd)
1328     {
1329       validate_commands_for_breakpoint (b, info->cmd->commands);
1330       incref_counted_command_line (info->cmd);
1331       decref_counted_command_line (&b->commands);
1332       b->commands = info->cmd;
1333       observer_notify_breakpoint_modified (b);
1334     }
1335 }
1336
1337 static void
1338 commands_command_1 (char *arg, int from_tty, 
1339                     struct command_line *control)
1340 {
1341   struct cleanup *cleanups;
1342   struct commands_info info;
1343
1344   info.from_tty = from_tty;
1345   info.control = control;
1346   info.cmd = NULL;
1347   /* If we read command lines from the user, then `info' will hold an
1348      extra reference to the commands that we must clean up.  */
1349   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1350
1351   if (arg == NULL || !*arg)
1352     {
1353       if (breakpoint_count - prev_breakpoint_count > 1)
1354         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1355                           breakpoint_count);
1356       else if (breakpoint_count > 0)
1357         arg = xstrprintf ("%d", breakpoint_count);
1358       else
1359         {
1360           /* So that we don't try to free the incoming non-NULL
1361              argument in the cleanup below.  Mapping breakpoint
1362              numbers will fail in this case.  */
1363           arg = NULL;
1364         }
1365     }
1366   else
1367     /* The command loop has some static state, so we need to preserve
1368        our argument.  */
1369     arg = xstrdup (arg);
1370
1371   if (arg != NULL)
1372     make_cleanup (xfree, arg);
1373
1374   info.arg = arg;
1375
1376   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1377
1378   if (info.cmd == NULL)
1379     error (_("No breakpoints specified."));
1380
1381   do_cleanups (cleanups);
1382 }
1383
1384 static void
1385 commands_command (char *arg, int from_tty)
1386 {
1387   commands_command_1 (arg, from_tty, NULL);
1388 }
1389
1390 /* Like commands_command, but instead of reading the commands from
1391    input stream, takes them from an already parsed command structure.
1392
1393    This is used by cli-script.c to DTRT with breakpoint commands
1394    that are part of if and while bodies.  */
1395 enum command_control_type
1396 commands_from_control_command (char *arg, struct command_line *cmd)
1397 {
1398   commands_command_1 (arg, 0, cmd);
1399   return simple_control;
1400 }
1401
1402 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1403
1404 static int
1405 bp_location_has_shadow (struct bp_location *bl)
1406 {
1407   if (bl->loc_type != bp_loc_software_breakpoint)
1408     return 0;
1409   if (!bl->inserted)
1410     return 0;
1411   if (bl->target_info.shadow_len == 0)
1412     /* BL isn't valid, or doesn't shadow memory.  */
1413     return 0;
1414   return 1;
1415 }
1416
1417 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1418    by replacing any memory breakpoints with their shadowed contents.
1419
1420    If READBUF is not NULL, this buffer must not overlap with any of
1421    the breakpoint location's shadow_contents buffers.  Otherwise,
1422    a failed assertion internal error will be raised.
1423
1424    The range of shadowed area by each bp_location is:
1425      bl->address - bp_location_placed_address_before_address_max
1426      up to bl->address + bp_location_shadow_len_after_address_max
1427    The range we were requested to resolve shadows for is:
1428      memaddr ... memaddr + len
1429    Thus the safe cutoff boundaries for performance optimization are
1430      memaddr + len <= (bl->address
1431                        - bp_location_placed_address_before_address_max)
1432    and:
1433      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1434
1435 void
1436 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1437                         const gdb_byte *writebuf_org,
1438                         ULONGEST memaddr, LONGEST len)
1439 {
1440   /* Left boundary, right boundary and median element of our binary
1441      search.  */
1442   unsigned bc_l, bc_r, bc;
1443
1444   /* Find BC_L which is a leftmost element which may affect BUF
1445      content.  It is safe to report lower value but a failure to
1446      report higher one.  */
1447
1448   bc_l = 0;
1449   bc_r = bp_location_count;
1450   while (bc_l + 1 < bc_r)
1451     {
1452       struct bp_location *bl;
1453
1454       bc = (bc_l + bc_r) / 2;
1455       bl = bp_location[bc];
1456
1457       /* Check first BL->ADDRESS will not overflow due to the added
1458          constant.  Then advance the left boundary only if we are sure
1459          the BC element can in no way affect the BUF content (MEMADDR
1460          to MEMADDR + LEN range).
1461
1462          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1463          offset so that we cannot miss a breakpoint with its shadow
1464          range tail still reaching MEMADDR.  */
1465
1466       if ((bl->address + bp_location_shadow_len_after_address_max
1467            >= bl->address)
1468           && (bl->address + bp_location_shadow_len_after_address_max
1469               <= memaddr))
1470         bc_l = bc;
1471       else
1472         bc_r = bc;
1473     }
1474
1475   /* Due to the binary search above, we need to make sure we pick the
1476      first location that's at BC_L's address.  E.g., if there are
1477      multiple locations at the same address, BC_L may end up pointing
1478      at a duplicate location, and miss the "master"/"inserted"
1479      location.  Say, given locations L1, L2 and L3 at addresses A and
1480      B:
1481
1482       L1@A, L2@A, L3@B, ...
1483
1484      BC_L could end up pointing at location L2, while the "master"
1485      location could be L1.  Since the `loc->inserted' flag is only set
1486      on "master" locations, we'd forget to restore the shadow of L1
1487      and L2.  */
1488   while (bc_l > 0
1489          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1490     bc_l--;
1491
1492   /* Now do full processing of the found relevant range of elements.  */
1493
1494   for (bc = bc_l; bc < bp_location_count; bc++)
1495   {
1496     struct bp_location *bl = bp_location[bc];
1497     CORE_ADDR bp_addr = 0;
1498     int bp_size = 0;
1499     int bptoffset = 0;
1500
1501     /* bp_location array has BL->OWNER always non-NULL.  */
1502     if (bl->owner->type == bp_none)
1503       warning (_("reading through apparently deleted breakpoint #%d?"),
1504                bl->owner->number);
1505
1506     /* Performance optimization: any further element can no longer affect BUF
1507        content.  */
1508
1509     if (bl->address >= bp_location_placed_address_before_address_max
1510         && memaddr + len <= (bl->address
1511                              - bp_location_placed_address_before_address_max))
1512       break;
1513
1514     if (!bp_location_has_shadow (bl))
1515       continue;
1516     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1517                                    current_program_space->aspace, 0))
1518       continue;
1519
1520     /* Addresses and length of the part of the breakpoint that
1521        we need to copy.  */
1522     bp_addr = bl->target_info.placed_address;
1523     bp_size = bl->target_info.shadow_len;
1524
1525     if (bp_addr + bp_size <= memaddr)
1526       /* The breakpoint is entirely before the chunk of memory we
1527          are reading.  */
1528       continue;
1529
1530     if (bp_addr >= memaddr + len)
1531       /* The breakpoint is entirely after the chunk of memory we are
1532          reading.  */
1533       continue;
1534
1535     /* Offset within shadow_contents.  */
1536     if (bp_addr < memaddr)
1537       {
1538         /* Only copy the second part of the breakpoint.  */
1539         bp_size -= memaddr - bp_addr;
1540         bptoffset = memaddr - bp_addr;
1541         bp_addr = memaddr;
1542       }
1543
1544     if (bp_addr + bp_size > memaddr + len)
1545       {
1546         /* Only copy the first part of the breakpoint.  */
1547         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1548       }
1549
1550     if (readbuf != NULL)
1551       {
1552         /* Verify that the readbuf buffer does not overlap with
1553            the shadow_contents buffer.  */
1554         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1555                     || readbuf >= (bl->target_info.shadow_contents
1556                                    + bl->target_info.shadow_len));
1557
1558         /* Update the read buffer with this inserted breakpoint's
1559            shadow.  */
1560         memcpy (readbuf + bp_addr - memaddr,
1561                 bl->target_info.shadow_contents + bptoffset, bp_size);
1562       }
1563     else
1564       {
1565         struct gdbarch *gdbarch = bl->gdbarch;
1566         const unsigned char *bp;
1567         CORE_ADDR placed_address = bl->target_info.placed_address;
1568         int placed_size = bl->target_info.placed_size;
1569
1570         /* Update the shadow with what we want to write to memory.  */
1571         memcpy (bl->target_info.shadow_contents + bptoffset,
1572                 writebuf_org + bp_addr - memaddr, bp_size);
1573
1574         /* Determine appropriate breakpoint contents and size for this
1575            address.  */
1576         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1577
1578         /* Update the final write buffer with this inserted
1579            breakpoint's INSN.  */
1580         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1581       }
1582   }
1583 }
1584 \f
1585
1586 /* Return true if BPT is either a software breakpoint or a hardware
1587    breakpoint.  */
1588
1589 int
1590 is_breakpoint (const struct breakpoint *bpt)
1591 {
1592   return (bpt->type == bp_breakpoint
1593           || bpt->type == bp_hardware_breakpoint
1594           || bpt->type == bp_dprintf);
1595 }
1596
1597 /* Return true if BPT is of any hardware watchpoint kind.  */
1598
1599 static int
1600 is_hardware_watchpoint (const struct breakpoint *bpt)
1601 {
1602   return (bpt->type == bp_hardware_watchpoint
1603           || bpt->type == bp_read_watchpoint
1604           || bpt->type == bp_access_watchpoint);
1605 }
1606
1607 /* Return true if BPT is of any watchpoint kind, hardware or
1608    software.  */
1609
1610 int
1611 is_watchpoint (const struct breakpoint *bpt)
1612 {
1613   return (is_hardware_watchpoint (bpt)
1614           || bpt->type == bp_watchpoint);
1615 }
1616
1617 /* Returns true if the current thread and its running state are safe
1618    to evaluate or update watchpoint B.  Watchpoints on local
1619    expressions need to be evaluated in the context of the thread that
1620    was current when the watchpoint was created, and, that thread needs
1621    to be stopped to be able to select the correct frame context.
1622    Watchpoints on global expressions can be evaluated on any thread,
1623    and in any state.  It is presently left to the target allowing
1624    memory accesses when threads are running.  */
1625
1626 static int
1627 watchpoint_in_thread_scope (struct watchpoint *b)
1628 {
1629   return (b->base.pspace == current_program_space
1630           && (ptid_equal (b->watchpoint_thread, null_ptid)
1631               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1632                   && !is_executing (inferior_ptid))));
1633 }
1634
1635 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1636    associated bp_watchpoint_scope breakpoint.  */
1637
1638 static void
1639 watchpoint_del_at_next_stop (struct watchpoint *w)
1640 {
1641   struct breakpoint *b = &w->base;
1642
1643   if (b->related_breakpoint != b)
1644     {
1645       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1646       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1647       b->related_breakpoint->disposition = disp_del_at_next_stop;
1648       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1649       b->related_breakpoint = b;
1650     }
1651   b->disposition = disp_del_at_next_stop;
1652 }
1653
1654 /* Assuming that B is a watchpoint:
1655    - Reparse watchpoint expression, if REPARSE is non-zero
1656    - Evaluate expression and store the result in B->val
1657    - Evaluate the condition if there is one, and store the result
1658      in b->loc->cond.
1659    - Update the list of values that must be watched in B->loc.
1660
1661    If the watchpoint disposition is disp_del_at_next_stop, then do
1662    nothing.  If this is local watchpoint that is out of scope, delete
1663    it.
1664
1665    Even with `set breakpoint always-inserted on' the watchpoints are
1666    removed + inserted on each stop here.  Normal breakpoints must
1667    never be removed because they might be missed by a running thread
1668    when debugging in non-stop mode.  On the other hand, hardware
1669    watchpoints (is_hardware_watchpoint; processed here) are specific
1670    to each LWP since they are stored in each LWP's hardware debug
1671    registers.  Therefore, such LWP must be stopped first in order to
1672    be able to modify its hardware watchpoints.
1673
1674    Hardware watchpoints must be reset exactly once after being
1675    presented to the user.  It cannot be done sooner, because it would
1676    reset the data used to present the watchpoint hit to the user.  And
1677    it must not be done later because it could display the same single
1678    watchpoint hit during multiple GDB stops.  Note that the latter is
1679    relevant only to the hardware watchpoint types bp_read_watchpoint
1680    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1681    not user-visible - its hit is suppressed if the memory content has
1682    not changed.
1683
1684    The following constraints influence the location where we can reset
1685    hardware watchpoints:
1686
1687    * target_stopped_by_watchpoint and target_stopped_data_address are
1688      called several times when GDB stops.
1689
1690    [linux] 
1691    * Multiple hardware watchpoints can be hit at the same time,
1692      causing GDB to stop.  GDB only presents one hardware watchpoint
1693      hit at a time as the reason for stopping, and all the other hits
1694      are presented later, one after the other, each time the user
1695      requests the execution to be resumed.  Execution is not resumed
1696      for the threads still having pending hit event stored in
1697      LWP_INFO->STATUS.  While the watchpoint is already removed from
1698      the inferior on the first stop the thread hit event is kept being
1699      reported from its cached value by linux_nat_stopped_data_address
1700      until the real thread resume happens after the watchpoint gets
1701      presented and thus its LWP_INFO->STATUS gets reset.
1702
1703    Therefore the hardware watchpoint hit can get safely reset on the
1704    watchpoint removal from inferior.  */
1705
1706 static void
1707 update_watchpoint (struct watchpoint *b, int reparse)
1708 {
1709   int within_current_scope;
1710   struct frame_id saved_frame_id;
1711   int frame_saved;
1712
1713   /* If this is a local watchpoint, we only want to check if the
1714      watchpoint frame is in scope if the current thread is the thread
1715      that was used to create the watchpoint.  */
1716   if (!watchpoint_in_thread_scope (b))
1717     return;
1718
1719   if (b->base.disposition == disp_del_at_next_stop)
1720     return;
1721  
1722   frame_saved = 0;
1723
1724   /* Determine if the watchpoint is within scope.  */
1725   if (b->exp_valid_block == NULL)
1726     within_current_scope = 1;
1727   else
1728     {
1729       struct frame_info *fi = get_current_frame ();
1730       struct gdbarch *frame_arch = get_frame_arch (fi);
1731       CORE_ADDR frame_pc = get_frame_pc (fi);
1732
1733       /* If we're in a function epilogue, unwinding may not work
1734          properly, so do not attempt to recreate locations at this
1735          point.  See similar comments in watchpoint_check.  */
1736       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1737         return;
1738
1739       /* Save the current frame's ID so we can restore it after
1740          evaluating the watchpoint expression on its own frame.  */
1741       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1742          took a frame parameter, so that we didn't have to change the
1743          selected frame.  */
1744       frame_saved = 1;
1745       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1746
1747       fi = frame_find_by_id (b->watchpoint_frame);
1748       within_current_scope = (fi != NULL);
1749       if (within_current_scope)
1750         select_frame (fi);
1751     }
1752
1753   /* We don't free locations.  They are stored in the bp_location array
1754      and update_global_location_list will eventually delete them and
1755      remove breakpoints if needed.  */
1756   b->base.loc = NULL;
1757
1758   if (within_current_scope && reparse)
1759     {
1760       const char *s;
1761
1762       if (b->exp)
1763         {
1764           xfree (b->exp);
1765           b->exp = NULL;
1766         }
1767       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1768       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1769       /* If the meaning of expression itself changed, the old value is
1770          no longer relevant.  We don't want to report a watchpoint hit
1771          to the user when the old value and the new value may actually
1772          be completely different objects.  */
1773       value_free (b->val);
1774       b->val = NULL;
1775       b->val_valid = 0;
1776
1777       /* Note that unlike with breakpoints, the watchpoint's condition
1778          expression is stored in the breakpoint object, not in the
1779          locations (re)created below.  */
1780       if (b->base.cond_string != NULL)
1781         {
1782           if (b->cond_exp != NULL)
1783             {
1784               xfree (b->cond_exp);
1785               b->cond_exp = NULL;
1786             }
1787
1788           s = b->base.cond_string;
1789           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1790         }
1791     }
1792
1793   /* If we failed to parse the expression, for example because
1794      it refers to a global variable in a not-yet-loaded shared library,
1795      don't try to insert watchpoint.  We don't automatically delete
1796      such watchpoint, though, since failure to parse expression
1797      is different from out-of-scope watchpoint.  */
1798   if ( !target_has_execution)
1799     {
1800       /* Without execution, memory can't change.  No use to try and
1801          set watchpoint locations.  The watchpoint will be reset when
1802          the target gains execution, through breakpoint_re_set.  */
1803     }
1804   else if (within_current_scope && b->exp)
1805     {
1806       int pc = 0;
1807       struct value *val_chain, *v, *result, *next;
1808       struct program_space *frame_pspace;
1809
1810       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1811
1812       /* Avoid setting b->val if it's already set.  The meaning of
1813          b->val is 'the last value' user saw, and we should update
1814          it only if we reported that last value to user.  As it
1815          happens, the code that reports it updates b->val directly.
1816          We don't keep track of the memory value for masked
1817          watchpoints.  */
1818       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1819         {
1820           b->val = v;
1821           b->val_valid = 1;
1822         }
1823
1824       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1825
1826       /* Look at each value on the value chain.  */
1827       for (v = val_chain; v; v = value_next (v))
1828         {
1829           /* If it's a memory location, and GDB actually needed
1830              its contents to evaluate the expression, then we
1831              must watch it.  If the first value returned is
1832              still lazy, that means an error occurred reading it;
1833              watch it anyway in case it becomes readable.  */
1834           if (VALUE_LVAL (v) == lval_memory
1835               && (v == val_chain || ! value_lazy (v)))
1836             {
1837               struct type *vtype = check_typedef (value_type (v));
1838
1839               /* We only watch structs and arrays if user asked
1840                  for it explicitly, never if they just happen to
1841                  appear in the middle of some value chain.  */
1842               if (v == result
1843                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1844                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1845                 {
1846                   CORE_ADDR addr;
1847                   int type;
1848                   struct bp_location *loc, **tmp;
1849
1850                   addr = value_address (v);
1851                   type = hw_write;
1852                   if (b->base.type == bp_read_watchpoint)
1853                     type = hw_read;
1854                   else if (b->base.type == bp_access_watchpoint)
1855                     type = hw_access;
1856
1857                   loc = allocate_bp_location (&b->base);
1858                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1859                     ;
1860                   *tmp = loc;
1861                   loc->gdbarch = get_type_arch (value_type (v));
1862
1863                   loc->pspace = frame_pspace;
1864                   loc->address = addr;
1865                   loc->length = TYPE_LENGTH (value_type (v));
1866                   loc->watchpoint_type = type;
1867                 }
1868             }
1869         }
1870
1871       /* Change the type of breakpoint between hardware assisted or
1872          an ordinary watchpoint depending on the hardware support
1873          and free hardware slots.  REPARSE is set when the inferior
1874          is started.  */
1875       if (reparse)
1876         {
1877           int reg_cnt;
1878           enum bp_loc_type loc_type;
1879           struct bp_location *bl;
1880
1881           reg_cnt = can_use_hardware_watchpoint (val_chain);
1882
1883           if (reg_cnt)
1884             {
1885               int i, target_resources_ok, other_type_used;
1886               enum bptype type;
1887
1888               /* Use an exact watchpoint when there's only one memory region to be
1889                  watched, and only one debug register is needed to watch it.  */
1890               b->exact = target_exact_watchpoints && reg_cnt == 1;
1891
1892               /* We need to determine how many resources are already
1893                  used for all other hardware watchpoints plus this one
1894                  to see if we still have enough resources to also fit
1895                  this watchpoint in as well.  */
1896
1897               /* If this is a software watchpoint, we try to turn it
1898                  to a hardware one -- count resources as if B was of
1899                  hardware watchpoint type.  */
1900               type = b->base.type;
1901               if (type == bp_watchpoint)
1902                 type = bp_hardware_watchpoint;
1903
1904               /* This watchpoint may or may not have been placed on
1905                  the list yet at this point (it won't be in the list
1906                  if we're trying to create it for the first time,
1907                  through watch_command), so always account for it
1908                  manually.  */
1909
1910               /* Count resources used by all watchpoints except B.  */
1911               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1912
1913               /* Add in the resources needed for B.  */
1914               i += hw_watchpoint_use_count (&b->base);
1915
1916               target_resources_ok
1917                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1918               if (target_resources_ok <= 0)
1919                 {
1920                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1921
1922                   if (target_resources_ok == 0 && !sw_mode)
1923                     error (_("Target does not support this type of "
1924                              "hardware watchpoint."));
1925                   else if (target_resources_ok < 0 && !sw_mode)
1926                     error (_("There are not enough available hardware "
1927                              "resources for this watchpoint."));
1928
1929                   /* Downgrade to software watchpoint.  */
1930                   b->base.type = bp_watchpoint;
1931                 }
1932               else
1933                 {
1934                   /* If this was a software watchpoint, we've just
1935                      found we have enough resources to turn it to a
1936                      hardware watchpoint.  Otherwise, this is a
1937                      nop.  */
1938                   b->base.type = type;
1939                 }
1940             }
1941           else if (!b->base.ops->works_in_software_mode (&b->base))
1942             error (_("Expression cannot be implemented with "
1943                      "read/access watchpoint."));
1944           else
1945             b->base.type = bp_watchpoint;
1946
1947           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1948                       : bp_loc_hardware_watchpoint);
1949           for (bl = b->base.loc; bl; bl = bl->next)
1950             bl->loc_type = loc_type;
1951         }
1952
1953       for (v = val_chain; v; v = next)
1954         {
1955           next = value_next (v);
1956           if (v != b->val)
1957             value_free (v);
1958         }
1959
1960       /* If a software watchpoint is not watching any memory, then the
1961          above left it without any location set up.  But,
1962          bpstat_stop_status requires a location to be able to report
1963          stops, so make sure there's at least a dummy one.  */
1964       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1965         {
1966           struct breakpoint *base = &b->base;
1967           base->loc = allocate_bp_location (base);
1968           base->loc->pspace = frame_pspace;
1969           base->loc->address = -1;
1970           base->loc->length = -1;
1971           base->loc->watchpoint_type = -1;
1972         }
1973     }
1974   else if (!within_current_scope)
1975     {
1976       printf_filtered (_("\
1977 Watchpoint %d deleted because the program has left the block\n\
1978 in which its expression is valid.\n"),
1979                        b->base.number);
1980       watchpoint_del_at_next_stop (b);
1981     }
1982
1983   /* Restore the selected frame.  */
1984   if (frame_saved)
1985     select_frame (frame_find_by_id (saved_frame_id));
1986 }
1987
1988
1989 /* Returns 1 iff breakpoint location should be
1990    inserted in the inferior.  We don't differentiate the type of BL's owner
1991    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1992    breakpoint_ops is not defined, because in insert_bp_location,
1993    tracepoint's insert_location will not be called.  */
1994 static int
1995 should_be_inserted (struct bp_location *bl)
1996 {
1997   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1998     return 0;
1999
2000   if (bl->owner->disposition == disp_del_at_next_stop)
2001     return 0;
2002
2003   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2004     return 0;
2005
2006   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2007     return 0;
2008
2009   /* This is set for example, when we're attached to the parent of a
2010      vfork, and have detached from the child.  The child is running
2011      free, and we expect it to do an exec or exit, at which point the
2012      OS makes the parent schedulable again (and the target reports
2013      that the vfork is done).  Until the child is done with the shared
2014      memory region, do not insert breakpoints in the parent, otherwise
2015      the child could still trip on the parent's breakpoints.  Since
2016      the parent is blocked anyway, it won't miss any breakpoint.  */
2017   if (bl->pspace->breakpoints_not_allowed)
2018     return 0;
2019
2020   return 1;
2021 }
2022
2023 /* Same as should_be_inserted but does the check assuming
2024    that the location is not duplicated.  */
2025
2026 static int
2027 unduplicated_should_be_inserted (struct bp_location *bl)
2028 {
2029   int result;
2030   const int save_duplicate = bl->duplicate;
2031
2032   bl->duplicate = 0;
2033   result = should_be_inserted (bl);
2034   bl->duplicate = save_duplicate;
2035   return result;
2036 }
2037
2038 /* Parses a conditional described by an expression COND into an
2039    agent expression bytecode suitable for evaluation
2040    by the bytecode interpreter.  Return NULL if there was
2041    any error during parsing.  */
2042
2043 static struct agent_expr *
2044 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2045 {
2046   struct agent_expr *aexpr = NULL;
2047   volatile struct gdb_exception ex;
2048
2049   if (!cond)
2050     return NULL;
2051
2052   /* We don't want to stop processing, so catch any errors
2053      that may show up.  */
2054   TRY_CATCH (ex, RETURN_MASK_ERROR)
2055     {
2056       aexpr = gen_eval_for_expr (scope, cond);
2057     }
2058
2059   if (ex.reason < 0)
2060     {
2061       /* If we got here, it means the condition could not be parsed to a valid
2062          bytecode expression and thus can't be evaluated on the target's side.
2063          It's no use iterating through the conditions.  */
2064       return NULL;
2065     }
2066
2067   /* We have a valid agent expression.  */
2068   return aexpr;
2069 }
2070
2071 /* Based on location BL, create a list of breakpoint conditions to be
2072    passed on to the target.  If we have duplicated locations with different
2073    conditions, we will add such conditions to the list.  The idea is that the
2074    target will evaluate the list of conditions and will only notify GDB when
2075    one of them is true.  */
2076
2077 static void
2078 build_target_condition_list (struct bp_location *bl)
2079 {
2080   struct bp_location **locp = NULL, **loc2p;
2081   int null_condition_or_parse_error = 0;
2082   int modified = bl->needs_update;
2083   struct bp_location *loc;
2084
2085   /* This is only meaningful if the target is
2086      evaluating conditions and if the user has
2087      opted for condition evaluation on the target's
2088      side.  */
2089   if (gdb_evaluates_breakpoint_condition_p ()
2090       || !target_supports_evaluation_of_breakpoint_conditions ())
2091     return;
2092
2093   /* Do a first pass to check for locations with no assigned
2094      conditions or conditions that fail to parse to a valid agent expression
2095      bytecode.  If any of these happen, then it's no use to send conditions
2096      to the target since this location will always trigger and generate a
2097      response back to GDB.  */
2098   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2099     {
2100       loc = (*loc2p);
2101       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2102         {
2103           if (modified)
2104             {
2105               struct agent_expr *aexpr;
2106
2107               /* Re-parse the conditions since something changed.  In that
2108                  case we already freed the condition bytecodes (see
2109                  force_breakpoint_reinsertion).  We just
2110                  need to parse the condition to bytecodes again.  */
2111               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2112               loc->cond_bytecode = aexpr;
2113
2114               /* Check if we managed to parse the conditional expression
2115                  correctly.  If not, we will not send this condition
2116                  to the target.  */
2117               if (aexpr)
2118                 continue;
2119             }
2120
2121           /* If we have a NULL bytecode expression, it means something
2122              went wrong or we have a null condition expression.  */
2123           if (!loc->cond_bytecode)
2124             {
2125               null_condition_or_parse_error = 1;
2126               break;
2127             }
2128         }
2129     }
2130
2131   /* If any of these happened, it means we will have to evaluate the conditions
2132      for the location's address on gdb's side.  It is no use keeping bytecodes
2133      for all the other duplicate locations, thus we free all of them here.
2134
2135      This is so we have a finer control over which locations' conditions are
2136      being evaluated by GDB or the remote stub.  */
2137   if (null_condition_or_parse_error)
2138     {
2139       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2140         {
2141           loc = (*loc2p);
2142           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2143             {
2144               /* Only go as far as the first NULL bytecode is
2145                  located.  */
2146               if (!loc->cond_bytecode)
2147                 return;
2148
2149               free_agent_expr (loc->cond_bytecode);
2150               loc->cond_bytecode = NULL;
2151             }
2152         }
2153     }
2154
2155   /* No NULL conditions or failed bytecode generation.  Build a condition list
2156      for this location's address.  */
2157   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2158     {
2159       loc = (*loc2p);
2160       if (loc->cond
2161           && is_breakpoint (loc->owner)
2162           && loc->pspace->num == bl->pspace->num
2163           && loc->owner->enable_state == bp_enabled
2164           && loc->enabled)
2165         /* Add the condition to the vector.  This will be used later to send the
2166            conditions to the target.  */
2167         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2168                        loc->cond_bytecode);
2169     }
2170
2171   return;
2172 }
2173
2174 /* Parses a command described by string CMD into an agent expression
2175    bytecode suitable for evaluation by the bytecode interpreter.
2176    Return NULL if there was any error during parsing.  */
2177
2178 static struct agent_expr *
2179 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2180 {
2181   struct cleanup *old_cleanups = 0;
2182   struct expression *expr, **argvec;
2183   struct agent_expr *aexpr = NULL;
2184   volatile struct gdb_exception ex;
2185   const char *cmdrest;
2186   const char *format_start, *format_end;
2187   struct format_piece *fpieces;
2188   int nargs;
2189   struct gdbarch *gdbarch = get_current_arch ();
2190
2191   if (!cmd)
2192     return NULL;
2193
2194   cmdrest = cmd;
2195
2196   if (*cmdrest == ',')
2197     ++cmdrest;
2198   cmdrest = skip_spaces_const (cmdrest);
2199
2200   if (*cmdrest++ != '"')
2201     error (_("No format string following the location"));
2202
2203   format_start = cmdrest;
2204
2205   fpieces = parse_format_string (&cmdrest);
2206
2207   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2208
2209   format_end = cmdrest;
2210
2211   if (*cmdrest++ != '"')
2212     error (_("Bad format string, non-terminated '\"'."));
2213   
2214   cmdrest = skip_spaces_const (cmdrest);
2215
2216   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2217     error (_("Invalid argument syntax"));
2218
2219   if (*cmdrest == ',')
2220     cmdrest++;
2221   cmdrest = skip_spaces_const (cmdrest);
2222
2223   /* For each argument, make an expression.  */
2224
2225   argvec = (struct expression **) alloca (strlen (cmd)
2226                                          * sizeof (struct expression *));
2227
2228   nargs = 0;
2229   while (*cmdrest != '\0')
2230     {
2231       const char *cmd1;
2232
2233       cmd1 = cmdrest;
2234       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2235       argvec[nargs++] = expr;
2236       cmdrest = cmd1;
2237       if (*cmdrest == ',')
2238         ++cmdrest;
2239     }
2240
2241   /* We don't want to stop processing, so catch any errors
2242      that may show up.  */
2243   TRY_CATCH (ex, RETURN_MASK_ERROR)
2244     {
2245       aexpr = gen_printf (scope, gdbarch, 0, 0,
2246                           format_start, format_end - format_start,
2247                           fpieces, nargs, argvec);
2248     }
2249
2250   do_cleanups (old_cleanups);
2251
2252   if (ex.reason < 0)
2253     {
2254       /* If we got here, it means the command could not be parsed to a valid
2255          bytecode expression and thus can't be evaluated on the target's side.
2256          It's no use iterating through the other commands.  */
2257       return NULL;
2258     }
2259
2260   /* We have a valid agent expression, return it.  */
2261   return aexpr;
2262 }
2263
2264 /* Based on location BL, create a list of breakpoint commands to be
2265    passed on to the target.  If we have duplicated locations with
2266    different commands, we will add any such to the list.  */
2267
2268 static void
2269 build_target_command_list (struct bp_location *bl)
2270 {
2271   struct bp_location **locp = NULL, **loc2p;
2272   int null_command_or_parse_error = 0;
2273   int modified = bl->needs_update;
2274   struct bp_location *loc;
2275
2276   /* For now, limit to agent-style dprintf breakpoints.  */
2277   if (bl->owner->type != bp_dprintf
2278       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2279     return;
2280
2281   if (!target_can_run_breakpoint_commands ())
2282     return;
2283
2284   /* Do a first pass to check for locations with no assigned
2285      conditions or conditions that fail to parse to a valid agent expression
2286      bytecode.  If any of these happen, then it's no use to send conditions
2287      to the target since this location will always trigger and generate a
2288      response back to GDB.  */
2289   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2290     {
2291       loc = (*loc2p);
2292       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2293         {
2294           if (modified)
2295             {
2296               struct agent_expr *aexpr;
2297
2298               /* Re-parse the commands since something changed.  In that
2299                  case we already freed the command bytecodes (see
2300                  force_breakpoint_reinsertion).  We just
2301                  need to parse the command to bytecodes again.  */
2302               aexpr = parse_cmd_to_aexpr (bl->address,
2303                                           loc->owner->extra_string);
2304               loc->cmd_bytecode = aexpr;
2305
2306               if (!aexpr)
2307                 continue;
2308             }
2309
2310           /* If we have a NULL bytecode expression, it means something
2311              went wrong or we have a null command expression.  */
2312           if (!loc->cmd_bytecode)
2313             {
2314               null_command_or_parse_error = 1;
2315               break;
2316             }
2317         }
2318     }
2319
2320   /* If anything failed, then we're not doing target-side commands,
2321      and so clean up.  */
2322   if (null_command_or_parse_error)
2323     {
2324       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2325         {
2326           loc = (*loc2p);
2327           if (is_breakpoint (loc->owner)
2328               && loc->pspace->num == bl->pspace->num)
2329             {
2330               /* Only go as far as the first NULL bytecode is
2331                  located.  */
2332               if (loc->cmd_bytecode == NULL)
2333                 return;
2334
2335               free_agent_expr (loc->cmd_bytecode);
2336               loc->cmd_bytecode = NULL;
2337             }
2338         }
2339     }
2340
2341   /* No NULL commands or failed bytecode generation.  Build a command list
2342      for this location's address.  */
2343   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2344     {
2345       loc = (*loc2p);
2346       if (loc->owner->extra_string
2347           && is_breakpoint (loc->owner)
2348           && loc->pspace->num == bl->pspace->num
2349           && loc->owner->enable_state == bp_enabled
2350           && loc->enabled)
2351         /* Add the command to the vector.  This will be used later
2352            to send the commands to the target.  */
2353         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2354                        loc->cmd_bytecode);
2355     }
2356
2357   bl->target_info.persist = 0;
2358   /* Maybe flag this location as persistent.  */
2359   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2360     bl->target_info.persist = 1;
2361 }
2362
2363 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2364    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2365    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2366    Returns 0 for success, 1 if the bp_location type is not supported or
2367    -1 for failure.
2368
2369    NOTE drow/2003-09-09: This routine could be broken down to an
2370    object-style method for each breakpoint or catchpoint type.  */
2371 static int
2372 insert_bp_location (struct bp_location *bl,
2373                     struct ui_file *tmp_error_stream,
2374                     int *disabled_breaks,
2375                     int *hw_breakpoint_error,
2376                     int *hw_bp_error_explained_already)
2377 {
2378   int val = 0;
2379   char *hw_bp_err_string = NULL;
2380   struct gdb_exception e;
2381
2382   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2383     return 0;
2384
2385   /* Note we don't initialize bl->target_info, as that wipes out
2386      the breakpoint location's shadow_contents if the breakpoint
2387      is still inserted at that location.  This in turn breaks
2388      target_read_memory which depends on these buffers when
2389      a memory read is requested at the breakpoint location:
2390      Once the target_info has been wiped, we fail to see that
2391      we have a breakpoint inserted at that address and thus
2392      read the breakpoint instead of returning the data saved in
2393      the breakpoint location's shadow contents.  */
2394   bl->target_info.placed_address = bl->address;
2395   bl->target_info.placed_address_space = bl->pspace->aspace;
2396   bl->target_info.length = bl->length;
2397
2398   /* When working with target-side conditions, we must pass all the conditions
2399      for the same breakpoint address down to the target since GDB will not
2400      insert those locations.  With a list of breakpoint conditions, the target
2401      can decide when to stop and notify GDB.  */
2402
2403   if (is_breakpoint (bl->owner))
2404     {
2405       build_target_condition_list (bl);
2406       build_target_command_list (bl);
2407       /* Reset the modification marker.  */
2408       bl->needs_update = 0;
2409     }
2410
2411   if (bl->loc_type == bp_loc_software_breakpoint
2412       || bl->loc_type == bp_loc_hardware_breakpoint)
2413     {
2414       if (bl->owner->type != bp_hardware_breakpoint)
2415         {
2416           /* If the explicitly specified breakpoint type
2417              is not hardware breakpoint, check the memory map to see
2418              if the breakpoint address is in read only memory or not.
2419
2420              Two important cases are:
2421              - location type is not hardware breakpoint, memory
2422              is readonly.  We change the type of the location to
2423              hardware breakpoint.
2424              - location type is hardware breakpoint, memory is
2425              read-write.  This means we've previously made the
2426              location hardware one, but then the memory map changed,
2427              so we undo.
2428              
2429              When breakpoints are removed, remove_breakpoints will use
2430              location types we've just set here, the only possible
2431              problem is that memory map has changed during running
2432              program, but it's not going to work anyway with current
2433              gdb.  */
2434           struct mem_region *mr 
2435             = lookup_mem_region (bl->target_info.placed_address);
2436           
2437           if (mr)
2438             {
2439               if (automatic_hardware_breakpoints)
2440                 {
2441                   enum bp_loc_type new_type;
2442                   
2443                   if (mr->attrib.mode != MEM_RW)
2444                     new_type = bp_loc_hardware_breakpoint;
2445                   else 
2446                     new_type = bp_loc_software_breakpoint;
2447                   
2448                   if (new_type != bl->loc_type)
2449                     {
2450                       static int said = 0;
2451
2452                       bl->loc_type = new_type;
2453                       if (!said)
2454                         {
2455                           fprintf_filtered (gdb_stdout,
2456                                             _("Note: automatically using "
2457                                               "hardware breakpoints for "
2458                                               "read-only addresses.\n"));
2459                           said = 1;
2460                         }
2461                     }
2462                 }
2463               else if (bl->loc_type == bp_loc_software_breakpoint
2464                        && mr->attrib.mode != MEM_RW)        
2465                 warning (_("cannot set software breakpoint "
2466                            "at readonly address %s"),
2467                          paddress (bl->gdbarch, bl->address));
2468             }
2469         }
2470         
2471       /* First check to see if we have to handle an overlay.  */
2472       if (overlay_debugging == ovly_off
2473           || bl->section == NULL
2474           || !(section_is_overlay (bl->section)))
2475         {
2476           /* No overlay handling: just set the breakpoint.  */
2477           TRY_CATCH (e, RETURN_MASK_ALL)
2478             {
2479               val = bl->owner->ops->insert_location (bl);
2480             }
2481           if (e.reason < 0)
2482             {
2483               val = 1;
2484               hw_bp_err_string = (char *) e.message;
2485             }
2486         }
2487       else
2488         {
2489           /* This breakpoint is in an overlay section.
2490              Shall we set a breakpoint at the LMA?  */
2491           if (!overlay_events_enabled)
2492             {
2493               /* Yes -- overlay event support is not active, 
2494                  so we must try to set a breakpoint at the LMA.
2495                  This will not work for a hardware breakpoint.  */
2496               if (bl->loc_type == bp_loc_hardware_breakpoint)
2497                 warning (_("hardware breakpoint %d not supported in overlay!"),
2498                          bl->owner->number);
2499               else
2500                 {
2501                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2502                                                              bl->section);
2503                   /* Set a software (trap) breakpoint at the LMA.  */
2504                   bl->overlay_target_info = bl->target_info;
2505                   bl->overlay_target_info.placed_address = addr;
2506                   val = target_insert_breakpoint (bl->gdbarch,
2507                                                   &bl->overlay_target_info);
2508                   if (val != 0)
2509                     fprintf_unfiltered (tmp_error_stream,
2510                                         "Overlay breakpoint %d "
2511                                         "failed: in ROM?\n",
2512                                         bl->owner->number);
2513                 }
2514             }
2515           /* Shall we set a breakpoint at the VMA? */
2516           if (section_is_mapped (bl->section))
2517             {
2518               /* Yes.  This overlay section is mapped into memory.  */
2519               TRY_CATCH (e, RETURN_MASK_ALL)
2520                 {
2521                   val = bl->owner->ops->insert_location (bl);
2522                 }
2523               if (e.reason < 0)
2524                 {
2525                   val = 1;
2526                   hw_bp_err_string = (char *) e.message;
2527                 }
2528             }
2529           else
2530             {
2531               /* No.  This breakpoint will not be inserted.  
2532                  No error, but do not mark the bp as 'inserted'.  */
2533               return 0;
2534             }
2535         }
2536
2537       if (val)
2538         {
2539           /* Can't set the breakpoint.  */
2540           if (solib_name_from_address (bl->pspace, bl->address))
2541             {
2542               /* See also: disable_breakpoints_in_shlibs.  */
2543               val = 0;
2544               bl->shlib_disabled = 1;
2545               observer_notify_breakpoint_modified (bl->owner);
2546               if (!*disabled_breaks)
2547                 {
2548                   fprintf_unfiltered (tmp_error_stream, 
2549                                       "Cannot insert breakpoint %d.\n", 
2550                                       bl->owner->number);
2551                   fprintf_unfiltered (tmp_error_stream, 
2552                                       "Temporarily disabling shared "
2553                                       "library breakpoints:\n");
2554                 }
2555               *disabled_breaks = 1;
2556               fprintf_unfiltered (tmp_error_stream,
2557                                   "breakpoint #%d\n", bl->owner->number);
2558             }
2559           else
2560             {
2561               if (bl->loc_type == bp_loc_hardware_breakpoint)
2562                 {
2563                   *hw_breakpoint_error = 1;
2564                   *hw_bp_error_explained_already = hw_bp_err_string != NULL;
2565                   fprintf_unfiltered (tmp_error_stream,
2566                                       "Cannot insert hardware breakpoint %d%s",
2567                                       bl->owner->number, hw_bp_err_string ? ":" : ".\n");
2568                   if (hw_bp_err_string)
2569                     fprintf_unfiltered (tmp_error_stream, "%s.\n", hw_bp_err_string);
2570                 }
2571               else
2572                 {
2573                   fprintf_unfiltered (tmp_error_stream, 
2574                                       "Cannot insert breakpoint %d.\n", 
2575                                       bl->owner->number);
2576                   fprintf_filtered (tmp_error_stream, 
2577                                     "Error accessing memory address ");
2578                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2579                                   tmp_error_stream);
2580                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2581                                     safe_strerror (val));
2582                 }
2583
2584             }
2585         }
2586       else
2587         bl->inserted = 1;
2588
2589       return val;
2590     }
2591
2592   else if (bl->loc_type == bp_loc_hardware_watchpoint
2593            /* NOTE drow/2003-09-08: This state only exists for removing
2594               watchpoints.  It's not clear that it's necessary...  */
2595            && bl->owner->disposition != disp_del_at_next_stop)
2596     {
2597       gdb_assert (bl->owner->ops != NULL
2598                   && bl->owner->ops->insert_location != NULL);
2599
2600       val = bl->owner->ops->insert_location (bl);
2601
2602       /* If trying to set a read-watchpoint, and it turns out it's not
2603          supported, try emulating one with an access watchpoint.  */
2604       if (val == 1 && bl->watchpoint_type == hw_read)
2605         {
2606           struct bp_location *loc, **loc_temp;
2607
2608           /* But don't try to insert it, if there's already another
2609              hw_access location that would be considered a duplicate
2610              of this one.  */
2611           ALL_BP_LOCATIONS (loc, loc_temp)
2612             if (loc != bl
2613                 && loc->watchpoint_type == hw_access
2614                 && watchpoint_locations_match (bl, loc))
2615               {
2616                 bl->duplicate = 1;
2617                 bl->inserted = 1;
2618                 bl->target_info = loc->target_info;
2619                 bl->watchpoint_type = hw_access;
2620                 val = 0;
2621                 break;
2622               }
2623
2624           if (val == 1)
2625             {
2626               bl->watchpoint_type = hw_access;
2627               val = bl->owner->ops->insert_location (bl);
2628
2629               if (val)
2630                 /* Back to the original value.  */
2631                 bl->watchpoint_type = hw_read;
2632             }
2633         }
2634
2635       bl->inserted = (val == 0);
2636     }
2637
2638   else if (bl->owner->type == bp_catchpoint)
2639     {
2640       gdb_assert (bl->owner->ops != NULL
2641                   && bl->owner->ops->insert_location != NULL);
2642
2643       val = bl->owner->ops->insert_location (bl);
2644       if (val)
2645         {
2646           bl->owner->enable_state = bp_disabled;
2647
2648           if (val == 1)
2649             warning (_("\
2650 Error inserting catchpoint %d: Your system does not support this type\n\
2651 of catchpoint."), bl->owner->number);
2652           else
2653             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2654         }
2655
2656       bl->inserted = (val == 0);
2657
2658       /* We've already printed an error message if there was a problem
2659          inserting this catchpoint, and we've disabled the catchpoint,
2660          so just return success.  */
2661       return 0;
2662     }
2663
2664   return 0;
2665 }
2666
2667 /* This function is called when program space PSPACE is about to be
2668    deleted.  It takes care of updating breakpoints to not reference
2669    PSPACE anymore.  */
2670
2671 void
2672 breakpoint_program_space_exit (struct program_space *pspace)
2673 {
2674   struct breakpoint *b, *b_temp;
2675   struct bp_location *loc, **loc_temp;
2676
2677   /* Remove any breakpoint that was set through this program space.  */
2678   ALL_BREAKPOINTS_SAFE (b, b_temp)
2679     {
2680       if (b->pspace == pspace)
2681         delete_breakpoint (b);
2682     }
2683
2684   /* Breakpoints set through other program spaces could have locations
2685      bound to PSPACE as well.  Remove those.  */
2686   ALL_BP_LOCATIONS (loc, loc_temp)
2687     {
2688       struct bp_location *tmp;
2689
2690       if (loc->pspace == pspace)
2691         {
2692           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2693           if (loc->owner->loc == loc)
2694             loc->owner->loc = loc->next;
2695           else
2696             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2697               if (tmp->next == loc)
2698                 {
2699                   tmp->next = loc->next;
2700                   break;
2701                 }
2702         }
2703     }
2704
2705   /* Now update the global location list to permanently delete the
2706      removed locations above.  */
2707   update_global_location_list (0);
2708 }
2709
2710 /* Make sure all breakpoints are inserted in inferior.
2711    Throws exception on any error.
2712    A breakpoint that is already inserted won't be inserted
2713    again, so calling this function twice is safe.  */
2714 void
2715 insert_breakpoints (void)
2716 {
2717   struct breakpoint *bpt;
2718
2719   ALL_BREAKPOINTS (bpt)
2720     if (is_hardware_watchpoint (bpt))
2721       {
2722         struct watchpoint *w = (struct watchpoint *) bpt;
2723
2724         update_watchpoint (w, 0 /* don't reparse.  */);
2725       }
2726
2727   update_global_location_list (1);
2728
2729   /* update_global_location_list does not insert breakpoints when
2730      always_inserted_mode is not enabled.  Explicitly insert them
2731      now.  */
2732   if (!breakpoints_always_inserted_mode ())
2733     insert_breakpoint_locations ();
2734 }
2735
2736 /* Invoke CALLBACK for each of bp_location.  */
2737
2738 void
2739 iterate_over_bp_locations (walk_bp_location_callback callback)
2740 {
2741   struct bp_location *loc, **loc_tmp;
2742
2743   ALL_BP_LOCATIONS (loc, loc_tmp)
2744     {
2745       callback (loc, NULL);
2746     }
2747 }
2748
2749 /* This is used when we need to synch breakpoint conditions between GDB and the
2750    target.  It is the case with deleting and disabling of breakpoints when using
2751    always-inserted mode.  */
2752
2753 static void
2754 update_inserted_breakpoint_locations (void)
2755 {
2756   struct bp_location *bl, **blp_tmp;
2757   int error_flag = 0;
2758   int val = 0;
2759   int disabled_breaks = 0;
2760   int hw_breakpoint_error = 0;
2761   int hw_bp_details_reported = 0;
2762
2763   struct ui_file *tmp_error_stream = mem_fileopen ();
2764   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2765
2766   /* Explicitly mark the warning -- this will only be printed if
2767      there was an error.  */
2768   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2769
2770   save_current_space_and_thread ();
2771
2772   ALL_BP_LOCATIONS (bl, blp_tmp)
2773     {
2774       /* We only want to update software breakpoints and hardware
2775          breakpoints.  */
2776       if (!is_breakpoint (bl->owner))
2777         continue;
2778
2779       /* We only want to update locations that are already inserted
2780          and need updating.  This is to avoid unwanted insertion during
2781          deletion of breakpoints.  */
2782       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2783         continue;
2784
2785       switch_to_program_space_and_thread (bl->pspace);
2786
2787       /* For targets that support global breakpoints, there's no need
2788          to select an inferior to insert breakpoint to.  In fact, even
2789          if we aren't attached to any process yet, we should still
2790          insert breakpoints.  */
2791       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2792           && ptid_equal (inferior_ptid, null_ptid))
2793         continue;
2794
2795       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2796                                     &hw_breakpoint_error, &hw_bp_details_reported);
2797       if (val)
2798         error_flag = val;
2799     }
2800
2801   if (error_flag)
2802     {
2803       target_terminal_ours_for_output ();
2804       error_stream (tmp_error_stream);
2805     }
2806
2807   do_cleanups (cleanups);
2808 }
2809
2810 /* Used when starting or continuing the program.  */
2811
2812 static void
2813 insert_breakpoint_locations (void)
2814 {
2815   struct breakpoint *bpt;
2816   struct bp_location *bl, **blp_tmp;
2817   int error_flag = 0;
2818   int val = 0;
2819   int disabled_breaks = 0;
2820   int hw_breakpoint_error = 0;
2821   int hw_bp_error_explained_already = 0;
2822
2823   struct ui_file *tmp_error_stream = mem_fileopen ();
2824   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2825   
2826   /* Explicitly mark the warning -- this will only be printed if
2827      there was an error.  */
2828   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2829
2830   save_current_space_and_thread ();
2831
2832   ALL_BP_LOCATIONS (bl, blp_tmp)
2833     {
2834       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2835         continue;
2836
2837       /* There is no point inserting thread-specific breakpoints if
2838          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2839          has BL->OWNER always non-NULL.  */
2840       if (bl->owner->thread != -1
2841           && !valid_thread_id (bl->owner->thread))
2842         continue;
2843
2844       switch_to_program_space_and_thread (bl->pspace);
2845
2846       /* For targets that support global breakpoints, there's no need
2847          to select an inferior to insert breakpoint to.  In fact, even
2848          if we aren't attached to any process yet, we should still
2849          insert breakpoints.  */
2850       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2851           && ptid_equal (inferior_ptid, null_ptid))
2852         continue;
2853
2854       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2855                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2856       if (val)
2857         error_flag = val;
2858     }
2859
2860   /* If we failed to insert all locations of a watchpoint, remove
2861      them, as half-inserted watchpoint is of limited use.  */
2862   ALL_BREAKPOINTS (bpt)  
2863     {
2864       int some_failed = 0;
2865       struct bp_location *loc;
2866
2867       if (!is_hardware_watchpoint (bpt))
2868         continue;
2869
2870       if (!breakpoint_enabled (bpt))
2871         continue;
2872
2873       if (bpt->disposition == disp_del_at_next_stop)
2874         continue;
2875       
2876       for (loc = bpt->loc; loc; loc = loc->next)
2877         if (!loc->inserted && should_be_inserted (loc))
2878           {
2879             some_failed = 1;
2880             break;
2881           }
2882       if (some_failed)
2883         {
2884           for (loc = bpt->loc; loc; loc = loc->next)
2885             if (loc->inserted)
2886               remove_breakpoint (loc, mark_uninserted);
2887
2888           hw_breakpoint_error = 1;
2889           fprintf_unfiltered (tmp_error_stream,
2890                               "Could not insert hardware watchpoint %d.\n", 
2891                               bpt->number);
2892           error_flag = -1;
2893         }
2894     }
2895
2896   if (error_flag)
2897     {
2898       /* If a hardware breakpoint or watchpoint was inserted, add a
2899          message about possibly exhausted resources.  */
2900       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2901         {
2902           fprintf_unfiltered (tmp_error_stream, 
2903                               "Could not insert hardware breakpoints:\n\
2904 You may have requested too many hardware breakpoints/watchpoints.\n");
2905         }
2906       target_terminal_ours_for_output ();
2907       error_stream (tmp_error_stream);
2908     }
2909
2910   do_cleanups (cleanups);
2911 }
2912
2913 /* Used when the program stops.
2914    Returns zero if successful, or non-zero if there was a problem
2915    removing a breakpoint location.  */
2916
2917 int
2918 remove_breakpoints (void)
2919 {
2920   struct bp_location *bl, **blp_tmp;
2921   int val = 0;
2922
2923   ALL_BP_LOCATIONS (bl, blp_tmp)
2924   {
2925     if (bl->inserted && !is_tracepoint (bl->owner))
2926       val |= remove_breakpoint (bl, mark_uninserted);
2927   }
2928   return val;
2929 }
2930
2931 /* Remove breakpoints of process PID.  */
2932
2933 int
2934 remove_breakpoints_pid (int pid)
2935 {
2936   struct bp_location *bl, **blp_tmp;
2937   int val;
2938   struct inferior *inf = find_inferior_pid (pid);
2939
2940   ALL_BP_LOCATIONS (bl, blp_tmp)
2941   {
2942     if (bl->pspace != inf->pspace)
2943       continue;
2944
2945     if (bl->owner->type == bp_dprintf)
2946       continue;
2947
2948     if (bl->inserted)
2949       {
2950         val = remove_breakpoint (bl, mark_uninserted);
2951         if (val != 0)
2952           return val;
2953       }
2954   }
2955   return 0;
2956 }
2957
2958 int
2959 reattach_breakpoints (int pid)
2960 {
2961   struct cleanup *old_chain;
2962   struct bp_location *bl, **blp_tmp;
2963   int val;
2964   struct ui_file *tmp_error_stream;
2965   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2966   struct inferior *inf;
2967   struct thread_info *tp;
2968
2969   tp = any_live_thread_of_process (pid);
2970   if (tp == NULL)
2971     return 1;
2972
2973   inf = find_inferior_pid (pid);
2974   old_chain = save_inferior_ptid ();
2975
2976   inferior_ptid = tp->ptid;
2977
2978   tmp_error_stream = mem_fileopen ();
2979   make_cleanup_ui_file_delete (tmp_error_stream);
2980
2981   ALL_BP_LOCATIONS (bl, blp_tmp)
2982   {
2983     if (bl->pspace != inf->pspace)
2984       continue;
2985
2986     if (bl->inserted)
2987       {
2988         bl->inserted = 0;
2989         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
2990         if (val != 0)
2991           {
2992             do_cleanups (old_chain);
2993             return val;
2994           }
2995       }
2996   }
2997   do_cleanups (old_chain);
2998   return 0;
2999 }
3000
3001 static int internal_breakpoint_number = -1;
3002
3003 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3004    If INTERNAL is non-zero, the breakpoint number will be populated
3005    from internal_breakpoint_number and that variable decremented.
3006    Otherwise the breakpoint number will be populated from
3007    breakpoint_count and that value incremented.  Internal breakpoints
3008    do not set the internal var bpnum.  */
3009 static void
3010 set_breakpoint_number (int internal, struct breakpoint *b)
3011 {
3012   if (internal)
3013     b->number = internal_breakpoint_number--;
3014   else
3015     {
3016       set_breakpoint_count (breakpoint_count + 1);
3017       b->number = breakpoint_count;
3018     }
3019 }
3020
3021 static struct breakpoint *
3022 create_internal_breakpoint (struct gdbarch *gdbarch,
3023                             CORE_ADDR address, enum bptype type,
3024                             const struct breakpoint_ops *ops)
3025 {
3026   struct symtab_and_line sal;
3027   struct breakpoint *b;
3028
3029   init_sal (&sal);              /* Initialize to zeroes.  */
3030
3031   sal.pc = address;
3032   sal.section = find_pc_overlay (sal.pc);
3033   sal.pspace = current_program_space;
3034
3035   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3036   b->number = internal_breakpoint_number--;
3037   b->disposition = disp_donttouch;
3038
3039   return b;
3040 }
3041
3042 static const char *const longjmp_names[] =
3043   {
3044     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3045   };
3046 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3047
3048 /* Per-objfile data private to breakpoint.c.  */
3049 struct breakpoint_objfile_data
3050 {
3051   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3052   struct minimal_symbol *overlay_msym;
3053
3054   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3055   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3056
3057   /* True if we have looked for longjmp probes.  */
3058   int longjmp_searched;
3059
3060   /* SystemTap probe points for longjmp (if any).  */
3061   VEC (probe_p) *longjmp_probes;
3062
3063   /* Minimal symbol for "std::terminate()" (if any).  */
3064   struct minimal_symbol *terminate_msym;
3065
3066   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3067   struct minimal_symbol *exception_msym;
3068
3069   /* True if we have looked for exception probes.  */
3070   int exception_searched;
3071
3072   /* SystemTap probe points for unwinding (if any).  */
3073   VEC (probe_p) *exception_probes;
3074 };
3075
3076 static const struct objfile_data *breakpoint_objfile_key;
3077
3078 /* Minimal symbol not found sentinel.  */
3079 static struct minimal_symbol msym_not_found;
3080
3081 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3082
3083 static int
3084 msym_not_found_p (const struct minimal_symbol *msym)
3085 {
3086   return msym == &msym_not_found;
3087 }
3088
3089 /* Return per-objfile data needed by breakpoint.c.
3090    Allocate the data if necessary.  */
3091
3092 static struct breakpoint_objfile_data *
3093 get_breakpoint_objfile_data (struct objfile *objfile)
3094 {
3095   struct breakpoint_objfile_data *bp_objfile_data;
3096
3097   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3098   if (bp_objfile_data == NULL)
3099     {
3100       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3101                                        sizeof (*bp_objfile_data));
3102
3103       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3104       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3105     }
3106   return bp_objfile_data;
3107 }
3108
3109 static void
3110 free_breakpoint_probes (struct objfile *obj, void *data)
3111 {
3112   struct breakpoint_objfile_data *bp_objfile_data = data;
3113
3114   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3115   VEC_free (probe_p, bp_objfile_data->exception_probes);
3116 }
3117
3118 static void
3119 create_overlay_event_breakpoint (void)
3120 {
3121   struct objfile *objfile;
3122   const char *const func_name = "_ovly_debug_event";
3123
3124   ALL_OBJFILES (objfile)
3125     {
3126       struct breakpoint *b;
3127       struct breakpoint_objfile_data *bp_objfile_data;
3128       CORE_ADDR addr;
3129
3130       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3131
3132       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3133         continue;
3134
3135       if (bp_objfile_data->overlay_msym == NULL)
3136         {
3137           struct minimal_symbol *m;
3138
3139           m = lookup_minimal_symbol_text (func_name, objfile);
3140           if (m == NULL)
3141             {
3142               /* Avoid future lookups in this objfile.  */
3143               bp_objfile_data->overlay_msym = &msym_not_found;
3144               continue;
3145             }
3146           bp_objfile_data->overlay_msym = m;
3147         }
3148
3149       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3150       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3151                                       bp_overlay_event,
3152                                       &internal_breakpoint_ops);
3153       b->addr_string = xstrdup (func_name);
3154
3155       if (overlay_debugging == ovly_auto)
3156         {
3157           b->enable_state = bp_enabled;
3158           overlay_events_enabled = 1;
3159         }
3160       else
3161        {
3162          b->enable_state = bp_disabled;
3163          overlay_events_enabled = 0;
3164        }
3165     }
3166   update_global_location_list (1);
3167 }
3168
3169 static void
3170 create_longjmp_master_breakpoint (void)
3171 {
3172   struct program_space *pspace;
3173   struct cleanup *old_chain;
3174
3175   old_chain = save_current_program_space ();
3176
3177   ALL_PSPACES (pspace)
3178   {
3179     struct objfile *objfile;
3180
3181     set_current_program_space (pspace);
3182
3183     ALL_OBJFILES (objfile)
3184     {
3185       int i;
3186       struct gdbarch *gdbarch;
3187       struct breakpoint_objfile_data *bp_objfile_data;
3188
3189       gdbarch = get_objfile_arch (objfile);
3190       if (!gdbarch_get_longjmp_target_p (gdbarch))
3191         continue;
3192
3193       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3194
3195       if (!bp_objfile_data->longjmp_searched)
3196         {
3197           bp_objfile_data->longjmp_probes
3198             = find_probes_in_objfile (objfile, "libc", "longjmp");
3199           bp_objfile_data->longjmp_searched = 1;
3200         }
3201
3202       if (bp_objfile_data->longjmp_probes != NULL)
3203         {
3204           int i;
3205           struct probe *probe;
3206           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3207
3208           for (i = 0;
3209                VEC_iterate (probe_p,
3210                             bp_objfile_data->longjmp_probes,
3211                             i, probe);
3212                ++i)
3213             {
3214               struct breakpoint *b;
3215
3216               b = create_internal_breakpoint (gdbarch, probe->address,
3217                                               bp_longjmp_master,
3218                                               &internal_breakpoint_ops);
3219               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3220               b->enable_state = bp_disabled;
3221             }
3222
3223           continue;
3224         }
3225
3226       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3227         {
3228           struct breakpoint *b;
3229           const char *func_name;
3230           CORE_ADDR addr;
3231
3232           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3233             continue;
3234
3235           func_name = longjmp_names[i];
3236           if (bp_objfile_data->longjmp_msym[i] == NULL)
3237             {
3238               struct minimal_symbol *m;
3239
3240               m = lookup_minimal_symbol_text (func_name, objfile);
3241               if (m == NULL)
3242                 {
3243                   /* Prevent future lookups in this objfile.  */
3244                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3245                   continue;
3246                 }
3247               bp_objfile_data->longjmp_msym[i] = m;
3248             }
3249
3250           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3251           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3252                                           &internal_breakpoint_ops);
3253           b->addr_string = xstrdup (func_name);
3254           b->enable_state = bp_disabled;
3255         }
3256     }
3257   }
3258   update_global_location_list (1);
3259
3260   do_cleanups (old_chain);
3261 }
3262
3263 /* Create a master std::terminate breakpoint.  */
3264 static void
3265 create_std_terminate_master_breakpoint (void)
3266 {
3267   struct program_space *pspace;
3268   struct cleanup *old_chain;
3269   const char *const func_name = "std::terminate()";
3270
3271   old_chain = save_current_program_space ();
3272
3273   ALL_PSPACES (pspace)
3274   {
3275     struct objfile *objfile;
3276     CORE_ADDR addr;
3277
3278     set_current_program_space (pspace);
3279
3280     ALL_OBJFILES (objfile)
3281     {
3282       struct breakpoint *b;
3283       struct breakpoint_objfile_data *bp_objfile_data;
3284
3285       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3286
3287       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3288         continue;
3289
3290       if (bp_objfile_data->terminate_msym == NULL)
3291         {
3292           struct minimal_symbol *m;
3293
3294           m = lookup_minimal_symbol (func_name, NULL, objfile);
3295           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3296                             && MSYMBOL_TYPE (m) != mst_file_text))
3297             {
3298               /* Prevent future lookups in this objfile.  */
3299               bp_objfile_data->terminate_msym = &msym_not_found;
3300               continue;
3301             }
3302           bp_objfile_data->terminate_msym = m;
3303         }
3304
3305       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3306       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3307                                       bp_std_terminate_master,
3308                                       &internal_breakpoint_ops);
3309       b->addr_string = xstrdup (func_name);
3310       b->enable_state = bp_disabled;
3311     }
3312   }
3313
3314   update_global_location_list (1);
3315
3316   do_cleanups (old_chain);
3317 }
3318
3319 /* Install a master breakpoint on the unwinder's debug hook.  */
3320
3321 static void
3322 create_exception_master_breakpoint (void)
3323 {
3324   struct objfile *objfile;
3325   const char *const func_name = "_Unwind_DebugHook";
3326
3327   ALL_OBJFILES (objfile)
3328     {
3329       struct breakpoint *b;
3330       struct gdbarch *gdbarch;
3331       struct breakpoint_objfile_data *bp_objfile_data;
3332       CORE_ADDR addr;
3333
3334       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3335
3336       /* We prefer the SystemTap probe point if it exists.  */
3337       if (!bp_objfile_data->exception_searched)
3338         {
3339           bp_objfile_data->exception_probes
3340             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3341           bp_objfile_data->exception_searched = 1;
3342         }
3343
3344       if (bp_objfile_data->exception_probes != NULL)
3345         {
3346           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3347           int i;
3348           struct probe *probe;
3349
3350           for (i = 0;
3351                VEC_iterate (probe_p,
3352                             bp_objfile_data->exception_probes,
3353                             i, probe);
3354                ++i)
3355             {
3356               struct breakpoint *b;
3357
3358               b = create_internal_breakpoint (gdbarch, probe->address,
3359                                               bp_exception_master,
3360                                               &internal_breakpoint_ops);
3361               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3362               b->enable_state = bp_disabled;
3363             }
3364
3365           continue;
3366         }
3367
3368       /* Otherwise, try the hook function.  */
3369
3370       if (msym_not_found_p (bp_objfile_data->exception_msym))
3371         continue;
3372
3373       gdbarch = get_objfile_arch (objfile);
3374
3375       if (bp_objfile_data->exception_msym == NULL)
3376         {
3377           struct minimal_symbol *debug_hook;
3378
3379           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3380           if (debug_hook == NULL)
3381             {
3382               bp_objfile_data->exception_msym = &msym_not_found;
3383               continue;
3384             }
3385
3386           bp_objfile_data->exception_msym = debug_hook;
3387         }
3388
3389       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3390       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3391                                                  &current_target);
3392       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3393                                       &internal_breakpoint_ops);
3394       b->addr_string = xstrdup (func_name);
3395       b->enable_state = bp_disabled;
3396     }
3397
3398   update_global_location_list (1);
3399 }
3400
3401 void
3402 update_breakpoints_after_exec (void)
3403 {
3404   struct breakpoint *b, *b_tmp;
3405   struct bp_location *bploc, **bplocp_tmp;
3406
3407   /* We're about to delete breakpoints from GDB's lists.  If the
3408      INSERTED flag is true, GDB will try to lift the breakpoints by
3409      writing the breakpoints' "shadow contents" back into memory.  The
3410      "shadow contents" are NOT valid after an exec, so GDB should not
3411      do that.  Instead, the target is responsible from marking
3412      breakpoints out as soon as it detects an exec.  We don't do that
3413      here instead, because there may be other attempts to delete
3414      breakpoints after detecting an exec and before reaching here.  */
3415   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3416     if (bploc->pspace == current_program_space)
3417       gdb_assert (!bploc->inserted);
3418
3419   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3420   {
3421     if (b->pspace != current_program_space)
3422       continue;
3423
3424     /* Solib breakpoints must be explicitly reset after an exec().  */
3425     if (b->type == bp_shlib_event)
3426       {
3427         delete_breakpoint (b);
3428         continue;
3429       }
3430
3431     /* JIT breakpoints must be explicitly reset after an exec().  */
3432     if (b->type == bp_jit_event)
3433       {
3434         delete_breakpoint (b);
3435         continue;
3436       }
3437
3438     /* Thread event breakpoints must be set anew after an exec(),
3439        as must overlay event and longjmp master breakpoints.  */
3440     if (b->type == bp_thread_event || b->type == bp_overlay_event
3441         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3442         || b->type == bp_exception_master)
3443       {
3444         delete_breakpoint (b);
3445         continue;
3446       }
3447
3448     /* Step-resume breakpoints are meaningless after an exec().  */
3449     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3450       {
3451         delete_breakpoint (b);
3452         continue;
3453       }
3454
3455     /* Longjmp and longjmp-resume breakpoints are also meaningless
3456        after an exec.  */
3457     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3458         || b->type == bp_longjmp_call_dummy
3459         || b->type == bp_exception || b->type == bp_exception_resume)
3460       {
3461         delete_breakpoint (b);
3462         continue;
3463       }
3464
3465     if (b->type == bp_catchpoint)
3466       {
3467         /* For now, none of the bp_catchpoint breakpoints need to
3468            do anything at this point.  In the future, if some of
3469            the catchpoints need to something, we will need to add
3470            a new method, and call this method from here.  */
3471         continue;
3472       }
3473
3474     /* bp_finish is a special case.  The only way we ought to be able
3475        to see one of these when an exec() has happened, is if the user
3476        caught a vfork, and then said "finish".  Ordinarily a finish just
3477        carries them to the call-site of the current callee, by setting
3478        a temporary bp there and resuming.  But in this case, the finish
3479        will carry them entirely through the vfork & exec.
3480
3481        We don't want to allow a bp_finish to remain inserted now.  But
3482        we can't safely delete it, 'cause finish_command has a handle to
3483        the bp on a bpstat, and will later want to delete it.  There's a
3484        chance (and I've seen it happen) that if we delete the bp_finish
3485        here, that its storage will get reused by the time finish_command
3486        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3487        We really must allow finish_command to delete a bp_finish.
3488
3489        In the absence of a general solution for the "how do we know
3490        it's safe to delete something others may have handles to?"
3491        problem, what we'll do here is just uninsert the bp_finish, and
3492        let finish_command delete it.
3493
3494        (We know the bp_finish is "doomed" in the sense that it's
3495        momentary, and will be deleted as soon as finish_command sees
3496        the inferior stopped.  So it doesn't matter that the bp's
3497        address is probably bogus in the new a.out, unlike e.g., the
3498        solib breakpoints.)  */
3499
3500     if (b->type == bp_finish)
3501       {
3502         continue;
3503       }
3504
3505     /* Without a symbolic address, we have little hope of the
3506        pre-exec() address meaning the same thing in the post-exec()
3507        a.out.  */
3508     if (b->addr_string == NULL)
3509       {
3510         delete_breakpoint (b);
3511         continue;
3512       }
3513   }
3514   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3515   create_overlay_event_breakpoint ();
3516   create_longjmp_master_breakpoint ();
3517   create_std_terminate_master_breakpoint ();
3518   create_exception_master_breakpoint ();
3519 }
3520
3521 int
3522 detach_breakpoints (ptid_t ptid)
3523 {
3524   struct bp_location *bl, **blp_tmp;
3525   int val = 0;
3526   struct cleanup *old_chain = save_inferior_ptid ();
3527   struct inferior *inf = current_inferior ();
3528
3529   if (PIDGET (ptid) == PIDGET (inferior_ptid))
3530     error (_("Cannot detach breakpoints of inferior_ptid"));
3531
3532   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3533   inferior_ptid = ptid;
3534   ALL_BP_LOCATIONS (bl, blp_tmp)
3535   {
3536     if (bl->pspace != inf->pspace)
3537       continue;
3538
3539     /* This function must physically remove breakpoints locations
3540        from the specified ptid, without modifying the breakpoint
3541        package's state.  Locations of type bp_loc_other are only
3542        maintained at GDB side.  So, there is no need to remove
3543        these bp_loc_other locations.  Moreover, removing these
3544        would modify the breakpoint package's state.  */
3545     if (bl->loc_type == bp_loc_other)
3546       continue;
3547
3548     if (bl->inserted)
3549       val |= remove_breakpoint_1 (bl, mark_inserted);
3550   }
3551
3552   /* Detach single-step breakpoints as well.  */
3553   detach_single_step_breakpoints ();
3554
3555   do_cleanups (old_chain);
3556   return val;
3557 }
3558
3559 /* Remove the breakpoint location BL from the current address space.
3560    Note that this is used to detach breakpoints from a child fork.
3561    When we get here, the child isn't in the inferior list, and neither
3562    do we have objects to represent its address space --- we should
3563    *not* look at bl->pspace->aspace here.  */
3564
3565 static int
3566 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3567 {
3568   int val;
3569
3570   /* BL is never in moribund_locations by our callers.  */
3571   gdb_assert (bl->owner != NULL);
3572
3573   if (bl->owner->enable_state == bp_permanent)
3574     /* Permanent breakpoints cannot be inserted or removed.  */
3575     return 0;
3576
3577   /* The type of none suggests that owner is actually deleted.
3578      This should not ever happen.  */
3579   gdb_assert (bl->owner->type != bp_none);
3580
3581   if (bl->loc_type == bp_loc_software_breakpoint
3582       || bl->loc_type == bp_loc_hardware_breakpoint)
3583     {
3584       /* "Normal" instruction breakpoint: either the standard
3585          trap-instruction bp (bp_breakpoint), or a
3586          bp_hardware_breakpoint.  */
3587
3588       /* First check to see if we have to handle an overlay.  */
3589       if (overlay_debugging == ovly_off
3590           || bl->section == NULL
3591           || !(section_is_overlay (bl->section)))
3592         {
3593           /* No overlay handling: just remove the breakpoint.  */
3594           val = bl->owner->ops->remove_location (bl);
3595         }
3596       else
3597         {
3598           /* This breakpoint is in an overlay section.
3599              Did we set a breakpoint at the LMA?  */
3600           if (!overlay_events_enabled)
3601               {
3602                 /* Yes -- overlay event support is not active, so we
3603                    should have set a breakpoint at the LMA.  Remove it.  
3604                 */
3605                 /* Ignore any failures: if the LMA is in ROM, we will
3606                    have already warned when we failed to insert it.  */
3607                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3608                   target_remove_hw_breakpoint (bl->gdbarch,
3609                                                &bl->overlay_target_info);
3610                 else
3611                   target_remove_breakpoint (bl->gdbarch,
3612                                             &bl->overlay_target_info);
3613               }
3614           /* Did we set a breakpoint at the VMA? 
3615              If so, we will have marked the breakpoint 'inserted'.  */
3616           if (bl->inserted)
3617             {
3618               /* Yes -- remove it.  Previously we did not bother to
3619                  remove the breakpoint if the section had been
3620                  unmapped, but let's not rely on that being safe.  We
3621                  don't know what the overlay manager might do.  */
3622
3623               /* However, we should remove *software* breakpoints only
3624                  if the section is still mapped, or else we overwrite
3625                  wrong code with the saved shadow contents.  */
3626               if (bl->loc_type == bp_loc_hardware_breakpoint
3627                   || section_is_mapped (bl->section))
3628                 val = bl->owner->ops->remove_location (bl);
3629               else
3630                 val = 0;
3631             }
3632           else
3633             {
3634               /* No -- not inserted, so no need to remove.  No error.  */
3635               val = 0;
3636             }
3637         }
3638
3639       /* In some cases, we might not be able to remove a breakpoint
3640          in a shared library that has already been removed, but we
3641          have not yet processed the shlib unload event.  */
3642       if (val && solib_name_from_address (bl->pspace, bl->address))
3643         val = 0;
3644
3645       if (val)
3646         return val;
3647       bl->inserted = (is == mark_inserted);
3648     }
3649   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3650     {
3651       gdb_assert (bl->owner->ops != NULL
3652                   && bl->owner->ops->remove_location != NULL);
3653
3654       bl->inserted = (is == mark_inserted);
3655       bl->owner->ops->remove_location (bl);
3656
3657       /* Failure to remove any of the hardware watchpoints comes here.  */
3658       if ((is == mark_uninserted) && (bl->inserted))
3659         warning (_("Could not remove hardware watchpoint %d."),
3660                  bl->owner->number);
3661     }
3662   else if (bl->owner->type == bp_catchpoint
3663            && breakpoint_enabled (bl->owner)
3664            && !bl->duplicate)
3665     {
3666       gdb_assert (bl->owner->ops != NULL
3667                   && bl->owner->ops->remove_location != NULL);
3668
3669       val = bl->owner->ops->remove_location (bl);
3670       if (val)
3671         return val;
3672
3673       bl->inserted = (is == mark_inserted);
3674     }
3675
3676   return 0;
3677 }
3678
3679 static int
3680 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3681 {
3682   int ret;
3683   struct cleanup *old_chain;
3684
3685   /* BL is never in moribund_locations by our callers.  */
3686   gdb_assert (bl->owner != NULL);
3687
3688   if (bl->owner->enable_state == bp_permanent)
3689     /* Permanent breakpoints cannot be inserted or removed.  */
3690     return 0;
3691
3692   /* The type of none suggests that owner is actually deleted.
3693      This should not ever happen.  */
3694   gdb_assert (bl->owner->type != bp_none);
3695
3696   old_chain = save_current_space_and_thread ();
3697
3698   switch_to_program_space_and_thread (bl->pspace);
3699
3700   ret = remove_breakpoint_1 (bl, is);
3701
3702   do_cleanups (old_chain);
3703   return ret;
3704 }
3705
3706 /* Clear the "inserted" flag in all breakpoints.  */
3707
3708 void
3709 mark_breakpoints_out (void)
3710 {
3711   struct bp_location *bl, **blp_tmp;
3712
3713   ALL_BP_LOCATIONS (bl, blp_tmp)
3714     if (bl->pspace == current_program_space)
3715       bl->inserted = 0;
3716 }
3717
3718 /* Clear the "inserted" flag in all breakpoints and delete any
3719    breakpoints which should go away between runs of the program.
3720
3721    Plus other such housekeeping that has to be done for breakpoints
3722    between runs.
3723
3724    Note: this function gets called at the end of a run (by
3725    generic_mourn_inferior) and when a run begins (by
3726    init_wait_for_inferior).  */
3727
3728
3729
3730 void
3731 breakpoint_init_inferior (enum inf_context context)
3732 {
3733   struct breakpoint *b, *b_tmp;
3734   struct bp_location *bl, **blp_tmp;
3735   int ix;
3736   struct program_space *pspace = current_program_space;
3737
3738   /* If breakpoint locations are shared across processes, then there's
3739      nothing to do.  */
3740   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3741     return;
3742
3743   ALL_BP_LOCATIONS (bl, blp_tmp)
3744   {
3745     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3746     if (bl->pspace == pspace
3747         && bl->owner->enable_state != bp_permanent)
3748       bl->inserted = 0;
3749   }
3750
3751   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3752   {
3753     if (b->loc && b->loc->pspace != pspace)
3754       continue;
3755
3756     switch (b->type)
3757       {
3758       case bp_call_dummy:
3759       case bp_longjmp_call_dummy:
3760
3761         /* If the call dummy breakpoint is at the entry point it will
3762            cause problems when the inferior is rerun, so we better get
3763            rid of it.  */
3764
3765       case bp_watchpoint_scope:
3766
3767         /* Also get rid of scope breakpoints.  */
3768
3769       case bp_shlib_event:
3770
3771         /* Also remove solib event breakpoints.  Their addresses may
3772            have changed since the last time we ran the program.
3773            Actually we may now be debugging against different target;
3774            and so the solib backend that installed this breakpoint may
3775            not be used in by the target.  E.g.,
3776
3777            (gdb) file prog-linux
3778            (gdb) run               # native linux target
3779            ...
3780            (gdb) kill
3781            (gdb) file prog-win.exe
3782            (gdb) tar rem :9999     # remote Windows gdbserver.
3783         */
3784
3785       case bp_step_resume:
3786
3787         /* Also remove step-resume breakpoints.  */
3788
3789         delete_breakpoint (b);
3790         break;
3791
3792       case bp_watchpoint:
3793       case bp_hardware_watchpoint:
3794       case bp_read_watchpoint:
3795       case bp_access_watchpoint:
3796         {
3797           struct watchpoint *w = (struct watchpoint *) b;
3798
3799           /* Likewise for watchpoints on local expressions.  */
3800           if (w->exp_valid_block != NULL)
3801             delete_breakpoint (b);
3802           else if (context == inf_starting)
3803             {
3804               /* Reset val field to force reread of starting value in
3805                  insert_breakpoints.  */
3806               if (w->val)
3807                 value_free (w->val);
3808               w->val = NULL;
3809               w->val_valid = 0;
3810           }
3811         }
3812         break;
3813       default:
3814         break;
3815       }
3816   }
3817
3818   /* Get rid of the moribund locations.  */
3819   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3820     decref_bp_location (&bl);
3821   VEC_free (bp_location_p, moribund_locations);
3822 }
3823
3824 /* These functions concern about actual breakpoints inserted in the
3825    target --- to e.g. check if we need to do decr_pc adjustment or if
3826    we need to hop over the bkpt --- so we check for address space
3827    match, not program space.  */
3828
3829 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3830    exists at PC.  It returns ordinary_breakpoint_here if it's an
3831    ordinary breakpoint, or permanent_breakpoint_here if it's a
3832    permanent breakpoint.
3833    - When continuing from a location with an ordinary breakpoint, we
3834      actually single step once before calling insert_breakpoints.
3835    - When continuing from a location with a permanent breakpoint, we
3836      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3837      the target, to advance the PC past the breakpoint.  */
3838
3839 enum breakpoint_here
3840 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3841 {
3842   struct bp_location *bl, **blp_tmp;
3843   int any_breakpoint_here = 0;
3844
3845   ALL_BP_LOCATIONS (bl, blp_tmp)
3846     {
3847       if (bl->loc_type != bp_loc_software_breakpoint
3848           && bl->loc_type != bp_loc_hardware_breakpoint)
3849         continue;
3850
3851       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3852       if ((breakpoint_enabled (bl->owner)
3853            || bl->owner->enable_state == bp_permanent)
3854           && breakpoint_location_address_match (bl, aspace, pc))
3855         {
3856           if (overlay_debugging 
3857               && section_is_overlay (bl->section)
3858               && !section_is_mapped (bl->section))
3859             continue;           /* unmapped overlay -- can't be a match */
3860           else if (bl->owner->enable_state == bp_permanent)
3861             return permanent_breakpoint_here;
3862           else
3863             any_breakpoint_here = 1;
3864         }
3865     }
3866
3867   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3868 }
3869
3870 /* Return true if there's a moribund breakpoint at PC.  */
3871
3872 int
3873 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3874 {
3875   struct bp_location *loc;
3876   int ix;
3877
3878   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3879     if (breakpoint_location_address_match (loc, aspace, pc))
3880       return 1;
3881
3882   return 0;
3883 }
3884
3885 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3886    inserted using regular breakpoint_chain / bp_location array
3887    mechanism.  This does not check for single-step breakpoints, which
3888    are inserted and removed using direct target manipulation.  */
3889
3890 int
3891 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3892                                     CORE_ADDR pc)
3893 {
3894   struct bp_location *bl, **blp_tmp;
3895
3896   ALL_BP_LOCATIONS (bl, blp_tmp)
3897     {
3898       if (bl->loc_type != bp_loc_software_breakpoint
3899           && bl->loc_type != bp_loc_hardware_breakpoint)
3900         continue;
3901
3902       if (bl->inserted
3903           && breakpoint_location_address_match (bl, aspace, pc))
3904         {
3905           if (overlay_debugging 
3906               && section_is_overlay (bl->section)
3907               && !section_is_mapped (bl->section))
3908             continue;           /* unmapped overlay -- can't be a match */
3909           else
3910             return 1;
3911         }
3912     }
3913   return 0;
3914 }
3915
3916 /* Returns non-zero iff there's either regular breakpoint
3917    or a single step breakpoint inserted at PC.  */
3918
3919 int
3920 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3921 {
3922   if (regular_breakpoint_inserted_here_p (aspace, pc))
3923     return 1;
3924
3925   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3926     return 1;
3927
3928   return 0;
3929 }
3930
3931 /* This function returns non-zero iff there is a software breakpoint
3932    inserted at PC.  */
3933
3934 int
3935 software_breakpoint_inserted_here_p (struct address_space *aspace,
3936                                      CORE_ADDR pc)
3937 {
3938   struct bp_location *bl, **blp_tmp;
3939
3940   ALL_BP_LOCATIONS (bl, blp_tmp)
3941     {
3942       if (bl->loc_type != bp_loc_software_breakpoint)
3943         continue;
3944
3945       if (bl->inserted
3946           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3947                                        aspace, pc))
3948         {
3949           if (overlay_debugging 
3950               && section_is_overlay (bl->section)
3951               && !section_is_mapped (bl->section))
3952             continue;           /* unmapped overlay -- can't be a match */
3953           else
3954             return 1;
3955         }
3956     }
3957
3958   /* Also check for software single-step breakpoints.  */
3959   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3960     return 1;
3961
3962   return 0;
3963 }
3964
3965 int
3966 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3967                                        CORE_ADDR addr, ULONGEST len)
3968 {
3969   struct breakpoint *bpt;
3970
3971   ALL_BREAKPOINTS (bpt)
3972     {
3973       struct bp_location *loc;
3974
3975       if (bpt->type != bp_hardware_watchpoint
3976           && bpt->type != bp_access_watchpoint)
3977         continue;
3978
3979       if (!breakpoint_enabled (bpt))
3980         continue;
3981
3982       for (loc = bpt->loc; loc; loc = loc->next)
3983         if (loc->pspace->aspace == aspace && loc->inserted)
3984           {
3985             CORE_ADDR l, h;
3986
3987             /* Check for intersection.  */
3988             l = max (loc->address, addr);
3989             h = min (loc->address + loc->length, addr + len);
3990             if (l < h)
3991               return 1;
3992           }
3993     }
3994   return 0;
3995 }
3996
3997 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3998    PC is valid for process/thread PTID.  */
3999
4000 int
4001 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4002                          ptid_t ptid)
4003 {
4004   struct bp_location *bl, **blp_tmp;
4005   /* The thread and task IDs associated to PTID, computed lazily.  */
4006   int thread = -1;
4007   int task = 0;
4008   
4009   ALL_BP_LOCATIONS (bl, blp_tmp)
4010     {
4011       if (bl->loc_type != bp_loc_software_breakpoint
4012           && bl->loc_type != bp_loc_hardware_breakpoint)
4013         continue;
4014
4015       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4016       if (!breakpoint_enabled (bl->owner)
4017           && bl->owner->enable_state != bp_permanent)
4018         continue;
4019
4020       if (!breakpoint_location_address_match (bl, aspace, pc))
4021         continue;
4022
4023       if (bl->owner->thread != -1)
4024         {
4025           /* This is a thread-specific breakpoint.  Check that ptid
4026              matches that thread.  If thread hasn't been computed yet,
4027              it is now time to do so.  */
4028           if (thread == -1)
4029             thread = pid_to_thread_id (ptid);
4030           if (bl->owner->thread != thread)
4031             continue;
4032         }
4033
4034       if (bl->owner->task != 0)
4035         {
4036           /* This is a task-specific breakpoint.  Check that ptid
4037              matches that task.  If task hasn't been computed yet,
4038              it is now time to do so.  */
4039           if (task == 0)
4040             task = ada_get_task_number (ptid);
4041           if (bl->owner->task != task)
4042             continue;
4043         }
4044
4045       if (overlay_debugging 
4046           && section_is_overlay (bl->section)
4047           && !section_is_mapped (bl->section))
4048         continue;           /* unmapped overlay -- can't be a match */
4049
4050       return 1;
4051     }
4052
4053   return 0;
4054 }
4055 \f
4056
4057 /* bpstat stuff.  External routines' interfaces are documented
4058    in breakpoint.h.  */
4059
4060 int
4061 is_catchpoint (struct breakpoint *ep)
4062 {
4063   return (ep->type == bp_catchpoint);
4064 }
4065
4066 /* Frees any storage that is part of a bpstat.  Does not walk the
4067    'next' chain.  */
4068
4069 static void
4070 bpstat_free (bpstat bs)
4071 {
4072   if (bs->old_val != NULL)
4073     value_free (bs->old_val);
4074   decref_counted_command_line (&bs->commands);
4075   decref_bp_location (&bs->bp_location_at);
4076   xfree (bs);
4077 }
4078
4079 /* Clear a bpstat so that it says we are not at any breakpoint.
4080    Also free any storage that is part of a bpstat.  */
4081
4082 void
4083 bpstat_clear (bpstat *bsp)
4084 {
4085   bpstat p;
4086   bpstat q;
4087
4088   if (bsp == 0)
4089     return;
4090   p = *bsp;
4091   while (p != NULL)
4092     {
4093       q = p->next;
4094       bpstat_free (p);
4095       p = q;
4096     }
4097   *bsp = NULL;
4098 }
4099
4100 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4101    is part of the bpstat is copied as well.  */
4102
4103 bpstat
4104 bpstat_copy (bpstat bs)
4105 {
4106   bpstat p = NULL;
4107   bpstat tmp;
4108   bpstat retval = NULL;
4109
4110   if (bs == NULL)
4111     return bs;
4112
4113   for (; bs != NULL; bs = bs->next)
4114     {
4115       tmp = (bpstat) xmalloc (sizeof (*tmp));
4116       memcpy (tmp, bs, sizeof (*tmp));
4117       incref_counted_command_line (tmp->commands);
4118       incref_bp_location (tmp->bp_location_at);
4119       if (bs->old_val != NULL)
4120         {
4121           tmp->old_val = value_copy (bs->old_val);
4122           release_value (tmp->old_val);
4123         }
4124
4125       if (p == NULL)
4126         /* This is the first thing in the chain.  */
4127         retval = tmp;
4128       else
4129         p->next = tmp;
4130       p = tmp;
4131     }
4132   p->next = NULL;
4133   return retval;
4134 }
4135
4136 /* Find the bpstat associated with this breakpoint.  */
4137
4138 bpstat
4139 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4140 {
4141   if (bsp == NULL)
4142     return NULL;
4143
4144   for (; bsp != NULL; bsp = bsp->next)
4145     {
4146       if (bsp->breakpoint_at == breakpoint)
4147         return bsp;
4148     }
4149   return NULL;
4150 }
4151
4152 /* See breakpoint.h.  */
4153
4154 enum bpstat_signal_value
4155 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4156 {
4157   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4158
4159   for (; bsp != NULL; bsp = bsp->next)
4160     {
4161       /* Ensure that, if we ever entered this loop, then we at least
4162          return BPSTAT_SIGNAL_HIDE.  */
4163       enum bpstat_signal_value newval;
4164
4165       if (bsp->breakpoint_at == NULL)
4166         {
4167           /* A moribund location can never explain a signal other than
4168              GDB_SIGNAL_TRAP.  */
4169           if (sig == GDB_SIGNAL_TRAP)
4170             newval = BPSTAT_SIGNAL_HIDE;
4171           else
4172             newval = BPSTAT_SIGNAL_NO;
4173         }
4174       else
4175         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4176                                                            sig);
4177
4178       if (newval > result)
4179         result = newval;
4180     }
4181
4182   return result;
4183 }
4184
4185 /* Put in *NUM the breakpoint number of the first breakpoint we are
4186    stopped at.  *BSP upon return is a bpstat which points to the
4187    remaining breakpoints stopped at (but which is not guaranteed to be
4188    good for anything but further calls to bpstat_num).
4189
4190    Return 0 if passed a bpstat which does not indicate any breakpoints.
4191    Return -1 if stopped at a breakpoint that has been deleted since
4192    we set it.
4193    Return 1 otherwise.  */
4194
4195 int
4196 bpstat_num (bpstat *bsp, int *num)
4197 {
4198   struct breakpoint *b;
4199
4200   if ((*bsp) == NULL)
4201     return 0;                   /* No more breakpoint values */
4202
4203   /* We assume we'll never have several bpstats that correspond to a
4204      single breakpoint -- otherwise, this function might return the
4205      same number more than once and this will look ugly.  */
4206   b = (*bsp)->breakpoint_at;
4207   *bsp = (*bsp)->next;
4208   if (b == NULL)
4209     return -1;                  /* breakpoint that's been deleted since */
4210
4211   *num = b->number;             /* We have its number */
4212   return 1;
4213 }
4214
4215 /* See breakpoint.h.  */
4216
4217 void
4218 bpstat_clear_actions (void)
4219 {
4220   struct thread_info *tp;
4221   bpstat bs;
4222
4223   if (ptid_equal (inferior_ptid, null_ptid))
4224     return;
4225
4226   tp = find_thread_ptid (inferior_ptid);
4227   if (tp == NULL)
4228     return;
4229
4230   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4231     {
4232       decref_counted_command_line (&bs->commands);
4233
4234       if (bs->old_val != NULL)
4235         {
4236           value_free (bs->old_val);
4237           bs->old_val = NULL;
4238         }
4239     }
4240 }
4241
4242 /* Called when a command is about to proceed the inferior.  */
4243
4244 static void
4245 breakpoint_about_to_proceed (void)
4246 {
4247   if (!ptid_equal (inferior_ptid, null_ptid))
4248     {
4249       struct thread_info *tp = inferior_thread ();
4250
4251       /* Allow inferior function calls in breakpoint commands to not
4252          interrupt the command list.  When the call finishes
4253          successfully, the inferior will be standing at the same
4254          breakpoint as if nothing happened.  */
4255       if (tp->control.in_infcall)
4256         return;
4257     }
4258
4259   breakpoint_proceeded = 1;
4260 }
4261
4262 /* Stub for cleaning up our state if we error-out of a breakpoint
4263    command.  */
4264 static void
4265 cleanup_executing_breakpoints (void *ignore)
4266 {
4267   executing_breakpoint_commands = 0;
4268 }
4269
4270 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4271    or its equivalent.  */
4272
4273 static int
4274 command_line_is_silent (struct command_line *cmd)
4275 {
4276   return cmd && (strcmp ("silent", cmd->line) == 0
4277                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4278 }
4279
4280 /* Execute all the commands associated with all the breakpoints at
4281    this location.  Any of these commands could cause the process to
4282    proceed beyond this point, etc.  We look out for such changes by
4283    checking the global "breakpoint_proceeded" after each command.
4284
4285    Returns true if a breakpoint command resumed the inferior.  In that
4286    case, it is the caller's responsibility to recall it again with the
4287    bpstat of the current thread.  */
4288
4289 static int
4290 bpstat_do_actions_1 (bpstat *bsp)
4291 {
4292   bpstat bs;
4293   struct cleanup *old_chain;
4294   int again = 0;
4295
4296   /* Avoid endless recursion if a `source' command is contained
4297      in bs->commands.  */
4298   if (executing_breakpoint_commands)
4299     return 0;
4300
4301   executing_breakpoint_commands = 1;
4302   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4303
4304   prevent_dont_repeat ();
4305
4306   /* This pointer will iterate over the list of bpstat's.  */
4307   bs = *bsp;
4308
4309   breakpoint_proceeded = 0;
4310   for (; bs != NULL; bs = bs->next)
4311     {
4312       struct counted_command_line *ccmd;
4313       struct command_line *cmd;
4314       struct cleanup *this_cmd_tree_chain;
4315
4316       /* Take ownership of the BSP's command tree, if it has one.
4317
4318          The command tree could legitimately contain commands like
4319          'step' and 'next', which call clear_proceed_status, which
4320          frees stop_bpstat's command tree.  To make sure this doesn't
4321          free the tree we're executing out from under us, we need to
4322          take ownership of the tree ourselves.  Since a given bpstat's
4323          commands are only executed once, we don't need to copy it; we
4324          can clear the pointer in the bpstat, and make sure we free
4325          the tree when we're done.  */
4326       ccmd = bs->commands;
4327       bs->commands = NULL;
4328       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4329       cmd = ccmd ? ccmd->commands : NULL;
4330       if (command_line_is_silent (cmd))
4331         {
4332           /* The action has been already done by bpstat_stop_status.  */
4333           cmd = cmd->next;
4334         }
4335
4336       while (cmd != NULL)
4337         {
4338           execute_control_command (cmd);
4339
4340           if (breakpoint_proceeded)
4341             break;
4342           else
4343             cmd = cmd->next;
4344         }
4345
4346       /* We can free this command tree now.  */
4347       do_cleanups (this_cmd_tree_chain);
4348
4349       if (breakpoint_proceeded)
4350         {
4351           if (target_can_async_p ())
4352             /* If we are in async mode, then the target might be still
4353                running, not stopped at any breakpoint, so nothing for
4354                us to do here -- just return to the event loop.  */
4355             ;
4356           else
4357             /* In sync mode, when execute_control_command returns
4358                we're already standing on the next breakpoint.
4359                Breakpoint commands for that stop were not run, since
4360                execute_command does not run breakpoint commands --
4361                only command_line_handler does, but that one is not
4362                involved in execution of breakpoint commands.  So, we
4363                can now execute breakpoint commands.  It should be
4364                noted that making execute_command do bpstat actions is
4365                not an option -- in this case we'll have recursive
4366                invocation of bpstat for each breakpoint with a
4367                command, and can easily blow up GDB stack.  Instead, we
4368                return true, which will trigger the caller to recall us
4369                with the new stop_bpstat.  */
4370             again = 1;
4371           break;
4372         }
4373     }
4374   do_cleanups (old_chain);
4375   return again;
4376 }
4377
4378 void
4379 bpstat_do_actions (void)
4380 {
4381   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4382
4383   /* Do any commands attached to breakpoint we are stopped at.  */
4384   while (!ptid_equal (inferior_ptid, null_ptid)
4385          && target_has_execution
4386          && !is_exited (inferior_ptid)
4387          && !is_executing (inferior_ptid))
4388     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4389        and only return when it is stopped at the next breakpoint, we
4390        keep doing breakpoint actions until it returns false to
4391        indicate the inferior was not resumed.  */
4392     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4393       break;
4394
4395   discard_cleanups (cleanup_if_error);
4396 }
4397
4398 /* Print out the (old or new) value associated with a watchpoint.  */
4399
4400 static void
4401 watchpoint_value_print (struct value *val, struct ui_file *stream)
4402 {
4403   if (val == NULL)
4404     fprintf_unfiltered (stream, _("<unreadable>"));
4405   else
4406     {
4407       struct value_print_options opts;
4408       get_user_print_options (&opts);
4409       value_print (val, stream, &opts);
4410     }
4411 }
4412
4413 /* Generic routine for printing messages indicating why we
4414    stopped.  The behavior of this function depends on the value
4415    'print_it' in the bpstat structure.  Under some circumstances we
4416    may decide not to print anything here and delegate the task to
4417    normal_stop().  */
4418
4419 static enum print_stop_action
4420 print_bp_stop_message (bpstat bs)
4421 {
4422   switch (bs->print_it)
4423     {
4424     case print_it_noop:
4425       /* Nothing should be printed for this bpstat entry.  */
4426       return PRINT_UNKNOWN;
4427       break;
4428
4429     case print_it_done:
4430       /* We still want to print the frame, but we already printed the
4431          relevant messages.  */
4432       return PRINT_SRC_AND_LOC;
4433       break;
4434
4435     case print_it_normal:
4436       {
4437         struct breakpoint *b = bs->breakpoint_at;
4438
4439         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4440            which has since been deleted.  */
4441         if (b == NULL)
4442           return PRINT_UNKNOWN;
4443
4444         /* Normal case.  Call the breakpoint's print_it method.  */
4445         return b->ops->print_it (bs);
4446       }
4447       break;
4448
4449     default:
4450       internal_error (__FILE__, __LINE__,
4451                       _("print_bp_stop_message: unrecognized enum value"));
4452       break;
4453     }
4454 }
4455
4456 /* A helper function that prints a shared library stopped event.  */
4457
4458 static void
4459 print_solib_event (int is_catchpoint)
4460 {
4461   int any_deleted
4462     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4463   int any_added
4464     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4465
4466   if (!is_catchpoint)
4467     {
4468       if (any_added || any_deleted)
4469         ui_out_text (current_uiout,
4470                      _("Stopped due to shared library event:\n"));
4471       else
4472         ui_out_text (current_uiout,
4473                      _("Stopped due to shared library event (no "
4474                        "libraries added or removed)\n"));
4475     }
4476
4477   if (ui_out_is_mi_like_p (current_uiout))
4478     ui_out_field_string (current_uiout, "reason",
4479                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4480
4481   if (any_deleted)
4482     {
4483       struct cleanup *cleanup;
4484       char *name;
4485       int ix;
4486
4487       ui_out_text (current_uiout, _("  Inferior unloaded "));
4488       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4489                                                     "removed");
4490       for (ix = 0;
4491            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4492                         ix, name);
4493            ++ix)
4494         {
4495           if (ix > 0)
4496             ui_out_text (current_uiout, "    ");
4497           ui_out_field_string (current_uiout, "library", name);
4498           ui_out_text (current_uiout, "\n");
4499         }
4500
4501       do_cleanups (cleanup);
4502     }
4503
4504   if (any_added)
4505     {
4506       struct so_list *iter;
4507       int ix;
4508       struct cleanup *cleanup;
4509
4510       ui_out_text (current_uiout, _("  Inferior loaded "));
4511       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4512                                                     "added");
4513       for (ix = 0;
4514            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4515                         ix, iter);
4516            ++ix)
4517         {
4518           if (ix > 0)
4519             ui_out_text (current_uiout, "    ");
4520           ui_out_field_string (current_uiout, "library", iter->so_name);
4521           ui_out_text (current_uiout, "\n");
4522         }
4523
4524       do_cleanups (cleanup);
4525     }
4526 }
4527
4528 /* Print a message indicating what happened.  This is called from
4529    normal_stop().  The input to this routine is the head of the bpstat
4530    list - a list of the eventpoints that caused this stop.  KIND is
4531    the target_waitkind for the stopping event.  This
4532    routine calls the generic print routine for printing a message
4533    about reasons for stopping.  This will print (for example) the
4534    "Breakpoint n," part of the output.  The return value of this
4535    routine is one of:
4536
4537    PRINT_UNKNOWN: Means we printed nothing.
4538    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4539    code to print the location.  An example is 
4540    "Breakpoint 1, " which should be followed by
4541    the location.
4542    PRINT_SRC_ONLY: Means we printed something, but there is no need
4543    to also print the location part of the message.
4544    An example is the catch/throw messages, which
4545    don't require a location appended to the end.
4546    PRINT_NOTHING: We have done some printing and we don't need any 
4547    further info to be printed.  */
4548
4549 enum print_stop_action
4550 bpstat_print (bpstat bs, int kind)
4551 {
4552   int val;
4553
4554   /* Maybe another breakpoint in the chain caused us to stop.
4555      (Currently all watchpoints go on the bpstat whether hit or not.
4556      That probably could (should) be changed, provided care is taken
4557      with respect to bpstat_explains_signal).  */
4558   for (; bs; bs = bs->next)
4559     {
4560       val = print_bp_stop_message (bs);
4561       if (val == PRINT_SRC_ONLY 
4562           || val == PRINT_SRC_AND_LOC 
4563           || val == PRINT_NOTHING)
4564         return val;
4565     }
4566
4567   /* If we had hit a shared library event breakpoint,
4568      print_bp_stop_message would print out this message.  If we hit an
4569      OS-level shared library event, do the same thing.  */
4570   if (kind == TARGET_WAITKIND_LOADED)
4571     {
4572       print_solib_event (0);
4573       return PRINT_NOTHING;
4574     }
4575
4576   /* We reached the end of the chain, or we got a null BS to start
4577      with and nothing was printed.  */
4578   return PRINT_UNKNOWN;
4579 }
4580
4581 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4582    used inside a catch_errors to evaluate the breakpoint condition.
4583    The argument is a "struct expression *" that has been cast to a
4584    "char *" to make it pass through catch_errors.  */
4585
4586 static int
4587 breakpoint_cond_eval (void *exp)
4588 {
4589   struct value *mark = value_mark ();
4590   int i = !value_true (evaluate_expression ((struct expression *) exp));
4591
4592   value_free_to_mark (mark);
4593   return i;
4594 }
4595
4596 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4597
4598 static bpstat
4599 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4600 {
4601   bpstat bs;
4602
4603   bs = (bpstat) xmalloc (sizeof (*bs));
4604   bs->next = NULL;
4605   **bs_link_pointer = bs;
4606   *bs_link_pointer = &bs->next;
4607   bs->breakpoint_at = bl->owner;
4608   bs->bp_location_at = bl;
4609   incref_bp_location (bl);
4610   /* If the condition is false, etc., don't do the commands.  */
4611   bs->commands = NULL;
4612   bs->old_val = NULL;
4613   bs->print_it = print_it_normal;
4614   return bs;
4615 }
4616 \f
4617 /* The target has stopped with waitstatus WS.  Check if any hardware
4618    watchpoints have triggered, according to the target.  */
4619
4620 int
4621 watchpoints_triggered (struct target_waitstatus *ws)
4622 {
4623   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4624   CORE_ADDR addr;
4625   struct breakpoint *b;
4626
4627   if (!stopped_by_watchpoint)
4628     {
4629       /* We were not stopped by a watchpoint.  Mark all watchpoints
4630          as not triggered.  */
4631       ALL_BREAKPOINTS (b)
4632         if (is_hardware_watchpoint (b))
4633           {
4634             struct watchpoint *w = (struct watchpoint *) b;
4635
4636             w->watchpoint_triggered = watch_triggered_no;
4637           }
4638
4639       return 0;
4640     }
4641
4642   if (!target_stopped_data_address (&current_target, &addr))
4643     {
4644       /* We were stopped by a watchpoint, but we don't know where.
4645          Mark all watchpoints as unknown.  */
4646       ALL_BREAKPOINTS (b)
4647         if (is_hardware_watchpoint (b))
4648           {
4649             struct watchpoint *w = (struct watchpoint *) b;
4650
4651             w->watchpoint_triggered = watch_triggered_unknown;
4652           }
4653
4654       return stopped_by_watchpoint;
4655     }
4656
4657   /* The target could report the data address.  Mark watchpoints
4658      affected by this data address as triggered, and all others as not
4659      triggered.  */
4660
4661   ALL_BREAKPOINTS (b)
4662     if (is_hardware_watchpoint (b))
4663       {
4664         struct watchpoint *w = (struct watchpoint *) b;
4665         struct bp_location *loc;
4666
4667         w->watchpoint_triggered = watch_triggered_no;
4668         for (loc = b->loc; loc; loc = loc->next)
4669           {
4670             if (is_masked_watchpoint (b))
4671               {
4672                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4673                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4674
4675                 if (newaddr == start)
4676                   {
4677                     w->watchpoint_triggered = watch_triggered_yes;
4678                     break;
4679                   }
4680               }
4681             /* Exact match not required.  Within range is sufficient.  */
4682             else if (target_watchpoint_addr_within_range (&current_target,
4683                                                          addr, loc->address,
4684                                                          loc->length))
4685               {
4686                 w->watchpoint_triggered = watch_triggered_yes;
4687                 break;
4688               }
4689           }
4690       }
4691
4692   return 1;
4693 }
4694
4695 /* Possible return values for watchpoint_check (this can't be an enum
4696    because of check_errors).  */
4697 /* The watchpoint has been deleted.  */
4698 #define WP_DELETED 1
4699 /* The value has changed.  */
4700 #define WP_VALUE_CHANGED 2
4701 /* The value has not changed.  */
4702 #define WP_VALUE_NOT_CHANGED 3
4703 /* Ignore this watchpoint, no matter if the value changed or not.  */
4704 #define WP_IGNORE 4
4705
4706 #define BP_TEMPFLAG 1
4707 #define BP_HARDWAREFLAG 2
4708
4709 /* Evaluate watchpoint condition expression and check if its value
4710    changed.
4711
4712    P should be a pointer to struct bpstat, but is defined as a void *
4713    in order for this function to be usable with catch_errors.  */
4714
4715 static int
4716 watchpoint_check (void *p)
4717 {
4718   bpstat bs = (bpstat) p;
4719   struct watchpoint *b;
4720   struct frame_info *fr;
4721   int within_current_scope;
4722
4723   /* BS is built from an existing struct breakpoint.  */
4724   gdb_assert (bs->breakpoint_at != NULL);
4725   b = (struct watchpoint *) bs->breakpoint_at;
4726
4727   /* If this is a local watchpoint, we only want to check if the
4728      watchpoint frame is in scope if the current thread is the thread
4729      that was used to create the watchpoint.  */
4730   if (!watchpoint_in_thread_scope (b))
4731     return WP_IGNORE;
4732
4733   if (b->exp_valid_block == NULL)
4734     within_current_scope = 1;
4735   else
4736     {
4737       struct frame_info *frame = get_current_frame ();
4738       struct gdbarch *frame_arch = get_frame_arch (frame);
4739       CORE_ADDR frame_pc = get_frame_pc (frame);
4740
4741       /* in_function_epilogue_p() returns a non-zero value if we're
4742          still in the function but the stack frame has already been
4743          invalidated.  Since we can't rely on the values of local
4744          variables after the stack has been destroyed, we are treating
4745          the watchpoint in that state as `not changed' without further
4746          checking.  Don't mark watchpoints as changed if the current
4747          frame is in an epilogue - even if they are in some other
4748          frame, our view of the stack is likely to be wrong and
4749          frame_find_by_id could error out.  */
4750       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4751         return WP_IGNORE;
4752
4753       fr = frame_find_by_id (b->watchpoint_frame);
4754       within_current_scope = (fr != NULL);
4755
4756       /* If we've gotten confused in the unwinder, we might have
4757          returned a frame that can't describe this variable.  */
4758       if (within_current_scope)
4759         {
4760           struct symbol *function;
4761
4762           function = get_frame_function (fr);
4763           if (function == NULL
4764               || !contained_in (b->exp_valid_block,
4765                                 SYMBOL_BLOCK_VALUE (function)))
4766             within_current_scope = 0;
4767         }
4768
4769       if (within_current_scope)
4770         /* If we end up stopping, the current frame will get selected
4771            in normal_stop.  So this call to select_frame won't affect
4772            the user.  */
4773         select_frame (fr);
4774     }
4775
4776   if (within_current_scope)
4777     {
4778       /* We use value_{,free_to_}mark because it could be a *long*
4779          time before we return to the command level and call
4780          free_all_values.  We can't call free_all_values because we
4781          might be in the middle of evaluating a function call.  */
4782
4783       int pc = 0;
4784       struct value *mark;
4785       struct value *new_val;
4786
4787       if (is_masked_watchpoint (&b->base))
4788         /* Since we don't know the exact trigger address (from
4789            stopped_data_address), just tell the user we've triggered
4790            a mask watchpoint.  */
4791         return WP_VALUE_CHANGED;
4792
4793       mark = value_mark ();
4794       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4795
4796       /* We use value_equal_contents instead of value_equal because
4797          the latter coerces an array to a pointer, thus comparing just
4798          the address of the array instead of its contents.  This is
4799          not what we want.  */
4800       if ((b->val != NULL) != (new_val != NULL)
4801           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4802         {
4803           if (new_val != NULL)
4804             {
4805               release_value (new_val);
4806               value_free_to_mark (mark);
4807             }
4808           bs->old_val = b->val;
4809           b->val = new_val;
4810           b->val_valid = 1;
4811           return WP_VALUE_CHANGED;
4812         }
4813       else
4814         {
4815           /* Nothing changed.  */
4816           value_free_to_mark (mark);
4817           return WP_VALUE_NOT_CHANGED;
4818         }
4819     }
4820   else
4821     {
4822       struct ui_out *uiout = current_uiout;
4823
4824       /* This seems like the only logical thing to do because
4825          if we temporarily ignored the watchpoint, then when
4826          we reenter the block in which it is valid it contains
4827          garbage (in the case of a function, it may have two
4828          garbage values, one before and one after the prologue).
4829          So we can't even detect the first assignment to it and
4830          watch after that (since the garbage may or may not equal
4831          the first value assigned).  */
4832       /* We print all the stop information in
4833          breakpoint_ops->print_it, but in this case, by the time we
4834          call breakpoint_ops->print_it this bp will be deleted
4835          already.  So we have no choice but print the information
4836          here.  */
4837       if (ui_out_is_mi_like_p (uiout))
4838         ui_out_field_string
4839           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4840       ui_out_text (uiout, "\nWatchpoint ");
4841       ui_out_field_int (uiout, "wpnum", b->base.number);
4842       ui_out_text (uiout,
4843                    " deleted because the program has left the block in\n\
4844 which its expression is valid.\n");     
4845
4846       /* Make sure the watchpoint's commands aren't executed.  */
4847       decref_counted_command_line (&b->base.commands);
4848       watchpoint_del_at_next_stop (b);
4849
4850       return WP_DELETED;
4851     }
4852 }
4853
4854 /* Return true if it looks like target has stopped due to hitting
4855    breakpoint location BL.  This function does not check if we should
4856    stop, only if BL explains the stop.  */
4857
4858 static int
4859 bpstat_check_location (const struct bp_location *bl,
4860                        struct address_space *aspace, CORE_ADDR bp_addr,
4861                        const struct target_waitstatus *ws)
4862 {
4863   struct breakpoint *b = bl->owner;
4864
4865   /* BL is from an existing breakpoint.  */
4866   gdb_assert (b != NULL);
4867
4868   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4869 }
4870
4871 /* Determine if the watched values have actually changed, and we
4872    should stop.  If not, set BS->stop to 0.  */
4873
4874 static void
4875 bpstat_check_watchpoint (bpstat bs)
4876 {
4877   const struct bp_location *bl;
4878   struct watchpoint *b;
4879
4880   /* BS is built for existing struct breakpoint.  */
4881   bl = bs->bp_location_at;
4882   gdb_assert (bl != NULL);
4883   b = (struct watchpoint *) bs->breakpoint_at;
4884   gdb_assert (b != NULL);
4885
4886     {
4887       int must_check_value = 0;
4888       
4889       if (b->base.type == bp_watchpoint)
4890         /* For a software watchpoint, we must always check the
4891            watched value.  */
4892         must_check_value = 1;
4893       else if (b->watchpoint_triggered == watch_triggered_yes)
4894         /* We have a hardware watchpoint (read, write, or access)
4895            and the target earlier reported an address watched by
4896            this watchpoint.  */
4897         must_check_value = 1;
4898       else if (b->watchpoint_triggered == watch_triggered_unknown
4899                && b->base.type == bp_hardware_watchpoint)
4900         /* We were stopped by a hardware watchpoint, but the target could
4901            not report the data address.  We must check the watchpoint's
4902            value.  Access and read watchpoints are out of luck; without
4903            a data address, we can't figure it out.  */
4904         must_check_value = 1;
4905
4906       if (must_check_value)
4907         {
4908           char *message
4909             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4910                           b->base.number);
4911           struct cleanup *cleanups = make_cleanup (xfree, message);
4912           int e = catch_errors (watchpoint_check, bs, message,
4913                                 RETURN_MASK_ALL);
4914           do_cleanups (cleanups);
4915           switch (e)
4916             {
4917             case WP_DELETED:
4918               /* We've already printed what needs to be printed.  */
4919               bs->print_it = print_it_done;
4920               /* Stop.  */
4921               break;
4922             case WP_IGNORE:
4923               bs->print_it = print_it_noop;
4924               bs->stop = 0;
4925               break;
4926             case WP_VALUE_CHANGED:
4927               if (b->base.type == bp_read_watchpoint)
4928                 {
4929                   /* There are two cases to consider here:
4930
4931                      1. We're watching the triggered memory for reads.
4932                      In that case, trust the target, and always report
4933                      the watchpoint hit to the user.  Even though
4934                      reads don't cause value changes, the value may
4935                      have changed since the last time it was read, and
4936                      since we're not trapping writes, we will not see
4937                      those, and as such we should ignore our notion of
4938                      old value.
4939
4940                      2. We're watching the triggered memory for both
4941                      reads and writes.  There are two ways this may
4942                      happen:
4943
4944                      2.1. This is a target that can't break on data
4945                      reads only, but can break on accesses (reads or
4946                      writes), such as e.g., x86.  We detect this case
4947                      at the time we try to insert read watchpoints.
4948
4949                      2.2. Otherwise, the target supports read
4950                      watchpoints, but, the user set an access or write
4951                      watchpoint watching the same memory as this read
4952                      watchpoint.
4953
4954                      If we're watching memory writes as well as reads,
4955                      ignore watchpoint hits when we find that the
4956                      value hasn't changed, as reads don't cause
4957                      changes.  This still gives false positives when
4958                      the program writes the same value to memory as
4959                      what there was already in memory (we will confuse
4960                      it for a read), but it's much better than
4961                      nothing.  */
4962
4963                   int other_write_watchpoint = 0;
4964
4965                   if (bl->watchpoint_type == hw_read)
4966                     {
4967                       struct breakpoint *other_b;
4968
4969                       ALL_BREAKPOINTS (other_b)
4970                         if (other_b->type == bp_hardware_watchpoint
4971                             || other_b->type == bp_access_watchpoint)
4972                           {
4973                             struct watchpoint *other_w =
4974                               (struct watchpoint *) other_b;
4975
4976                             if (other_w->watchpoint_triggered
4977                                 == watch_triggered_yes)
4978                               {
4979                                 other_write_watchpoint = 1;
4980                                 break;
4981                               }
4982                           }
4983                     }
4984
4985                   if (other_write_watchpoint
4986                       || bl->watchpoint_type == hw_access)
4987                     {
4988                       /* We're watching the same memory for writes,
4989                          and the value changed since the last time we
4990                          updated it, so this trap must be for a write.
4991                          Ignore it.  */
4992                       bs->print_it = print_it_noop;
4993                       bs->stop = 0;
4994                     }
4995                 }
4996               break;
4997             case WP_VALUE_NOT_CHANGED:
4998               if (b->base.type == bp_hardware_watchpoint
4999                   || b->base.type == bp_watchpoint)
5000                 {
5001                   /* Don't stop: write watchpoints shouldn't fire if
5002                      the value hasn't changed.  */
5003                   bs->print_it = print_it_noop;
5004                   bs->stop = 0;
5005                 }
5006               /* Stop.  */
5007               break;
5008             default:
5009               /* Can't happen.  */
5010             case 0:
5011               /* Error from catch_errors.  */
5012               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5013               watchpoint_del_at_next_stop (b);
5014               /* We've already printed what needs to be printed.  */
5015               bs->print_it = print_it_done;
5016               break;
5017             }
5018         }
5019       else      /* must_check_value == 0 */
5020         {
5021           /* This is a case where some watchpoint(s) triggered, but
5022              not at the address of this watchpoint, or else no
5023              watchpoint triggered after all.  So don't print
5024              anything for this watchpoint.  */
5025           bs->print_it = print_it_noop;
5026           bs->stop = 0;
5027         }
5028     }
5029 }
5030
5031
5032 /* Check conditions (condition proper, frame, thread and ignore count)
5033    of breakpoint referred to by BS.  If we should not stop for this
5034    breakpoint, set BS->stop to 0.  */
5035
5036 static void
5037 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5038 {
5039   int thread_id = pid_to_thread_id (ptid);
5040   const struct bp_location *bl;
5041   struct breakpoint *b;
5042
5043   /* BS is built for existing struct breakpoint.  */
5044   bl = bs->bp_location_at;
5045   gdb_assert (bl != NULL);
5046   b = bs->breakpoint_at;
5047   gdb_assert (b != NULL);
5048
5049   /* Even if the target evaluated the condition on its end and notified GDB, we
5050      need to do so again since GDB does not know if we stopped due to a
5051      breakpoint or a single step breakpoint.  */
5052
5053   if (frame_id_p (b->frame_id)
5054       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5055     bs->stop = 0;
5056   else if (bs->stop)
5057     {
5058       int value_is_zero = 0;
5059       struct expression *cond;
5060
5061       /* Evaluate Python breakpoints that have a "stop"
5062          method implemented.  */
5063       if (b->py_bp_object)
5064         bs->stop = gdbpy_should_stop (b->py_bp_object);
5065
5066       if (is_watchpoint (b))
5067         {
5068           struct watchpoint *w = (struct watchpoint *) b;
5069
5070           cond = w->cond_exp;
5071         }
5072       else
5073         cond = bl->cond;
5074
5075       if (cond && b->disposition != disp_del_at_next_stop)
5076         {
5077           int within_current_scope = 1;
5078           struct watchpoint * w;
5079
5080           /* We use value_mark and value_free_to_mark because it could
5081              be a long time before we return to the command level and
5082              call free_all_values.  We can't call free_all_values
5083              because we might be in the middle of evaluating a
5084              function call.  */
5085           struct value *mark = value_mark ();
5086
5087           if (is_watchpoint (b))
5088             w = (struct watchpoint *) b;
5089           else
5090             w = NULL;
5091
5092           /* Need to select the frame, with all that implies so that
5093              the conditions will have the right context.  Because we
5094              use the frame, we will not see an inlined function's
5095              variables when we arrive at a breakpoint at the start
5096              of the inlined function; the current frame will be the
5097              call site.  */
5098           if (w == NULL || w->cond_exp_valid_block == NULL)
5099             select_frame (get_current_frame ());
5100           else
5101             {
5102               struct frame_info *frame;
5103
5104               /* For local watchpoint expressions, which particular
5105                  instance of a local is being watched matters, so we
5106                  keep track of the frame to evaluate the expression
5107                  in.  To evaluate the condition however, it doesn't
5108                  really matter which instantiation of the function
5109                  where the condition makes sense triggers the
5110                  watchpoint.  This allows an expression like "watch
5111                  global if q > 10" set in `func', catch writes to
5112                  global on all threads that call `func', or catch
5113                  writes on all recursive calls of `func' by a single
5114                  thread.  We simply always evaluate the condition in
5115                  the innermost frame that's executing where it makes
5116                  sense to evaluate the condition.  It seems
5117                  intuitive.  */
5118               frame = block_innermost_frame (w->cond_exp_valid_block);
5119               if (frame != NULL)
5120                 select_frame (frame);
5121               else
5122                 within_current_scope = 0;
5123             }
5124           if (within_current_scope)
5125             value_is_zero
5126               = catch_errors (breakpoint_cond_eval, cond,
5127                               "Error in testing breakpoint condition:\n",
5128                               RETURN_MASK_ALL);
5129           else
5130             {
5131               warning (_("Watchpoint condition cannot be tested "
5132                          "in the current scope"));
5133               /* If we failed to set the right context for this
5134                  watchpoint, unconditionally report it.  */
5135               value_is_zero = 0;
5136             }
5137           /* FIXME-someday, should give breakpoint #.  */
5138           value_free_to_mark (mark);
5139         }
5140
5141       if (cond && value_is_zero)
5142         {
5143           bs->stop = 0;
5144         }
5145       else if (b->thread != -1 && b->thread != thread_id)
5146         {
5147           bs->stop = 0;
5148         }
5149       else if (b->ignore_count > 0)
5150         {
5151           b->ignore_count--;
5152           bs->stop = 0;
5153           /* Increase the hit count even though we don't stop.  */
5154           ++(b->hit_count);
5155           observer_notify_breakpoint_modified (b);
5156         }       
5157     }
5158 }
5159
5160
5161 /* Get a bpstat associated with having just stopped at address
5162    BP_ADDR in thread PTID.
5163
5164    Determine whether we stopped at a breakpoint, etc, or whether we
5165    don't understand this stop.  Result is a chain of bpstat's such
5166    that:
5167
5168    if we don't understand the stop, the result is a null pointer.
5169
5170    if we understand why we stopped, the result is not null.
5171
5172    Each element of the chain refers to a particular breakpoint or
5173    watchpoint at which we have stopped.  (We may have stopped for
5174    several reasons concurrently.)
5175
5176    Each element of the chain has valid next, breakpoint_at,
5177    commands, FIXME??? fields.  */
5178
5179 bpstat
5180 bpstat_stop_status (struct address_space *aspace,
5181                     CORE_ADDR bp_addr, ptid_t ptid,
5182                     const struct target_waitstatus *ws)
5183 {
5184   struct breakpoint *b = NULL;
5185   struct bp_location *bl;
5186   struct bp_location *loc;
5187   /* First item of allocated bpstat's.  */
5188   bpstat bs_head = NULL, *bs_link = &bs_head;
5189   /* Pointer to the last thing in the chain currently.  */
5190   bpstat bs;
5191   int ix;
5192   int need_remove_insert;
5193   int removed_any;
5194
5195   /* First, build the bpstat chain with locations that explain a
5196      target stop, while being careful to not set the target running,
5197      as that may invalidate locations (in particular watchpoint
5198      locations are recreated).  Resuming will happen here with
5199      breakpoint conditions or watchpoint expressions that include
5200      inferior function calls.  */
5201
5202   ALL_BREAKPOINTS (b)
5203     {
5204       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5205         continue;
5206
5207       for (bl = b->loc; bl != NULL; bl = bl->next)
5208         {
5209           /* For hardware watchpoints, we look only at the first
5210              location.  The watchpoint_check function will work on the
5211              entire expression, not the individual locations.  For
5212              read watchpoints, the watchpoints_triggered function has
5213              checked all locations already.  */
5214           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5215             break;
5216
5217           if (!bl->enabled || bl->shlib_disabled)
5218             continue;
5219
5220           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5221             continue;
5222
5223           /* Come here if it's a watchpoint, or if the break address
5224              matches.  */
5225
5226           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5227                                                    explain stop.  */
5228
5229           /* Assume we stop.  Should we find a watchpoint that is not
5230              actually triggered, or if the condition of the breakpoint
5231              evaluates as false, we'll reset 'stop' to 0.  */
5232           bs->stop = 1;
5233           bs->print = 1;
5234
5235           /* If this is a scope breakpoint, mark the associated
5236              watchpoint as triggered so that we will handle the
5237              out-of-scope event.  We'll get to the watchpoint next
5238              iteration.  */
5239           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5240             {
5241               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5242
5243               w->watchpoint_triggered = watch_triggered_yes;
5244             }
5245         }
5246     }
5247
5248   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5249     {
5250       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5251         {
5252           bs = bpstat_alloc (loc, &bs_link);
5253           /* For hits of moribund locations, we should just proceed.  */
5254           bs->stop = 0;
5255           bs->print = 0;
5256           bs->print_it = print_it_noop;
5257         }
5258     }
5259
5260   /* A bit of special processing for shlib breakpoints.  We need to
5261      process solib loading here, so that the lists of loaded and
5262      unloaded libraries are correct before we handle "catch load" and
5263      "catch unload".  */
5264   for (bs = bs_head; bs != NULL; bs = bs->next)
5265     {
5266       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5267         {
5268           handle_solib_event ();
5269           break;
5270         }
5271     }
5272
5273   /* Now go through the locations that caused the target to stop, and
5274      check whether we're interested in reporting this stop to higher
5275      layers, or whether we should resume the target transparently.  */
5276
5277   removed_any = 0;
5278
5279   for (bs = bs_head; bs != NULL; bs = bs->next)
5280     {
5281       if (!bs->stop)
5282         continue;
5283
5284       b = bs->breakpoint_at;
5285       b->ops->check_status (bs);
5286       if (bs->stop)
5287         {
5288           bpstat_check_breakpoint_conditions (bs, ptid);
5289
5290           if (bs->stop)
5291             {
5292               ++(b->hit_count);
5293               observer_notify_breakpoint_modified (b);
5294
5295               /* We will stop here.  */
5296               if (b->disposition == disp_disable)
5297                 {
5298                   --(b->enable_count);
5299                   if (b->enable_count <= 0
5300                       && b->enable_state != bp_permanent)
5301                     b->enable_state = bp_disabled;
5302                   removed_any = 1;
5303                 }
5304               if (b->silent)
5305                 bs->print = 0;
5306               bs->commands = b->commands;
5307               incref_counted_command_line (bs->commands);
5308               if (command_line_is_silent (bs->commands
5309                                           ? bs->commands->commands : NULL))
5310                 bs->print = 0;
5311             }
5312
5313         }
5314
5315       /* Print nothing for this entry if we don't stop or don't
5316          print.  */
5317       if (!bs->stop || !bs->print)
5318         bs->print_it = print_it_noop;
5319     }
5320
5321   /* If we aren't stopping, the value of some hardware watchpoint may
5322      not have changed, but the intermediate memory locations we are
5323      watching may have.  Don't bother if we're stopping; this will get
5324      done later.  */
5325   need_remove_insert = 0;
5326   if (! bpstat_causes_stop (bs_head))
5327     for (bs = bs_head; bs != NULL; bs = bs->next)
5328       if (!bs->stop
5329           && bs->breakpoint_at
5330           && is_hardware_watchpoint (bs->breakpoint_at))
5331         {
5332           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5333
5334           update_watchpoint (w, 0 /* don't reparse.  */);
5335           need_remove_insert = 1;
5336         }
5337
5338   if (need_remove_insert)
5339     update_global_location_list (1);
5340   else if (removed_any)
5341     update_global_location_list (0);
5342
5343   return bs_head;
5344 }
5345
5346 static void
5347 handle_jit_event (void)
5348 {
5349   struct frame_info *frame;
5350   struct gdbarch *gdbarch;
5351
5352   /* Switch terminal for any messages produced by
5353      breakpoint_re_set.  */
5354   target_terminal_ours_for_output ();
5355
5356   frame = get_current_frame ();
5357   gdbarch = get_frame_arch (frame);
5358
5359   jit_event_handler (gdbarch);
5360
5361   target_terminal_inferior ();
5362 }
5363
5364 /* Prepare WHAT final decision for infrun.  */
5365
5366 /* Decide what infrun needs to do with this bpstat.  */
5367
5368 struct bpstat_what
5369 bpstat_what (bpstat bs_head)
5370 {
5371   struct bpstat_what retval;
5372   int jit_event = 0;
5373   bpstat bs;
5374
5375   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5376   retval.call_dummy = STOP_NONE;
5377   retval.is_longjmp = 0;
5378
5379   for (bs = bs_head; bs != NULL; bs = bs->next)
5380     {
5381       /* Extract this BS's action.  After processing each BS, we check
5382          if its action overrides all we've seem so far.  */
5383       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5384       enum bptype bptype;
5385
5386       if (bs->breakpoint_at == NULL)
5387         {
5388           /* I suspect this can happen if it was a momentary
5389              breakpoint which has since been deleted.  */
5390           bptype = bp_none;
5391         }
5392       else
5393         bptype = bs->breakpoint_at->type;
5394
5395       switch (bptype)
5396         {
5397         case bp_none:
5398           break;
5399         case bp_breakpoint:
5400         case bp_hardware_breakpoint:
5401         case bp_until:
5402         case bp_finish:
5403         case bp_shlib_event:
5404           if (bs->stop)
5405             {
5406               if (bs->print)
5407                 this_action = BPSTAT_WHAT_STOP_NOISY;
5408               else
5409                 this_action = BPSTAT_WHAT_STOP_SILENT;
5410             }
5411           else
5412             this_action = BPSTAT_WHAT_SINGLE;
5413           break;
5414         case bp_watchpoint:
5415         case bp_hardware_watchpoint:
5416         case bp_read_watchpoint:
5417         case bp_access_watchpoint:
5418           if (bs->stop)
5419             {
5420               if (bs->print)
5421                 this_action = BPSTAT_WHAT_STOP_NOISY;
5422               else
5423                 this_action = BPSTAT_WHAT_STOP_SILENT;
5424             }
5425           else
5426             {
5427               /* There was a watchpoint, but we're not stopping.
5428                  This requires no further action.  */
5429             }
5430           break;
5431         case bp_longjmp:
5432         case bp_longjmp_call_dummy:
5433         case bp_exception:
5434           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5435           retval.is_longjmp = bptype != bp_exception;
5436           break;
5437         case bp_longjmp_resume:
5438         case bp_exception_resume:
5439           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5440           retval.is_longjmp = bptype == bp_longjmp_resume;
5441           break;
5442         case bp_step_resume:
5443           if (bs->stop)
5444             this_action = BPSTAT_WHAT_STEP_RESUME;
5445           else
5446             {
5447               /* It is for the wrong frame.  */
5448               this_action = BPSTAT_WHAT_SINGLE;
5449             }
5450           break;
5451         case bp_hp_step_resume:
5452           if (bs->stop)
5453             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5454           else
5455             {
5456               /* It is for the wrong frame.  */
5457               this_action = BPSTAT_WHAT_SINGLE;
5458             }
5459           break;
5460         case bp_watchpoint_scope:
5461         case bp_thread_event:
5462         case bp_overlay_event:
5463         case bp_longjmp_master:
5464         case bp_std_terminate_master:
5465         case bp_exception_master:
5466           this_action = BPSTAT_WHAT_SINGLE;
5467           break;
5468         case bp_catchpoint:
5469           if (bs->stop)
5470             {
5471               if (bs->print)
5472                 this_action = BPSTAT_WHAT_STOP_NOISY;
5473               else
5474                 this_action = BPSTAT_WHAT_STOP_SILENT;
5475             }
5476           else
5477             {
5478               /* There was a catchpoint, but we're not stopping.
5479                  This requires no further action.  */
5480             }
5481           break;
5482         case bp_jit_event:
5483           jit_event = 1;
5484           this_action = BPSTAT_WHAT_SINGLE;
5485           break;
5486         case bp_call_dummy:
5487           /* Make sure the action is stop (silent or noisy),
5488              so infrun.c pops the dummy frame.  */
5489           retval.call_dummy = STOP_STACK_DUMMY;
5490           this_action = BPSTAT_WHAT_STOP_SILENT;
5491           break;
5492         case bp_std_terminate:
5493           /* Make sure the action is stop (silent or noisy),
5494              so infrun.c pops the dummy frame.  */
5495           retval.call_dummy = STOP_STD_TERMINATE;
5496           this_action = BPSTAT_WHAT_STOP_SILENT;
5497           break;
5498         case bp_tracepoint:
5499         case bp_fast_tracepoint:
5500         case bp_static_tracepoint:
5501           /* Tracepoint hits should not be reported back to GDB, and
5502              if one got through somehow, it should have been filtered
5503              out already.  */
5504           internal_error (__FILE__, __LINE__,
5505                           _("bpstat_what: tracepoint encountered"));
5506           break;
5507         case bp_gnu_ifunc_resolver:
5508           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5509           this_action = BPSTAT_WHAT_SINGLE;
5510           break;
5511         case bp_gnu_ifunc_resolver_return:
5512           /* The breakpoint will be removed, execution will restart from the
5513              PC of the former breakpoint.  */
5514           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5515           break;
5516
5517         case bp_dprintf:
5518           if (bs->stop)
5519             this_action = BPSTAT_WHAT_STOP_SILENT;
5520           else
5521             this_action = BPSTAT_WHAT_SINGLE;
5522           break;
5523
5524         default:
5525           internal_error (__FILE__, __LINE__,
5526                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5527         }
5528
5529       retval.main_action = max (retval.main_action, this_action);
5530     }
5531
5532   /* These operations may affect the bs->breakpoint_at state so they are
5533      delayed after MAIN_ACTION is decided above.  */
5534
5535   if (jit_event)
5536     {
5537       if (debug_infrun)
5538         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5539
5540       handle_jit_event ();
5541     }
5542
5543   for (bs = bs_head; bs != NULL; bs = bs->next)
5544     {
5545       struct breakpoint *b = bs->breakpoint_at;
5546
5547       if (b == NULL)
5548         continue;
5549       switch (b->type)
5550         {
5551         case bp_gnu_ifunc_resolver:
5552           gnu_ifunc_resolver_stop (b);
5553           break;
5554         case bp_gnu_ifunc_resolver_return:
5555           gnu_ifunc_resolver_return_stop (b);
5556           break;
5557         }
5558     }
5559
5560   return retval;
5561 }
5562
5563 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5564    without hardware support).  This isn't related to a specific bpstat,
5565    just to things like whether watchpoints are set.  */
5566
5567 int
5568 bpstat_should_step (void)
5569 {
5570   struct breakpoint *b;
5571
5572   ALL_BREAKPOINTS (b)
5573     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5574       return 1;
5575   return 0;
5576 }
5577
5578 int
5579 bpstat_causes_stop (bpstat bs)
5580 {
5581   for (; bs != NULL; bs = bs->next)
5582     if (bs->stop)
5583       return 1;
5584
5585   return 0;
5586 }
5587
5588 \f
5589
5590 /* Compute a string of spaces suitable to indent the next line
5591    so it starts at the position corresponding to the table column
5592    named COL_NAME in the currently active table of UIOUT.  */
5593
5594 static char *
5595 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5596 {
5597   static char wrap_indent[80];
5598   int i, total_width, width, align;
5599   char *text;
5600
5601   total_width = 0;
5602   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5603     {
5604       if (strcmp (text, col_name) == 0)
5605         {
5606           gdb_assert (total_width < sizeof wrap_indent);
5607           memset (wrap_indent, ' ', total_width);
5608           wrap_indent[total_width] = 0;
5609
5610           return wrap_indent;
5611         }
5612
5613       total_width += width + 1;
5614     }
5615
5616   return NULL;
5617 }
5618
5619 /* Determine if the locations of this breakpoint will have their conditions
5620    evaluated by the target, host or a mix of both.  Returns the following:
5621
5622     "host": Host evals condition.
5623     "host or target": Host or Target evals condition.
5624     "target": Target evals condition.
5625 */
5626
5627 static const char *
5628 bp_condition_evaluator (struct breakpoint *b)
5629 {
5630   struct bp_location *bl;
5631   char host_evals = 0;
5632   char target_evals = 0;
5633
5634   if (!b)
5635     return NULL;
5636
5637   if (!is_breakpoint (b))
5638     return NULL;
5639
5640   if (gdb_evaluates_breakpoint_condition_p ()
5641       || !target_supports_evaluation_of_breakpoint_conditions ())
5642     return condition_evaluation_host;
5643
5644   for (bl = b->loc; bl; bl = bl->next)
5645     {
5646       if (bl->cond_bytecode)
5647         target_evals++;
5648       else
5649         host_evals++;
5650     }
5651
5652   if (host_evals && target_evals)
5653     return condition_evaluation_both;
5654   else if (target_evals)
5655     return condition_evaluation_target;
5656   else
5657     return condition_evaluation_host;
5658 }
5659
5660 /* Determine the breakpoint location's condition evaluator.  This is
5661    similar to bp_condition_evaluator, but for locations.  */
5662
5663 static const char *
5664 bp_location_condition_evaluator (struct bp_location *bl)
5665 {
5666   if (bl && !is_breakpoint (bl->owner))
5667     return NULL;
5668
5669   if (gdb_evaluates_breakpoint_condition_p ()
5670       || !target_supports_evaluation_of_breakpoint_conditions ())
5671     return condition_evaluation_host;
5672
5673   if (bl && bl->cond_bytecode)
5674     return condition_evaluation_target;
5675   else
5676     return condition_evaluation_host;
5677 }
5678
5679 /* Print the LOC location out of the list of B->LOC locations.  */
5680
5681 static void
5682 print_breakpoint_location (struct breakpoint *b,
5683                            struct bp_location *loc)
5684 {
5685   struct ui_out *uiout = current_uiout;
5686   struct cleanup *old_chain = save_current_program_space ();
5687
5688   if (loc != NULL && loc->shlib_disabled)
5689     loc = NULL;
5690
5691   if (loc != NULL)
5692     set_current_program_space (loc->pspace);
5693
5694   if (b->display_canonical)
5695     ui_out_field_string (uiout, "what", b->addr_string);
5696   else if (loc && loc->symtab)
5697     {
5698       struct symbol *sym 
5699         = find_pc_sect_function (loc->address, loc->section);
5700       if (sym)
5701         {
5702           ui_out_text (uiout, "in ");
5703           ui_out_field_string (uiout, "func",
5704                                SYMBOL_PRINT_NAME (sym));
5705           ui_out_text (uiout, " ");
5706           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5707           ui_out_text (uiout, "at ");
5708         }
5709       ui_out_field_string (uiout, "file",
5710                            symtab_to_filename_for_display (loc->symtab));
5711       ui_out_text (uiout, ":");
5712
5713       if (ui_out_is_mi_like_p (uiout))
5714         ui_out_field_string (uiout, "fullname",
5715                              symtab_to_fullname (loc->symtab));
5716       
5717       ui_out_field_int (uiout, "line", loc->line_number);
5718     }
5719   else if (loc)
5720     {
5721       struct ui_file *stb = mem_fileopen ();
5722       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5723
5724       print_address_symbolic (loc->gdbarch, loc->address, stb,
5725                               demangle, "");
5726       ui_out_field_stream (uiout, "at", stb);
5727
5728       do_cleanups (stb_chain);
5729     }
5730   else
5731     ui_out_field_string (uiout, "pending", b->addr_string);
5732
5733   if (loc && is_breakpoint (b)
5734       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5735       && bp_condition_evaluator (b) == condition_evaluation_both)
5736     {
5737       ui_out_text (uiout, " (");
5738       ui_out_field_string (uiout, "evaluated-by",
5739                            bp_location_condition_evaluator (loc));
5740       ui_out_text (uiout, ")");
5741     }
5742
5743   do_cleanups (old_chain);
5744 }
5745
5746 static const char *
5747 bptype_string (enum bptype type)
5748 {
5749   struct ep_type_description
5750     {
5751       enum bptype type;
5752       char *description;
5753     };
5754   static struct ep_type_description bptypes[] =
5755   {
5756     {bp_none, "?deleted?"},
5757     {bp_breakpoint, "breakpoint"},
5758     {bp_hardware_breakpoint, "hw breakpoint"},
5759     {bp_until, "until"},
5760     {bp_finish, "finish"},
5761     {bp_watchpoint, "watchpoint"},
5762     {bp_hardware_watchpoint, "hw watchpoint"},
5763     {bp_read_watchpoint, "read watchpoint"},
5764     {bp_access_watchpoint, "acc watchpoint"},
5765     {bp_longjmp, "longjmp"},
5766     {bp_longjmp_resume, "longjmp resume"},
5767     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5768     {bp_exception, "exception"},
5769     {bp_exception_resume, "exception resume"},
5770     {bp_step_resume, "step resume"},
5771     {bp_hp_step_resume, "high-priority step resume"},
5772     {bp_watchpoint_scope, "watchpoint scope"},
5773     {bp_call_dummy, "call dummy"},
5774     {bp_std_terminate, "std::terminate"},
5775     {bp_shlib_event, "shlib events"},
5776     {bp_thread_event, "thread events"},
5777     {bp_overlay_event, "overlay events"},
5778     {bp_longjmp_master, "longjmp master"},
5779     {bp_std_terminate_master, "std::terminate master"},
5780     {bp_exception_master, "exception master"},
5781     {bp_catchpoint, "catchpoint"},
5782     {bp_tracepoint, "tracepoint"},
5783     {bp_fast_tracepoint, "fast tracepoint"},
5784     {bp_static_tracepoint, "static tracepoint"},
5785     {bp_dprintf, "dprintf"},
5786     {bp_jit_event, "jit events"},
5787     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5788     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5789   };
5790
5791   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5792       || ((int) type != bptypes[(int) type].type))
5793     internal_error (__FILE__, __LINE__,
5794                     _("bptypes table does not describe type #%d."),
5795                     (int) type);
5796
5797   return bptypes[(int) type].description;
5798 }
5799
5800 DEF_VEC_I(int);
5801
5802 /* For MI, output a field named 'thread-groups' with a list as the value.
5803    For CLI, prefix the list with the string 'inf'. */
5804
5805 static void
5806 output_thread_groups (struct ui_out *uiout,
5807                       const char *field_name,
5808                       VEC(int) *inf_num,
5809                       int mi_only)
5810 {
5811   struct cleanup *back_to;
5812   int is_mi = ui_out_is_mi_like_p (uiout);
5813   int inf;
5814   int i;
5815
5816   /* For backward compatibility, don't display inferiors in CLI unless
5817      there are several.  Always display them for MI. */
5818   if (!is_mi && mi_only)
5819     return;
5820
5821   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
5822
5823   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5824     {
5825       if (is_mi)
5826         {
5827           char mi_group[10];
5828
5829           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5830           ui_out_field_string (uiout, NULL, mi_group);
5831         }
5832       else
5833         {
5834           if (i == 0)
5835             ui_out_text (uiout, " inf ");
5836           else
5837             ui_out_text (uiout, ", ");
5838         
5839           ui_out_text (uiout, plongest (inf));
5840         }
5841     }
5842
5843   do_cleanups (back_to);
5844 }
5845
5846 /* Print B to gdb_stdout.  */
5847
5848 static void
5849 print_one_breakpoint_location (struct breakpoint *b,
5850                                struct bp_location *loc,
5851                                int loc_number,
5852                                struct bp_location **last_loc,
5853                                int allflag)
5854 {
5855   struct command_line *l;
5856   static char bpenables[] = "nynny";
5857
5858   struct ui_out *uiout = current_uiout;
5859   int header_of_multiple = 0;
5860   int part_of_multiple = (loc != NULL);
5861   struct value_print_options opts;
5862
5863   get_user_print_options (&opts);
5864
5865   gdb_assert (!loc || loc_number != 0);
5866   /* See comment in print_one_breakpoint concerning treatment of
5867      breakpoints with single disabled location.  */
5868   if (loc == NULL 
5869       && (b->loc != NULL 
5870           && (b->loc->next != NULL || !b->loc->enabled)))
5871     header_of_multiple = 1;
5872   if (loc == NULL)
5873     loc = b->loc;
5874
5875   annotate_record ();
5876
5877   /* 1 */
5878   annotate_field (0);
5879   if (part_of_multiple)
5880     {
5881       char *formatted;
5882       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5883       ui_out_field_string (uiout, "number", formatted);
5884       xfree (formatted);
5885     }
5886   else
5887     {
5888       ui_out_field_int (uiout, "number", b->number);
5889     }
5890
5891   /* 2 */
5892   annotate_field (1);
5893   if (part_of_multiple)
5894     ui_out_field_skip (uiout, "type");
5895   else
5896     ui_out_field_string (uiout, "type", bptype_string (b->type));
5897
5898   /* 3 */
5899   annotate_field (2);
5900   if (part_of_multiple)
5901     ui_out_field_skip (uiout, "disp");
5902   else
5903     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5904
5905
5906   /* 4 */
5907   annotate_field (3);
5908   if (part_of_multiple)
5909     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5910   else
5911     ui_out_field_fmt (uiout, "enabled", "%c", 
5912                       bpenables[(int) b->enable_state]);
5913   ui_out_spaces (uiout, 2);
5914
5915   
5916   /* 5 and 6 */
5917   if (b->ops != NULL && b->ops->print_one != NULL)
5918     {
5919       /* Although the print_one can possibly print all locations,
5920          calling it here is not likely to get any nice result.  So,
5921          make sure there's just one location.  */
5922       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5923       b->ops->print_one (b, last_loc);
5924     }
5925   else
5926     switch (b->type)
5927       {
5928       case bp_none:
5929         internal_error (__FILE__, __LINE__,
5930                         _("print_one_breakpoint: bp_none encountered\n"));
5931         break;
5932
5933       case bp_watchpoint:
5934       case bp_hardware_watchpoint:
5935       case bp_read_watchpoint:
5936       case bp_access_watchpoint:
5937         {
5938           struct watchpoint *w = (struct watchpoint *) b;
5939
5940           /* Field 4, the address, is omitted (which makes the columns
5941              not line up too nicely with the headers, but the effect
5942              is relatively readable).  */
5943           if (opts.addressprint)
5944             ui_out_field_skip (uiout, "addr");
5945           annotate_field (5);
5946           ui_out_field_string (uiout, "what", w->exp_string);
5947         }
5948         break;
5949
5950       case bp_breakpoint:
5951       case bp_hardware_breakpoint:
5952       case bp_until:
5953       case bp_finish:
5954       case bp_longjmp:
5955       case bp_longjmp_resume:
5956       case bp_longjmp_call_dummy:
5957       case bp_exception:
5958       case bp_exception_resume:
5959       case bp_step_resume:
5960       case bp_hp_step_resume:
5961       case bp_watchpoint_scope:
5962       case bp_call_dummy:
5963       case bp_std_terminate:
5964       case bp_shlib_event:
5965       case bp_thread_event:
5966       case bp_overlay_event:
5967       case bp_longjmp_master:
5968       case bp_std_terminate_master:
5969       case bp_exception_master:
5970       case bp_tracepoint:
5971       case bp_fast_tracepoint:
5972       case bp_static_tracepoint:
5973       case bp_dprintf:
5974       case bp_jit_event:
5975       case bp_gnu_ifunc_resolver:
5976       case bp_gnu_ifunc_resolver_return:
5977         if (opts.addressprint)
5978           {
5979             annotate_field (4);
5980             if (header_of_multiple)
5981               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5982             else if (b->loc == NULL || loc->shlib_disabled)
5983               ui_out_field_string (uiout, "addr", "<PENDING>");
5984             else
5985               ui_out_field_core_addr (uiout, "addr",
5986                                       loc->gdbarch, loc->address);
5987           }
5988         annotate_field (5);
5989         if (!header_of_multiple)
5990           print_breakpoint_location (b, loc);
5991         if (b->loc)
5992           *last_loc = b->loc;
5993         break;
5994       }
5995
5996
5997   if (loc != NULL && !header_of_multiple)
5998     {
5999       struct inferior *inf;
6000       VEC(int) *inf_num = NULL;
6001       int mi_only = 1;
6002
6003       ALL_INFERIORS (inf)
6004         {
6005           if (inf->pspace == loc->pspace)
6006             VEC_safe_push (int, inf_num, inf->num);
6007         }
6008
6009         /* For backward compatibility, don't display inferiors in CLI unless
6010            there are several.  Always display for MI. */
6011         if (allflag
6012             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6013                 && (number_of_program_spaces () > 1
6014                     || number_of_inferiors () > 1)
6015                 /* LOC is for existing B, it cannot be in
6016                    moribund_locations and thus having NULL OWNER.  */
6017                 && loc->owner->type != bp_catchpoint))
6018         mi_only = 0;
6019       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6020       VEC_free (int, inf_num);
6021     }
6022
6023   if (!part_of_multiple)
6024     {
6025       if (b->thread != -1)
6026         {
6027           /* FIXME: This seems to be redundant and lost here; see the
6028              "stop only in" line a little further down.  */
6029           ui_out_text (uiout, " thread ");
6030           ui_out_field_int (uiout, "thread", b->thread);
6031         }
6032       else if (b->task != 0)
6033         {
6034           ui_out_text (uiout, " task ");
6035           ui_out_field_int (uiout, "task", b->task);
6036         }
6037     }
6038
6039   ui_out_text (uiout, "\n");
6040
6041   if (!part_of_multiple)
6042     b->ops->print_one_detail (b, uiout);
6043
6044   if (part_of_multiple && frame_id_p (b->frame_id))
6045     {
6046       annotate_field (6);
6047       ui_out_text (uiout, "\tstop only in stack frame at ");
6048       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6049          the frame ID.  */
6050       ui_out_field_core_addr (uiout, "frame",
6051                               b->gdbarch, b->frame_id.stack_addr);
6052       ui_out_text (uiout, "\n");
6053     }
6054   
6055   if (!part_of_multiple && b->cond_string)
6056     {
6057       annotate_field (7);
6058       if (is_tracepoint (b))
6059         ui_out_text (uiout, "\ttrace only if ");
6060       else
6061         ui_out_text (uiout, "\tstop only if ");
6062       ui_out_field_string (uiout, "cond", b->cond_string);
6063
6064       /* Print whether the target is doing the breakpoint's condition
6065          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6066       if (is_breakpoint (b)
6067           && breakpoint_condition_evaluation_mode ()
6068           == condition_evaluation_target)
6069         {
6070           ui_out_text (uiout, " (");
6071           ui_out_field_string (uiout, "evaluated-by",
6072                                bp_condition_evaluator (b));
6073           ui_out_text (uiout, " evals)");
6074         }
6075       ui_out_text (uiout, "\n");
6076     }
6077
6078   if (!part_of_multiple && b->thread != -1)
6079     {
6080       /* FIXME should make an annotation for this.  */
6081       ui_out_text (uiout, "\tstop only in thread ");
6082       ui_out_field_int (uiout, "thread", b->thread);
6083       ui_out_text (uiout, "\n");
6084     }
6085   
6086   if (!part_of_multiple)
6087     {
6088       if (b->hit_count)
6089         {
6090           /* FIXME should make an annotation for this.  */
6091           if (is_catchpoint (b))
6092             ui_out_text (uiout, "\tcatchpoint");
6093           else if (is_tracepoint (b))
6094             ui_out_text (uiout, "\ttracepoint");
6095           else
6096             ui_out_text (uiout, "\tbreakpoint");
6097           ui_out_text (uiout, " already hit ");
6098           ui_out_field_int (uiout, "times", b->hit_count);
6099           if (b->hit_count == 1)
6100             ui_out_text (uiout, " time\n");
6101           else
6102             ui_out_text (uiout, " times\n");
6103         }
6104       else
6105         {
6106           /* Output the count also if it is zero, but only if this is mi.  */
6107           if (ui_out_is_mi_like_p (uiout))
6108             ui_out_field_int (uiout, "times", b->hit_count);
6109         }
6110     }
6111
6112   if (!part_of_multiple && b->ignore_count)
6113     {
6114       annotate_field (8);
6115       ui_out_text (uiout, "\tignore next ");
6116       ui_out_field_int (uiout, "ignore", b->ignore_count);
6117       ui_out_text (uiout, " hits\n");
6118     }
6119
6120   /* Note that an enable count of 1 corresponds to "enable once"
6121      behavior, which is reported by the combination of enablement and
6122      disposition, so we don't need to mention it here.  */
6123   if (!part_of_multiple && b->enable_count > 1)
6124     {
6125       annotate_field (8);
6126       ui_out_text (uiout, "\tdisable after ");
6127       /* Tweak the wording to clarify that ignore and enable counts
6128          are distinct, and have additive effect.  */
6129       if (b->ignore_count)
6130         ui_out_text (uiout, "additional ");
6131       else
6132         ui_out_text (uiout, "next ");
6133       ui_out_field_int (uiout, "enable", b->enable_count);
6134       ui_out_text (uiout, " hits\n");
6135     }
6136
6137   if (!part_of_multiple && is_tracepoint (b))
6138     {
6139       struct tracepoint *tp = (struct tracepoint *) b;
6140
6141       if (tp->traceframe_usage)
6142         {
6143           ui_out_text (uiout, "\ttrace buffer usage ");
6144           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6145           ui_out_text (uiout, " bytes\n");
6146         }
6147     }
6148
6149   l = b->commands ? b->commands->commands : NULL;
6150   if (!part_of_multiple && l)
6151     {
6152       struct cleanup *script_chain;
6153
6154       annotate_field (9);
6155       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6156       print_command_lines (uiout, l, 4);
6157       do_cleanups (script_chain);
6158     }
6159
6160   if (is_tracepoint (b))
6161     {
6162       struct tracepoint *t = (struct tracepoint *) b;
6163
6164       if (!part_of_multiple && t->pass_count)
6165         {
6166           annotate_field (10);
6167           ui_out_text (uiout, "\tpass count ");
6168           ui_out_field_int (uiout, "pass", t->pass_count);
6169           ui_out_text (uiout, " \n");
6170         }
6171
6172       /* Don't display it when tracepoint or tracepoint location is
6173          pending.   */
6174       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6175         {
6176           annotate_field (11);
6177
6178           if (ui_out_is_mi_like_p (uiout))
6179             ui_out_field_string (uiout, "installed",
6180                                  loc->inserted ? "y" : "n");
6181           else
6182             {
6183               if (loc->inserted)
6184                 ui_out_text (uiout, "\t");
6185               else
6186                 ui_out_text (uiout, "\tnot ");
6187               ui_out_text (uiout, "installed on target\n");
6188             }
6189         }
6190     }
6191
6192   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6193     {
6194       if (is_watchpoint (b))
6195         {
6196           struct watchpoint *w = (struct watchpoint *) b;
6197
6198           ui_out_field_string (uiout, "original-location", w->exp_string);
6199         }
6200       else if (b->addr_string)
6201         ui_out_field_string (uiout, "original-location", b->addr_string);
6202     }
6203 }
6204
6205 static void
6206 print_one_breakpoint (struct breakpoint *b,
6207                       struct bp_location **last_loc, 
6208                       int allflag)
6209 {
6210   struct cleanup *bkpt_chain;
6211   struct ui_out *uiout = current_uiout;
6212
6213   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6214
6215   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6216   do_cleanups (bkpt_chain);
6217
6218   /* If this breakpoint has custom print function,
6219      it's already printed.  Otherwise, print individual
6220      locations, if any.  */
6221   if (b->ops == NULL || b->ops->print_one == NULL)
6222     {
6223       /* If breakpoint has a single location that is disabled, we
6224          print it as if it had several locations, since otherwise it's
6225          hard to represent "breakpoint enabled, location disabled"
6226          situation.
6227
6228          Note that while hardware watchpoints have several locations
6229          internally, that's not a property exposed to user.  */
6230       if (b->loc 
6231           && !is_hardware_watchpoint (b)
6232           && (b->loc->next || !b->loc->enabled))
6233         {
6234           struct bp_location *loc;
6235           int n = 1;
6236
6237           for (loc = b->loc; loc; loc = loc->next, ++n)
6238             {
6239               struct cleanup *inner2 =
6240                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6241               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6242               do_cleanups (inner2);
6243             }
6244         }
6245     }
6246 }
6247
6248 static int
6249 breakpoint_address_bits (struct breakpoint *b)
6250 {
6251   int print_address_bits = 0;
6252   struct bp_location *loc;
6253
6254   for (loc = b->loc; loc; loc = loc->next)
6255     {
6256       int addr_bit;
6257
6258       /* Software watchpoints that aren't watching memory don't have
6259          an address to print.  */
6260       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6261         continue;
6262
6263       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6264       if (addr_bit > print_address_bits)
6265         print_address_bits = addr_bit;
6266     }
6267
6268   return print_address_bits;
6269 }
6270
6271 struct captured_breakpoint_query_args
6272   {
6273     int bnum;
6274   };
6275
6276 static int
6277 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6278 {
6279   struct captured_breakpoint_query_args *args = data;
6280   struct breakpoint *b;
6281   struct bp_location *dummy_loc = NULL;
6282
6283   ALL_BREAKPOINTS (b)
6284     {
6285       if (args->bnum == b->number)
6286         {
6287           print_one_breakpoint (b, &dummy_loc, 0);
6288           return GDB_RC_OK;
6289         }
6290     }
6291   return GDB_RC_NONE;
6292 }
6293
6294 enum gdb_rc
6295 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6296                       char **error_message)
6297 {
6298   struct captured_breakpoint_query_args args;
6299
6300   args.bnum = bnum;
6301   /* For the moment we don't trust print_one_breakpoint() to not throw
6302      an error.  */
6303   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6304                                  error_message, RETURN_MASK_ALL) < 0)
6305     return GDB_RC_FAIL;
6306   else
6307     return GDB_RC_OK;
6308 }
6309
6310 /* Return true if this breakpoint was set by the user, false if it is
6311    internal or momentary.  */
6312
6313 int
6314 user_breakpoint_p (struct breakpoint *b)
6315 {
6316   return b->number > 0;
6317 }
6318
6319 /* Print information on user settable breakpoint (watchpoint, etc)
6320    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6321    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6322    FILTER is non-NULL, call it on each breakpoint and only include the
6323    ones for which it returns non-zero.  Return the total number of
6324    breakpoints listed.  */
6325
6326 static int
6327 breakpoint_1 (char *args, int allflag, 
6328               int (*filter) (const struct breakpoint *))
6329 {
6330   struct breakpoint *b;
6331   struct bp_location *last_loc = NULL;
6332   int nr_printable_breakpoints;
6333   struct cleanup *bkpttbl_chain;
6334   struct value_print_options opts;
6335   int print_address_bits = 0;
6336   int print_type_col_width = 14;
6337   struct ui_out *uiout = current_uiout;
6338
6339   get_user_print_options (&opts);
6340
6341   /* Compute the number of rows in the table, as well as the size
6342      required for address fields.  */
6343   nr_printable_breakpoints = 0;
6344   ALL_BREAKPOINTS (b)
6345     {
6346       /* If we have a filter, only list the breakpoints it accepts.  */
6347       if (filter && !filter (b))
6348         continue;
6349
6350       /* If we have an "args" string, it is a list of breakpoints to 
6351          accept.  Skip the others.  */
6352       if (args != NULL && *args != '\0')
6353         {
6354           if (allflag && parse_and_eval_long (args) != b->number)
6355             continue;
6356           if (!allflag && !number_is_in_list (args, b->number))
6357             continue;
6358         }
6359
6360       if (allflag || user_breakpoint_p (b))
6361         {
6362           int addr_bit, type_len;
6363
6364           addr_bit = breakpoint_address_bits (b);
6365           if (addr_bit > print_address_bits)
6366             print_address_bits = addr_bit;
6367
6368           type_len = strlen (bptype_string (b->type));
6369           if (type_len > print_type_col_width)
6370             print_type_col_width = type_len;
6371
6372           nr_printable_breakpoints++;
6373         }
6374     }
6375
6376   if (opts.addressprint)
6377     bkpttbl_chain 
6378       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6379                                              nr_printable_breakpoints,
6380                                              "BreakpointTable");
6381   else
6382     bkpttbl_chain 
6383       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6384                                              nr_printable_breakpoints,
6385                                              "BreakpointTable");
6386
6387   if (nr_printable_breakpoints > 0)
6388     annotate_breakpoints_headers ();
6389   if (nr_printable_breakpoints > 0)
6390     annotate_field (0);
6391   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6392   if (nr_printable_breakpoints > 0)
6393     annotate_field (1);
6394   ui_out_table_header (uiout, print_type_col_width, ui_left,
6395                        "type", "Type");                         /* 2 */
6396   if (nr_printable_breakpoints > 0)
6397     annotate_field (2);
6398   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6399   if (nr_printable_breakpoints > 0)
6400     annotate_field (3);
6401   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6402   if (opts.addressprint)
6403     {
6404       if (nr_printable_breakpoints > 0)
6405         annotate_field (4);
6406       if (print_address_bits <= 32)
6407         ui_out_table_header (uiout, 10, ui_left, 
6408                              "addr", "Address");                /* 5 */
6409       else
6410         ui_out_table_header (uiout, 18, ui_left, 
6411                              "addr", "Address");                /* 5 */
6412     }
6413   if (nr_printable_breakpoints > 0)
6414     annotate_field (5);
6415   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6416   ui_out_table_body (uiout);
6417   if (nr_printable_breakpoints > 0)
6418     annotate_breakpoints_table ();
6419
6420   ALL_BREAKPOINTS (b)
6421     {
6422       QUIT;
6423       /* If we have a filter, only list the breakpoints it accepts.  */
6424       if (filter && !filter (b))
6425         continue;
6426
6427       /* If we have an "args" string, it is a list of breakpoints to 
6428          accept.  Skip the others.  */
6429
6430       if (args != NULL && *args != '\0')
6431         {
6432           if (allflag)  /* maintenance info breakpoint */
6433             {
6434               if (parse_and_eval_long (args) != b->number)
6435                 continue;
6436             }
6437           else          /* all others */
6438             {
6439               if (!number_is_in_list (args, b->number))
6440                 continue;
6441             }
6442         }
6443       /* We only print out user settable breakpoints unless the
6444          allflag is set.  */
6445       if (allflag || user_breakpoint_p (b))
6446         print_one_breakpoint (b, &last_loc, allflag);
6447     }
6448
6449   do_cleanups (bkpttbl_chain);
6450
6451   if (nr_printable_breakpoints == 0)
6452     {
6453       /* If there's a filter, let the caller decide how to report
6454          empty list.  */
6455       if (!filter)
6456         {
6457           if (args == NULL || *args == '\0')
6458             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6459           else
6460             ui_out_message (uiout, 0, 
6461                             "No breakpoint or watchpoint matching '%s'.\n",
6462                             args);
6463         }
6464     }
6465   else
6466     {
6467       if (last_loc && !server_command)
6468         set_next_address (last_loc->gdbarch, last_loc->address);
6469     }
6470
6471   /* FIXME?  Should this be moved up so that it is only called when
6472      there have been breakpoints? */
6473   annotate_breakpoints_table_end ();
6474
6475   return nr_printable_breakpoints;
6476 }
6477
6478 /* Display the value of default-collect in a way that is generally
6479    compatible with the breakpoint list.  */
6480
6481 static void
6482 default_collect_info (void)
6483 {
6484   struct ui_out *uiout = current_uiout;
6485
6486   /* If it has no value (which is frequently the case), say nothing; a
6487      message like "No default-collect." gets in user's face when it's
6488      not wanted.  */
6489   if (!*default_collect)
6490     return;
6491
6492   /* The following phrase lines up nicely with per-tracepoint collect
6493      actions.  */
6494   ui_out_text (uiout, "default collect ");
6495   ui_out_field_string (uiout, "default-collect", default_collect);
6496   ui_out_text (uiout, " \n");
6497 }
6498   
6499 static void
6500 breakpoints_info (char *args, int from_tty)
6501 {
6502   breakpoint_1 (args, 0, NULL);
6503
6504   default_collect_info ();
6505 }
6506
6507 static void
6508 watchpoints_info (char *args, int from_tty)
6509 {
6510   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6511   struct ui_out *uiout = current_uiout;
6512
6513   if (num_printed == 0)
6514     {
6515       if (args == NULL || *args == '\0')
6516         ui_out_message (uiout, 0, "No watchpoints.\n");
6517       else
6518         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6519     }
6520 }
6521
6522 static void
6523 maintenance_info_breakpoints (char *args, int from_tty)
6524 {
6525   breakpoint_1 (args, 1, NULL);
6526
6527   default_collect_info ();
6528 }
6529
6530 static int
6531 breakpoint_has_pc (struct breakpoint *b,
6532                    struct program_space *pspace,
6533                    CORE_ADDR pc, struct obj_section *section)
6534 {
6535   struct bp_location *bl = b->loc;
6536
6537   for (; bl; bl = bl->next)
6538     {
6539       if (bl->pspace == pspace
6540           && bl->address == pc
6541           && (!overlay_debugging || bl->section == section))
6542         return 1;         
6543     }
6544   return 0;
6545 }
6546
6547 /* Print a message describing any user-breakpoints set at PC.  This
6548    concerns with logical breakpoints, so we match program spaces, not
6549    address spaces.  */
6550
6551 static void
6552 describe_other_breakpoints (struct gdbarch *gdbarch,
6553                             struct program_space *pspace, CORE_ADDR pc,
6554                             struct obj_section *section, int thread)
6555 {
6556   int others = 0;
6557   struct breakpoint *b;
6558
6559   ALL_BREAKPOINTS (b)
6560     others += (user_breakpoint_p (b)
6561                && breakpoint_has_pc (b, pspace, pc, section));
6562   if (others > 0)
6563     {
6564       if (others == 1)
6565         printf_filtered (_("Note: breakpoint "));
6566       else /* if (others == ???) */
6567         printf_filtered (_("Note: breakpoints "));
6568       ALL_BREAKPOINTS (b)
6569         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6570           {
6571             others--;
6572             printf_filtered ("%d", b->number);
6573             if (b->thread == -1 && thread != -1)
6574               printf_filtered (" (all threads)");
6575             else if (b->thread != -1)
6576               printf_filtered (" (thread %d)", b->thread);
6577             printf_filtered ("%s%s ",
6578                              ((b->enable_state == bp_disabled
6579                                || b->enable_state == bp_call_disabled)
6580                               ? " (disabled)"
6581                               : b->enable_state == bp_permanent 
6582                               ? " (permanent)"
6583                               : ""),
6584                              (others > 1) ? "," 
6585                              : ((others == 1) ? " and" : ""));
6586           }
6587       printf_filtered (_("also set at pc "));
6588       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6589       printf_filtered (".\n");
6590     }
6591 }
6592 \f
6593
6594 /* Return true iff it is meaningful to use the address member of
6595    BPT.  For some breakpoint types, the address member is irrelevant
6596    and it makes no sense to attempt to compare it to other addresses
6597    (or use it for any other purpose either).
6598
6599    More specifically, each of the following breakpoint types will
6600    always have a zero valued address and we don't want to mark
6601    breakpoints of any of these types to be a duplicate of an actual
6602    breakpoint at address zero:
6603
6604       bp_watchpoint
6605       bp_catchpoint
6606
6607 */
6608
6609 static int
6610 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6611 {
6612   enum bptype type = bpt->type;
6613
6614   return (type != bp_watchpoint && type != bp_catchpoint);
6615 }
6616
6617 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6618    true if LOC1 and LOC2 represent the same watchpoint location.  */
6619
6620 static int
6621 watchpoint_locations_match (struct bp_location *loc1, 
6622                             struct bp_location *loc2)
6623 {
6624   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6625   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6626
6627   /* Both of them must exist.  */
6628   gdb_assert (w1 != NULL);
6629   gdb_assert (w2 != NULL);
6630
6631   /* If the target can evaluate the condition expression in hardware,
6632      then we we need to insert both watchpoints even if they are at
6633      the same place.  Otherwise the watchpoint will only trigger when
6634      the condition of whichever watchpoint was inserted evaluates to
6635      true, not giving a chance for GDB to check the condition of the
6636      other watchpoint.  */
6637   if ((w1->cond_exp
6638        && target_can_accel_watchpoint_condition (loc1->address, 
6639                                                  loc1->length,
6640                                                  loc1->watchpoint_type,
6641                                                  w1->cond_exp))
6642       || (w2->cond_exp
6643           && target_can_accel_watchpoint_condition (loc2->address, 
6644                                                     loc2->length,
6645                                                     loc2->watchpoint_type,
6646                                                     w2->cond_exp)))
6647     return 0;
6648
6649   /* Note that this checks the owner's type, not the location's.  In
6650      case the target does not support read watchpoints, but does
6651      support access watchpoints, we'll have bp_read_watchpoint
6652      watchpoints with hw_access locations.  Those should be considered
6653      duplicates of hw_read locations.  The hw_read locations will
6654      become hw_access locations later.  */
6655   return (loc1->owner->type == loc2->owner->type
6656           && loc1->pspace->aspace == loc2->pspace->aspace
6657           && loc1->address == loc2->address
6658           && loc1->length == loc2->length);
6659 }
6660
6661 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6662    same breakpoint location.  In most targets, this can only be true
6663    if ASPACE1 matches ASPACE2.  On targets that have global
6664    breakpoints, the address space doesn't really matter.  */
6665
6666 static int
6667 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6668                           struct address_space *aspace2, CORE_ADDR addr2)
6669 {
6670   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6671            || aspace1 == aspace2)
6672           && addr1 == addr2);
6673 }
6674
6675 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6676    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6677    matches ASPACE2.  On targets that have global breakpoints, the address
6678    space doesn't really matter.  */
6679
6680 static int
6681 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6682                                 int len1, struct address_space *aspace2,
6683                                 CORE_ADDR addr2)
6684 {
6685   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6686            || aspace1 == aspace2)
6687           && addr2 >= addr1 && addr2 < addr1 + len1);
6688 }
6689
6690 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6691    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6692    matches the breakpoint's address space.  On targets that have global
6693    breakpoints, the address space doesn't really matter.  */
6694
6695 static int
6696 breakpoint_location_address_match (struct bp_location *bl,
6697                                    struct address_space *aspace,
6698                                    CORE_ADDR addr)
6699 {
6700   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6701                                     aspace, addr)
6702           || (bl->length
6703               && breakpoint_address_match_range (bl->pspace->aspace,
6704                                                  bl->address, bl->length,
6705                                                  aspace, addr)));
6706 }
6707
6708 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6709    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6710    true, otherwise returns false.  */
6711
6712 static int
6713 tracepoint_locations_match (struct bp_location *loc1,
6714                             struct bp_location *loc2)
6715 {
6716   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6717     /* Since tracepoint locations are never duplicated with others', tracepoint
6718        locations at the same address of different tracepoints are regarded as
6719        different locations.  */
6720     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6721   else
6722     return 0;
6723 }
6724
6725 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6726    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6727    represent the same location.  */
6728
6729 static int
6730 breakpoint_locations_match (struct bp_location *loc1, 
6731                             struct bp_location *loc2)
6732 {
6733   int hw_point1, hw_point2;
6734
6735   /* Both of them must not be in moribund_locations.  */
6736   gdb_assert (loc1->owner != NULL);
6737   gdb_assert (loc2->owner != NULL);
6738
6739   hw_point1 = is_hardware_watchpoint (loc1->owner);
6740   hw_point2 = is_hardware_watchpoint (loc2->owner);
6741
6742   if (hw_point1 != hw_point2)
6743     return 0;
6744   else if (hw_point1)
6745     return watchpoint_locations_match (loc1, loc2);
6746   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6747     return tracepoint_locations_match (loc1, loc2);
6748   else
6749     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6750     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6751                                      loc2->pspace->aspace, loc2->address)
6752             && loc1->length == loc2->length);
6753 }
6754
6755 static void
6756 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6757                                int bnum, int have_bnum)
6758 {
6759   /* The longest string possibly returned by hex_string_custom
6760      is 50 chars.  These must be at least that big for safety.  */
6761   char astr1[64];
6762   char astr2[64];
6763
6764   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6765   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6766   if (have_bnum)
6767     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6768              bnum, astr1, astr2);
6769   else
6770     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6771 }
6772
6773 /* Adjust a breakpoint's address to account for architectural
6774    constraints on breakpoint placement.  Return the adjusted address.
6775    Note: Very few targets require this kind of adjustment.  For most
6776    targets, this function is simply the identity function.  */
6777
6778 static CORE_ADDR
6779 adjust_breakpoint_address (struct gdbarch *gdbarch,
6780                            CORE_ADDR bpaddr, enum bptype bptype)
6781 {
6782   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6783     {
6784       /* Very few targets need any kind of breakpoint adjustment.  */
6785       return bpaddr;
6786     }
6787   else if (bptype == bp_watchpoint
6788            || bptype == bp_hardware_watchpoint
6789            || bptype == bp_read_watchpoint
6790            || bptype == bp_access_watchpoint
6791            || bptype == bp_catchpoint)
6792     {
6793       /* Watchpoints and the various bp_catch_* eventpoints should not
6794          have their addresses modified.  */
6795       return bpaddr;
6796     }
6797   else
6798     {
6799       CORE_ADDR adjusted_bpaddr;
6800
6801       /* Some targets have architectural constraints on the placement
6802          of breakpoint instructions.  Obtain the adjusted address.  */
6803       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6804
6805       /* An adjusted breakpoint address can significantly alter
6806          a user's expectations.  Print a warning if an adjustment
6807          is required.  */
6808       if (adjusted_bpaddr != bpaddr)
6809         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6810
6811       return adjusted_bpaddr;
6812     }
6813 }
6814
6815 void
6816 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6817                   struct breakpoint *owner)
6818 {
6819   memset (loc, 0, sizeof (*loc));
6820
6821   gdb_assert (ops != NULL);
6822
6823   loc->ops = ops;
6824   loc->owner = owner;
6825   loc->cond = NULL;
6826   loc->cond_bytecode = NULL;
6827   loc->shlib_disabled = 0;
6828   loc->enabled = 1;
6829
6830   switch (owner->type)
6831     {
6832     case bp_breakpoint:
6833     case bp_until:
6834     case bp_finish:
6835     case bp_longjmp:
6836     case bp_longjmp_resume:
6837     case bp_longjmp_call_dummy:
6838     case bp_exception:
6839     case bp_exception_resume:
6840     case bp_step_resume:
6841     case bp_hp_step_resume:
6842     case bp_watchpoint_scope:
6843     case bp_call_dummy:
6844     case bp_std_terminate:
6845     case bp_shlib_event:
6846     case bp_thread_event:
6847     case bp_overlay_event:
6848     case bp_jit_event:
6849     case bp_longjmp_master:
6850     case bp_std_terminate_master:
6851     case bp_exception_master:
6852     case bp_gnu_ifunc_resolver:
6853     case bp_gnu_ifunc_resolver_return:
6854     case bp_dprintf:
6855       loc->loc_type = bp_loc_software_breakpoint;
6856       mark_breakpoint_location_modified (loc);
6857       break;
6858     case bp_hardware_breakpoint:
6859       loc->loc_type = bp_loc_hardware_breakpoint;
6860       mark_breakpoint_location_modified (loc);
6861       break;
6862     case bp_hardware_watchpoint:
6863     case bp_read_watchpoint:
6864     case bp_access_watchpoint:
6865       loc->loc_type = bp_loc_hardware_watchpoint;
6866       break;
6867     case bp_watchpoint:
6868     case bp_catchpoint:
6869     case bp_tracepoint:
6870     case bp_fast_tracepoint:
6871     case bp_static_tracepoint:
6872       loc->loc_type = bp_loc_other;
6873       break;
6874     default:
6875       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6876     }
6877
6878   loc->refc = 1;
6879 }
6880
6881 /* Allocate a struct bp_location.  */
6882
6883 static struct bp_location *
6884 allocate_bp_location (struct breakpoint *bpt)
6885 {
6886   return bpt->ops->allocate_location (bpt);
6887 }
6888
6889 static void
6890 free_bp_location (struct bp_location *loc)
6891 {
6892   loc->ops->dtor (loc);
6893   xfree (loc);
6894 }
6895
6896 /* Increment reference count.  */
6897
6898 static void
6899 incref_bp_location (struct bp_location *bl)
6900 {
6901   ++bl->refc;
6902 }
6903
6904 /* Decrement reference count.  If the reference count reaches 0,
6905    destroy the bp_location.  Sets *BLP to NULL.  */
6906
6907 static void
6908 decref_bp_location (struct bp_location **blp)
6909 {
6910   gdb_assert ((*blp)->refc > 0);
6911
6912   if (--(*blp)->refc == 0)
6913     free_bp_location (*blp);
6914   *blp = NULL;
6915 }
6916
6917 /* Add breakpoint B at the end of the global breakpoint chain.  */
6918
6919 static void
6920 add_to_breakpoint_chain (struct breakpoint *b)
6921 {
6922   struct breakpoint *b1;
6923
6924   /* Add this breakpoint to the end of the chain so that a list of
6925      breakpoints will come out in order of increasing numbers.  */
6926
6927   b1 = breakpoint_chain;
6928   if (b1 == 0)
6929     breakpoint_chain = b;
6930   else
6931     {
6932       while (b1->next)
6933         b1 = b1->next;
6934       b1->next = b;
6935     }
6936 }
6937
6938 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6939
6940 static void
6941 init_raw_breakpoint_without_location (struct breakpoint *b,
6942                                       struct gdbarch *gdbarch,
6943                                       enum bptype bptype,
6944                                       const struct breakpoint_ops *ops)
6945 {
6946   memset (b, 0, sizeof (*b));
6947
6948   gdb_assert (ops != NULL);
6949
6950   b->ops = ops;
6951   b->type = bptype;
6952   b->gdbarch = gdbarch;
6953   b->language = current_language->la_language;
6954   b->input_radix = input_radix;
6955   b->thread = -1;
6956   b->enable_state = bp_enabled;
6957   b->next = 0;
6958   b->silent = 0;
6959   b->ignore_count = 0;
6960   b->commands = NULL;
6961   b->frame_id = null_frame_id;
6962   b->condition_not_parsed = 0;
6963   b->py_bp_object = NULL;
6964   b->related_breakpoint = b;
6965 }
6966
6967 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6968    that has type BPTYPE and has no locations as yet.  */
6969
6970 static struct breakpoint *
6971 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6972                                      enum bptype bptype,
6973                                      const struct breakpoint_ops *ops)
6974 {
6975   struct breakpoint *b = XNEW (struct breakpoint);
6976
6977   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6978   add_to_breakpoint_chain (b);
6979   return b;
6980 }
6981
6982 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6983    resolutions should be made as the user specified the location explicitly
6984    enough.  */
6985
6986 static void
6987 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6988 {
6989   gdb_assert (loc->owner != NULL);
6990
6991   if (loc->owner->type == bp_breakpoint
6992       || loc->owner->type == bp_hardware_breakpoint
6993       || is_tracepoint (loc->owner))
6994     {
6995       int is_gnu_ifunc;
6996       const char *function_name;
6997       CORE_ADDR func_addr;
6998
6999       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7000                                           &func_addr, NULL, &is_gnu_ifunc);
7001
7002       if (is_gnu_ifunc && !explicit_loc)
7003         {
7004           struct breakpoint *b = loc->owner;
7005
7006           gdb_assert (loc->pspace == current_program_space);
7007           if (gnu_ifunc_resolve_name (function_name,
7008                                       &loc->requested_address))
7009             {
7010               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7011               loc->address = adjust_breakpoint_address (loc->gdbarch,
7012                                                         loc->requested_address,
7013                                                         b->type);
7014             }
7015           else if (b->type == bp_breakpoint && b->loc == loc
7016                    && loc->next == NULL && b->related_breakpoint == b)
7017             {
7018               /* Create only the whole new breakpoint of this type but do not
7019                  mess more complicated breakpoints with multiple locations.  */
7020               b->type = bp_gnu_ifunc_resolver;
7021               /* Remember the resolver's address for use by the return
7022                  breakpoint.  */
7023               loc->related_address = func_addr;
7024             }
7025         }
7026
7027       if (function_name)
7028         loc->function_name = xstrdup (function_name);
7029     }
7030 }
7031
7032 /* Attempt to determine architecture of location identified by SAL.  */
7033 struct gdbarch *
7034 get_sal_arch (struct symtab_and_line sal)
7035 {
7036   if (sal.section)
7037     return get_objfile_arch (sal.section->objfile);
7038   if (sal.symtab)
7039     return get_objfile_arch (sal.symtab->objfile);
7040
7041   return NULL;
7042 }
7043
7044 /* Low level routine for partially initializing a breakpoint of type
7045    BPTYPE.  The newly created breakpoint's address, section, source
7046    file name, and line number are provided by SAL.
7047
7048    It is expected that the caller will complete the initialization of
7049    the newly created breakpoint struct as well as output any status
7050    information regarding the creation of a new breakpoint.  */
7051
7052 static void
7053 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7054                      struct symtab_and_line sal, enum bptype bptype,
7055                      const struct breakpoint_ops *ops)
7056 {
7057   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7058
7059   add_location_to_breakpoint (b, &sal);
7060
7061   if (bptype != bp_catchpoint)
7062     gdb_assert (sal.pspace != NULL);
7063
7064   /* Store the program space that was used to set the breakpoint,
7065      except for ordinary breakpoints, which are independent of the
7066      program space.  */
7067   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7068     b->pspace = sal.pspace;
7069 }
7070
7071 /* set_raw_breakpoint is a low level routine for allocating and
7072    partially initializing a breakpoint of type BPTYPE.  The newly
7073    created breakpoint's address, section, source file name, and line
7074    number are provided by SAL.  The newly created and partially
7075    initialized breakpoint is added to the breakpoint chain and
7076    is also returned as the value of this function.
7077
7078    It is expected that the caller will complete the initialization of
7079    the newly created breakpoint struct as well as output any status
7080    information regarding the creation of a new breakpoint.  In
7081    particular, set_raw_breakpoint does NOT set the breakpoint
7082    number!  Care should be taken to not allow an error to occur
7083    prior to completing the initialization of the breakpoint.  If this
7084    should happen, a bogus breakpoint will be left on the chain.  */
7085
7086 struct breakpoint *
7087 set_raw_breakpoint (struct gdbarch *gdbarch,
7088                     struct symtab_and_line sal, enum bptype bptype,
7089                     const struct breakpoint_ops *ops)
7090 {
7091   struct breakpoint *b = XNEW (struct breakpoint);
7092
7093   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7094   add_to_breakpoint_chain (b);
7095   return b;
7096 }
7097
7098
7099 /* Note that the breakpoint object B describes a permanent breakpoint
7100    instruction, hard-wired into the inferior's code.  */
7101 void
7102 make_breakpoint_permanent (struct breakpoint *b)
7103 {
7104   struct bp_location *bl;
7105
7106   b->enable_state = bp_permanent;
7107
7108   /* By definition, permanent breakpoints are already present in the
7109      code.  Mark all locations as inserted.  For now,
7110      make_breakpoint_permanent is called in just one place, so it's
7111      hard to say if it's reasonable to have permanent breakpoint with
7112      multiple locations or not, but it's easy to implement.  */
7113   for (bl = b->loc; bl; bl = bl->next)
7114     bl->inserted = 1;
7115 }
7116
7117 /* Call this routine when stepping and nexting to enable a breakpoint
7118    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7119    initiated the operation.  */
7120
7121 void
7122 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7123 {
7124   struct breakpoint *b, *b_tmp;
7125   int thread = tp->num;
7126
7127   /* To avoid having to rescan all objfile symbols at every step,
7128      we maintain a list of continually-inserted but always disabled
7129      longjmp "master" breakpoints.  Here, we simply create momentary
7130      clones of those and enable them for the requested thread.  */
7131   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7132     if (b->pspace == current_program_space
7133         && (b->type == bp_longjmp_master
7134             || b->type == bp_exception_master))
7135       {
7136         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7137         struct breakpoint *clone;
7138
7139         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7140            after their removal.  */
7141         clone = momentary_breakpoint_from_master (b, type,
7142                                                   &longjmp_breakpoint_ops);
7143         clone->thread = thread;
7144       }
7145
7146   tp->initiating_frame = frame;
7147 }
7148
7149 /* Delete all longjmp breakpoints from THREAD.  */
7150 void
7151 delete_longjmp_breakpoint (int thread)
7152 {
7153   struct breakpoint *b, *b_tmp;
7154
7155   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7156     if (b->type == bp_longjmp || b->type == bp_exception)
7157       {
7158         if (b->thread == thread)
7159           delete_breakpoint (b);
7160       }
7161 }
7162
7163 void
7164 delete_longjmp_breakpoint_at_next_stop (int thread)
7165 {
7166   struct breakpoint *b, *b_tmp;
7167
7168   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7169     if (b->type == bp_longjmp || b->type == bp_exception)
7170       {
7171         if (b->thread == thread)
7172           b->disposition = disp_del_at_next_stop;
7173       }
7174 }
7175
7176 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7177    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7178    pointer to any of them.  Return NULL if this system cannot place longjmp
7179    breakpoints.  */
7180
7181 struct breakpoint *
7182 set_longjmp_breakpoint_for_call_dummy (void)
7183 {
7184   struct breakpoint *b, *retval = NULL;
7185
7186   ALL_BREAKPOINTS (b)
7187     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7188       {
7189         struct breakpoint *new_b;
7190
7191         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7192                                                   &momentary_breakpoint_ops);
7193         new_b->thread = pid_to_thread_id (inferior_ptid);
7194
7195         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7196
7197         gdb_assert (new_b->related_breakpoint == new_b);
7198         if (retval == NULL)
7199           retval = new_b;
7200         new_b->related_breakpoint = retval;
7201         while (retval->related_breakpoint != new_b->related_breakpoint)
7202           retval = retval->related_breakpoint;
7203         retval->related_breakpoint = new_b;
7204       }
7205
7206   return retval;
7207 }
7208
7209 /* Verify all existing dummy frames and their associated breakpoints for
7210    THREAD.  Remove those which can no longer be found in the current frame
7211    stack.
7212
7213    You should call this function only at places where it is safe to currently
7214    unwind the whole stack.  Failed stack unwind would discard live dummy
7215    frames.  */
7216
7217 void
7218 check_longjmp_breakpoint_for_call_dummy (int thread)
7219 {
7220   struct breakpoint *b, *b_tmp;
7221
7222   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7223     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7224       {
7225         struct breakpoint *dummy_b = b->related_breakpoint;
7226
7227         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7228           dummy_b = dummy_b->related_breakpoint;
7229         if (dummy_b->type != bp_call_dummy
7230             || frame_find_by_id (dummy_b->frame_id) != NULL)
7231           continue;
7232         
7233         dummy_frame_discard (dummy_b->frame_id);
7234
7235         while (b->related_breakpoint != b)
7236           {
7237             if (b_tmp == b->related_breakpoint)
7238               b_tmp = b->related_breakpoint->next;
7239             delete_breakpoint (b->related_breakpoint);
7240           }
7241         delete_breakpoint (b);
7242       }
7243 }
7244
7245 void
7246 enable_overlay_breakpoints (void)
7247 {
7248   struct breakpoint *b;
7249
7250   ALL_BREAKPOINTS (b)
7251     if (b->type == bp_overlay_event)
7252     {
7253       b->enable_state = bp_enabled;
7254       update_global_location_list (1);
7255       overlay_events_enabled = 1;
7256     }
7257 }
7258
7259 void
7260 disable_overlay_breakpoints (void)
7261 {
7262   struct breakpoint *b;
7263
7264   ALL_BREAKPOINTS (b)
7265     if (b->type == bp_overlay_event)
7266     {
7267       b->enable_state = bp_disabled;
7268       update_global_location_list (0);
7269       overlay_events_enabled = 0;
7270     }
7271 }
7272
7273 /* Set an active std::terminate breakpoint for each std::terminate
7274    master breakpoint.  */
7275 void
7276 set_std_terminate_breakpoint (void)
7277 {
7278   struct breakpoint *b, *b_tmp;
7279
7280   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7281     if (b->pspace == current_program_space
7282         && b->type == bp_std_terminate_master)
7283       {
7284         momentary_breakpoint_from_master (b, bp_std_terminate,
7285                                           &momentary_breakpoint_ops);
7286       }
7287 }
7288
7289 /* Delete all the std::terminate breakpoints.  */
7290 void
7291 delete_std_terminate_breakpoint (void)
7292 {
7293   struct breakpoint *b, *b_tmp;
7294
7295   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7296     if (b->type == bp_std_terminate)
7297       delete_breakpoint (b);
7298 }
7299
7300 struct breakpoint *
7301 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7302 {
7303   struct breakpoint *b;
7304
7305   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7306                                   &internal_breakpoint_ops);
7307
7308   b->enable_state = bp_enabled;
7309   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7310   b->addr_string
7311     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7312
7313   update_global_location_list_nothrow (1);
7314
7315   return b;
7316 }
7317
7318 void
7319 remove_thread_event_breakpoints (void)
7320 {
7321   struct breakpoint *b, *b_tmp;
7322
7323   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7324     if (b->type == bp_thread_event
7325         && b->loc->pspace == current_program_space)
7326       delete_breakpoint (b);
7327 }
7328
7329 struct lang_and_radix
7330   {
7331     enum language lang;
7332     int radix;
7333   };
7334
7335 /* Create a breakpoint for JIT code registration and unregistration.  */
7336
7337 struct breakpoint *
7338 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7339 {
7340   struct breakpoint *b;
7341
7342   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7343                                   &internal_breakpoint_ops);
7344   update_global_location_list_nothrow (1);
7345   return b;
7346 }
7347
7348 /* Remove JIT code registration and unregistration breakpoint(s).  */
7349
7350 void
7351 remove_jit_event_breakpoints (void)
7352 {
7353   struct breakpoint *b, *b_tmp;
7354
7355   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7356     if (b->type == bp_jit_event
7357         && b->loc->pspace == current_program_space)
7358       delete_breakpoint (b);
7359 }
7360
7361 void
7362 remove_solib_event_breakpoints (void)
7363 {
7364   struct breakpoint *b, *b_tmp;
7365
7366   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7367     if (b->type == bp_shlib_event
7368         && b->loc->pspace == current_program_space)
7369       delete_breakpoint (b);
7370 }
7371
7372 struct breakpoint *
7373 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7374 {
7375   struct breakpoint *b;
7376
7377   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7378                                   &internal_breakpoint_ops);
7379   update_global_location_list_nothrow (1);
7380   return b;
7381 }
7382
7383 /* Disable any breakpoints that are on code in shared libraries.  Only
7384    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7385
7386 void
7387 disable_breakpoints_in_shlibs (void)
7388 {
7389   struct bp_location *loc, **locp_tmp;
7390
7391   ALL_BP_LOCATIONS (loc, locp_tmp)
7392   {
7393     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7394     struct breakpoint *b = loc->owner;
7395
7396     /* We apply the check to all breakpoints, including disabled for
7397        those with loc->duplicate set.  This is so that when breakpoint
7398        becomes enabled, or the duplicate is removed, gdb will try to
7399        insert all breakpoints.  If we don't set shlib_disabled here,
7400        we'll try to insert those breakpoints and fail.  */
7401     if (((b->type == bp_breakpoint)
7402          || (b->type == bp_jit_event)
7403          || (b->type == bp_hardware_breakpoint)
7404          || (is_tracepoint (b)))
7405         && loc->pspace == current_program_space
7406         && !loc->shlib_disabled
7407         && solib_name_from_address (loc->pspace, loc->address)
7408         )
7409       {
7410         loc->shlib_disabled = 1;
7411       }
7412   }
7413 }
7414
7415 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7416    library.  Only apply to enabled breakpoints, disabled ones can just stay
7417    disabled.  */
7418
7419 static void
7420 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7421 {
7422   struct bp_location *loc, **locp_tmp;
7423   int disabled_shlib_breaks = 0;
7424
7425   /* SunOS a.out shared libraries are always mapped, so do not
7426      disable breakpoints; they will only be reported as unloaded
7427      through clear_solib when GDB discards its shared library
7428      list.  See clear_solib for more information.  */
7429   if (exec_bfd != NULL
7430       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7431     return;
7432
7433   ALL_BP_LOCATIONS (loc, locp_tmp)
7434   {
7435     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7436     struct breakpoint *b = loc->owner;
7437
7438     if (solib->pspace == loc->pspace
7439         && !loc->shlib_disabled
7440         && (((b->type == bp_breakpoint
7441               || b->type == bp_jit_event
7442               || b->type == bp_hardware_breakpoint)
7443              && (loc->loc_type == bp_loc_hardware_breakpoint
7444                  || loc->loc_type == bp_loc_software_breakpoint))
7445             || is_tracepoint (b))
7446         && solib_contains_address_p (solib, loc->address))
7447       {
7448         loc->shlib_disabled = 1;
7449         /* At this point, we cannot rely on remove_breakpoint
7450            succeeding so we must mark the breakpoint as not inserted
7451            to prevent future errors occurring in remove_breakpoints.  */
7452         loc->inserted = 0;
7453
7454         /* This may cause duplicate notifications for the same breakpoint.  */
7455         observer_notify_breakpoint_modified (b);
7456
7457         if (!disabled_shlib_breaks)
7458           {
7459             target_terminal_ours_for_output ();
7460             warning (_("Temporarily disabling breakpoints "
7461                        "for unloaded shared library \"%s\""),
7462                      solib->so_name);
7463           }
7464         disabled_shlib_breaks = 1;
7465       }
7466   }
7467 }
7468
7469 /* FORK & VFORK catchpoints.  */
7470
7471 /* An instance of this type is used to represent a fork or vfork
7472    catchpoint.  It includes a "struct breakpoint" as a kind of base
7473    class; users downcast to "struct breakpoint *" when needed.  A
7474    breakpoint is really of this type iff its ops pointer points to
7475    CATCH_FORK_BREAKPOINT_OPS.  */
7476
7477 struct fork_catchpoint
7478 {
7479   /* The base class.  */
7480   struct breakpoint base;
7481
7482   /* Process id of a child process whose forking triggered this
7483      catchpoint.  This field is only valid immediately after this
7484      catchpoint has triggered.  */
7485   ptid_t forked_inferior_pid;
7486 };
7487
7488 /* Implement the "insert" breakpoint_ops method for fork
7489    catchpoints.  */
7490
7491 static int
7492 insert_catch_fork (struct bp_location *bl)
7493 {
7494   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7495 }
7496
7497 /* Implement the "remove" breakpoint_ops method for fork
7498    catchpoints.  */
7499
7500 static int
7501 remove_catch_fork (struct bp_location *bl)
7502 {
7503   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7504 }
7505
7506 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7507    catchpoints.  */
7508
7509 static int
7510 breakpoint_hit_catch_fork (const struct bp_location *bl,
7511                            struct address_space *aspace, CORE_ADDR bp_addr,
7512                            const struct target_waitstatus *ws)
7513 {
7514   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7515
7516   if (ws->kind != TARGET_WAITKIND_FORKED)
7517     return 0;
7518
7519   c->forked_inferior_pid = ws->value.related_pid;
7520   return 1;
7521 }
7522
7523 /* Implement the "print_it" breakpoint_ops method for fork
7524    catchpoints.  */
7525
7526 static enum print_stop_action
7527 print_it_catch_fork (bpstat bs)
7528 {
7529   struct ui_out *uiout = current_uiout;
7530   struct breakpoint *b = bs->breakpoint_at;
7531   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7532
7533   annotate_catchpoint (b->number);
7534   if (b->disposition == disp_del)
7535     ui_out_text (uiout, "\nTemporary catchpoint ");
7536   else
7537     ui_out_text (uiout, "\nCatchpoint ");
7538   if (ui_out_is_mi_like_p (uiout))
7539     {
7540       ui_out_field_string (uiout, "reason",
7541                            async_reason_lookup (EXEC_ASYNC_FORK));
7542       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7543     }
7544   ui_out_field_int (uiout, "bkptno", b->number);
7545   ui_out_text (uiout, " (forked process ");
7546   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7547   ui_out_text (uiout, "), ");
7548   return PRINT_SRC_AND_LOC;
7549 }
7550
7551 /* Implement the "print_one" breakpoint_ops method for fork
7552    catchpoints.  */
7553
7554 static void
7555 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7556 {
7557   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7558   struct value_print_options opts;
7559   struct ui_out *uiout = current_uiout;
7560
7561   get_user_print_options (&opts);
7562
7563   /* Field 4, the address, is omitted (which makes the columns not
7564      line up too nicely with the headers, but the effect is relatively
7565      readable).  */
7566   if (opts.addressprint)
7567     ui_out_field_skip (uiout, "addr");
7568   annotate_field (5);
7569   ui_out_text (uiout, "fork");
7570   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7571     {
7572       ui_out_text (uiout, ", process ");
7573       ui_out_field_int (uiout, "what",
7574                         ptid_get_pid (c->forked_inferior_pid));
7575       ui_out_spaces (uiout, 1);
7576     }
7577
7578   if (ui_out_is_mi_like_p (uiout))
7579     ui_out_field_string (uiout, "catch-type", "fork");
7580 }
7581
7582 /* Implement the "print_mention" breakpoint_ops method for fork
7583    catchpoints.  */
7584
7585 static void
7586 print_mention_catch_fork (struct breakpoint *b)
7587 {
7588   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7589 }
7590
7591 /* Implement the "print_recreate" breakpoint_ops method for fork
7592    catchpoints.  */
7593
7594 static void
7595 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7596 {
7597   fprintf_unfiltered (fp, "catch fork");
7598   print_recreate_thread (b, fp);
7599 }
7600
7601 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7602
7603 static struct breakpoint_ops catch_fork_breakpoint_ops;
7604
7605 /* Implement the "insert" breakpoint_ops method for vfork
7606    catchpoints.  */
7607
7608 static int
7609 insert_catch_vfork (struct bp_location *bl)
7610 {
7611   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7612 }
7613
7614 /* Implement the "remove" breakpoint_ops method for vfork
7615    catchpoints.  */
7616
7617 static int
7618 remove_catch_vfork (struct bp_location *bl)
7619 {
7620   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7621 }
7622
7623 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7624    catchpoints.  */
7625
7626 static int
7627 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7628                             struct address_space *aspace, CORE_ADDR bp_addr,
7629                             const struct target_waitstatus *ws)
7630 {
7631   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7632
7633   if (ws->kind != TARGET_WAITKIND_VFORKED)
7634     return 0;
7635
7636   c->forked_inferior_pid = ws->value.related_pid;
7637   return 1;
7638 }
7639
7640 /* Implement the "print_it" breakpoint_ops method for vfork
7641    catchpoints.  */
7642
7643 static enum print_stop_action
7644 print_it_catch_vfork (bpstat bs)
7645 {
7646   struct ui_out *uiout = current_uiout;
7647   struct breakpoint *b = bs->breakpoint_at;
7648   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7649
7650   annotate_catchpoint (b->number);
7651   if (b->disposition == disp_del)
7652     ui_out_text (uiout, "\nTemporary catchpoint ");
7653   else
7654     ui_out_text (uiout, "\nCatchpoint ");
7655   if (ui_out_is_mi_like_p (uiout))
7656     {
7657       ui_out_field_string (uiout, "reason",
7658                            async_reason_lookup (EXEC_ASYNC_VFORK));
7659       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7660     }
7661   ui_out_field_int (uiout, "bkptno", b->number);
7662   ui_out_text (uiout, " (vforked process ");
7663   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7664   ui_out_text (uiout, "), ");
7665   return PRINT_SRC_AND_LOC;
7666 }
7667
7668 /* Implement the "print_one" breakpoint_ops method for vfork
7669    catchpoints.  */
7670
7671 static void
7672 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7673 {
7674   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7675   struct value_print_options opts;
7676   struct ui_out *uiout = current_uiout;
7677
7678   get_user_print_options (&opts);
7679   /* Field 4, the address, is omitted (which makes the columns not
7680      line up too nicely with the headers, but the effect is relatively
7681      readable).  */
7682   if (opts.addressprint)
7683     ui_out_field_skip (uiout, "addr");
7684   annotate_field (5);
7685   ui_out_text (uiout, "vfork");
7686   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7687     {
7688       ui_out_text (uiout, ", process ");
7689       ui_out_field_int (uiout, "what",
7690                         ptid_get_pid (c->forked_inferior_pid));
7691       ui_out_spaces (uiout, 1);
7692     }
7693
7694   if (ui_out_is_mi_like_p (uiout))
7695     ui_out_field_string (uiout, "catch-type", "vfork");
7696 }
7697
7698 /* Implement the "print_mention" breakpoint_ops method for vfork
7699    catchpoints.  */
7700
7701 static void
7702 print_mention_catch_vfork (struct breakpoint *b)
7703 {
7704   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7705 }
7706
7707 /* Implement the "print_recreate" breakpoint_ops method for vfork
7708    catchpoints.  */
7709
7710 static void
7711 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7712 {
7713   fprintf_unfiltered (fp, "catch vfork");
7714   print_recreate_thread (b, fp);
7715 }
7716
7717 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7718
7719 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7720
7721 /* An instance of this type is used to represent an solib catchpoint.
7722    It includes a "struct breakpoint" as a kind of base class; users
7723    downcast to "struct breakpoint *" when needed.  A breakpoint is
7724    really of this type iff its ops pointer points to
7725    CATCH_SOLIB_BREAKPOINT_OPS.  */
7726
7727 struct solib_catchpoint
7728 {
7729   /* The base class.  */
7730   struct breakpoint base;
7731
7732   /* True for "catch load", false for "catch unload".  */
7733   unsigned char is_load;
7734
7735   /* Regular expression to match, if any.  COMPILED is only valid when
7736      REGEX is non-NULL.  */
7737   char *regex;
7738   regex_t compiled;
7739 };
7740
7741 static void
7742 dtor_catch_solib (struct breakpoint *b)
7743 {
7744   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7745
7746   if (self->regex)
7747     regfree (&self->compiled);
7748   xfree (self->regex);
7749
7750   base_breakpoint_ops.dtor (b);
7751 }
7752
7753 static int
7754 insert_catch_solib (struct bp_location *ignore)
7755 {
7756   return 0;
7757 }
7758
7759 static int
7760 remove_catch_solib (struct bp_location *ignore)
7761 {
7762   return 0;
7763 }
7764
7765 static int
7766 breakpoint_hit_catch_solib (const struct bp_location *bl,
7767                             struct address_space *aspace,
7768                             CORE_ADDR bp_addr,
7769                             const struct target_waitstatus *ws)
7770 {
7771   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7772   struct breakpoint *other;
7773
7774   if (ws->kind == TARGET_WAITKIND_LOADED)
7775     return 1;
7776
7777   ALL_BREAKPOINTS (other)
7778   {
7779     struct bp_location *other_bl;
7780
7781     if (other == bl->owner)
7782       continue;
7783
7784     if (other->type != bp_shlib_event)
7785       continue;
7786
7787     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7788       continue;
7789
7790     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7791       {
7792         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7793           return 1;
7794       }
7795   }
7796
7797   return 0;
7798 }
7799
7800 static void
7801 check_status_catch_solib (struct bpstats *bs)
7802 {
7803   struct solib_catchpoint *self
7804     = (struct solib_catchpoint *) bs->breakpoint_at;
7805   int ix;
7806
7807   if (self->is_load)
7808     {
7809       struct so_list *iter;
7810
7811       for (ix = 0;
7812            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7813                         ix, iter);
7814            ++ix)
7815         {
7816           if (!self->regex
7817               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7818             return;
7819         }
7820     }
7821   else
7822     {
7823       char *iter;
7824
7825       for (ix = 0;
7826            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7827                         ix, iter);
7828            ++ix)
7829         {
7830           if (!self->regex
7831               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7832             return;
7833         }
7834     }
7835
7836   bs->stop = 0;
7837   bs->print_it = print_it_noop;
7838 }
7839
7840 static enum print_stop_action
7841 print_it_catch_solib (bpstat bs)
7842 {
7843   struct breakpoint *b = bs->breakpoint_at;
7844   struct ui_out *uiout = current_uiout;
7845
7846   annotate_catchpoint (b->number);
7847   if (b->disposition == disp_del)
7848     ui_out_text (uiout, "\nTemporary catchpoint ");
7849   else
7850     ui_out_text (uiout, "\nCatchpoint ");
7851   ui_out_field_int (uiout, "bkptno", b->number);
7852   ui_out_text (uiout, "\n");
7853   if (ui_out_is_mi_like_p (uiout))
7854     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7855   print_solib_event (1);
7856   return PRINT_SRC_AND_LOC;
7857 }
7858
7859 static void
7860 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7861 {
7862   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7863   struct value_print_options opts;
7864   struct ui_out *uiout = current_uiout;
7865   char *msg;
7866
7867   get_user_print_options (&opts);
7868   /* Field 4, the address, is omitted (which makes the columns not
7869      line up too nicely with the headers, but the effect is relatively
7870      readable).  */
7871   if (opts.addressprint)
7872     {
7873       annotate_field (4);
7874       ui_out_field_skip (uiout, "addr");
7875     }
7876
7877   annotate_field (5);
7878   if (self->is_load)
7879     {
7880       if (self->regex)
7881         msg = xstrprintf (_("load of library matching %s"), self->regex);
7882       else
7883         msg = xstrdup (_("load of library"));
7884     }
7885   else
7886     {
7887       if (self->regex)
7888         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7889       else
7890         msg = xstrdup (_("unload of library"));
7891     }
7892   ui_out_field_string (uiout, "what", msg);
7893   xfree (msg);
7894
7895   if (ui_out_is_mi_like_p (uiout))
7896     ui_out_field_string (uiout, "catch-type",
7897                          self->is_load ? "load" : "unload");
7898 }
7899
7900 static void
7901 print_mention_catch_solib (struct breakpoint *b)
7902 {
7903   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7904
7905   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7906                    self->is_load ? "load" : "unload");
7907 }
7908
7909 static void
7910 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7911 {
7912   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7913
7914   fprintf_unfiltered (fp, "%s %s",
7915                       b->disposition == disp_del ? "tcatch" : "catch",
7916                       self->is_load ? "load" : "unload");
7917   if (self->regex)
7918     fprintf_unfiltered (fp, " %s", self->regex);
7919   fprintf_unfiltered (fp, "\n");
7920 }
7921
7922 static struct breakpoint_ops catch_solib_breakpoint_ops;
7923
7924 /* Shared helper function (MI and CLI) for creating and installing
7925    a shared object event catchpoint.  If IS_LOAD is non-zero then
7926    the events to be caught are load events, otherwise they are
7927    unload events.  If IS_TEMP is non-zero the catchpoint is a
7928    temporary one.  If ENABLED is non-zero the catchpoint is
7929    created in an enabled state.  */
7930
7931 void
7932 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7933 {
7934   struct solib_catchpoint *c;
7935   struct gdbarch *gdbarch = get_current_arch ();
7936   struct cleanup *cleanup;
7937
7938   if (!arg)
7939     arg = "";
7940   arg = skip_spaces (arg);
7941
7942   c = XCNEW (struct solib_catchpoint);
7943   cleanup = make_cleanup (xfree, c);
7944
7945   if (*arg != '\0')
7946     {
7947       int errcode;
7948
7949       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7950       if (errcode != 0)
7951         {
7952           char *err = get_regcomp_error (errcode, &c->compiled);
7953
7954           make_cleanup (xfree, err);
7955           error (_("Invalid regexp (%s): %s"), err, arg);
7956         }
7957       c->regex = xstrdup (arg);
7958     }
7959
7960   c->is_load = is_load;
7961   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
7962                    &catch_solib_breakpoint_ops);
7963
7964   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
7965
7966   discard_cleanups (cleanup);
7967   install_breakpoint (0, &c->base, 1);
7968 }
7969
7970 /* A helper function that does all the work for "catch load" and
7971    "catch unload".  */
7972
7973 static void
7974 catch_load_or_unload (char *arg, int from_tty, int is_load,
7975                       struct cmd_list_element *command)
7976 {
7977   int tempflag;
7978   const int enabled = 1;
7979
7980   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7981
7982   add_solib_catchpoint (arg, is_load, tempflag, enabled);
7983 }
7984
7985 static void
7986 catch_load_command_1 (char *arg, int from_tty,
7987                       struct cmd_list_element *command)
7988 {
7989   catch_load_or_unload (arg, from_tty, 1, command);
7990 }
7991
7992 static void
7993 catch_unload_command_1 (char *arg, int from_tty,
7994                         struct cmd_list_element *command)
7995 {
7996   catch_load_or_unload (arg, from_tty, 0, command);
7997 }
7998
7999 /* An instance of this type is used to represent a syscall catchpoint.
8000    It includes a "struct breakpoint" as a kind of base class; users
8001    downcast to "struct breakpoint *" when needed.  A breakpoint is
8002    really of this type iff its ops pointer points to
8003    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8004
8005 struct syscall_catchpoint
8006 {
8007   /* The base class.  */
8008   struct breakpoint base;
8009
8010   /* Syscall numbers used for the 'catch syscall' feature.  If no
8011      syscall has been specified for filtering, its value is NULL.
8012      Otherwise, it holds a list of all syscalls to be caught.  The
8013      list elements are allocated with xmalloc.  */
8014   VEC(int) *syscalls_to_be_caught;
8015 };
8016
8017 /* Implement the "dtor" breakpoint_ops method for syscall
8018    catchpoints.  */
8019
8020 static void
8021 dtor_catch_syscall (struct breakpoint *b)
8022 {
8023   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8024
8025   VEC_free (int, c->syscalls_to_be_caught);
8026
8027   base_breakpoint_ops.dtor (b);
8028 }
8029
8030 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8031
8032 struct catch_syscall_inferior_data
8033 {
8034   /* We keep a count of the number of times the user has requested a
8035      particular syscall to be tracked, and pass this information to the
8036      target.  This lets capable targets implement filtering directly.  */
8037
8038   /* Number of times that "any" syscall is requested.  */
8039   int any_syscall_count;
8040
8041   /* Count of each system call.  */
8042   VEC(int) *syscalls_counts;
8043
8044   /* This counts all syscall catch requests, so we can readily determine
8045      if any catching is necessary.  */
8046   int total_syscalls_count;
8047 };
8048
8049 static struct catch_syscall_inferior_data*
8050 get_catch_syscall_inferior_data (struct inferior *inf)
8051 {
8052   struct catch_syscall_inferior_data *inf_data;
8053
8054   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8055   if (inf_data == NULL)
8056     {
8057       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8058       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8059     }
8060
8061   return inf_data;
8062 }
8063
8064 static void
8065 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8066 {
8067   xfree (arg);
8068 }
8069
8070
8071 /* Implement the "insert" breakpoint_ops method for syscall
8072    catchpoints.  */
8073
8074 static int
8075 insert_catch_syscall (struct bp_location *bl)
8076 {
8077   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8078   struct inferior *inf = current_inferior ();
8079   struct catch_syscall_inferior_data *inf_data
8080     = get_catch_syscall_inferior_data (inf);
8081
8082   ++inf_data->total_syscalls_count;
8083   if (!c->syscalls_to_be_caught)
8084     ++inf_data->any_syscall_count;
8085   else
8086     {
8087       int i, iter;
8088
8089       for (i = 0;
8090            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8091            i++)
8092         {
8093           int elem;
8094
8095           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8096             {
8097               int old_size = VEC_length (int, inf_data->syscalls_counts);
8098               uintptr_t vec_addr_offset
8099                 = old_size * ((uintptr_t) sizeof (int));
8100               uintptr_t vec_addr;
8101               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8102               vec_addr = ((uintptr_t) VEC_address (int,
8103                                                   inf_data->syscalls_counts)
8104                           + vec_addr_offset);
8105               memset ((void *) vec_addr, 0,
8106                       (iter + 1 - old_size) * sizeof (int));
8107             }
8108           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8109           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8110         }
8111     }
8112
8113   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8114                                         inf_data->total_syscalls_count != 0,
8115                                         inf_data->any_syscall_count,
8116                                         VEC_length (int,
8117                                                     inf_data->syscalls_counts),
8118                                         VEC_address (int,
8119                                                      inf_data->syscalls_counts));
8120 }
8121
8122 /* Implement the "remove" breakpoint_ops method for syscall
8123    catchpoints.  */
8124
8125 static int
8126 remove_catch_syscall (struct bp_location *bl)
8127 {
8128   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8129   struct inferior *inf = current_inferior ();
8130   struct catch_syscall_inferior_data *inf_data
8131     = get_catch_syscall_inferior_data (inf);
8132
8133   --inf_data->total_syscalls_count;
8134   if (!c->syscalls_to_be_caught)
8135     --inf_data->any_syscall_count;
8136   else
8137     {
8138       int i, iter;
8139
8140       for (i = 0;
8141            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8142            i++)
8143         {
8144           int elem;
8145           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8146             /* Shouldn't happen.  */
8147             continue;
8148           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8149           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8150         }
8151     }
8152
8153   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8154                                         inf_data->total_syscalls_count != 0,
8155                                         inf_data->any_syscall_count,
8156                                         VEC_length (int,
8157                                                     inf_data->syscalls_counts),
8158                                         VEC_address (int,
8159                                                      inf_data->syscalls_counts));
8160 }
8161
8162 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8163    catchpoints.  */
8164
8165 static int
8166 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8167                               struct address_space *aspace, CORE_ADDR bp_addr,
8168                               const struct target_waitstatus *ws)
8169 {
8170   /* We must check if we are catching specific syscalls in this
8171      breakpoint.  If we are, then we must guarantee that the called
8172      syscall is the same syscall we are catching.  */
8173   int syscall_number = 0;
8174   const struct syscall_catchpoint *c
8175     = (const struct syscall_catchpoint *) bl->owner;
8176
8177   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8178       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8179     return 0;
8180
8181   syscall_number = ws->value.syscall_number;
8182
8183   /* Now, checking if the syscall is the same.  */
8184   if (c->syscalls_to_be_caught)
8185     {
8186       int i, iter;
8187
8188       for (i = 0;
8189            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8190            i++)
8191         if (syscall_number == iter)
8192           break;
8193       /* Not the same.  */
8194       if (!iter)
8195         return 0;
8196     }
8197
8198   return 1;
8199 }
8200
8201 /* Implement the "print_it" breakpoint_ops method for syscall
8202    catchpoints.  */
8203
8204 static enum print_stop_action
8205 print_it_catch_syscall (bpstat bs)
8206 {
8207   struct ui_out *uiout = current_uiout;
8208   struct breakpoint *b = bs->breakpoint_at;
8209   /* These are needed because we want to know in which state a
8210      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8211      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8212      must print "called syscall" or "returned from syscall".  */
8213   ptid_t ptid;
8214   struct target_waitstatus last;
8215   struct syscall s;
8216
8217   get_last_target_status (&ptid, &last);
8218
8219   get_syscall_by_number (last.value.syscall_number, &s);
8220
8221   annotate_catchpoint (b->number);
8222
8223   if (b->disposition == disp_del)
8224     ui_out_text (uiout, "\nTemporary catchpoint ");
8225   else
8226     ui_out_text (uiout, "\nCatchpoint ");
8227   if (ui_out_is_mi_like_p (uiout))
8228     {
8229       ui_out_field_string (uiout, "reason",
8230                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8231                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8232                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8233       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8234     }
8235   ui_out_field_int (uiout, "bkptno", b->number);
8236
8237   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8238     ui_out_text (uiout, " (call to syscall ");
8239   else
8240     ui_out_text (uiout, " (returned from syscall ");
8241
8242   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8243     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8244   if (s.name != NULL)
8245     ui_out_field_string (uiout, "syscall-name", s.name);
8246
8247   ui_out_text (uiout, "), ");
8248
8249   return PRINT_SRC_AND_LOC;
8250 }
8251
8252 /* Implement the "print_one" breakpoint_ops method for syscall
8253    catchpoints.  */
8254
8255 static void
8256 print_one_catch_syscall (struct breakpoint *b,
8257                          struct bp_location **last_loc)
8258 {
8259   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8260   struct value_print_options opts;
8261   struct ui_out *uiout = current_uiout;
8262
8263   get_user_print_options (&opts);
8264   /* Field 4, the address, is omitted (which makes the columns not
8265      line up too nicely with the headers, but the effect is relatively
8266      readable).  */
8267   if (opts.addressprint)
8268     ui_out_field_skip (uiout, "addr");
8269   annotate_field (5);
8270
8271   if (c->syscalls_to_be_caught
8272       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8273     ui_out_text (uiout, "syscalls \"");
8274   else
8275     ui_out_text (uiout, "syscall \"");
8276
8277   if (c->syscalls_to_be_caught)
8278     {
8279       int i, iter;
8280       char *text = xstrprintf ("%s", "");
8281
8282       for (i = 0;
8283            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8284            i++)
8285         {
8286           char *x = text;
8287           struct syscall s;
8288           get_syscall_by_number (iter, &s);
8289
8290           if (s.name != NULL)
8291             text = xstrprintf ("%s%s, ", text, s.name);
8292           else
8293             text = xstrprintf ("%s%d, ", text, iter);
8294
8295           /* We have to xfree the last 'text' (now stored at 'x')
8296              because xstrprintf dynamically allocates new space for it
8297              on every call.  */
8298           xfree (x);
8299         }
8300       /* Remove the last comma.  */
8301       text[strlen (text) - 2] = '\0';
8302       ui_out_field_string (uiout, "what", text);
8303     }
8304   else
8305     ui_out_field_string (uiout, "what", "<any syscall>");
8306   ui_out_text (uiout, "\" ");
8307
8308   if (ui_out_is_mi_like_p (uiout))
8309     ui_out_field_string (uiout, "catch-type", "syscall");
8310 }
8311
8312 /* Implement the "print_mention" breakpoint_ops method for syscall
8313    catchpoints.  */
8314
8315 static void
8316 print_mention_catch_syscall (struct breakpoint *b)
8317 {
8318   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8319
8320   if (c->syscalls_to_be_caught)
8321     {
8322       int i, iter;
8323
8324       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8325         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8326       else
8327         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8328
8329       for (i = 0;
8330            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8331            i++)
8332         {
8333           struct syscall s;
8334           get_syscall_by_number (iter, &s);
8335
8336           if (s.name)
8337             printf_filtered (" '%s' [%d]", s.name, s.number);
8338           else
8339             printf_filtered (" %d", s.number);
8340         }
8341       printf_filtered (")");
8342     }
8343   else
8344     printf_filtered (_("Catchpoint %d (any syscall)"),
8345                      b->number);
8346 }
8347
8348 /* Implement the "print_recreate" breakpoint_ops method for syscall
8349    catchpoints.  */
8350
8351 static void
8352 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8353 {
8354   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8355
8356   fprintf_unfiltered (fp, "catch syscall");
8357
8358   if (c->syscalls_to_be_caught)
8359     {
8360       int i, iter;
8361
8362       for (i = 0;
8363            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8364            i++)
8365         {
8366           struct syscall s;
8367
8368           get_syscall_by_number (iter, &s);
8369           if (s.name)
8370             fprintf_unfiltered (fp, " %s", s.name);
8371           else
8372             fprintf_unfiltered (fp, " %d", s.number);
8373         }
8374     }
8375   print_recreate_thread (b, fp);
8376 }
8377
8378 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8379
8380 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8381
8382 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8383
8384 static int
8385 syscall_catchpoint_p (struct breakpoint *b)
8386 {
8387   return (b->ops == &catch_syscall_breakpoint_ops);
8388 }
8389
8390 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8391    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8392    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8393    the breakpoint_ops structure associated to the catchpoint.  */
8394
8395 void
8396 init_catchpoint (struct breakpoint *b,
8397                  struct gdbarch *gdbarch, int tempflag,
8398                  char *cond_string,
8399                  const struct breakpoint_ops *ops)
8400 {
8401   struct symtab_and_line sal;
8402
8403   init_sal (&sal);
8404   sal.pspace = current_program_space;
8405
8406   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8407
8408   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8409   b->disposition = tempflag ? disp_del : disp_donttouch;
8410 }
8411
8412 void
8413 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8414 {
8415   add_to_breakpoint_chain (b);
8416   set_breakpoint_number (internal, b);
8417   if (is_tracepoint (b))
8418     set_tracepoint_count (breakpoint_count);
8419   if (!internal)
8420     mention (b);
8421   observer_notify_breakpoint_created (b);
8422
8423   if (update_gll)
8424     update_global_location_list (1);
8425 }
8426
8427 static void
8428 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8429                                     int tempflag, char *cond_string,
8430                                     const struct breakpoint_ops *ops)
8431 {
8432   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8433
8434   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8435
8436   c->forked_inferior_pid = null_ptid;
8437
8438   install_breakpoint (0, &c->base, 1);
8439 }
8440
8441 /* Exec catchpoints.  */
8442
8443 /* An instance of this type is used to represent an exec catchpoint.
8444    It includes a "struct breakpoint" as a kind of base class; users
8445    downcast to "struct breakpoint *" when needed.  A breakpoint is
8446    really of this type iff its ops pointer points to
8447    CATCH_EXEC_BREAKPOINT_OPS.  */
8448
8449 struct exec_catchpoint
8450 {
8451   /* The base class.  */
8452   struct breakpoint base;
8453
8454   /* Filename of a program whose exec triggered this catchpoint.
8455      This field is only valid immediately after this catchpoint has
8456      triggered.  */
8457   char *exec_pathname;
8458 };
8459
8460 /* Implement the "dtor" breakpoint_ops method for exec
8461    catchpoints.  */
8462
8463 static void
8464 dtor_catch_exec (struct breakpoint *b)
8465 {
8466   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8467
8468   xfree (c->exec_pathname);
8469
8470   base_breakpoint_ops.dtor (b);
8471 }
8472
8473 static int
8474 insert_catch_exec (struct bp_location *bl)
8475 {
8476   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8477 }
8478
8479 static int
8480 remove_catch_exec (struct bp_location *bl)
8481 {
8482   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8483 }
8484
8485 static int
8486 breakpoint_hit_catch_exec (const struct bp_location *bl,
8487                            struct address_space *aspace, CORE_ADDR bp_addr,
8488                            const struct target_waitstatus *ws)
8489 {
8490   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8491
8492   if (ws->kind != TARGET_WAITKIND_EXECD)
8493     return 0;
8494
8495   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8496   return 1;
8497 }
8498
8499 static enum print_stop_action
8500 print_it_catch_exec (bpstat bs)
8501 {
8502   struct ui_out *uiout = current_uiout;
8503   struct breakpoint *b = bs->breakpoint_at;
8504   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8505
8506   annotate_catchpoint (b->number);
8507   if (b->disposition == disp_del)
8508     ui_out_text (uiout, "\nTemporary catchpoint ");
8509   else
8510     ui_out_text (uiout, "\nCatchpoint ");
8511   if (ui_out_is_mi_like_p (uiout))
8512     {
8513       ui_out_field_string (uiout, "reason",
8514                            async_reason_lookup (EXEC_ASYNC_EXEC));
8515       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8516     }
8517   ui_out_field_int (uiout, "bkptno", b->number);
8518   ui_out_text (uiout, " (exec'd ");
8519   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8520   ui_out_text (uiout, "), ");
8521
8522   return PRINT_SRC_AND_LOC;
8523 }
8524
8525 static void
8526 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8527 {
8528   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8529   struct value_print_options opts;
8530   struct ui_out *uiout = current_uiout;
8531
8532   get_user_print_options (&opts);
8533
8534   /* Field 4, the address, is omitted (which makes the columns
8535      not line up too nicely with the headers, but the effect
8536      is relatively readable).  */
8537   if (opts.addressprint)
8538     ui_out_field_skip (uiout, "addr");
8539   annotate_field (5);
8540   ui_out_text (uiout, "exec");
8541   if (c->exec_pathname != NULL)
8542     {
8543       ui_out_text (uiout, ", program \"");
8544       ui_out_field_string (uiout, "what", c->exec_pathname);
8545       ui_out_text (uiout, "\" ");
8546     }
8547
8548   if (ui_out_is_mi_like_p (uiout))
8549     ui_out_field_string (uiout, "catch-type", "exec");
8550 }
8551
8552 static void
8553 print_mention_catch_exec (struct breakpoint *b)
8554 {
8555   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8556 }
8557
8558 /* Implement the "print_recreate" breakpoint_ops method for exec
8559    catchpoints.  */
8560
8561 static void
8562 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8563 {
8564   fprintf_unfiltered (fp, "catch exec");
8565   print_recreate_thread (b, fp);
8566 }
8567
8568 static struct breakpoint_ops catch_exec_breakpoint_ops;
8569
8570 static void
8571 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8572                                  const struct breakpoint_ops *ops)
8573 {
8574   struct syscall_catchpoint *c;
8575   struct gdbarch *gdbarch = get_current_arch ();
8576
8577   c = XNEW (struct syscall_catchpoint);
8578   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8579   c->syscalls_to_be_caught = filter;
8580
8581   install_breakpoint (0, &c->base, 1);
8582 }
8583
8584 static int
8585 hw_breakpoint_used_count (void)
8586 {
8587   int i = 0;
8588   struct breakpoint *b;
8589   struct bp_location *bl;
8590
8591   ALL_BREAKPOINTS (b)
8592   {
8593     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8594       for (bl = b->loc; bl; bl = bl->next)
8595         {
8596           /* Special types of hardware breakpoints may use more than
8597              one register.  */
8598           i += b->ops->resources_needed (bl);
8599         }
8600   }
8601
8602   return i;
8603 }
8604
8605 /* Returns the resources B would use if it were a hardware
8606    watchpoint.  */
8607
8608 static int
8609 hw_watchpoint_use_count (struct breakpoint *b)
8610 {
8611   int i = 0;
8612   struct bp_location *bl;
8613
8614   if (!breakpoint_enabled (b))
8615     return 0;
8616
8617   for (bl = b->loc; bl; bl = bl->next)
8618     {
8619       /* Special types of hardware watchpoints may use more than
8620          one register.  */
8621       i += b->ops->resources_needed (bl);
8622     }
8623
8624   return i;
8625 }
8626
8627 /* Returns the sum the used resources of all hardware watchpoints of
8628    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8629    the sum of the used resources of all hardware watchpoints of other
8630    types _not_ TYPE.  */
8631
8632 static int
8633 hw_watchpoint_used_count_others (struct breakpoint *except,
8634                                  enum bptype type, int *other_type_used)
8635 {
8636   int i = 0;
8637   struct breakpoint *b;
8638
8639   *other_type_used = 0;
8640   ALL_BREAKPOINTS (b)
8641     {
8642       if (b == except)
8643         continue;
8644       if (!breakpoint_enabled (b))
8645         continue;
8646
8647       if (b->type == type)
8648         i += hw_watchpoint_use_count (b);
8649       else if (is_hardware_watchpoint (b))
8650         *other_type_used = 1;
8651     }
8652
8653   return i;
8654 }
8655
8656 void
8657 disable_watchpoints_before_interactive_call_start (void)
8658 {
8659   struct breakpoint *b;
8660
8661   ALL_BREAKPOINTS (b)
8662   {
8663     if (is_watchpoint (b) && breakpoint_enabled (b))
8664       {
8665         b->enable_state = bp_call_disabled;
8666         update_global_location_list (0);
8667       }
8668   }
8669 }
8670
8671 void
8672 enable_watchpoints_after_interactive_call_stop (void)
8673 {
8674   struct breakpoint *b;
8675
8676   ALL_BREAKPOINTS (b)
8677   {
8678     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8679       {
8680         b->enable_state = bp_enabled;
8681         update_global_location_list (1);
8682       }
8683   }
8684 }
8685
8686 void
8687 disable_breakpoints_before_startup (void)
8688 {
8689   current_program_space->executing_startup = 1;
8690   update_global_location_list (0);
8691 }
8692
8693 void
8694 enable_breakpoints_after_startup (void)
8695 {
8696   current_program_space->executing_startup = 0;
8697   breakpoint_re_set ();
8698 }
8699
8700
8701 /* Set a breakpoint that will evaporate an end of command
8702    at address specified by SAL.
8703    Restrict it to frame FRAME if FRAME is nonzero.  */
8704
8705 struct breakpoint *
8706 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8707                           struct frame_id frame_id, enum bptype type)
8708 {
8709   struct breakpoint *b;
8710
8711   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8712      tail-called one.  */
8713   gdb_assert (!frame_id_artificial_p (frame_id));
8714
8715   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8716   b->enable_state = bp_enabled;
8717   b->disposition = disp_donttouch;
8718   b->frame_id = frame_id;
8719
8720   /* If we're debugging a multi-threaded program, then we want
8721      momentary breakpoints to be active in only a single thread of
8722      control.  */
8723   if (in_thread_list (inferior_ptid))
8724     b->thread = pid_to_thread_id (inferior_ptid);
8725
8726   update_global_location_list_nothrow (1);
8727
8728   return b;
8729 }
8730
8731 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8732    The new breakpoint will have type TYPE, and use OPS as it
8733    breakpoint_ops.  */
8734
8735 static struct breakpoint *
8736 momentary_breakpoint_from_master (struct breakpoint *orig,
8737                                   enum bptype type,
8738                                   const struct breakpoint_ops *ops)
8739 {
8740   struct breakpoint *copy;
8741
8742   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8743   copy->loc = allocate_bp_location (copy);
8744   set_breakpoint_location_function (copy->loc, 1);
8745
8746   copy->loc->gdbarch = orig->loc->gdbarch;
8747   copy->loc->requested_address = orig->loc->requested_address;
8748   copy->loc->address = orig->loc->address;
8749   copy->loc->section = orig->loc->section;
8750   copy->loc->pspace = orig->loc->pspace;
8751   copy->loc->probe = orig->loc->probe;
8752   copy->loc->line_number = orig->loc->line_number;
8753   copy->loc->symtab = orig->loc->symtab;
8754   copy->frame_id = orig->frame_id;
8755   copy->thread = orig->thread;
8756   copy->pspace = orig->pspace;
8757
8758   copy->enable_state = bp_enabled;
8759   copy->disposition = disp_donttouch;
8760   copy->number = internal_breakpoint_number--;
8761
8762   update_global_location_list_nothrow (0);
8763   return copy;
8764 }
8765
8766 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8767    ORIG is NULL.  */
8768
8769 struct breakpoint *
8770 clone_momentary_breakpoint (struct breakpoint *orig)
8771 {
8772   /* If there's nothing to clone, then return nothing.  */
8773   if (orig == NULL)
8774     return NULL;
8775
8776   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8777 }
8778
8779 struct breakpoint *
8780 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8781                                 enum bptype type)
8782 {
8783   struct symtab_and_line sal;
8784
8785   sal = find_pc_line (pc, 0);
8786   sal.pc = pc;
8787   sal.section = find_pc_overlay (pc);
8788   sal.explicit_pc = 1;
8789
8790   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8791 }
8792 \f
8793
8794 /* Tell the user we have just set a breakpoint B.  */
8795
8796 static void
8797 mention (struct breakpoint *b)
8798 {
8799   b->ops->print_mention (b);
8800   if (ui_out_is_mi_like_p (current_uiout))
8801     return;
8802   printf_filtered ("\n");
8803 }
8804 \f
8805
8806 static struct bp_location *
8807 add_location_to_breakpoint (struct breakpoint *b,
8808                             const struct symtab_and_line *sal)
8809 {
8810   struct bp_location *loc, **tmp;
8811   CORE_ADDR adjusted_address;
8812   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8813
8814   if (loc_gdbarch == NULL)
8815     loc_gdbarch = b->gdbarch;
8816
8817   /* Adjust the breakpoint's address prior to allocating a location.
8818      Once we call allocate_bp_location(), that mostly uninitialized
8819      location will be placed on the location chain.  Adjustment of the
8820      breakpoint may cause target_read_memory() to be called and we do
8821      not want its scan of the location chain to find a breakpoint and
8822      location that's only been partially initialized.  */
8823   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8824                                                 sal->pc, b->type);
8825
8826   /* Sort the locations by their ADDRESS.  */
8827   loc = allocate_bp_location (b);
8828   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8829        tmp = &((*tmp)->next))
8830     ;
8831   loc->next = *tmp;
8832   *tmp = loc;
8833
8834   loc->requested_address = sal->pc;
8835   loc->address = adjusted_address;
8836   loc->pspace = sal->pspace;
8837   loc->probe = sal->probe;
8838   gdb_assert (loc->pspace != NULL);
8839   loc->section = sal->section;
8840   loc->gdbarch = loc_gdbarch;
8841   loc->line_number = sal->line;
8842   loc->symtab = sal->symtab;
8843
8844   set_breakpoint_location_function (loc,
8845                                     sal->explicit_pc || sal->explicit_line);
8846   return loc;
8847 }
8848 \f
8849
8850 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8851    return 0 otherwise.  */
8852
8853 static int
8854 bp_loc_is_permanent (struct bp_location *loc)
8855 {
8856   int len;
8857   CORE_ADDR addr;
8858   const gdb_byte *bpoint;
8859   gdb_byte *target_mem;
8860   struct cleanup *cleanup;
8861   int retval = 0;
8862
8863   gdb_assert (loc != NULL);
8864
8865   addr = loc->address;
8866   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8867
8868   /* Software breakpoints unsupported?  */
8869   if (bpoint == NULL)
8870     return 0;
8871
8872   target_mem = alloca (len);
8873
8874   /* Enable the automatic memory restoration from breakpoints while
8875      we read the memory.  Otherwise we could say about our temporary
8876      breakpoints they are permanent.  */
8877   cleanup = save_current_space_and_thread ();
8878
8879   switch_to_program_space_and_thread (loc->pspace);
8880   make_show_memory_breakpoints_cleanup (0);
8881
8882   if (target_read_memory (loc->address, target_mem, len) == 0
8883       && memcmp (target_mem, bpoint, len) == 0)
8884     retval = 1;
8885
8886   do_cleanups (cleanup);
8887
8888   return retval;
8889 }
8890
8891 /* Build a command list for the dprintf corresponding to the current
8892    settings of the dprintf style options.  */
8893
8894 static void
8895 update_dprintf_command_list (struct breakpoint *b)
8896 {
8897   char *dprintf_args = b->extra_string;
8898   char *printf_line = NULL;
8899
8900   if (!dprintf_args)
8901     return;
8902
8903   dprintf_args = skip_spaces (dprintf_args);
8904
8905   /* Allow a comma, as it may have terminated a location, but don't
8906      insist on it.  */
8907   if (*dprintf_args == ',')
8908     ++dprintf_args;
8909   dprintf_args = skip_spaces (dprintf_args);
8910
8911   if (*dprintf_args != '"')
8912     error (_("Bad format string, missing '\"'."));
8913
8914   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8915     printf_line = xstrprintf ("printf %s", dprintf_args);
8916   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8917     {
8918       if (!dprintf_function)
8919         error (_("No function supplied for dprintf call"));
8920
8921       if (dprintf_channel && strlen (dprintf_channel) > 0)
8922         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8923                                   dprintf_function,
8924                                   dprintf_channel,
8925                                   dprintf_args);
8926       else
8927         printf_line = xstrprintf ("call (void) %s (%s)",
8928                                   dprintf_function,
8929                                   dprintf_args);
8930     }
8931   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8932     {
8933       if (target_can_run_breakpoint_commands ())
8934         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8935       else
8936         {
8937           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8938           printf_line = xstrprintf ("printf %s", dprintf_args);
8939         }
8940     }
8941   else
8942     internal_error (__FILE__, __LINE__,
8943                     _("Invalid dprintf style."));
8944
8945   gdb_assert (printf_line != NULL);
8946   /* Manufacture a printf/continue sequence.  */
8947   {
8948     struct command_line *printf_cmd_line, *cont_cmd_line = NULL;
8949
8950     if (strcmp (dprintf_style, dprintf_style_agent) != 0)
8951       {
8952         cont_cmd_line = xmalloc (sizeof (struct command_line));
8953         cont_cmd_line->control_type = simple_control;
8954         cont_cmd_line->body_count = 0;
8955         cont_cmd_line->body_list = NULL;
8956         cont_cmd_line->next = NULL;
8957         cont_cmd_line->line = xstrdup ("continue");
8958       }
8959
8960     printf_cmd_line = xmalloc (sizeof (struct command_line));
8961     printf_cmd_line->control_type = simple_control;
8962     printf_cmd_line->body_count = 0;
8963     printf_cmd_line->body_list = NULL;
8964     printf_cmd_line->next = cont_cmd_line;
8965     printf_cmd_line->line = printf_line;
8966
8967     breakpoint_set_commands (b, printf_cmd_line);
8968   }
8969 }
8970
8971 /* Update all dprintf commands, making their command lists reflect
8972    current style settings.  */
8973
8974 static void
8975 update_dprintf_commands (char *args, int from_tty,
8976                          struct cmd_list_element *c)
8977 {
8978   struct breakpoint *b;
8979
8980   ALL_BREAKPOINTS (b)
8981     {
8982       if (b->type == bp_dprintf)
8983         update_dprintf_command_list (b);
8984     }
8985 }
8986
8987 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8988    as textual description of the location, and COND_STRING
8989    as condition expression.  */
8990
8991 static void
8992 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8993                      struct symtabs_and_lines sals, char *addr_string,
8994                      char *filter, char *cond_string,
8995                      char *extra_string,
8996                      enum bptype type, enum bpdisp disposition,
8997                      int thread, int task, int ignore_count,
8998                      const struct breakpoint_ops *ops, int from_tty,
8999                      int enabled, int internal, unsigned flags,
9000                      int display_canonical)
9001 {
9002   int i;
9003
9004   if (type == bp_hardware_breakpoint)
9005     {
9006       int target_resources_ok;
9007
9008       i = hw_breakpoint_used_count ();
9009       target_resources_ok =
9010         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9011                                             i + 1, 0);
9012       if (target_resources_ok == 0)
9013         error (_("No hardware breakpoint support in the target."));
9014       else if (target_resources_ok < 0)
9015         error (_("Hardware breakpoints used exceeds limit."));
9016     }
9017
9018   gdb_assert (sals.nelts > 0);
9019
9020   for (i = 0; i < sals.nelts; ++i)
9021     {
9022       struct symtab_and_line sal = sals.sals[i];
9023       struct bp_location *loc;
9024
9025       if (from_tty)
9026         {
9027           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9028           if (!loc_gdbarch)
9029             loc_gdbarch = gdbarch;
9030
9031           describe_other_breakpoints (loc_gdbarch,
9032                                       sal.pspace, sal.pc, sal.section, thread);
9033         }
9034
9035       if (i == 0)
9036         {
9037           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9038           b->thread = thread;
9039           b->task = task;
9040
9041           b->cond_string = cond_string;
9042           b->extra_string = extra_string;
9043           b->ignore_count = ignore_count;
9044           b->enable_state = enabled ? bp_enabled : bp_disabled;
9045           b->disposition = disposition;
9046
9047           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9048             b->loc->inserted = 1;
9049
9050           if (type == bp_static_tracepoint)
9051             {
9052               struct tracepoint *t = (struct tracepoint *) b;
9053               struct static_tracepoint_marker marker;
9054
9055               if (strace_marker_p (b))
9056                 {
9057                   /* We already know the marker exists, otherwise, we
9058                      wouldn't see a sal for it.  */
9059                   char *p = &addr_string[3];
9060                   char *endp;
9061                   char *marker_str;
9062
9063                   p = skip_spaces (p);
9064
9065                   endp = skip_to_space (p);
9066
9067                   marker_str = savestring (p, endp - p);
9068                   t->static_trace_marker_id = marker_str;
9069
9070                   printf_filtered (_("Probed static tracepoint "
9071                                      "marker \"%s\"\n"),
9072                                    t->static_trace_marker_id);
9073                 }
9074               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9075                 {
9076                   t->static_trace_marker_id = xstrdup (marker.str_id);
9077                   release_static_tracepoint_marker (&marker);
9078
9079                   printf_filtered (_("Probed static tracepoint "
9080                                      "marker \"%s\"\n"),
9081                                    t->static_trace_marker_id);
9082                 }
9083               else
9084                 warning (_("Couldn't determine the static "
9085                            "tracepoint marker to probe"));
9086             }
9087
9088           loc = b->loc;
9089         }
9090       else
9091         {
9092           loc = add_location_to_breakpoint (b, &sal);
9093           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9094             loc->inserted = 1;
9095         }
9096
9097       if (bp_loc_is_permanent (loc))
9098         make_breakpoint_permanent (b);
9099
9100       if (b->cond_string)
9101         {
9102           const char *arg = b->cond_string;
9103
9104           loc->cond = parse_exp_1 (&arg, loc->address,
9105                                    block_for_pc (loc->address), 0);
9106           if (*arg)
9107               error (_("Garbage '%s' follows condition"), arg);
9108         }
9109
9110       /* Dynamic printf requires and uses additional arguments on the
9111          command line, otherwise it's an error.  */
9112       if (type == bp_dprintf)
9113         {
9114           if (b->extra_string)
9115             update_dprintf_command_list (b);
9116           else
9117             error (_("Format string required"));
9118         }
9119       else if (b->extra_string)
9120         error (_("Garbage '%s' at end of command"), b->extra_string);
9121     }
9122
9123   b->display_canonical = display_canonical;
9124   if (addr_string)
9125     b->addr_string = addr_string;
9126   else
9127     /* addr_string has to be used or breakpoint_re_set will delete
9128        me.  */
9129     b->addr_string
9130       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9131   b->filter = filter;
9132 }
9133
9134 static void
9135 create_breakpoint_sal (struct gdbarch *gdbarch,
9136                        struct symtabs_and_lines sals, char *addr_string,
9137                        char *filter, char *cond_string,
9138                        char *extra_string,
9139                        enum bptype type, enum bpdisp disposition,
9140                        int thread, int task, int ignore_count,
9141                        const struct breakpoint_ops *ops, int from_tty,
9142                        int enabled, int internal, unsigned flags,
9143                        int display_canonical)
9144 {
9145   struct breakpoint *b;
9146   struct cleanup *old_chain;
9147
9148   if (is_tracepoint_type (type))
9149     {
9150       struct tracepoint *t;
9151
9152       t = XCNEW (struct tracepoint);
9153       b = &t->base;
9154     }
9155   else
9156     b = XNEW (struct breakpoint);
9157
9158   old_chain = make_cleanup (xfree, b);
9159
9160   init_breakpoint_sal (b, gdbarch,
9161                        sals, addr_string,
9162                        filter, cond_string, extra_string,
9163                        type, disposition,
9164                        thread, task, ignore_count,
9165                        ops, from_tty,
9166                        enabled, internal, flags,
9167                        display_canonical);
9168   discard_cleanups (old_chain);
9169
9170   install_breakpoint (internal, b, 0);
9171 }
9172
9173 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9174    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9175    value.  COND_STRING, if not NULL, specified the condition to be
9176    used for all breakpoints.  Essentially the only case where
9177    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9178    function.  In that case, it's still not possible to specify
9179    separate conditions for different overloaded functions, so
9180    we take just a single condition string.
9181    
9182    NOTE: If the function succeeds, the caller is expected to cleanup
9183    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9184    array contents).  If the function fails (error() is called), the
9185    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9186    COND and SALS arrays and each of those arrays contents.  */
9187
9188 static void
9189 create_breakpoints_sal (struct gdbarch *gdbarch,
9190                         struct linespec_result *canonical,
9191                         char *cond_string, char *extra_string,
9192                         enum bptype type, enum bpdisp disposition,
9193                         int thread, int task, int ignore_count,
9194                         const struct breakpoint_ops *ops, int from_tty,
9195                         int enabled, int internal, unsigned flags)
9196 {
9197   int i;
9198   struct linespec_sals *lsal;
9199
9200   if (canonical->pre_expanded)
9201     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9202
9203   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9204     {
9205       /* Note that 'addr_string' can be NULL in the case of a plain
9206          'break', without arguments.  */
9207       char *addr_string = (canonical->addr_string
9208                            ? xstrdup (canonical->addr_string)
9209                            : NULL);
9210       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9211       struct cleanup *inner = make_cleanup (xfree, addr_string);
9212
9213       make_cleanup (xfree, filter_string);
9214       create_breakpoint_sal (gdbarch, lsal->sals,
9215                              addr_string,
9216                              filter_string,
9217                              cond_string, extra_string,
9218                              type, disposition,
9219                              thread, task, ignore_count, ops,
9220                              from_tty, enabled, internal, flags,
9221                              canonical->special_display);
9222       discard_cleanups (inner);
9223     }
9224 }
9225
9226 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9227    followed by conditionals.  On return, SALS contains an array of SAL
9228    addresses found.  ADDR_STRING contains a vector of (canonical)
9229    address strings.  ADDRESS points to the end of the SAL.
9230
9231    The array and the line spec strings are allocated on the heap, it is
9232    the caller's responsibility to free them.  */
9233
9234 static void
9235 parse_breakpoint_sals (char **address,
9236                        struct linespec_result *canonical)
9237 {
9238   /* If no arg given, or if first arg is 'if ', use the default
9239      breakpoint.  */
9240   if ((*address) == NULL
9241       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9242     {
9243       /* The last displayed codepoint, if it's valid, is our default breakpoint
9244          address.  */
9245       if (last_displayed_sal_is_valid ())
9246         {
9247           struct linespec_sals lsal;
9248           struct symtab_and_line sal;
9249           CORE_ADDR pc;
9250
9251           init_sal (&sal);              /* Initialize to zeroes.  */
9252           lsal.sals.sals = (struct symtab_and_line *)
9253             xmalloc (sizeof (struct symtab_and_line));
9254
9255           /* Set sal's pspace, pc, symtab, and line to the values
9256              corresponding to the last call to print_frame_info.
9257              Be sure to reinitialize LINE with NOTCURRENT == 0
9258              as the breakpoint line number is inappropriate otherwise.
9259              find_pc_line would adjust PC, re-set it back.  */
9260           get_last_displayed_sal (&sal);
9261           pc = sal.pc;
9262           sal = find_pc_line (pc, 0);
9263
9264           /* "break" without arguments is equivalent to "break *PC"
9265              where PC is the last displayed codepoint's address.  So
9266              make sure to set sal.explicit_pc to prevent GDB from
9267              trying to expand the list of sals to include all other
9268              instances with the same symtab and line.  */
9269           sal.pc = pc;
9270           sal.explicit_pc = 1;
9271
9272           lsal.sals.sals[0] = sal;
9273           lsal.sals.nelts = 1;
9274           lsal.canonical = NULL;
9275
9276           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9277         }
9278       else
9279         error (_("No default breakpoint address now."));
9280     }
9281   else
9282     {
9283       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9284
9285       /* Force almost all breakpoints to be in terms of the
9286          current_source_symtab (which is decode_line_1's default).
9287          This should produce the results we want almost all of the
9288          time while leaving default_breakpoint_* alone.
9289
9290          ObjC: However, don't match an Objective-C method name which
9291          may have a '+' or '-' succeeded by a '['.  */
9292       if (last_displayed_sal_is_valid ()
9293           && (!cursal.symtab
9294               || ((strchr ("+-", (*address)[0]) != NULL)
9295                   && ((*address)[1] != '['))))
9296         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9297                           get_last_displayed_symtab (),
9298                           get_last_displayed_line (),
9299                           canonical, NULL, NULL);
9300       else
9301         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9302                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9303     }
9304 }
9305
9306
9307 /* Convert each SAL into a real PC.  Verify that the PC can be
9308    inserted as a breakpoint.  If it can't throw an error.  */
9309
9310 static void
9311 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9312 {    
9313   int i;
9314
9315   for (i = 0; i < sals->nelts; i++)
9316     resolve_sal_pc (&sals->sals[i]);
9317 }
9318
9319 /* Fast tracepoints may have restrictions on valid locations.  For
9320    instance, a fast tracepoint using a jump instead of a trap will
9321    likely have to overwrite more bytes than a trap would, and so can
9322    only be placed where the instruction is longer than the jump, or a
9323    multi-instruction sequence does not have a jump into the middle of
9324    it, etc.  */
9325
9326 static void
9327 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9328                             struct symtabs_and_lines *sals)
9329 {
9330   int i, rslt;
9331   struct symtab_and_line *sal;
9332   char *msg;
9333   struct cleanup *old_chain;
9334
9335   for (i = 0; i < sals->nelts; i++)
9336     {
9337       struct gdbarch *sarch;
9338
9339       sal = &sals->sals[i];
9340
9341       sarch = get_sal_arch (*sal);
9342       /* We fall back to GDBARCH if there is no architecture
9343          associated with SAL.  */
9344       if (sarch == NULL)
9345         sarch = gdbarch;
9346       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9347                                                NULL, &msg);
9348       old_chain = make_cleanup (xfree, msg);
9349
9350       if (!rslt)
9351         error (_("May not have a fast tracepoint at 0x%s%s"),
9352                paddress (sarch, sal->pc), (msg ? msg : ""));
9353
9354       do_cleanups (old_chain);
9355     }
9356 }
9357
9358 /* Issue an invalid thread ID error.  */
9359
9360 static void ATTRIBUTE_NORETURN
9361 invalid_thread_id_error (int id)
9362 {
9363   error (_("Unknown thread %d."), id);
9364 }
9365
9366 /* Given TOK, a string specification of condition and thread, as
9367    accepted by the 'break' command, extract the condition
9368    string and thread number and set *COND_STRING and *THREAD.
9369    PC identifies the context at which the condition should be parsed.
9370    If no condition is found, *COND_STRING is set to NULL.
9371    If no thread is found, *THREAD is set to -1.  */
9372
9373 static void
9374 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9375                            char **cond_string, int *thread, int *task,
9376                            char **rest)
9377 {
9378   *cond_string = NULL;
9379   *thread = -1;
9380   *task = 0;
9381   *rest = NULL;
9382
9383   while (tok && *tok)
9384     {
9385       const char *end_tok;
9386       int toklen;
9387       const char *cond_start = NULL;
9388       const char *cond_end = NULL;
9389
9390       tok = skip_spaces_const (tok);
9391
9392       if ((*tok == '"' || *tok == ',') && rest)
9393         {
9394           *rest = savestring (tok, strlen (tok));
9395           return;
9396         }
9397
9398       end_tok = skip_to_space_const (tok);
9399
9400       toklen = end_tok - tok;
9401
9402       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9403         {
9404           struct expression *expr;
9405
9406           tok = cond_start = end_tok + 1;
9407           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9408           xfree (expr);
9409           cond_end = tok;
9410           *cond_string = savestring (cond_start, cond_end - cond_start);
9411         }
9412       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9413         {
9414           char *tmptok;
9415
9416           tok = end_tok + 1;
9417           *thread = strtol (tok, &tmptok, 0);
9418           if (tok == tmptok)
9419             error (_("Junk after thread keyword."));
9420           if (!valid_thread_id (*thread))
9421             invalid_thread_id_error (*thread);
9422           tok = tmptok;
9423         }
9424       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9425         {
9426           char *tmptok;
9427
9428           tok = end_tok + 1;
9429           *task = strtol (tok, &tmptok, 0);
9430           if (tok == tmptok)
9431             error (_("Junk after task keyword."));
9432           if (!valid_task_id (*task))
9433             error (_("Unknown task %d."), *task);
9434           tok = tmptok;
9435         }
9436       else if (rest)
9437         {
9438           *rest = savestring (tok, strlen (tok));
9439           return;
9440         }
9441       else
9442         error (_("Junk at end of arguments."));
9443     }
9444 }
9445
9446 /* Decode a static tracepoint marker spec.  */
9447
9448 static struct symtabs_and_lines
9449 decode_static_tracepoint_spec (char **arg_p)
9450 {
9451   VEC(static_tracepoint_marker_p) *markers = NULL;
9452   struct symtabs_and_lines sals;
9453   struct cleanup *old_chain;
9454   char *p = &(*arg_p)[3];
9455   char *endp;
9456   char *marker_str;
9457   int i;
9458
9459   p = skip_spaces (p);
9460
9461   endp = skip_to_space (p);
9462
9463   marker_str = savestring (p, endp - p);
9464   old_chain = make_cleanup (xfree, marker_str);
9465
9466   markers = target_static_tracepoint_markers_by_strid (marker_str);
9467   if (VEC_empty(static_tracepoint_marker_p, markers))
9468     error (_("No known static tracepoint marker named %s"), marker_str);
9469
9470   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9471   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9472
9473   for (i = 0; i < sals.nelts; i++)
9474     {
9475       struct static_tracepoint_marker *marker;
9476
9477       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9478
9479       init_sal (&sals.sals[i]);
9480
9481       sals.sals[i] = find_pc_line (marker->address, 0);
9482       sals.sals[i].pc = marker->address;
9483
9484       release_static_tracepoint_marker (marker);
9485     }
9486
9487   do_cleanups (old_chain);
9488
9489   *arg_p = endp;
9490   return sals;
9491 }
9492
9493 /* Set a breakpoint.  This function is shared between CLI and MI
9494    functions for setting a breakpoint.  This function has two major
9495    modes of operations, selected by the PARSE_ARG parameter.  If
9496    non-zero, the function will parse ARG, extracting location,
9497    condition, thread and extra string.  Otherwise, ARG is just the
9498    breakpoint's location, with condition, thread, and extra string
9499    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9500    If INTERNAL is non-zero, the breakpoint number will be allocated
9501    from the internal breakpoint count.  Returns true if any breakpoint
9502    was created; false otherwise.  */
9503
9504 int
9505 create_breakpoint (struct gdbarch *gdbarch,
9506                    char *arg, char *cond_string,
9507                    int thread, char *extra_string,
9508                    int parse_arg,
9509                    int tempflag, enum bptype type_wanted,
9510                    int ignore_count,
9511                    enum auto_boolean pending_break_support,
9512                    const struct breakpoint_ops *ops,
9513                    int from_tty, int enabled, int internal,
9514                    unsigned flags)
9515 {
9516   volatile struct gdb_exception e;
9517   char *copy_arg = NULL;
9518   char *addr_start = arg;
9519   struct linespec_result canonical;
9520   struct cleanup *old_chain;
9521   struct cleanup *bkpt_chain = NULL;
9522   int pending = 0;
9523   int task = 0;
9524   int prev_bkpt_count = breakpoint_count;
9525
9526   gdb_assert (ops != NULL);
9527
9528   init_linespec_result (&canonical);
9529
9530   TRY_CATCH (e, RETURN_MASK_ALL)
9531     {
9532       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9533                                      addr_start, &copy_arg);
9534     }
9535
9536   /* If caller is interested in rc value from parse, set value.  */
9537   switch (e.reason)
9538     {
9539     case GDB_NO_ERROR:
9540       if (VEC_empty (linespec_sals, canonical.sals))
9541         return 0;
9542       break;
9543     case RETURN_ERROR:
9544       switch (e.error)
9545         {
9546         case NOT_FOUND_ERROR:
9547
9548           /* If pending breakpoint support is turned off, throw
9549              error.  */
9550
9551           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9552             throw_exception (e);
9553
9554           exception_print (gdb_stderr, e);
9555
9556           /* If pending breakpoint support is auto query and the user
9557              selects no, then simply return the error code.  */
9558           if (pending_break_support == AUTO_BOOLEAN_AUTO
9559               && !nquery (_("Make %s pending on future shared library load? "),
9560                           bptype_string (type_wanted)))
9561             return 0;
9562
9563           /* At this point, either the user was queried about setting
9564              a pending breakpoint and selected yes, or pending
9565              breakpoint behavior is on and thus a pending breakpoint
9566              is defaulted on behalf of the user.  */
9567           {
9568             struct linespec_sals lsal;
9569
9570             copy_arg = xstrdup (addr_start);
9571             lsal.canonical = xstrdup (copy_arg);
9572             lsal.sals.nelts = 1;
9573             lsal.sals.sals = XNEW (struct symtab_and_line);
9574             init_sal (&lsal.sals.sals[0]);
9575             pending = 1;
9576             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9577           }
9578           break;
9579         default:
9580           throw_exception (e);
9581         }
9582       break;
9583     default:
9584       throw_exception (e);
9585     }
9586
9587   /* Create a chain of things that always need to be cleaned up.  */
9588   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9589
9590   /* ----------------------------- SNIP -----------------------------
9591      Anything added to the cleanup chain beyond this point is assumed
9592      to be part of a breakpoint.  If the breakpoint create succeeds
9593      then the memory is not reclaimed.  */
9594   bkpt_chain = make_cleanup (null_cleanup, 0);
9595
9596   /* Resolve all line numbers to PC's and verify that the addresses
9597      are ok for the target.  */
9598   if (!pending)
9599     {
9600       int ix;
9601       struct linespec_sals *iter;
9602
9603       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9604         breakpoint_sals_to_pc (&iter->sals);
9605     }
9606
9607   /* Fast tracepoints may have additional restrictions on location.  */
9608   if (!pending && type_wanted == bp_fast_tracepoint)
9609     {
9610       int ix;
9611       struct linespec_sals *iter;
9612
9613       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9614         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9615     }
9616
9617   /* Verify that condition can be parsed, before setting any
9618      breakpoints.  Allocate a separate condition expression for each
9619      breakpoint.  */
9620   if (!pending)
9621     {
9622       struct linespec_sals *lsal;
9623
9624       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9625
9626       if (parse_arg)
9627         {
9628             char *rest;
9629             /* Here we only parse 'arg' to separate condition
9630                from thread number, so parsing in context of first
9631                sal is OK.  When setting the breakpoint we'll 
9632                re-parse it in context of each sal.  */
9633
9634             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9635                                        &thread, &task, &rest);
9636             if (cond_string)
9637                 make_cleanup (xfree, cond_string);
9638             if (rest)
9639               make_cleanup (xfree, rest);
9640             if (rest)
9641               extra_string = rest;
9642         }
9643       else
9644         {
9645             if (*arg != '\0')
9646               error (_("Garbage '%s' at end of location"), arg);
9647
9648             /* Create a private copy of condition string.  */
9649             if (cond_string)
9650             {
9651                 cond_string = xstrdup (cond_string);
9652                 make_cleanup (xfree, cond_string);
9653             }
9654             /* Create a private copy of any extra string.  */
9655             if (extra_string)
9656               {
9657                 extra_string = xstrdup (extra_string);
9658                 make_cleanup (xfree, extra_string);
9659               }
9660         }
9661
9662       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9663                                    cond_string, extra_string, type_wanted,
9664                                    tempflag ? disp_del : disp_donttouch,
9665                                    thread, task, ignore_count, ops,
9666                                    from_tty, enabled, internal, flags);
9667     }
9668   else
9669     {
9670       struct breakpoint *b;
9671
9672       make_cleanup (xfree, copy_arg);
9673
9674       if (is_tracepoint_type (type_wanted))
9675         {
9676           struct tracepoint *t;
9677
9678           t = XCNEW (struct tracepoint);
9679           b = &t->base;
9680         }
9681       else
9682         b = XNEW (struct breakpoint);
9683
9684       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9685
9686       b->addr_string = copy_arg;
9687       if (parse_arg)
9688         b->cond_string = NULL;
9689       else
9690         {
9691           /* Create a private copy of condition string.  */
9692           if (cond_string)
9693             {
9694               cond_string = xstrdup (cond_string);
9695               make_cleanup (xfree, cond_string);
9696             }
9697           b->cond_string = cond_string;
9698         }
9699       b->extra_string = NULL;
9700       b->ignore_count = ignore_count;
9701       b->disposition = tempflag ? disp_del : disp_donttouch;
9702       b->condition_not_parsed = 1;
9703       b->enable_state = enabled ? bp_enabled : bp_disabled;
9704       if ((type_wanted != bp_breakpoint
9705            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9706         b->pspace = current_program_space;
9707
9708       install_breakpoint (internal, b, 0);
9709     }
9710   
9711   if (VEC_length (linespec_sals, canonical.sals) > 1)
9712     {
9713       warning (_("Multiple breakpoints were set.\nUse the "
9714                  "\"delete\" command to delete unwanted breakpoints."));
9715       prev_breakpoint_count = prev_bkpt_count;
9716     }
9717
9718   /* That's it.  Discard the cleanups for data inserted into the
9719      breakpoint.  */
9720   discard_cleanups (bkpt_chain);
9721   /* But cleanup everything else.  */
9722   do_cleanups (old_chain);
9723
9724   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9725   update_global_location_list (1);
9726
9727   return 1;
9728 }
9729
9730 /* Set a breakpoint.
9731    ARG is a string describing breakpoint address,
9732    condition, and thread.
9733    FLAG specifies if a breakpoint is hardware on,
9734    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9735    and BP_TEMPFLAG.  */
9736
9737 static void
9738 break_command_1 (char *arg, int flag, int from_tty)
9739 {
9740   int tempflag = flag & BP_TEMPFLAG;
9741   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9742                              ? bp_hardware_breakpoint
9743                              : bp_breakpoint);
9744   struct breakpoint_ops *ops;
9745   const char *arg_cp = arg;
9746
9747   /* Matching breakpoints on probes.  */
9748   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9749     ops = &bkpt_probe_breakpoint_ops;
9750   else
9751     ops = &bkpt_breakpoint_ops;
9752
9753   create_breakpoint (get_current_arch (),
9754                      arg,
9755                      NULL, 0, NULL, 1 /* parse arg */,
9756                      tempflag, type_wanted,
9757                      0 /* Ignore count */,
9758                      pending_break_support,
9759                      ops,
9760                      from_tty,
9761                      1 /* enabled */,
9762                      0 /* internal */,
9763                      0);
9764 }
9765
9766 /* Helper function for break_command_1 and disassemble_command.  */
9767
9768 void
9769 resolve_sal_pc (struct symtab_and_line *sal)
9770 {
9771   CORE_ADDR pc;
9772
9773   if (sal->pc == 0 && sal->symtab != NULL)
9774     {
9775       if (!find_line_pc (sal->symtab, sal->line, &pc))
9776         error (_("No line %d in file \"%s\"."),
9777                sal->line, symtab_to_filename_for_display (sal->symtab));
9778       sal->pc = pc;
9779
9780       /* If this SAL corresponds to a breakpoint inserted using a line
9781          number, then skip the function prologue if necessary.  */
9782       if (sal->explicit_line)
9783         skip_prologue_sal (sal);
9784     }
9785
9786   if (sal->section == 0 && sal->symtab != NULL)
9787     {
9788       struct blockvector *bv;
9789       struct block *b;
9790       struct symbol *sym;
9791
9792       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9793       if (bv != NULL)
9794         {
9795           sym = block_linkage_function (b);
9796           if (sym != NULL)
9797             {
9798               fixup_symbol_section (sym, sal->symtab->objfile);
9799               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
9800             }
9801           else
9802             {
9803               /* It really is worthwhile to have the section, so we'll
9804                  just have to look harder. This case can be executed
9805                  if we have line numbers but no functions (as can
9806                  happen in assembly source).  */
9807
9808               struct bound_minimal_symbol msym;
9809               struct cleanup *old_chain = save_current_space_and_thread ();
9810
9811               switch_to_program_space_and_thread (sal->pspace);
9812
9813               msym = lookup_minimal_symbol_by_pc (sal->pc);
9814               if (msym.minsym)
9815                 sal->section = SYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9816
9817               do_cleanups (old_chain);
9818             }
9819         }
9820     }
9821 }
9822
9823 void
9824 break_command (char *arg, int from_tty)
9825 {
9826   break_command_1 (arg, 0, from_tty);
9827 }
9828
9829 void
9830 tbreak_command (char *arg, int from_tty)
9831 {
9832   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9833 }
9834
9835 static void
9836 hbreak_command (char *arg, int from_tty)
9837 {
9838   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9839 }
9840
9841 static void
9842 thbreak_command (char *arg, int from_tty)
9843 {
9844   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9845 }
9846
9847 static void
9848 stop_command (char *arg, int from_tty)
9849 {
9850   printf_filtered (_("Specify the type of breakpoint to set.\n\
9851 Usage: stop in <function | address>\n\
9852        stop at <line>\n"));
9853 }
9854
9855 static void
9856 stopin_command (char *arg, int from_tty)
9857 {
9858   int badInput = 0;
9859
9860   if (arg == (char *) NULL)
9861     badInput = 1;
9862   else if (*arg != '*')
9863     {
9864       char *argptr = arg;
9865       int hasColon = 0;
9866
9867       /* Look for a ':'.  If this is a line number specification, then
9868          say it is bad, otherwise, it should be an address or
9869          function/method name.  */
9870       while (*argptr && !hasColon)
9871         {
9872           hasColon = (*argptr == ':');
9873           argptr++;
9874         }
9875
9876       if (hasColon)
9877         badInput = (*argptr != ':');    /* Not a class::method */
9878       else
9879         badInput = isdigit (*arg);      /* a simple line number */
9880     }
9881
9882   if (badInput)
9883     printf_filtered (_("Usage: stop in <function | address>\n"));
9884   else
9885     break_command_1 (arg, 0, from_tty);
9886 }
9887
9888 static void
9889 stopat_command (char *arg, int from_tty)
9890 {
9891   int badInput = 0;
9892
9893   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9894     badInput = 1;
9895   else
9896     {
9897       char *argptr = arg;
9898       int hasColon = 0;
9899
9900       /* Look for a ':'.  If there is a '::' then get out, otherwise
9901          it is probably a line number.  */
9902       while (*argptr && !hasColon)
9903         {
9904           hasColon = (*argptr == ':');
9905           argptr++;
9906         }
9907
9908       if (hasColon)
9909         badInput = (*argptr == ':');    /* we have class::method */
9910       else
9911         badInput = !isdigit (*arg);     /* not a line number */
9912     }
9913
9914   if (badInput)
9915     printf_filtered (_("Usage: stop at <line>\n"));
9916   else
9917     break_command_1 (arg, 0, from_tty);
9918 }
9919
9920 /* The dynamic printf command is mostly like a regular breakpoint, but
9921    with a prewired command list consisting of a single output command,
9922    built from extra arguments supplied on the dprintf command
9923    line.  */
9924
9925 static void
9926 dprintf_command (char *arg, int from_tty)
9927 {
9928   create_breakpoint (get_current_arch (),
9929                      arg,
9930                      NULL, 0, NULL, 1 /* parse arg */,
9931                      0, bp_dprintf,
9932                      0 /* Ignore count */,
9933                      pending_break_support,
9934                      &dprintf_breakpoint_ops,
9935                      from_tty,
9936                      1 /* enabled */,
9937                      0 /* internal */,
9938                      0);
9939 }
9940
9941 static void
9942 agent_printf_command (char *arg, int from_tty)
9943 {
9944   error (_("May only run agent-printf on the target"));
9945 }
9946
9947 /* Implement the "breakpoint_hit" breakpoint_ops method for
9948    ranged breakpoints.  */
9949
9950 static int
9951 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9952                                   struct address_space *aspace,
9953                                   CORE_ADDR bp_addr,
9954                                   const struct target_waitstatus *ws)
9955 {
9956   if (ws->kind != TARGET_WAITKIND_STOPPED
9957       || ws->value.sig != GDB_SIGNAL_TRAP)
9958     return 0;
9959
9960   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9961                                          bl->length, aspace, bp_addr);
9962 }
9963
9964 /* Implement the "resources_needed" breakpoint_ops method for
9965    ranged breakpoints.  */
9966
9967 static int
9968 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9969 {
9970   return target_ranged_break_num_registers ();
9971 }
9972
9973 /* Implement the "print_it" breakpoint_ops method for
9974    ranged breakpoints.  */
9975
9976 static enum print_stop_action
9977 print_it_ranged_breakpoint (bpstat bs)
9978 {
9979   struct breakpoint *b = bs->breakpoint_at;
9980   struct bp_location *bl = b->loc;
9981   struct ui_out *uiout = current_uiout;
9982
9983   gdb_assert (b->type == bp_hardware_breakpoint);
9984
9985   /* Ranged breakpoints have only one location.  */
9986   gdb_assert (bl && bl->next == NULL);
9987
9988   annotate_breakpoint (b->number);
9989   if (b->disposition == disp_del)
9990     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9991   else
9992     ui_out_text (uiout, "\nRanged breakpoint ");
9993   if (ui_out_is_mi_like_p (uiout))
9994     {
9995       ui_out_field_string (uiout, "reason",
9996                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9997       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9998     }
9999   ui_out_field_int (uiout, "bkptno", b->number);
10000   ui_out_text (uiout, ", ");
10001
10002   return PRINT_SRC_AND_LOC;
10003 }
10004
10005 /* Implement the "print_one" breakpoint_ops method for
10006    ranged breakpoints.  */
10007
10008 static void
10009 print_one_ranged_breakpoint (struct breakpoint *b,
10010                              struct bp_location **last_loc)
10011 {
10012   struct bp_location *bl = b->loc;
10013   struct value_print_options opts;
10014   struct ui_out *uiout = current_uiout;
10015
10016   /* Ranged breakpoints have only one location.  */
10017   gdb_assert (bl && bl->next == NULL);
10018
10019   get_user_print_options (&opts);
10020
10021   if (opts.addressprint)
10022     /* We don't print the address range here, it will be printed later
10023        by print_one_detail_ranged_breakpoint.  */
10024     ui_out_field_skip (uiout, "addr");
10025   annotate_field (5);
10026   print_breakpoint_location (b, bl);
10027   *last_loc = bl;
10028 }
10029
10030 /* Implement the "print_one_detail" breakpoint_ops method for
10031    ranged breakpoints.  */
10032
10033 static void
10034 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10035                                     struct ui_out *uiout)
10036 {
10037   CORE_ADDR address_start, address_end;
10038   struct bp_location *bl = b->loc;
10039   struct ui_file *stb = mem_fileopen ();
10040   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10041
10042   gdb_assert (bl);
10043
10044   address_start = bl->address;
10045   address_end = address_start + bl->length - 1;
10046
10047   ui_out_text (uiout, "\taddress range: ");
10048   fprintf_unfiltered (stb, "[%s, %s]",
10049                       print_core_address (bl->gdbarch, address_start),
10050                       print_core_address (bl->gdbarch, address_end));
10051   ui_out_field_stream (uiout, "addr", stb);
10052   ui_out_text (uiout, "\n");
10053
10054   do_cleanups (cleanup);
10055 }
10056
10057 /* Implement the "print_mention" breakpoint_ops method for
10058    ranged breakpoints.  */
10059
10060 static void
10061 print_mention_ranged_breakpoint (struct breakpoint *b)
10062 {
10063   struct bp_location *bl = b->loc;
10064   struct ui_out *uiout = current_uiout;
10065
10066   gdb_assert (bl);
10067   gdb_assert (b->type == bp_hardware_breakpoint);
10068
10069   if (ui_out_is_mi_like_p (uiout))
10070     return;
10071
10072   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10073                    b->number, paddress (bl->gdbarch, bl->address),
10074                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10075 }
10076
10077 /* Implement the "print_recreate" breakpoint_ops method for
10078    ranged breakpoints.  */
10079
10080 static void
10081 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10082 {
10083   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10084                       b->addr_string_range_end);
10085   print_recreate_thread (b, fp);
10086 }
10087
10088 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10089
10090 static struct breakpoint_ops ranged_breakpoint_ops;
10091
10092 /* Find the address where the end of the breakpoint range should be
10093    placed, given the SAL of the end of the range.  This is so that if
10094    the user provides a line number, the end of the range is set to the
10095    last instruction of the given line.  */
10096
10097 static CORE_ADDR
10098 find_breakpoint_range_end (struct symtab_and_line sal)
10099 {
10100   CORE_ADDR end;
10101
10102   /* If the user provided a PC value, use it.  Otherwise,
10103      find the address of the end of the given location.  */
10104   if (sal.explicit_pc)
10105     end = sal.pc;
10106   else
10107     {
10108       int ret;
10109       CORE_ADDR start;
10110
10111       ret = find_line_pc_range (sal, &start, &end);
10112       if (!ret)
10113         error (_("Could not find location of the end of the range."));
10114
10115       /* find_line_pc_range returns the start of the next line.  */
10116       end--;
10117     }
10118
10119   return end;
10120 }
10121
10122 /* Implement the "break-range" CLI command.  */
10123
10124 static void
10125 break_range_command (char *arg, int from_tty)
10126 {
10127   char *arg_start, *addr_string_start, *addr_string_end;
10128   struct linespec_result canonical_start, canonical_end;
10129   int bp_count, can_use_bp, length;
10130   CORE_ADDR end;
10131   struct breakpoint *b;
10132   struct symtab_and_line sal_start, sal_end;
10133   struct cleanup *cleanup_bkpt;
10134   struct linespec_sals *lsal_start, *lsal_end;
10135
10136   /* We don't support software ranged breakpoints.  */
10137   if (target_ranged_break_num_registers () < 0)
10138     error (_("This target does not support hardware ranged breakpoints."));
10139
10140   bp_count = hw_breakpoint_used_count ();
10141   bp_count += target_ranged_break_num_registers ();
10142   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10143                                                    bp_count, 0);
10144   if (can_use_bp < 0)
10145     error (_("Hardware breakpoints used exceeds limit."));
10146
10147   arg = skip_spaces (arg);
10148   if (arg == NULL || arg[0] == '\0')
10149     error(_("No address range specified."));
10150
10151   init_linespec_result (&canonical_start);
10152
10153   arg_start = arg;
10154   parse_breakpoint_sals (&arg, &canonical_start);
10155
10156   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10157
10158   if (arg[0] != ',')
10159     error (_("Too few arguments."));
10160   else if (VEC_empty (linespec_sals, canonical_start.sals))
10161     error (_("Could not find location of the beginning of the range."));
10162
10163   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10164
10165   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10166       || lsal_start->sals.nelts != 1)
10167     error (_("Cannot create a ranged breakpoint with multiple locations."));
10168
10169   sal_start = lsal_start->sals.sals[0];
10170   addr_string_start = savestring (arg_start, arg - arg_start);
10171   make_cleanup (xfree, addr_string_start);
10172
10173   arg++;        /* Skip the comma.  */
10174   arg = skip_spaces (arg);
10175
10176   /* Parse the end location.  */
10177
10178   init_linespec_result (&canonical_end);
10179   arg_start = arg;
10180
10181   /* We call decode_line_full directly here instead of using
10182      parse_breakpoint_sals because we need to specify the start location's
10183      symtab and line as the default symtab and line for the end of the
10184      range.  This makes it possible to have ranges like "foo.c:27, +14",
10185      where +14 means 14 lines from the start location.  */
10186   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10187                     sal_start.symtab, sal_start.line,
10188                     &canonical_end, NULL, NULL);
10189
10190   make_cleanup_destroy_linespec_result (&canonical_end);
10191
10192   if (VEC_empty (linespec_sals, canonical_end.sals))
10193     error (_("Could not find location of the end of the range."));
10194
10195   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10196   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10197       || lsal_end->sals.nelts != 1)
10198     error (_("Cannot create a ranged breakpoint with multiple locations."));
10199
10200   sal_end = lsal_end->sals.sals[0];
10201   addr_string_end = savestring (arg_start, arg - arg_start);
10202   make_cleanup (xfree, addr_string_end);
10203
10204   end = find_breakpoint_range_end (sal_end);
10205   if (sal_start.pc > end)
10206     error (_("Invalid address range, end precedes start."));
10207
10208   length = end - sal_start.pc + 1;
10209   if (length < 0)
10210     /* Length overflowed.  */
10211     error (_("Address range too large."));
10212   else if (length == 1)
10213     {
10214       /* This range is simple enough to be handled by
10215          the `hbreak' command.  */
10216       hbreak_command (addr_string_start, 1);
10217
10218       do_cleanups (cleanup_bkpt);
10219
10220       return;
10221     }
10222
10223   /* Now set up the breakpoint.  */
10224   b = set_raw_breakpoint (get_current_arch (), sal_start,
10225                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10226   set_breakpoint_count (breakpoint_count + 1);
10227   b->number = breakpoint_count;
10228   b->disposition = disp_donttouch;
10229   b->addr_string = xstrdup (addr_string_start);
10230   b->addr_string_range_end = xstrdup (addr_string_end);
10231   b->loc->length = length;
10232
10233   do_cleanups (cleanup_bkpt);
10234
10235   mention (b);
10236   observer_notify_breakpoint_created (b);
10237   update_global_location_list (1);
10238 }
10239
10240 /*  Return non-zero if EXP is verified as constant.  Returned zero
10241     means EXP is variable.  Also the constant detection may fail for
10242     some constant expressions and in such case still falsely return
10243     zero.  */
10244
10245 static int
10246 watchpoint_exp_is_const (const struct expression *exp)
10247 {
10248   int i = exp->nelts;
10249
10250   while (i > 0)
10251     {
10252       int oplenp, argsp;
10253
10254       /* We are only interested in the descriptor of each element.  */
10255       operator_length (exp, i, &oplenp, &argsp);
10256       i -= oplenp;
10257
10258       switch (exp->elts[i].opcode)
10259         {
10260         case BINOP_ADD:
10261         case BINOP_SUB:
10262         case BINOP_MUL:
10263         case BINOP_DIV:
10264         case BINOP_REM:
10265         case BINOP_MOD:
10266         case BINOP_LSH:
10267         case BINOP_RSH:
10268         case BINOP_LOGICAL_AND:
10269         case BINOP_LOGICAL_OR:
10270         case BINOP_BITWISE_AND:
10271         case BINOP_BITWISE_IOR:
10272         case BINOP_BITWISE_XOR:
10273         case BINOP_EQUAL:
10274         case BINOP_NOTEQUAL:
10275         case BINOP_LESS:
10276         case BINOP_GTR:
10277         case BINOP_LEQ:
10278         case BINOP_GEQ:
10279         case BINOP_REPEAT:
10280         case BINOP_COMMA:
10281         case BINOP_EXP:
10282         case BINOP_MIN:
10283         case BINOP_MAX:
10284         case BINOP_INTDIV:
10285         case BINOP_CONCAT:
10286         case BINOP_IN:
10287         case BINOP_RANGE:
10288         case TERNOP_COND:
10289         case TERNOP_SLICE:
10290
10291         case OP_LONG:
10292         case OP_DOUBLE:
10293         case OP_DECFLOAT:
10294         case OP_LAST:
10295         case OP_COMPLEX:
10296         case OP_STRING:
10297         case OP_ARRAY:
10298         case OP_TYPE:
10299         case OP_TYPEOF:
10300         case OP_DECLTYPE:
10301         case OP_TYPEID:
10302         case OP_NAME:
10303         case OP_OBJC_NSSTRING:
10304
10305         case UNOP_NEG:
10306         case UNOP_LOGICAL_NOT:
10307         case UNOP_COMPLEMENT:
10308         case UNOP_ADDR:
10309         case UNOP_HIGH:
10310         case UNOP_CAST:
10311
10312         case UNOP_CAST_TYPE:
10313         case UNOP_REINTERPRET_CAST:
10314         case UNOP_DYNAMIC_CAST:
10315           /* Unary, binary and ternary operators: We have to check
10316              their operands.  If they are constant, then so is the
10317              result of that operation.  For instance, if A and B are
10318              determined to be constants, then so is "A + B".
10319
10320              UNOP_IND is one exception to the rule above, because the
10321              value of *ADDR is not necessarily a constant, even when
10322              ADDR is.  */
10323           break;
10324
10325         case OP_VAR_VALUE:
10326           /* Check whether the associated symbol is a constant.
10327
10328              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10329              possible that a buggy compiler could mark a variable as
10330              constant even when it is not, and TYPE_CONST would return
10331              true in this case, while SYMBOL_CLASS wouldn't.
10332
10333              We also have to check for function symbols because they
10334              are always constant.  */
10335           {
10336             struct symbol *s = exp->elts[i + 2].symbol;
10337
10338             if (SYMBOL_CLASS (s) != LOC_BLOCK
10339                 && SYMBOL_CLASS (s) != LOC_CONST
10340                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10341               return 0;
10342             break;
10343           }
10344
10345         /* The default action is to return 0 because we are using
10346            the optimistic approach here: If we don't know something,
10347            then it is not a constant.  */
10348         default:
10349           return 0;
10350         }
10351     }
10352
10353   return 1;
10354 }
10355
10356 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10357
10358 static void
10359 dtor_watchpoint (struct breakpoint *self)
10360 {
10361   struct watchpoint *w = (struct watchpoint *) self;
10362
10363   xfree (w->cond_exp);
10364   xfree (w->exp);
10365   xfree (w->exp_string);
10366   xfree (w->exp_string_reparse);
10367   value_free (w->val);
10368
10369   base_breakpoint_ops.dtor (self);
10370 }
10371
10372 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10373
10374 static void
10375 re_set_watchpoint (struct breakpoint *b)
10376 {
10377   struct watchpoint *w = (struct watchpoint *) b;
10378
10379   /* Watchpoint can be either on expression using entirely global
10380      variables, or it can be on local variables.
10381
10382      Watchpoints of the first kind are never auto-deleted, and even
10383      persist across program restarts.  Since they can use variables
10384      from shared libraries, we need to reparse expression as libraries
10385      are loaded and unloaded.
10386
10387      Watchpoints on local variables can also change meaning as result
10388      of solib event.  For example, if a watchpoint uses both a local
10389      and a global variables in expression, it's a local watchpoint,
10390      but unloading of a shared library will make the expression
10391      invalid.  This is not a very common use case, but we still
10392      re-evaluate expression, to avoid surprises to the user.
10393
10394      Note that for local watchpoints, we re-evaluate it only if
10395      watchpoints frame id is still valid.  If it's not, it means the
10396      watchpoint is out of scope and will be deleted soon.  In fact,
10397      I'm not sure we'll ever be called in this case.
10398
10399      If a local watchpoint's frame id is still valid, then
10400      w->exp_valid_block is likewise valid, and we can safely use it.
10401
10402      Don't do anything about disabled watchpoints, since they will be
10403      reevaluated again when enabled.  */
10404   update_watchpoint (w, 1 /* reparse */);
10405 }
10406
10407 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10408
10409 static int
10410 insert_watchpoint (struct bp_location *bl)
10411 {
10412   struct watchpoint *w = (struct watchpoint *) bl->owner;
10413   int length = w->exact ? 1 : bl->length;
10414
10415   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10416                                    w->cond_exp);
10417 }
10418
10419 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10420
10421 static int
10422 remove_watchpoint (struct bp_location *bl)
10423 {
10424   struct watchpoint *w = (struct watchpoint *) bl->owner;
10425   int length = w->exact ? 1 : bl->length;
10426
10427   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10428                                    w->cond_exp);
10429 }
10430
10431 static int
10432 breakpoint_hit_watchpoint (const struct bp_location *bl,
10433                            struct address_space *aspace, CORE_ADDR bp_addr,
10434                            const struct target_waitstatus *ws)
10435 {
10436   struct breakpoint *b = bl->owner;
10437   struct watchpoint *w = (struct watchpoint *) b;
10438
10439   /* Continuable hardware watchpoints are treated as non-existent if the
10440      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10441      some data address).  Otherwise gdb won't stop on a break instruction
10442      in the code (not from a breakpoint) when a hardware watchpoint has
10443      been defined.  Also skip watchpoints which we know did not trigger
10444      (did not match the data address).  */
10445   if (is_hardware_watchpoint (b)
10446       && w->watchpoint_triggered == watch_triggered_no)
10447     return 0;
10448
10449   return 1;
10450 }
10451
10452 static void
10453 check_status_watchpoint (bpstat bs)
10454 {
10455   gdb_assert (is_watchpoint (bs->breakpoint_at));
10456
10457   bpstat_check_watchpoint (bs);
10458 }
10459
10460 /* Implement the "resources_needed" breakpoint_ops method for
10461    hardware watchpoints.  */
10462
10463 static int
10464 resources_needed_watchpoint (const struct bp_location *bl)
10465 {
10466   struct watchpoint *w = (struct watchpoint *) bl->owner;
10467   int length = w->exact? 1 : bl->length;
10468
10469   return target_region_ok_for_hw_watchpoint (bl->address, length);
10470 }
10471
10472 /* Implement the "works_in_software_mode" breakpoint_ops method for
10473    hardware watchpoints.  */
10474
10475 static int
10476 works_in_software_mode_watchpoint (const struct breakpoint *b)
10477 {
10478   /* Read and access watchpoints only work with hardware support.  */
10479   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10480 }
10481
10482 static enum print_stop_action
10483 print_it_watchpoint (bpstat bs)
10484 {
10485   struct cleanup *old_chain;
10486   struct breakpoint *b;
10487   struct ui_file *stb;
10488   enum print_stop_action result;
10489   struct watchpoint *w;
10490   struct ui_out *uiout = current_uiout;
10491
10492   gdb_assert (bs->bp_location_at != NULL);
10493
10494   b = bs->breakpoint_at;
10495   w = (struct watchpoint *) b;
10496
10497   stb = mem_fileopen ();
10498   old_chain = make_cleanup_ui_file_delete (stb);
10499
10500   switch (b->type)
10501     {
10502     case bp_watchpoint:
10503     case bp_hardware_watchpoint:
10504       annotate_watchpoint (b->number);
10505       if (ui_out_is_mi_like_p (uiout))
10506         ui_out_field_string
10507           (uiout, "reason",
10508            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10509       mention (b);
10510       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10511       ui_out_text (uiout, "\nOld value = ");
10512       watchpoint_value_print (bs->old_val, stb);
10513       ui_out_field_stream (uiout, "old", stb);
10514       ui_out_text (uiout, "\nNew value = ");
10515       watchpoint_value_print (w->val, stb);
10516       ui_out_field_stream (uiout, "new", stb);
10517       ui_out_text (uiout, "\n");
10518       /* More than one watchpoint may have been triggered.  */
10519       result = PRINT_UNKNOWN;
10520       break;
10521
10522     case bp_read_watchpoint:
10523       if (ui_out_is_mi_like_p (uiout))
10524         ui_out_field_string
10525           (uiout, "reason",
10526            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10527       mention (b);
10528       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10529       ui_out_text (uiout, "\nValue = ");
10530       watchpoint_value_print (w->val, stb);
10531       ui_out_field_stream (uiout, "value", stb);
10532       ui_out_text (uiout, "\n");
10533       result = PRINT_UNKNOWN;
10534       break;
10535
10536     case bp_access_watchpoint:
10537       if (bs->old_val != NULL)
10538         {
10539           annotate_watchpoint (b->number);
10540           if (ui_out_is_mi_like_p (uiout))
10541             ui_out_field_string
10542               (uiout, "reason",
10543                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10544           mention (b);
10545           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10546           ui_out_text (uiout, "\nOld value = ");
10547           watchpoint_value_print (bs->old_val, stb);
10548           ui_out_field_stream (uiout, "old", stb);
10549           ui_out_text (uiout, "\nNew value = ");
10550         }
10551       else
10552         {
10553           mention (b);
10554           if (ui_out_is_mi_like_p (uiout))
10555             ui_out_field_string
10556               (uiout, "reason",
10557                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10558           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10559           ui_out_text (uiout, "\nValue = ");
10560         }
10561       watchpoint_value_print (w->val, stb);
10562       ui_out_field_stream (uiout, "new", stb);
10563       ui_out_text (uiout, "\n");
10564       result = PRINT_UNKNOWN;
10565       break;
10566     default:
10567       result = PRINT_UNKNOWN;
10568     }
10569
10570   do_cleanups (old_chain);
10571   return result;
10572 }
10573
10574 /* Implement the "print_mention" breakpoint_ops method for hardware
10575    watchpoints.  */
10576
10577 static void
10578 print_mention_watchpoint (struct breakpoint *b)
10579 {
10580   struct cleanup *ui_out_chain;
10581   struct watchpoint *w = (struct watchpoint *) b;
10582   struct ui_out *uiout = current_uiout;
10583
10584   switch (b->type)
10585     {
10586     case bp_watchpoint:
10587       ui_out_text (uiout, "Watchpoint ");
10588       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10589       break;
10590     case bp_hardware_watchpoint:
10591       ui_out_text (uiout, "Hardware watchpoint ");
10592       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10593       break;
10594     case bp_read_watchpoint:
10595       ui_out_text (uiout, "Hardware read watchpoint ");
10596       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10597       break;
10598     case bp_access_watchpoint:
10599       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10600       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10601       break;
10602     default:
10603       internal_error (__FILE__, __LINE__,
10604                       _("Invalid hardware watchpoint type."));
10605     }
10606
10607   ui_out_field_int (uiout, "number", b->number);
10608   ui_out_text (uiout, ": ");
10609   ui_out_field_string (uiout, "exp", w->exp_string);
10610   do_cleanups (ui_out_chain);
10611 }
10612
10613 /* Implement the "print_recreate" breakpoint_ops method for
10614    watchpoints.  */
10615
10616 static void
10617 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10618 {
10619   struct watchpoint *w = (struct watchpoint *) b;
10620
10621   switch (b->type)
10622     {
10623     case bp_watchpoint:
10624     case bp_hardware_watchpoint:
10625       fprintf_unfiltered (fp, "watch");
10626       break;
10627     case bp_read_watchpoint:
10628       fprintf_unfiltered (fp, "rwatch");
10629       break;
10630     case bp_access_watchpoint:
10631       fprintf_unfiltered (fp, "awatch");
10632       break;
10633     default:
10634       internal_error (__FILE__, __LINE__,
10635                       _("Invalid watchpoint type."));
10636     }
10637
10638   fprintf_unfiltered (fp, " %s", w->exp_string);
10639   print_recreate_thread (b, fp);
10640 }
10641
10642 /* Implement the "explains_signal" breakpoint_ops method for
10643    watchpoints.  */
10644
10645 static enum bpstat_signal_value
10646 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10647 {
10648   /* A software watchpoint cannot cause a signal other than
10649      GDB_SIGNAL_TRAP.  */
10650   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10651     return BPSTAT_SIGNAL_NO;
10652
10653   return BPSTAT_SIGNAL_HIDE;
10654 }
10655
10656 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10657
10658 static struct breakpoint_ops watchpoint_breakpoint_ops;
10659
10660 /* Implement the "insert" breakpoint_ops method for
10661    masked hardware watchpoints.  */
10662
10663 static int
10664 insert_masked_watchpoint (struct bp_location *bl)
10665 {
10666   struct watchpoint *w = (struct watchpoint *) bl->owner;
10667
10668   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10669                                         bl->watchpoint_type);
10670 }
10671
10672 /* Implement the "remove" breakpoint_ops method for
10673    masked hardware watchpoints.  */
10674
10675 static int
10676 remove_masked_watchpoint (struct bp_location *bl)
10677 {
10678   struct watchpoint *w = (struct watchpoint *) bl->owner;
10679
10680   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10681                                         bl->watchpoint_type);
10682 }
10683
10684 /* Implement the "resources_needed" breakpoint_ops method for
10685    masked hardware watchpoints.  */
10686
10687 static int
10688 resources_needed_masked_watchpoint (const struct bp_location *bl)
10689 {
10690   struct watchpoint *w = (struct watchpoint *) bl->owner;
10691
10692   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10693 }
10694
10695 /* Implement the "works_in_software_mode" breakpoint_ops method for
10696    masked hardware watchpoints.  */
10697
10698 static int
10699 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10700 {
10701   return 0;
10702 }
10703
10704 /* Implement the "print_it" breakpoint_ops method for
10705    masked hardware watchpoints.  */
10706
10707 static enum print_stop_action
10708 print_it_masked_watchpoint (bpstat bs)
10709 {
10710   struct breakpoint *b = bs->breakpoint_at;
10711   struct ui_out *uiout = current_uiout;
10712
10713   /* Masked watchpoints have only one location.  */
10714   gdb_assert (b->loc && b->loc->next == NULL);
10715
10716   switch (b->type)
10717     {
10718     case bp_hardware_watchpoint:
10719       annotate_watchpoint (b->number);
10720       if (ui_out_is_mi_like_p (uiout))
10721         ui_out_field_string
10722           (uiout, "reason",
10723            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10724       break;
10725
10726     case bp_read_watchpoint:
10727       if (ui_out_is_mi_like_p (uiout))
10728         ui_out_field_string
10729           (uiout, "reason",
10730            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10731       break;
10732
10733     case bp_access_watchpoint:
10734       if (ui_out_is_mi_like_p (uiout))
10735         ui_out_field_string
10736           (uiout, "reason",
10737            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10738       break;
10739     default:
10740       internal_error (__FILE__, __LINE__,
10741                       _("Invalid hardware watchpoint type."));
10742     }
10743
10744   mention (b);
10745   ui_out_text (uiout, _("\n\
10746 Check the underlying instruction at PC for the memory\n\
10747 address and value which triggered this watchpoint.\n"));
10748   ui_out_text (uiout, "\n");
10749
10750   /* More than one watchpoint may have been triggered.  */
10751   return PRINT_UNKNOWN;
10752 }
10753
10754 /* Implement the "print_one_detail" breakpoint_ops method for
10755    masked hardware watchpoints.  */
10756
10757 static void
10758 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10759                                     struct ui_out *uiout)
10760 {
10761   struct watchpoint *w = (struct watchpoint *) b;
10762
10763   /* Masked watchpoints have only one location.  */
10764   gdb_assert (b->loc && b->loc->next == NULL);
10765
10766   ui_out_text (uiout, "\tmask ");
10767   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10768   ui_out_text (uiout, "\n");
10769 }
10770
10771 /* Implement the "print_mention" breakpoint_ops method for
10772    masked hardware watchpoints.  */
10773
10774 static void
10775 print_mention_masked_watchpoint (struct breakpoint *b)
10776 {
10777   struct watchpoint *w = (struct watchpoint *) b;
10778   struct ui_out *uiout = current_uiout;
10779   struct cleanup *ui_out_chain;
10780
10781   switch (b->type)
10782     {
10783     case bp_hardware_watchpoint:
10784       ui_out_text (uiout, "Masked hardware watchpoint ");
10785       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10786       break;
10787     case bp_read_watchpoint:
10788       ui_out_text (uiout, "Masked hardware read watchpoint ");
10789       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10790       break;
10791     case bp_access_watchpoint:
10792       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10793       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10794       break;
10795     default:
10796       internal_error (__FILE__, __LINE__,
10797                       _("Invalid hardware watchpoint type."));
10798     }
10799
10800   ui_out_field_int (uiout, "number", b->number);
10801   ui_out_text (uiout, ": ");
10802   ui_out_field_string (uiout, "exp", w->exp_string);
10803   do_cleanups (ui_out_chain);
10804 }
10805
10806 /* Implement the "print_recreate" breakpoint_ops method for
10807    masked hardware watchpoints.  */
10808
10809 static void
10810 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10811 {
10812   struct watchpoint *w = (struct watchpoint *) b;
10813   char tmp[40];
10814
10815   switch (b->type)
10816     {
10817     case bp_hardware_watchpoint:
10818       fprintf_unfiltered (fp, "watch");
10819       break;
10820     case bp_read_watchpoint:
10821       fprintf_unfiltered (fp, "rwatch");
10822       break;
10823     case bp_access_watchpoint:
10824       fprintf_unfiltered (fp, "awatch");
10825       break;
10826     default:
10827       internal_error (__FILE__, __LINE__,
10828                       _("Invalid hardware watchpoint type."));
10829     }
10830
10831   sprintf_vma (tmp, w->hw_wp_mask);
10832   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10833   print_recreate_thread (b, fp);
10834 }
10835
10836 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10837
10838 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10839
10840 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10841
10842 static int
10843 is_masked_watchpoint (const struct breakpoint *b)
10844 {
10845   return b->ops == &masked_watchpoint_breakpoint_ops;
10846 }
10847
10848 /* accessflag:  hw_write:  watch write, 
10849                 hw_read:   watch read, 
10850                 hw_access: watch access (read or write) */
10851 static void
10852 watch_command_1 (const char *arg, int accessflag, int from_tty,
10853                  int just_location, int internal)
10854 {
10855   volatile struct gdb_exception e;
10856   struct breakpoint *b, *scope_breakpoint = NULL;
10857   struct expression *exp;
10858   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10859   struct value *val, *mark, *result;
10860   struct frame_info *frame;
10861   const char *exp_start = NULL;
10862   const char *exp_end = NULL;
10863   const char *tok, *end_tok;
10864   int toklen = -1;
10865   const char *cond_start = NULL;
10866   const char *cond_end = NULL;
10867   enum bptype bp_type;
10868   int thread = -1;
10869   int pc = 0;
10870   /* Flag to indicate whether we are going to use masks for
10871      the hardware watchpoint.  */
10872   int use_mask = 0;
10873   CORE_ADDR mask = 0;
10874   struct watchpoint *w;
10875   char *expression;
10876   struct cleanup *back_to;
10877
10878   /* Make sure that we actually have parameters to parse.  */
10879   if (arg != NULL && arg[0] != '\0')
10880     {
10881       const char *value_start;
10882
10883       exp_end = arg + strlen (arg);
10884
10885       /* Look for "parameter value" pairs at the end
10886          of the arguments string.  */
10887       for (tok = exp_end - 1; tok > arg; tok--)
10888         {
10889           /* Skip whitespace at the end of the argument list.  */
10890           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10891             tok--;
10892
10893           /* Find the beginning of the last token.
10894              This is the value of the parameter.  */
10895           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10896             tok--;
10897           value_start = tok + 1;
10898
10899           /* Skip whitespace.  */
10900           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10901             tok--;
10902
10903           end_tok = tok;
10904
10905           /* Find the beginning of the second to last token.
10906              This is the parameter itself.  */
10907           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10908             tok--;
10909           tok++;
10910           toklen = end_tok - tok + 1;
10911
10912           if (toklen == 6 && !strncmp (tok, "thread", 6))
10913             {
10914               /* At this point we've found a "thread" token, which means
10915                  the user is trying to set a watchpoint that triggers
10916                  only in a specific thread.  */
10917               char *endp;
10918
10919               if (thread != -1)
10920                 error(_("You can specify only one thread."));
10921
10922               /* Extract the thread ID from the next token.  */
10923               thread = strtol (value_start, &endp, 0);
10924
10925               /* Check if the user provided a valid numeric value for the
10926                  thread ID.  */
10927               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10928                 error (_("Invalid thread ID specification %s."), value_start);
10929
10930               /* Check if the thread actually exists.  */
10931               if (!valid_thread_id (thread))
10932                 invalid_thread_id_error (thread);
10933             }
10934           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10935             {
10936               /* We've found a "mask" token, which means the user wants to
10937                  create a hardware watchpoint that is going to have the mask
10938                  facility.  */
10939               struct value *mask_value, *mark;
10940
10941               if (use_mask)
10942                 error(_("You can specify only one mask."));
10943
10944               use_mask = just_location = 1;
10945
10946               mark = value_mark ();
10947               mask_value = parse_to_comma_and_eval (&value_start);
10948               mask = value_as_address (mask_value);
10949               value_free_to_mark (mark);
10950             }
10951           else
10952             /* We didn't recognize what we found.  We should stop here.  */
10953             break;
10954
10955           /* Truncate the string and get rid of the "parameter value" pair before
10956              the arguments string is parsed by the parse_exp_1 function.  */
10957           exp_end = tok;
10958         }
10959     }
10960   else
10961     exp_end = arg;
10962
10963   /* Parse the rest of the arguments.  From here on out, everything
10964      is in terms of a newly allocated string instead of the original
10965      ARG.  */
10966   innermost_block = NULL;
10967   expression = savestring (arg, exp_end - arg);
10968   back_to = make_cleanup (xfree, expression);
10969   exp_start = arg = expression;
10970   exp = parse_exp_1 (&arg, 0, 0, 0);
10971   exp_end = arg;
10972   /* Remove trailing whitespace from the expression before saving it.
10973      This makes the eventual display of the expression string a bit
10974      prettier.  */
10975   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10976     --exp_end;
10977
10978   /* Checking if the expression is not constant.  */
10979   if (watchpoint_exp_is_const (exp))
10980     {
10981       int len;
10982
10983       len = exp_end - exp_start;
10984       while (len > 0 && isspace (exp_start[len - 1]))
10985         len--;
10986       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10987     }
10988
10989   exp_valid_block = innermost_block;
10990   mark = value_mark ();
10991   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10992
10993   if (just_location)
10994     {
10995       int ret;
10996
10997       exp_valid_block = NULL;
10998       val = value_addr (result);
10999       release_value (val);
11000       value_free_to_mark (mark);
11001
11002       if (use_mask)
11003         {
11004           ret = target_masked_watch_num_registers (value_as_address (val),
11005                                                    mask);
11006           if (ret == -1)
11007             error (_("This target does not support masked watchpoints."));
11008           else if (ret == -2)
11009             error (_("Invalid mask or memory region."));
11010         }
11011     }
11012   else if (val != NULL)
11013     release_value (val);
11014
11015   tok = skip_spaces_const (arg);
11016   end_tok = skip_to_space_const (tok);
11017
11018   toklen = end_tok - tok;
11019   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11020     {
11021       struct expression *cond;
11022
11023       innermost_block = NULL;
11024       tok = cond_start = end_tok + 1;
11025       cond = parse_exp_1 (&tok, 0, 0, 0);
11026
11027       /* The watchpoint expression may not be local, but the condition
11028          may still be.  E.g.: `watch global if local > 0'.  */
11029       cond_exp_valid_block = innermost_block;
11030
11031       xfree (cond);
11032       cond_end = tok;
11033     }
11034   if (*tok)
11035     error (_("Junk at end of command."));
11036
11037   if (accessflag == hw_read)
11038     bp_type = bp_read_watchpoint;
11039   else if (accessflag == hw_access)
11040     bp_type = bp_access_watchpoint;
11041   else
11042     bp_type = bp_hardware_watchpoint;
11043
11044   frame = block_innermost_frame (exp_valid_block);
11045
11046   /* If the expression is "local", then set up a "watchpoint scope"
11047      breakpoint at the point where we've left the scope of the watchpoint
11048      expression.  Create the scope breakpoint before the watchpoint, so
11049      that we will encounter it first in bpstat_stop_status.  */
11050   if (exp_valid_block && frame)
11051     {
11052       if (frame_id_p (frame_unwind_caller_id (frame)))
11053         {
11054           scope_breakpoint
11055             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11056                                           frame_unwind_caller_pc (frame),
11057                                           bp_watchpoint_scope,
11058                                           &momentary_breakpoint_ops);
11059
11060           scope_breakpoint->enable_state = bp_enabled;
11061
11062           /* Automatically delete the breakpoint when it hits.  */
11063           scope_breakpoint->disposition = disp_del;
11064
11065           /* Only break in the proper frame (help with recursion).  */
11066           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11067
11068           /* Set the address at which we will stop.  */
11069           scope_breakpoint->loc->gdbarch
11070             = frame_unwind_caller_arch (frame);
11071           scope_breakpoint->loc->requested_address
11072             = frame_unwind_caller_pc (frame);
11073           scope_breakpoint->loc->address
11074             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11075                                          scope_breakpoint->loc->requested_address,
11076                                          scope_breakpoint->type);
11077         }
11078     }
11079
11080   /* Now set up the breakpoint.  */
11081
11082   w = XCNEW (struct watchpoint);
11083   b = &w->base;
11084   if (use_mask)
11085     init_raw_breakpoint_without_location (b, NULL, bp_type,
11086                                           &masked_watchpoint_breakpoint_ops);
11087   else
11088     init_raw_breakpoint_without_location (b, NULL, bp_type,
11089                                           &watchpoint_breakpoint_ops);
11090   b->thread = thread;
11091   b->disposition = disp_donttouch;
11092   b->pspace = current_program_space;
11093   w->exp = exp;
11094   w->exp_valid_block = exp_valid_block;
11095   w->cond_exp_valid_block = cond_exp_valid_block;
11096   if (just_location)
11097     {
11098       struct type *t = value_type (val);
11099       CORE_ADDR addr = value_as_address (val);
11100       char *name;
11101
11102       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11103       name = type_to_string (t);
11104
11105       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11106                                           core_addr_to_string (addr));
11107       xfree (name);
11108
11109       w->exp_string = xstrprintf ("-location %.*s",
11110                                   (int) (exp_end - exp_start), exp_start);
11111
11112       /* The above expression is in C.  */
11113       b->language = language_c;
11114     }
11115   else
11116     w->exp_string = savestring (exp_start, exp_end - exp_start);
11117
11118   if (use_mask)
11119     {
11120       w->hw_wp_mask = mask;
11121     }
11122   else
11123     {
11124       w->val = val;
11125       w->val_valid = 1;
11126     }
11127
11128   if (cond_start)
11129     b->cond_string = savestring (cond_start, cond_end - cond_start);
11130   else
11131     b->cond_string = 0;
11132
11133   if (frame)
11134     {
11135       w->watchpoint_frame = get_frame_id (frame);
11136       w->watchpoint_thread = inferior_ptid;
11137     }
11138   else
11139     {
11140       w->watchpoint_frame = null_frame_id;
11141       w->watchpoint_thread = null_ptid;
11142     }
11143
11144   if (scope_breakpoint != NULL)
11145     {
11146       /* The scope breakpoint is related to the watchpoint.  We will
11147          need to act on them together.  */
11148       b->related_breakpoint = scope_breakpoint;
11149       scope_breakpoint->related_breakpoint = b;
11150     }
11151
11152   if (!just_location)
11153     value_free_to_mark (mark);
11154
11155   TRY_CATCH (e, RETURN_MASK_ALL)
11156     {
11157       /* Finally update the new watchpoint.  This creates the locations
11158          that should be inserted.  */
11159       update_watchpoint (w, 1);
11160     }
11161   if (e.reason < 0)
11162     {
11163       delete_breakpoint (b);
11164       throw_exception (e);
11165     }
11166
11167   install_breakpoint (internal, b, 1);
11168   do_cleanups (back_to);
11169 }
11170
11171 /* Return count of debug registers needed to watch the given expression.
11172    If the watchpoint cannot be handled in hardware return zero.  */
11173
11174 static int
11175 can_use_hardware_watchpoint (struct value *v)
11176 {
11177   int found_memory_cnt = 0;
11178   struct value *head = v;
11179
11180   /* Did the user specifically forbid us to use hardware watchpoints? */
11181   if (!can_use_hw_watchpoints)
11182     return 0;
11183
11184   /* Make sure that the value of the expression depends only upon
11185      memory contents, and values computed from them within GDB.  If we
11186      find any register references or function calls, we can't use a
11187      hardware watchpoint.
11188
11189      The idea here is that evaluating an expression generates a series
11190      of values, one holding the value of every subexpression.  (The
11191      expression a*b+c has five subexpressions: a, b, a*b, c, and
11192      a*b+c.)  GDB's values hold almost enough information to establish
11193      the criteria given above --- they identify memory lvalues,
11194      register lvalues, computed values, etcetera.  So we can evaluate
11195      the expression, and then scan the chain of values that leaves
11196      behind to decide whether we can detect any possible change to the
11197      expression's final value using only hardware watchpoints.
11198
11199      However, I don't think that the values returned by inferior
11200      function calls are special in any way.  So this function may not
11201      notice that an expression involving an inferior function call
11202      can't be watched with hardware watchpoints.  FIXME.  */
11203   for (; v; v = value_next (v))
11204     {
11205       if (VALUE_LVAL (v) == lval_memory)
11206         {
11207           if (v != head && value_lazy (v))
11208             /* A lazy memory lvalue in the chain is one that GDB never
11209                needed to fetch; we either just used its address (e.g.,
11210                `a' in `a.b') or we never needed it at all (e.g., `a'
11211                in `a,b').  This doesn't apply to HEAD; if that is
11212                lazy then it was not readable, but watch it anyway.  */
11213             ;
11214           else
11215             {
11216               /* Ahh, memory we actually used!  Check if we can cover
11217                  it with hardware watchpoints.  */
11218               struct type *vtype = check_typedef (value_type (v));
11219
11220               /* We only watch structs and arrays if user asked for it
11221                  explicitly, never if they just happen to appear in a
11222                  middle of some value chain.  */
11223               if (v == head
11224                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11225                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11226                 {
11227                   CORE_ADDR vaddr = value_address (v);
11228                   int len;
11229                   int num_regs;
11230
11231                   len = (target_exact_watchpoints
11232                          && is_scalar_type_recursive (vtype))?
11233                     1 : TYPE_LENGTH (value_type (v));
11234
11235                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11236                   if (!num_regs)
11237                     return 0;
11238                   else
11239                     found_memory_cnt += num_regs;
11240                 }
11241             }
11242         }
11243       else if (VALUE_LVAL (v) != not_lval
11244                && deprecated_value_modifiable (v) == 0)
11245         return 0;       /* These are values from the history (e.g., $1).  */
11246       else if (VALUE_LVAL (v) == lval_register)
11247         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11248     }
11249
11250   /* The expression itself looks suitable for using a hardware
11251      watchpoint, but give the target machine a chance to reject it.  */
11252   return found_memory_cnt;
11253 }
11254
11255 void
11256 watch_command_wrapper (char *arg, int from_tty, int internal)
11257 {
11258   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11259 }
11260
11261 /* A helper function that looks for the "-location" argument and then
11262    calls watch_command_1.  */
11263
11264 static void
11265 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11266 {
11267   int just_location = 0;
11268
11269   if (arg
11270       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11271           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11272     {
11273       arg = skip_spaces (arg);
11274       just_location = 1;
11275     }
11276
11277   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11278 }
11279
11280 static void
11281 watch_command (char *arg, int from_tty)
11282 {
11283   watch_maybe_just_location (arg, hw_write, from_tty);
11284 }
11285
11286 void
11287 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11288 {
11289   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11290 }
11291
11292 static void
11293 rwatch_command (char *arg, int from_tty)
11294 {
11295   watch_maybe_just_location (arg, hw_read, from_tty);
11296 }
11297
11298 void
11299 awatch_command_wrapper (char *arg, int from_tty, int internal)
11300 {
11301   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11302 }
11303
11304 static void
11305 awatch_command (char *arg, int from_tty)
11306 {
11307   watch_maybe_just_location (arg, hw_access, from_tty);
11308 }
11309 \f
11310
11311 /* Helper routines for the until_command routine in infcmd.c.  Here
11312    because it uses the mechanisms of breakpoints.  */
11313
11314 struct until_break_command_continuation_args
11315 {
11316   struct breakpoint *breakpoint;
11317   struct breakpoint *breakpoint2;
11318   int thread_num;
11319 };
11320
11321 /* This function is called by fetch_inferior_event via the
11322    cmd_continuation pointer, to complete the until command.  It takes
11323    care of cleaning up the temporary breakpoints set up by the until
11324    command.  */
11325 static void
11326 until_break_command_continuation (void *arg, int err)
11327 {
11328   struct until_break_command_continuation_args *a = arg;
11329
11330   delete_breakpoint (a->breakpoint);
11331   if (a->breakpoint2)
11332     delete_breakpoint (a->breakpoint2);
11333   delete_longjmp_breakpoint (a->thread_num);
11334 }
11335
11336 void
11337 until_break_command (char *arg, int from_tty, int anywhere)
11338 {
11339   struct symtabs_and_lines sals;
11340   struct symtab_and_line sal;
11341   struct frame_info *frame;
11342   struct gdbarch *frame_gdbarch;
11343   struct frame_id stack_frame_id;
11344   struct frame_id caller_frame_id;
11345   struct breakpoint *breakpoint;
11346   struct breakpoint *breakpoint2 = NULL;
11347   struct cleanup *old_chain;
11348   int thread;
11349   struct thread_info *tp;
11350
11351   clear_proceed_status ();
11352
11353   /* Set a breakpoint where the user wants it and at return from
11354      this function.  */
11355
11356   if (last_displayed_sal_is_valid ())
11357     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11358                           get_last_displayed_symtab (),
11359                           get_last_displayed_line ());
11360   else
11361     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11362                           (struct symtab *) NULL, 0);
11363
11364   if (sals.nelts != 1)
11365     error (_("Couldn't get information on specified line."));
11366
11367   sal = sals.sals[0];
11368   xfree (sals.sals);    /* malloc'd, so freed.  */
11369
11370   if (*arg)
11371     error (_("Junk at end of arguments."));
11372
11373   resolve_sal_pc (&sal);
11374
11375   tp = inferior_thread ();
11376   thread = tp->num;
11377
11378   old_chain = make_cleanup (null_cleanup, NULL);
11379
11380   /* Note linespec handling above invalidates the frame chain.
11381      Installing a breakpoint also invalidates the frame chain (as it
11382      may need to switch threads), so do any frame handling before
11383      that.  */
11384
11385   frame = get_selected_frame (NULL);
11386   frame_gdbarch = get_frame_arch (frame);
11387   stack_frame_id = get_stack_frame_id (frame);
11388   caller_frame_id = frame_unwind_caller_id (frame);
11389
11390   /* Keep within the current frame, or in frames called by the current
11391      one.  */
11392
11393   if (frame_id_p (caller_frame_id))
11394     {
11395       struct symtab_and_line sal2;
11396
11397       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11398       sal2.pc = frame_unwind_caller_pc (frame);
11399       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11400                                               sal2,
11401                                               caller_frame_id,
11402                                               bp_until);
11403       make_cleanup_delete_breakpoint (breakpoint2);
11404
11405       set_longjmp_breakpoint (tp, caller_frame_id);
11406       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11407     }
11408
11409   /* set_momentary_breakpoint could invalidate FRAME.  */
11410   frame = NULL;
11411
11412   if (anywhere)
11413     /* If the user told us to continue until a specified location,
11414        we don't specify a frame at which we need to stop.  */
11415     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11416                                            null_frame_id, bp_until);
11417   else
11418     /* Otherwise, specify the selected frame, because we want to stop
11419        only at the very same frame.  */
11420     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11421                                            stack_frame_id, bp_until);
11422   make_cleanup_delete_breakpoint (breakpoint);
11423
11424   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11425
11426   /* If we are running asynchronously, and proceed call above has
11427      actually managed to start the target, arrange for breakpoints to
11428      be deleted when the target stops.  Otherwise, we're already
11429      stopped and delete breakpoints via cleanup chain.  */
11430
11431   if (target_can_async_p () && is_running (inferior_ptid))
11432     {
11433       struct until_break_command_continuation_args *args;
11434       args = xmalloc (sizeof (*args));
11435
11436       args->breakpoint = breakpoint;
11437       args->breakpoint2 = breakpoint2;
11438       args->thread_num = thread;
11439
11440       discard_cleanups (old_chain);
11441       add_continuation (inferior_thread (),
11442                         until_break_command_continuation, args,
11443                         xfree);
11444     }
11445   else
11446     do_cleanups (old_chain);
11447 }
11448
11449 /* This function attempts to parse an optional "if <cond>" clause
11450    from the arg string.  If one is not found, it returns NULL.
11451
11452    Else, it returns a pointer to the condition string.  (It does not
11453    attempt to evaluate the string against a particular block.)  And,
11454    it updates arg to point to the first character following the parsed
11455    if clause in the arg string.  */
11456
11457 char *
11458 ep_parse_optional_if_clause (char **arg)
11459 {
11460   char *cond_string;
11461
11462   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11463     return NULL;
11464
11465   /* Skip the "if" keyword.  */
11466   (*arg) += 2;
11467
11468   /* Skip any extra leading whitespace, and record the start of the
11469      condition string.  */
11470   *arg = skip_spaces (*arg);
11471   cond_string = *arg;
11472
11473   /* Assume that the condition occupies the remainder of the arg
11474      string.  */
11475   (*arg) += strlen (cond_string);
11476
11477   return cond_string;
11478 }
11479
11480 /* Commands to deal with catching events, such as signals, exceptions,
11481    process start/exit, etc.  */
11482
11483 typedef enum
11484 {
11485   catch_fork_temporary, catch_vfork_temporary,
11486   catch_fork_permanent, catch_vfork_permanent
11487 }
11488 catch_fork_kind;
11489
11490 static void
11491 catch_fork_command_1 (char *arg, int from_tty, 
11492                       struct cmd_list_element *command)
11493 {
11494   struct gdbarch *gdbarch = get_current_arch ();
11495   char *cond_string = NULL;
11496   catch_fork_kind fork_kind;
11497   int tempflag;
11498
11499   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11500   tempflag = (fork_kind == catch_fork_temporary
11501               || fork_kind == catch_vfork_temporary);
11502
11503   if (!arg)
11504     arg = "";
11505   arg = skip_spaces (arg);
11506
11507   /* The allowed syntax is:
11508      catch [v]fork
11509      catch [v]fork if <cond>
11510
11511      First, check if there's an if clause.  */
11512   cond_string = ep_parse_optional_if_clause (&arg);
11513
11514   if ((*arg != '\0') && !isspace (*arg))
11515     error (_("Junk at end of arguments."));
11516
11517   /* If this target supports it, create a fork or vfork catchpoint
11518      and enable reporting of such events.  */
11519   switch (fork_kind)
11520     {
11521     case catch_fork_temporary:
11522     case catch_fork_permanent:
11523       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11524                                           &catch_fork_breakpoint_ops);
11525       break;
11526     case catch_vfork_temporary:
11527     case catch_vfork_permanent:
11528       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11529                                           &catch_vfork_breakpoint_ops);
11530       break;
11531     default:
11532       error (_("unsupported or unknown fork kind; cannot catch it"));
11533       break;
11534     }
11535 }
11536
11537 static void
11538 catch_exec_command_1 (char *arg, int from_tty, 
11539                       struct cmd_list_element *command)
11540 {
11541   struct exec_catchpoint *c;
11542   struct gdbarch *gdbarch = get_current_arch ();
11543   int tempflag;
11544   char *cond_string = NULL;
11545
11546   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11547
11548   if (!arg)
11549     arg = "";
11550   arg = skip_spaces (arg);
11551
11552   /* The allowed syntax is:
11553      catch exec
11554      catch exec if <cond>
11555
11556      First, check if there's an if clause.  */
11557   cond_string = ep_parse_optional_if_clause (&arg);
11558
11559   if ((*arg != '\0') && !isspace (*arg))
11560     error (_("Junk at end of arguments."));
11561
11562   c = XNEW (struct exec_catchpoint);
11563   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11564                    &catch_exec_breakpoint_ops);
11565   c->exec_pathname = NULL;
11566
11567   install_breakpoint (0, &c->base, 1);
11568 }
11569
11570 void
11571 init_ada_exception_breakpoint (struct breakpoint *b,
11572                                struct gdbarch *gdbarch,
11573                                struct symtab_and_line sal,
11574                                char *addr_string,
11575                                const struct breakpoint_ops *ops,
11576                                int tempflag,
11577                                int from_tty)
11578 {
11579   if (from_tty)
11580     {
11581       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11582       if (!loc_gdbarch)
11583         loc_gdbarch = gdbarch;
11584
11585       describe_other_breakpoints (loc_gdbarch,
11586                                   sal.pspace, sal.pc, sal.section, -1);
11587       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11588          version for exception catchpoints, because two catchpoints
11589          used for different exception names will use the same address.
11590          In this case, a "breakpoint ... also set at..." warning is
11591          unproductive.  Besides, the warning phrasing is also a bit
11592          inappropriate, we should use the word catchpoint, and tell
11593          the user what type of catchpoint it is.  The above is good
11594          enough for now, though.  */
11595     }
11596
11597   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11598
11599   b->enable_state = bp_enabled;
11600   b->disposition = tempflag ? disp_del : disp_donttouch;
11601   b->addr_string = addr_string;
11602   b->language = language_ada;
11603 }
11604
11605 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11606    filter list, or NULL if no filtering is required.  */
11607 static VEC(int) *
11608 catch_syscall_split_args (char *arg)
11609 {
11610   VEC(int) *result = NULL;
11611   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11612
11613   while (*arg != '\0')
11614     {
11615       int i, syscall_number;
11616       char *endptr;
11617       char cur_name[128];
11618       struct syscall s;
11619
11620       /* Skip whitespace.  */
11621       arg = skip_spaces (arg);
11622
11623       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11624         cur_name[i] = arg[i];
11625       cur_name[i] = '\0';
11626       arg += i;
11627
11628       /* Check if the user provided a syscall name or a number.  */
11629       syscall_number = (int) strtol (cur_name, &endptr, 0);
11630       if (*endptr == '\0')
11631         get_syscall_by_number (syscall_number, &s);
11632       else
11633         {
11634           /* We have a name.  Let's check if it's valid and convert it
11635              to a number.  */
11636           get_syscall_by_name (cur_name, &s);
11637
11638           if (s.number == UNKNOWN_SYSCALL)
11639             /* Here we have to issue an error instead of a warning,
11640                because GDB cannot do anything useful if there's no
11641                syscall number to be caught.  */
11642             error (_("Unknown syscall name '%s'."), cur_name);
11643         }
11644
11645       /* Ok, it's valid.  */
11646       VEC_safe_push (int, result, s.number);
11647     }
11648
11649   discard_cleanups (cleanup);
11650   return result;
11651 }
11652
11653 /* Implement the "catch syscall" command.  */
11654
11655 static void
11656 catch_syscall_command_1 (char *arg, int from_tty, 
11657                          struct cmd_list_element *command)
11658 {
11659   int tempflag;
11660   VEC(int) *filter;
11661   struct syscall s;
11662   struct gdbarch *gdbarch = get_current_arch ();
11663
11664   /* Checking if the feature if supported.  */
11665   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11666     error (_("The feature 'catch syscall' is not supported on \
11667 this architecture yet."));
11668
11669   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11670
11671   arg = skip_spaces (arg);
11672
11673   /* We need to do this first "dummy" translation in order
11674      to get the syscall XML file loaded or, most important,
11675      to display a warning to the user if there's no XML file
11676      for his/her architecture.  */
11677   get_syscall_by_number (0, &s);
11678
11679   /* The allowed syntax is:
11680      catch syscall
11681      catch syscall <name | number> [<name | number> ... <name | number>]
11682
11683      Let's check if there's a syscall name.  */
11684
11685   if (arg != NULL)
11686     filter = catch_syscall_split_args (arg);
11687   else
11688     filter = NULL;
11689
11690   create_syscall_event_catchpoint (tempflag, filter,
11691                                    &catch_syscall_breakpoint_ops);
11692 }
11693
11694 static void
11695 catch_command (char *arg, int from_tty)
11696 {
11697   error (_("Catch requires an event name."));
11698 }
11699 \f
11700
11701 static void
11702 tcatch_command (char *arg, int from_tty)
11703 {
11704   error (_("Catch requires an event name."));
11705 }
11706
11707 /* A qsort comparison function that sorts breakpoints in order.  */
11708
11709 static int
11710 compare_breakpoints (const void *a, const void *b)
11711 {
11712   const breakpoint_p *ba = a;
11713   uintptr_t ua = (uintptr_t) *ba;
11714   const breakpoint_p *bb = b;
11715   uintptr_t ub = (uintptr_t) *bb;
11716
11717   if ((*ba)->number < (*bb)->number)
11718     return -1;
11719   else if ((*ba)->number > (*bb)->number)
11720     return 1;
11721
11722   /* Now sort by address, in case we see, e..g, two breakpoints with
11723      the number 0.  */
11724   if (ua < ub)
11725     return -1;
11726   return ua > ub ? 1 : 0;
11727 }
11728
11729 /* Delete breakpoints by address or line.  */
11730
11731 static void
11732 clear_command (char *arg, int from_tty)
11733 {
11734   struct breakpoint *b, *prev;
11735   VEC(breakpoint_p) *found = 0;
11736   int ix;
11737   int default_match;
11738   struct symtabs_and_lines sals;
11739   struct symtab_and_line sal;
11740   int i;
11741   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11742
11743   if (arg)
11744     {
11745       sals = decode_line_with_current_source (arg,
11746                                               (DECODE_LINE_FUNFIRSTLINE
11747                                                | DECODE_LINE_LIST_MODE));
11748       make_cleanup (xfree, sals.sals);
11749       default_match = 0;
11750     }
11751   else
11752     {
11753       sals.sals = (struct symtab_and_line *)
11754         xmalloc (sizeof (struct symtab_and_line));
11755       make_cleanup (xfree, sals.sals);
11756       init_sal (&sal);          /* Initialize to zeroes.  */
11757
11758       /* Set sal's line, symtab, pc, and pspace to the values
11759          corresponding to the last call to print_frame_info.  If the
11760          codepoint is not valid, this will set all the fields to 0.  */
11761       get_last_displayed_sal (&sal);
11762       if (sal.symtab == 0)
11763         error (_("No source file specified."));
11764
11765       sals.sals[0] = sal;
11766       sals.nelts = 1;
11767
11768       default_match = 1;
11769     }
11770
11771   /* We don't call resolve_sal_pc here.  That's not as bad as it
11772      seems, because all existing breakpoints typically have both
11773      file/line and pc set.  So, if clear is given file/line, we can
11774      match this to existing breakpoint without obtaining pc at all.
11775
11776      We only support clearing given the address explicitly 
11777      present in breakpoint table.  Say, we've set breakpoint 
11778      at file:line.  There were several PC values for that file:line,
11779      due to optimization, all in one block.
11780
11781      We've picked one PC value.  If "clear" is issued with another
11782      PC corresponding to the same file:line, the breakpoint won't
11783      be cleared.  We probably can still clear the breakpoint, but 
11784      since the other PC value is never presented to user, user
11785      can only find it by guessing, and it does not seem important
11786      to support that.  */
11787
11788   /* For each line spec given, delete bps which correspond to it.  Do
11789      it in two passes, solely to preserve the current behavior that
11790      from_tty is forced true if we delete more than one
11791      breakpoint.  */
11792
11793   found = NULL;
11794   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11795   for (i = 0; i < sals.nelts; i++)
11796     {
11797       const char *sal_fullname;
11798
11799       /* If exact pc given, clear bpts at that pc.
11800          If line given (pc == 0), clear all bpts on specified line.
11801          If defaulting, clear all bpts on default line
11802          or at default pc.
11803
11804          defaulting    sal.pc != 0    tests to do
11805
11806          0              1             pc
11807          1              1             pc _and_ line
11808          0              0             line
11809          1              0             <can't happen> */
11810
11811       sal = sals.sals[i];
11812       sal_fullname = (sal.symtab == NULL
11813                       ? NULL : symtab_to_fullname (sal.symtab));
11814
11815       /* Find all matching breakpoints and add them to 'found'.  */
11816       ALL_BREAKPOINTS (b)
11817         {
11818           int match = 0;
11819           /* Are we going to delete b?  */
11820           if (b->type != bp_none && !is_watchpoint (b))
11821             {
11822               struct bp_location *loc = b->loc;
11823               for (; loc; loc = loc->next)
11824                 {
11825                   /* If the user specified file:line, don't allow a PC
11826                      match.  This matches historical gdb behavior.  */
11827                   int pc_match = (!sal.explicit_line
11828                                   && sal.pc
11829                                   && (loc->pspace == sal.pspace)
11830                                   && (loc->address == sal.pc)
11831                                   && (!section_is_overlay (loc->section)
11832                                       || loc->section == sal.section));
11833                   int line_match = 0;
11834
11835                   if ((default_match || sal.explicit_line)
11836                       && loc->symtab != NULL
11837                       && sal_fullname != NULL
11838                       && sal.pspace == loc->pspace
11839                       && loc->line_number == sal.line
11840                       && filename_cmp (symtab_to_fullname (loc->symtab),
11841                                        sal_fullname) == 0)
11842                     line_match = 1;
11843
11844                   if (pc_match || line_match)
11845                     {
11846                       match = 1;
11847                       break;
11848                     }
11849                 }
11850             }
11851
11852           if (match)
11853             VEC_safe_push(breakpoint_p, found, b);
11854         }
11855     }
11856
11857   /* Now go thru the 'found' chain and delete them.  */
11858   if (VEC_empty(breakpoint_p, found))
11859     {
11860       if (arg)
11861         error (_("No breakpoint at %s."), arg);
11862       else
11863         error (_("No breakpoint at this line."));
11864     }
11865
11866   /* Remove duplicates from the vec.  */
11867   qsort (VEC_address (breakpoint_p, found),
11868          VEC_length (breakpoint_p, found),
11869          sizeof (breakpoint_p),
11870          compare_breakpoints);
11871   prev = VEC_index (breakpoint_p, found, 0);
11872   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11873     {
11874       if (b == prev)
11875         {
11876           VEC_ordered_remove (breakpoint_p, found, ix);
11877           --ix;
11878         }
11879     }
11880
11881   if (VEC_length(breakpoint_p, found) > 1)
11882     from_tty = 1;       /* Always report if deleted more than one.  */
11883   if (from_tty)
11884     {
11885       if (VEC_length(breakpoint_p, found) == 1)
11886         printf_unfiltered (_("Deleted breakpoint "));
11887       else
11888         printf_unfiltered (_("Deleted breakpoints "));
11889     }
11890
11891   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11892     {
11893       if (from_tty)
11894         printf_unfiltered ("%d ", b->number);
11895       delete_breakpoint (b);
11896     }
11897   if (from_tty)
11898     putchar_unfiltered ('\n');
11899
11900   do_cleanups (cleanups);
11901 }
11902 \f
11903 /* Delete breakpoint in BS if they are `delete' breakpoints and
11904    all breakpoints that are marked for deletion, whether hit or not.
11905    This is called after any breakpoint is hit, or after errors.  */
11906
11907 void
11908 breakpoint_auto_delete (bpstat bs)
11909 {
11910   struct breakpoint *b, *b_tmp;
11911
11912   for (; bs; bs = bs->next)
11913     if (bs->breakpoint_at
11914         && bs->breakpoint_at->disposition == disp_del
11915         && bs->stop)
11916       delete_breakpoint (bs->breakpoint_at);
11917
11918   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11919   {
11920     if (b->disposition == disp_del_at_next_stop)
11921       delete_breakpoint (b);
11922   }
11923 }
11924
11925 /* A comparison function for bp_location AP and BP being interfaced to
11926    qsort.  Sort elements primarily by their ADDRESS (no matter what
11927    does breakpoint_address_is_meaningful say for its OWNER),
11928    secondarily by ordering first bp_permanent OWNERed elements and
11929    terciarily just ensuring the array is sorted stable way despite
11930    qsort being an unstable algorithm.  */
11931
11932 static int
11933 bp_location_compare (const void *ap, const void *bp)
11934 {
11935   struct bp_location *a = *(void **) ap;
11936   struct bp_location *b = *(void **) bp;
11937   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11938   int a_perm = a->owner->enable_state == bp_permanent;
11939   int b_perm = b->owner->enable_state == bp_permanent;
11940
11941   if (a->address != b->address)
11942     return (a->address > b->address) - (a->address < b->address);
11943
11944   /* Sort locations at the same address by their pspace number, keeping
11945      locations of the same inferior (in a multi-inferior environment)
11946      grouped.  */
11947
11948   if (a->pspace->num != b->pspace->num)
11949     return ((a->pspace->num > b->pspace->num)
11950             - (a->pspace->num < b->pspace->num));
11951
11952   /* Sort permanent breakpoints first.  */
11953   if (a_perm != b_perm)
11954     return (a_perm < b_perm) - (a_perm > b_perm);
11955
11956   /* Make the internal GDB representation stable across GDB runs
11957      where A and B memory inside GDB can differ.  Breakpoint locations of
11958      the same type at the same address can be sorted in arbitrary order.  */
11959
11960   if (a->owner->number != b->owner->number)
11961     return ((a->owner->number > b->owner->number)
11962             - (a->owner->number < b->owner->number));
11963
11964   return (a > b) - (a < b);
11965 }
11966
11967 /* Set bp_location_placed_address_before_address_max and
11968    bp_location_shadow_len_after_address_max according to the current
11969    content of the bp_location array.  */
11970
11971 static void
11972 bp_location_target_extensions_update (void)
11973 {
11974   struct bp_location *bl, **blp_tmp;
11975
11976   bp_location_placed_address_before_address_max = 0;
11977   bp_location_shadow_len_after_address_max = 0;
11978
11979   ALL_BP_LOCATIONS (bl, blp_tmp)
11980     {
11981       CORE_ADDR start, end, addr;
11982
11983       if (!bp_location_has_shadow (bl))
11984         continue;
11985
11986       start = bl->target_info.placed_address;
11987       end = start + bl->target_info.shadow_len;
11988
11989       gdb_assert (bl->address >= start);
11990       addr = bl->address - start;
11991       if (addr > bp_location_placed_address_before_address_max)
11992         bp_location_placed_address_before_address_max = addr;
11993
11994       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11995
11996       gdb_assert (bl->address < end);
11997       addr = end - bl->address;
11998       if (addr > bp_location_shadow_len_after_address_max)
11999         bp_location_shadow_len_after_address_max = addr;
12000     }
12001 }
12002
12003 /* Download tracepoint locations if they haven't been.  */
12004
12005 static void
12006 download_tracepoint_locations (void)
12007 {
12008   struct breakpoint *b;
12009   struct cleanup *old_chain;
12010
12011   if (!target_can_download_tracepoint ())
12012     return;
12013
12014   old_chain = save_current_space_and_thread ();
12015
12016   ALL_TRACEPOINTS (b)
12017     {
12018       struct bp_location *bl;
12019       struct tracepoint *t;
12020       int bp_location_downloaded = 0;
12021
12022       if ((b->type == bp_fast_tracepoint
12023            ? !may_insert_fast_tracepoints
12024            : !may_insert_tracepoints))
12025         continue;
12026
12027       for (bl = b->loc; bl; bl = bl->next)
12028         {
12029           /* In tracepoint, locations are _never_ duplicated, so
12030              should_be_inserted is equivalent to
12031              unduplicated_should_be_inserted.  */
12032           if (!should_be_inserted (bl) || bl->inserted)
12033             continue;
12034
12035           switch_to_program_space_and_thread (bl->pspace);
12036
12037           target_download_tracepoint (bl);
12038
12039           bl->inserted = 1;
12040           bp_location_downloaded = 1;
12041         }
12042       t = (struct tracepoint *) b;
12043       t->number_on_target = b->number;
12044       if (bp_location_downloaded)
12045         observer_notify_breakpoint_modified (b);
12046     }
12047
12048   do_cleanups (old_chain);
12049 }
12050
12051 /* Swap the insertion/duplication state between two locations.  */
12052
12053 static void
12054 swap_insertion (struct bp_location *left, struct bp_location *right)
12055 {
12056   const int left_inserted = left->inserted;
12057   const int left_duplicate = left->duplicate;
12058   const int left_needs_update = left->needs_update;
12059   const struct bp_target_info left_target_info = left->target_info;
12060
12061   /* Locations of tracepoints can never be duplicated.  */
12062   if (is_tracepoint (left->owner))
12063     gdb_assert (!left->duplicate);
12064   if (is_tracepoint (right->owner))
12065     gdb_assert (!right->duplicate);
12066
12067   left->inserted = right->inserted;
12068   left->duplicate = right->duplicate;
12069   left->needs_update = right->needs_update;
12070   left->target_info = right->target_info;
12071   right->inserted = left_inserted;
12072   right->duplicate = left_duplicate;
12073   right->needs_update = left_needs_update;
12074   right->target_info = left_target_info;
12075 }
12076
12077 /* Force the re-insertion of the locations at ADDRESS.  This is called
12078    once a new/deleted/modified duplicate location is found and we are evaluating
12079    conditions on the target's side.  Such conditions need to be updated on
12080    the target.  */
12081
12082 static void
12083 force_breakpoint_reinsertion (struct bp_location *bl)
12084 {
12085   struct bp_location **locp = NULL, **loc2p;
12086   struct bp_location *loc;
12087   CORE_ADDR address = 0;
12088   int pspace_num;
12089
12090   address = bl->address;
12091   pspace_num = bl->pspace->num;
12092
12093   /* This is only meaningful if the target is
12094      evaluating conditions and if the user has
12095      opted for condition evaluation on the target's
12096      side.  */
12097   if (gdb_evaluates_breakpoint_condition_p ()
12098       || !target_supports_evaluation_of_breakpoint_conditions ())
12099     return;
12100
12101   /* Flag all breakpoint locations with this address and
12102      the same program space as the location
12103      as "its condition has changed".  We need to
12104      update the conditions on the target's side.  */
12105   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12106     {
12107       loc = *loc2p;
12108
12109       if (!is_breakpoint (loc->owner)
12110           || pspace_num != loc->pspace->num)
12111         continue;
12112
12113       /* Flag the location appropriately.  We use a different state to
12114          let everyone know that we already updated the set of locations
12115          with addr bl->address and program space bl->pspace.  This is so
12116          we don't have to keep calling these functions just to mark locations
12117          that have already been marked.  */
12118       loc->condition_changed = condition_updated;
12119
12120       /* Free the agent expression bytecode as well.  We will compute
12121          it later on.  */
12122       if (loc->cond_bytecode)
12123         {
12124           free_agent_expr (loc->cond_bytecode);
12125           loc->cond_bytecode = NULL;
12126         }
12127     }
12128 }
12129
12130 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12131    into the inferior, only remove already-inserted locations that no
12132    longer should be inserted.  Functions that delete a breakpoint or
12133    breakpoints should pass false, so that deleting a breakpoint
12134    doesn't have the side effect of inserting the locations of other
12135    breakpoints that are marked not-inserted, but should_be_inserted
12136    returns true on them.
12137
12138    This behaviour is useful is situations close to tear-down -- e.g.,
12139    after an exec, while the target still has execution, but breakpoint
12140    shadows of the previous executable image should *NOT* be restored
12141    to the new image; or before detaching, where the target still has
12142    execution and wants to delete breakpoints from GDB's lists, and all
12143    breakpoints had already been removed from the inferior.  */
12144
12145 static void
12146 update_global_location_list (int should_insert)
12147 {
12148   struct breakpoint *b;
12149   struct bp_location **locp, *loc;
12150   struct cleanup *cleanups;
12151   /* Last breakpoint location address that was marked for update.  */
12152   CORE_ADDR last_addr = 0;
12153   /* Last breakpoint location program space that was marked for update.  */
12154   int last_pspace_num = -1;
12155
12156   /* Used in the duplicates detection below.  When iterating over all
12157      bp_locations, points to the first bp_location of a given address.
12158      Breakpoints and watchpoints of different types are never
12159      duplicates of each other.  Keep one pointer for each type of
12160      breakpoint/watchpoint, so we only need to loop over all locations
12161      once.  */
12162   struct bp_location *bp_loc_first;  /* breakpoint */
12163   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12164   struct bp_location *awp_loc_first; /* access watchpoint */
12165   struct bp_location *rwp_loc_first; /* read watchpoint */
12166
12167   /* Saved former bp_location array which we compare against the newly
12168      built bp_location from the current state of ALL_BREAKPOINTS.  */
12169   struct bp_location **old_location, **old_locp;
12170   unsigned old_location_count;
12171
12172   old_location = bp_location;
12173   old_location_count = bp_location_count;
12174   bp_location = NULL;
12175   bp_location_count = 0;
12176   cleanups = make_cleanup (xfree, old_location);
12177
12178   ALL_BREAKPOINTS (b)
12179     for (loc = b->loc; loc; loc = loc->next)
12180       bp_location_count++;
12181
12182   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12183   locp = bp_location;
12184   ALL_BREAKPOINTS (b)
12185     for (loc = b->loc; loc; loc = loc->next)
12186       *locp++ = loc;
12187   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12188          bp_location_compare);
12189
12190   bp_location_target_extensions_update ();
12191
12192   /* Identify bp_location instances that are no longer present in the
12193      new list, and therefore should be freed.  Note that it's not
12194      necessary that those locations should be removed from inferior --
12195      if there's another location at the same address (previously
12196      marked as duplicate), we don't need to remove/insert the
12197      location.
12198      
12199      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12200      and former bp_location array state respectively.  */
12201
12202   locp = bp_location;
12203   for (old_locp = old_location; old_locp < old_location + old_location_count;
12204        old_locp++)
12205     {
12206       struct bp_location *old_loc = *old_locp;
12207       struct bp_location **loc2p;
12208
12209       /* Tells if 'old_loc' is found among the new locations.  If
12210          not, we have to free it.  */
12211       int found_object = 0;
12212       /* Tells if the location should remain inserted in the target.  */
12213       int keep_in_target = 0;
12214       int removed = 0;
12215
12216       /* Skip LOCP entries which will definitely never be needed.
12217          Stop either at or being the one matching OLD_LOC.  */
12218       while (locp < bp_location + bp_location_count
12219              && (*locp)->address < old_loc->address)
12220         locp++;
12221
12222       for (loc2p = locp;
12223            (loc2p < bp_location + bp_location_count
12224             && (*loc2p)->address == old_loc->address);
12225            loc2p++)
12226         {
12227           /* Check if this is a new/duplicated location or a duplicated
12228              location that had its condition modified.  If so, we want to send
12229              its condition to the target if evaluation of conditions is taking
12230              place there.  */
12231           if ((*loc2p)->condition_changed == condition_modified
12232               && (last_addr != old_loc->address
12233                   || last_pspace_num != old_loc->pspace->num))
12234             {
12235               force_breakpoint_reinsertion (*loc2p);
12236               last_pspace_num = old_loc->pspace->num;
12237             }
12238
12239           if (*loc2p == old_loc)
12240             found_object = 1;
12241         }
12242
12243       /* We have already handled this address, update it so that we don't
12244          have to go through updates again.  */
12245       last_addr = old_loc->address;
12246
12247       /* Target-side condition evaluation: Handle deleted locations.  */
12248       if (!found_object)
12249         force_breakpoint_reinsertion (old_loc);
12250
12251       /* If this location is no longer present, and inserted, look if
12252          there's maybe a new location at the same address.  If so,
12253          mark that one inserted, and don't remove this one.  This is
12254          needed so that we don't have a time window where a breakpoint
12255          at certain location is not inserted.  */
12256
12257       if (old_loc->inserted)
12258         {
12259           /* If the location is inserted now, we might have to remove
12260              it.  */
12261
12262           if (found_object && should_be_inserted (old_loc))
12263             {
12264               /* The location is still present in the location list,
12265                  and still should be inserted.  Don't do anything.  */
12266               keep_in_target = 1;
12267             }
12268           else
12269             {
12270               /* This location still exists, but it won't be kept in the
12271                  target since it may have been disabled.  We proceed to
12272                  remove its target-side condition.  */
12273
12274               /* The location is either no longer present, or got
12275                  disabled.  See if there's another location at the
12276                  same address, in which case we don't need to remove
12277                  this one from the target.  */
12278
12279               /* OLD_LOC comes from existing struct breakpoint.  */
12280               if (breakpoint_address_is_meaningful (old_loc->owner))
12281                 {
12282                   for (loc2p = locp;
12283                        (loc2p < bp_location + bp_location_count
12284                         && (*loc2p)->address == old_loc->address);
12285                        loc2p++)
12286                     {
12287                       struct bp_location *loc2 = *loc2p;
12288
12289                       if (breakpoint_locations_match (loc2, old_loc))
12290                         {
12291                           /* Read watchpoint locations are switched to
12292                              access watchpoints, if the former are not
12293                              supported, but the latter are.  */
12294                           if (is_hardware_watchpoint (old_loc->owner))
12295                             {
12296                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12297                               loc2->watchpoint_type = old_loc->watchpoint_type;
12298                             }
12299
12300                           /* loc2 is a duplicated location. We need to check
12301                              if it should be inserted in case it will be
12302                              unduplicated.  */
12303                           if (loc2 != old_loc
12304                               && unduplicated_should_be_inserted (loc2))
12305                             {
12306                               swap_insertion (old_loc, loc2);
12307                               keep_in_target = 1;
12308                               break;
12309                             }
12310                         }
12311                     }
12312                 }
12313             }
12314
12315           if (!keep_in_target)
12316             {
12317               if (remove_breakpoint (old_loc, mark_uninserted))
12318                 {
12319                   /* This is just about all we can do.  We could keep
12320                      this location on the global list, and try to
12321                      remove it next time, but there's no particular
12322                      reason why we will succeed next time.
12323                      
12324                      Note that at this point, old_loc->owner is still
12325                      valid, as delete_breakpoint frees the breakpoint
12326                      only after calling us.  */
12327                   printf_filtered (_("warning: Error removing "
12328                                      "breakpoint %d\n"), 
12329                                    old_loc->owner->number);
12330                 }
12331               removed = 1;
12332             }
12333         }
12334
12335       if (!found_object)
12336         {
12337           if (removed && non_stop
12338               && breakpoint_address_is_meaningful (old_loc->owner)
12339               && !is_hardware_watchpoint (old_loc->owner))
12340             {
12341               /* This location was removed from the target.  In
12342                  non-stop mode, a race condition is possible where
12343                  we've removed a breakpoint, but stop events for that
12344                  breakpoint are already queued and will arrive later.
12345                  We apply an heuristic to be able to distinguish such
12346                  SIGTRAPs from other random SIGTRAPs: we keep this
12347                  breakpoint location for a bit, and will retire it
12348                  after we see some number of events.  The theory here
12349                  is that reporting of events should, "on the average",
12350                  be fair, so after a while we'll see events from all
12351                  threads that have anything of interest, and no longer
12352                  need to keep this breakpoint location around.  We
12353                  don't hold locations forever so to reduce chances of
12354                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12355                  SIGTRAP.
12356
12357                  The heuristic failing can be disastrous on
12358                  decr_pc_after_break targets.
12359
12360                  On decr_pc_after_break targets, like e.g., x86-linux,
12361                  if we fail to recognize a late breakpoint SIGTRAP,
12362                  because events_till_retirement has reached 0 too
12363                  soon, we'll fail to do the PC adjustment, and report
12364                  a random SIGTRAP to the user.  When the user resumes
12365                  the inferior, it will most likely immediately crash
12366                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12367                  corrupted, because of being resumed e.g., in the
12368                  middle of a multi-byte instruction, or skipped a
12369                  one-byte instruction.  This was actually seen happen
12370                  on native x86-linux, and should be less rare on
12371                  targets that do not support new thread events, like
12372                  remote, due to the heuristic depending on
12373                  thread_count.
12374
12375                  Mistaking a random SIGTRAP for a breakpoint trap
12376                  causes similar symptoms (PC adjustment applied when
12377                  it shouldn't), but then again, playing with SIGTRAPs
12378                  behind the debugger's back is asking for trouble.
12379
12380                  Since hardware watchpoint traps are always
12381                  distinguishable from other traps, so we don't need to
12382                  apply keep hardware watchpoint moribund locations
12383                  around.  We simply always ignore hardware watchpoint
12384                  traps we can no longer explain.  */
12385
12386               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12387               old_loc->owner = NULL;
12388
12389               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12390             }
12391           else
12392             {
12393               old_loc->owner = NULL;
12394               decref_bp_location (&old_loc);
12395             }
12396         }
12397     }
12398
12399   /* Rescan breakpoints at the same address and section, marking the
12400      first one as "first" and any others as "duplicates".  This is so
12401      that the bpt instruction is only inserted once.  If we have a
12402      permanent breakpoint at the same place as BPT, make that one the
12403      official one, and the rest as duplicates.  Permanent breakpoints
12404      are sorted first for the same address.
12405
12406      Do the same for hardware watchpoints, but also considering the
12407      watchpoint's type (regular/access/read) and length.  */
12408
12409   bp_loc_first = NULL;
12410   wp_loc_first = NULL;
12411   awp_loc_first = NULL;
12412   rwp_loc_first = NULL;
12413   ALL_BP_LOCATIONS (loc, locp)
12414     {
12415       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12416          non-NULL.  */
12417       struct bp_location **loc_first_p;
12418       b = loc->owner;
12419
12420       if (!unduplicated_should_be_inserted (loc)
12421           || !breakpoint_address_is_meaningful (b)
12422           /* Don't detect duplicate for tracepoint locations because they are
12423            never duplicated.  See the comments in field `duplicate' of
12424            `struct bp_location'.  */
12425           || is_tracepoint (b))
12426         {
12427           /* Clear the condition modification flag.  */
12428           loc->condition_changed = condition_unchanged;
12429           continue;
12430         }
12431
12432       /* Permanent breakpoint should always be inserted.  */
12433       if (b->enable_state == bp_permanent && ! loc->inserted)
12434         internal_error (__FILE__, __LINE__,
12435                         _("allegedly permanent breakpoint is not "
12436                         "actually inserted"));
12437
12438       if (b->type == bp_hardware_watchpoint)
12439         loc_first_p = &wp_loc_first;
12440       else if (b->type == bp_read_watchpoint)
12441         loc_first_p = &rwp_loc_first;
12442       else if (b->type == bp_access_watchpoint)
12443         loc_first_p = &awp_loc_first;
12444       else
12445         loc_first_p = &bp_loc_first;
12446
12447       if (*loc_first_p == NULL
12448           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12449           || !breakpoint_locations_match (loc, *loc_first_p))
12450         {
12451           *loc_first_p = loc;
12452           loc->duplicate = 0;
12453
12454           if (is_breakpoint (loc->owner) && loc->condition_changed)
12455             {
12456               loc->needs_update = 1;
12457               /* Clear the condition modification flag.  */
12458               loc->condition_changed = condition_unchanged;
12459             }
12460           continue;
12461         }
12462
12463
12464       /* This and the above ensure the invariant that the first location
12465          is not duplicated, and is the inserted one.
12466          All following are marked as duplicated, and are not inserted.  */
12467       if (loc->inserted)
12468         swap_insertion (loc, *loc_first_p);
12469       loc->duplicate = 1;
12470
12471       /* Clear the condition modification flag.  */
12472       loc->condition_changed = condition_unchanged;
12473
12474       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12475           && b->enable_state != bp_permanent)
12476         internal_error (__FILE__, __LINE__,
12477                         _("another breakpoint was inserted on top of "
12478                         "a permanent breakpoint"));
12479     }
12480
12481   if (breakpoints_always_inserted_mode ()
12482       && (have_live_inferiors ()
12483           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12484     {
12485       if (should_insert)
12486         insert_breakpoint_locations ();
12487       else
12488         {
12489           /* Though should_insert is false, we may need to update conditions
12490              on the target's side if it is evaluating such conditions.  We
12491              only update conditions for locations that are marked
12492              "needs_update".  */
12493           update_inserted_breakpoint_locations ();
12494         }
12495     }
12496
12497   if (should_insert)
12498     download_tracepoint_locations ();
12499
12500   do_cleanups (cleanups);
12501 }
12502
12503 void
12504 breakpoint_retire_moribund (void)
12505 {
12506   struct bp_location *loc;
12507   int ix;
12508
12509   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12510     if (--(loc->events_till_retirement) == 0)
12511       {
12512         decref_bp_location (&loc);
12513         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12514         --ix;
12515       }
12516 }
12517
12518 static void
12519 update_global_location_list_nothrow (int inserting)
12520 {
12521   volatile struct gdb_exception e;
12522
12523   TRY_CATCH (e, RETURN_MASK_ERROR)
12524     update_global_location_list (inserting);
12525 }
12526
12527 /* Clear BKP from a BPS.  */
12528
12529 static void
12530 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12531 {
12532   bpstat bs;
12533
12534   for (bs = bps; bs; bs = bs->next)
12535     if (bs->breakpoint_at == bpt)
12536       {
12537         bs->breakpoint_at = NULL;
12538         bs->old_val = NULL;
12539         /* bs->commands will be freed later.  */
12540       }
12541 }
12542
12543 /* Callback for iterate_over_threads.  */
12544 static int
12545 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12546 {
12547   struct breakpoint *bpt = data;
12548
12549   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12550   return 0;
12551 }
12552
12553 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12554    callbacks.  */
12555
12556 static void
12557 say_where (struct breakpoint *b)
12558 {
12559   struct value_print_options opts;
12560
12561   get_user_print_options (&opts);
12562
12563   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12564      single string.  */
12565   if (b->loc == NULL)
12566     {
12567       printf_filtered (_(" (%s) pending."), b->addr_string);
12568     }
12569   else
12570     {
12571       if (opts.addressprint || b->loc->symtab == NULL)
12572         {
12573           printf_filtered (" at ");
12574           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12575                           gdb_stdout);
12576         }
12577       if (b->loc->symtab != NULL)
12578         {
12579           /* If there is a single location, we can print the location
12580              more nicely.  */
12581           if (b->loc->next == NULL)
12582             printf_filtered (": file %s, line %d.",
12583                              symtab_to_filename_for_display (b->loc->symtab),
12584                              b->loc->line_number);
12585           else
12586             /* This is not ideal, but each location may have a
12587                different file name, and this at least reflects the
12588                real situation somewhat.  */
12589             printf_filtered (": %s.", b->addr_string);
12590         }
12591
12592       if (b->loc->next)
12593         {
12594           struct bp_location *loc = b->loc;
12595           int n = 0;
12596           for (; loc; loc = loc->next)
12597             ++n;
12598           printf_filtered (" (%d locations)", n);
12599         }
12600     }
12601 }
12602
12603 /* Default bp_location_ops methods.  */
12604
12605 static void
12606 bp_location_dtor (struct bp_location *self)
12607 {
12608   xfree (self->cond);
12609   if (self->cond_bytecode)
12610     free_agent_expr (self->cond_bytecode);
12611   xfree (self->function_name);
12612 }
12613
12614 static const struct bp_location_ops bp_location_ops =
12615 {
12616   bp_location_dtor
12617 };
12618
12619 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12620    inherit from.  */
12621
12622 static void
12623 base_breakpoint_dtor (struct breakpoint *self)
12624 {
12625   decref_counted_command_line (&self->commands);
12626   xfree (self->cond_string);
12627   xfree (self->extra_string);
12628   xfree (self->addr_string);
12629   xfree (self->filter);
12630   xfree (self->addr_string_range_end);
12631 }
12632
12633 static struct bp_location *
12634 base_breakpoint_allocate_location (struct breakpoint *self)
12635 {
12636   struct bp_location *loc;
12637
12638   loc = XNEW (struct bp_location);
12639   init_bp_location (loc, &bp_location_ops, self);
12640   return loc;
12641 }
12642
12643 static void
12644 base_breakpoint_re_set (struct breakpoint *b)
12645 {
12646   /* Nothing to re-set. */
12647 }
12648
12649 #define internal_error_pure_virtual_called() \
12650   gdb_assert_not_reached ("pure virtual function called")
12651
12652 static int
12653 base_breakpoint_insert_location (struct bp_location *bl)
12654 {
12655   internal_error_pure_virtual_called ();
12656 }
12657
12658 static int
12659 base_breakpoint_remove_location (struct bp_location *bl)
12660 {
12661   internal_error_pure_virtual_called ();
12662 }
12663
12664 static int
12665 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12666                                 struct address_space *aspace,
12667                                 CORE_ADDR bp_addr,
12668                                 const struct target_waitstatus *ws)
12669 {
12670   internal_error_pure_virtual_called ();
12671 }
12672
12673 static void
12674 base_breakpoint_check_status (bpstat bs)
12675 {
12676   /* Always stop.   */
12677 }
12678
12679 /* A "works_in_software_mode" breakpoint_ops method that just internal
12680    errors.  */
12681
12682 static int
12683 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12684 {
12685   internal_error_pure_virtual_called ();
12686 }
12687
12688 /* A "resources_needed" breakpoint_ops method that just internal
12689    errors.  */
12690
12691 static int
12692 base_breakpoint_resources_needed (const struct bp_location *bl)
12693 {
12694   internal_error_pure_virtual_called ();
12695 }
12696
12697 static enum print_stop_action
12698 base_breakpoint_print_it (bpstat bs)
12699 {
12700   internal_error_pure_virtual_called ();
12701 }
12702
12703 static void
12704 base_breakpoint_print_one_detail (const struct breakpoint *self,
12705                                   struct ui_out *uiout)
12706 {
12707   /* nothing */
12708 }
12709
12710 static void
12711 base_breakpoint_print_mention (struct breakpoint *b)
12712 {
12713   internal_error_pure_virtual_called ();
12714 }
12715
12716 static void
12717 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12718 {
12719   internal_error_pure_virtual_called ();
12720 }
12721
12722 static void
12723 base_breakpoint_create_sals_from_address (char **arg,
12724                                           struct linespec_result *canonical,
12725                                           enum bptype type_wanted,
12726                                           char *addr_start,
12727                                           char **copy_arg)
12728 {
12729   internal_error_pure_virtual_called ();
12730 }
12731
12732 static void
12733 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12734                                         struct linespec_result *c,
12735                                         struct linespec_sals *lsal,
12736                                         char *cond_string,
12737                                         char *extra_string,
12738                                         enum bptype type_wanted,
12739                                         enum bpdisp disposition,
12740                                         int thread,
12741                                         int task, int ignore_count,
12742                                         const struct breakpoint_ops *o,
12743                                         int from_tty, int enabled,
12744                                         int internal, unsigned flags)
12745 {
12746   internal_error_pure_virtual_called ();
12747 }
12748
12749 static void
12750 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12751                                  struct symtabs_and_lines *sals)
12752 {
12753   internal_error_pure_virtual_called ();
12754 }
12755
12756 /* The default 'explains_signal' method.  */
12757
12758 static enum bpstat_signal_value
12759 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12760 {
12761   return BPSTAT_SIGNAL_HIDE;
12762 }
12763
12764 struct breakpoint_ops base_breakpoint_ops =
12765 {
12766   base_breakpoint_dtor,
12767   base_breakpoint_allocate_location,
12768   base_breakpoint_re_set,
12769   base_breakpoint_insert_location,
12770   base_breakpoint_remove_location,
12771   base_breakpoint_breakpoint_hit,
12772   base_breakpoint_check_status,
12773   base_breakpoint_resources_needed,
12774   base_breakpoint_works_in_software_mode,
12775   base_breakpoint_print_it,
12776   NULL,
12777   base_breakpoint_print_one_detail,
12778   base_breakpoint_print_mention,
12779   base_breakpoint_print_recreate,
12780   base_breakpoint_create_sals_from_address,
12781   base_breakpoint_create_breakpoints_sal,
12782   base_breakpoint_decode_linespec,
12783   base_breakpoint_explains_signal
12784 };
12785
12786 /* Default breakpoint_ops methods.  */
12787
12788 static void
12789 bkpt_re_set (struct breakpoint *b)
12790 {
12791   /* FIXME: is this still reachable?  */
12792   if (b->addr_string == NULL)
12793     {
12794       /* Anything without a string can't be re-set.  */
12795       delete_breakpoint (b);
12796       return;
12797     }
12798
12799   breakpoint_re_set_default (b);
12800 }
12801
12802 static int
12803 bkpt_insert_location (struct bp_location *bl)
12804 {
12805   if (bl->loc_type == bp_loc_hardware_breakpoint)
12806     return target_insert_hw_breakpoint (bl->gdbarch,
12807                                         &bl->target_info);
12808   else
12809     return target_insert_breakpoint (bl->gdbarch,
12810                                      &bl->target_info);
12811 }
12812
12813 static int
12814 bkpt_remove_location (struct bp_location *bl)
12815 {
12816   if (bl->loc_type == bp_loc_hardware_breakpoint)
12817     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12818   else
12819     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12820 }
12821
12822 static int
12823 bkpt_breakpoint_hit (const struct bp_location *bl,
12824                      struct address_space *aspace, CORE_ADDR bp_addr,
12825                      const struct target_waitstatus *ws)
12826 {
12827   if (ws->kind != TARGET_WAITKIND_STOPPED
12828       || ws->value.sig != GDB_SIGNAL_TRAP)
12829     return 0;
12830
12831   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12832                                  aspace, bp_addr))
12833     return 0;
12834
12835   if (overlay_debugging         /* unmapped overlay section */
12836       && section_is_overlay (bl->section)
12837       && !section_is_mapped (bl->section))
12838     return 0;
12839
12840   return 1;
12841 }
12842
12843 static int
12844 bkpt_resources_needed (const struct bp_location *bl)
12845 {
12846   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12847
12848   return 1;
12849 }
12850
12851 static enum print_stop_action
12852 bkpt_print_it (bpstat bs)
12853 {
12854   struct breakpoint *b;
12855   const struct bp_location *bl;
12856   int bp_temp;
12857   struct ui_out *uiout = current_uiout;
12858
12859   gdb_assert (bs->bp_location_at != NULL);
12860
12861   bl = bs->bp_location_at;
12862   b = bs->breakpoint_at;
12863
12864   bp_temp = b->disposition == disp_del;
12865   if (bl->address != bl->requested_address)
12866     breakpoint_adjustment_warning (bl->requested_address,
12867                                    bl->address,
12868                                    b->number, 1);
12869   annotate_breakpoint (b->number);
12870   if (bp_temp)
12871     ui_out_text (uiout, "\nTemporary breakpoint ");
12872   else
12873     ui_out_text (uiout, "\nBreakpoint ");
12874   if (ui_out_is_mi_like_p (uiout))
12875     {
12876       ui_out_field_string (uiout, "reason",
12877                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12878       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12879     }
12880   ui_out_field_int (uiout, "bkptno", b->number);
12881   ui_out_text (uiout, ", ");
12882
12883   return PRINT_SRC_AND_LOC;
12884 }
12885
12886 static void
12887 bkpt_print_mention (struct breakpoint *b)
12888 {
12889   if (ui_out_is_mi_like_p (current_uiout))
12890     return;
12891
12892   switch (b->type)
12893     {
12894     case bp_breakpoint:
12895     case bp_gnu_ifunc_resolver:
12896       if (b->disposition == disp_del)
12897         printf_filtered (_("Temporary breakpoint"));
12898       else
12899         printf_filtered (_("Breakpoint"));
12900       printf_filtered (_(" %d"), b->number);
12901       if (b->type == bp_gnu_ifunc_resolver)
12902         printf_filtered (_(" at gnu-indirect-function resolver"));
12903       break;
12904     case bp_hardware_breakpoint:
12905       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12906       break;
12907     case bp_dprintf:
12908       printf_filtered (_("Dprintf %d"), b->number);
12909       break;
12910     }
12911
12912   say_where (b);
12913 }
12914
12915 static void
12916 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12917 {
12918   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12919     fprintf_unfiltered (fp, "tbreak");
12920   else if (tp->type == bp_breakpoint)
12921     fprintf_unfiltered (fp, "break");
12922   else if (tp->type == bp_hardware_breakpoint
12923            && tp->disposition == disp_del)
12924     fprintf_unfiltered (fp, "thbreak");
12925   else if (tp->type == bp_hardware_breakpoint)
12926     fprintf_unfiltered (fp, "hbreak");
12927   else
12928     internal_error (__FILE__, __LINE__,
12929                     _("unhandled breakpoint type %d"), (int) tp->type);
12930
12931   fprintf_unfiltered (fp, " %s", tp->addr_string);
12932   print_recreate_thread (tp, fp);
12933 }
12934
12935 static void
12936 bkpt_create_sals_from_address (char **arg,
12937                                struct linespec_result *canonical,
12938                                enum bptype type_wanted,
12939                                char *addr_start, char **copy_arg)
12940 {
12941   create_sals_from_address_default (arg, canonical, type_wanted,
12942                                     addr_start, copy_arg);
12943 }
12944
12945 static void
12946 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12947                              struct linespec_result *canonical,
12948                              struct linespec_sals *lsal,
12949                              char *cond_string,
12950                              char *extra_string,
12951                              enum bptype type_wanted,
12952                              enum bpdisp disposition,
12953                              int thread,
12954                              int task, int ignore_count,
12955                              const struct breakpoint_ops *ops,
12956                              int from_tty, int enabled,
12957                              int internal, unsigned flags)
12958 {
12959   create_breakpoints_sal_default (gdbarch, canonical,
12960                                   cond_string, extra_string,
12961                                   type_wanted,
12962                                   disposition, thread, task,
12963                                   ignore_count, ops, from_tty,
12964                                   enabled, internal, flags);
12965 }
12966
12967 static void
12968 bkpt_decode_linespec (struct breakpoint *b, char **s,
12969                       struct symtabs_and_lines *sals)
12970 {
12971   decode_linespec_default (b, s, sals);
12972 }
12973
12974 /* Virtual table for internal breakpoints.  */
12975
12976 static void
12977 internal_bkpt_re_set (struct breakpoint *b)
12978 {
12979   switch (b->type)
12980     {
12981       /* Delete overlay event and longjmp master breakpoints; they
12982          will be reset later by breakpoint_re_set.  */
12983     case bp_overlay_event:
12984     case bp_longjmp_master:
12985     case bp_std_terminate_master:
12986     case bp_exception_master:
12987       delete_breakpoint (b);
12988       break;
12989
12990       /* This breakpoint is special, it's set up when the inferior
12991          starts and we really don't want to touch it.  */
12992     case bp_shlib_event:
12993
12994       /* Like bp_shlib_event, this breakpoint type is special.  Once
12995          it is set up, we do not want to touch it.  */
12996     case bp_thread_event:
12997       break;
12998     }
12999 }
13000
13001 static void
13002 internal_bkpt_check_status (bpstat bs)
13003 {
13004   if (bs->breakpoint_at->type == bp_shlib_event)
13005     {
13006       /* If requested, stop when the dynamic linker notifies GDB of
13007          events.  This allows the user to get control and place
13008          breakpoints in initializer routines for dynamically loaded
13009          objects (among other things).  */
13010       bs->stop = stop_on_solib_events;
13011       bs->print = stop_on_solib_events;
13012     }
13013   else
13014     bs->stop = 0;
13015 }
13016
13017 static enum print_stop_action
13018 internal_bkpt_print_it (bpstat bs)
13019 {
13020   struct breakpoint *b;
13021
13022   b = bs->breakpoint_at;
13023
13024   switch (b->type)
13025     {
13026     case bp_shlib_event:
13027       /* Did we stop because the user set the stop_on_solib_events
13028          variable?  (If so, we report this as a generic, "Stopped due
13029          to shlib event" message.) */
13030       print_solib_event (0);
13031       break;
13032
13033     case bp_thread_event:
13034       /* Not sure how we will get here.
13035          GDB should not stop for these breakpoints.  */
13036       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13037       break;
13038
13039     case bp_overlay_event:
13040       /* By analogy with the thread event, GDB should not stop for these.  */
13041       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13042       break;
13043
13044     case bp_longjmp_master:
13045       /* These should never be enabled.  */
13046       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13047       break;
13048
13049     case bp_std_terminate_master:
13050       /* These should never be enabled.  */
13051       printf_filtered (_("std::terminate Master Breakpoint: "
13052                          "gdb should not stop!\n"));
13053       break;
13054
13055     case bp_exception_master:
13056       /* These should never be enabled.  */
13057       printf_filtered (_("Exception Master Breakpoint: "
13058                          "gdb should not stop!\n"));
13059       break;
13060     }
13061
13062   return PRINT_NOTHING;
13063 }
13064
13065 static void
13066 internal_bkpt_print_mention (struct breakpoint *b)
13067 {
13068   /* Nothing to mention.  These breakpoints are internal.  */
13069 }
13070
13071 /* Virtual table for momentary breakpoints  */
13072
13073 static void
13074 momentary_bkpt_re_set (struct breakpoint *b)
13075 {
13076   /* Keep temporary breakpoints, which can be encountered when we step
13077      over a dlopen call and solib_add is resetting the breakpoints.
13078      Otherwise these should have been blown away via the cleanup chain
13079      or by breakpoint_init_inferior when we rerun the executable.  */
13080 }
13081
13082 static void
13083 momentary_bkpt_check_status (bpstat bs)
13084 {
13085   /* Nothing.  The point of these breakpoints is causing a stop.  */
13086 }
13087
13088 static enum print_stop_action
13089 momentary_bkpt_print_it (bpstat bs)
13090 {
13091   struct ui_out *uiout = current_uiout;
13092
13093   if (ui_out_is_mi_like_p (uiout))
13094     {
13095       struct breakpoint *b = bs->breakpoint_at;
13096
13097       switch (b->type)
13098         {
13099         case bp_finish:
13100           ui_out_field_string
13101             (uiout, "reason",
13102              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13103           break;
13104
13105         case bp_until:
13106           ui_out_field_string
13107             (uiout, "reason",
13108              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13109           break;
13110         }
13111     }
13112
13113   return PRINT_UNKNOWN;
13114 }
13115
13116 static void
13117 momentary_bkpt_print_mention (struct breakpoint *b)
13118 {
13119   /* Nothing to mention.  These breakpoints are internal.  */
13120 }
13121
13122 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13123
13124    It gets cleared already on the removal of the first one of such placed
13125    breakpoints.  This is OK as they get all removed altogether.  */
13126
13127 static void
13128 longjmp_bkpt_dtor (struct breakpoint *self)
13129 {
13130   struct thread_info *tp = find_thread_id (self->thread);
13131
13132   if (tp)
13133     tp->initiating_frame = null_frame_id;
13134
13135   momentary_breakpoint_ops.dtor (self);
13136 }
13137
13138 /* Specific methods for probe breakpoints.  */
13139
13140 static int
13141 bkpt_probe_insert_location (struct bp_location *bl)
13142 {
13143   int v = bkpt_insert_location (bl);
13144
13145   if (v == 0)
13146     {
13147       /* The insertion was successful, now let's set the probe's semaphore
13148          if needed.  */
13149       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13150     }
13151
13152   return v;
13153 }
13154
13155 static int
13156 bkpt_probe_remove_location (struct bp_location *bl)
13157 {
13158   /* Let's clear the semaphore before removing the location.  */
13159   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13160
13161   return bkpt_remove_location (bl);
13162 }
13163
13164 static void
13165 bkpt_probe_create_sals_from_address (char **arg,
13166                                      struct linespec_result *canonical,
13167                                      enum bptype type_wanted,
13168                                      char *addr_start, char **copy_arg)
13169 {
13170   struct linespec_sals lsal;
13171
13172   lsal.sals = parse_probes (arg, canonical);
13173
13174   *copy_arg = xstrdup (canonical->addr_string);
13175   lsal.canonical = xstrdup (*copy_arg);
13176
13177   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13178 }
13179
13180 static void
13181 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13182                             struct symtabs_and_lines *sals)
13183 {
13184   *sals = parse_probes (s, NULL);
13185   if (!sals->sals)
13186     error (_("probe not found"));
13187 }
13188
13189 /* The breakpoint_ops structure to be used in tracepoints.  */
13190
13191 static void
13192 tracepoint_re_set (struct breakpoint *b)
13193 {
13194   breakpoint_re_set_default (b);
13195 }
13196
13197 static int
13198 tracepoint_breakpoint_hit (const struct bp_location *bl,
13199                            struct address_space *aspace, CORE_ADDR bp_addr,
13200                            const struct target_waitstatus *ws)
13201 {
13202   /* By definition, the inferior does not report stops at
13203      tracepoints.  */
13204   return 0;
13205 }
13206
13207 static void
13208 tracepoint_print_one_detail (const struct breakpoint *self,
13209                              struct ui_out *uiout)
13210 {
13211   struct tracepoint *tp = (struct tracepoint *) self;
13212   if (tp->static_trace_marker_id)
13213     {
13214       gdb_assert (self->type == bp_static_tracepoint);
13215
13216       ui_out_text (uiout, "\tmarker id is ");
13217       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13218                            tp->static_trace_marker_id);
13219       ui_out_text (uiout, "\n");
13220     }
13221 }
13222
13223 static void
13224 tracepoint_print_mention (struct breakpoint *b)
13225 {
13226   if (ui_out_is_mi_like_p (current_uiout))
13227     return;
13228
13229   switch (b->type)
13230     {
13231     case bp_tracepoint:
13232       printf_filtered (_("Tracepoint"));
13233       printf_filtered (_(" %d"), b->number);
13234       break;
13235     case bp_fast_tracepoint:
13236       printf_filtered (_("Fast tracepoint"));
13237       printf_filtered (_(" %d"), b->number);
13238       break;
13239     case bp_static_tracepoint:
13240       printf_filtered (_("Static tracepoint"));
13241       printf_filtered (_(" %d"), b->number);
13242       break;
13243     default:
13244       internal_error (__FILE__, __LINE__,
13245                       _("unhandled tracepoint type %d"), (int) b->type);
13246     }
13247
13248   say_where (b);
13249 }
13250
13251 static void
13252 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13253 {
13254   struct tracepoint *tp = (struct tracepoint *) self;
13255
13256   if (self->type == bp_fast_tracepoint)
13257     fprintf_unfiltered (fp, "ftrace");
13258   if (self->type == bp_static_tracepoint)
13259     fprintf_unfiltered (fp, "strace");
13260   else if (self->type == bp_tracepoint)
13261     fprintf_unfiltered (fp, "trace");
13262   else
13263     internal_error (__FILE__, __LINE__,
13264                     _("unhandled tracepoint type %d"), (int) self->type);
13265
13266   fprintf_unfiltered (fp, " %s", self->addr_string);
13267   print_recreate_thread (self, fp);
13268
13269   if (tp->pass_count)
13270     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13271 }
13272
13273 static void
13274 tracepoint_create_sals_from_address (char **arg,
13275                                      struct linespec_result *canonical,
13276                                      enum bptype type_wanted,
13277                                      char *addr_start, char **copy_arg)
13278 {
13279   create_sals_from_address_default (arg, canonical, type_wanted,
13280                                     addr_start, copy_arg);
13281 }
13282
13283 static void
13284 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13285                                    struct linespec_result *canonical,
13286                                    struct linespec_sals *lsal,
13287                                    char *cond_string,
13288                                    char *extra_string,
13289                                    enum bptype type_wanted,
13290                                    enum bpdisp disposition,
13291                                    int thread,
13292                                    int task, int ignore_count,
13293                                    const struct breakpoint_ops *ops,
13294                                    int from_tty, int enabled,
13295                                    int internal, unsigned flags)
13296 {
13297   create_breakpoints_sal_default (gdbarch, canonical,
13298                                   cond_string, extra_string,
13299                                   type_wanted,
13300                                   disposition, thread, task,
13301                                   ignore_count, ops, from_tty,
13302                                   enabled, internal, flags);
13303 }
13304
13305 static void
13306 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13307                             struct symtabs_and_lines *sals)
13308 {
13309   decode_linespec_default (b, s, sals);
13310 }
13311
13312 struct breakpoint_ops tracepoint_breakpoint_ops;
13313
13314 /* The breakpoint_ops structure to be use on tracepoints placed in a
13315    static probe.  */
13316
13317 static void
13318 tracepoint_probe_create_sals_from_address (char **arg,
13319                                            struct linespec_result *canonical,
13320                                            enum bptype type_wanted,
13321                                            char *addr_start, char **copy_arg)
13322 {
13323   /* We use the same method for breakpoint on probes.  */
13324   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13325                                        addr_start, copy_arg);
13326 }
13327
13328 static void
13329 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13330                                   struct symtabs_and_lines *sals)
13331 {
13332   /* We use the same method for breakpoint on probes.  */
13333   bkpt_probe_decode_linespec (b, s, sals);
13334 }
13335
13336 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13337
13338 /* Dprintf breakpoint_ops methods.  */
13339
13340 static void
13341 dprintf_re_set (struct breakpoint *b)
13342 {
13343   breakpoint_re_set_default (b);
13344
13345   /* This breakpoint could have been pending, and be resolved now, and
13346      if so, we should now have the extra string.  If we don't, the
13347      dprintf was malformed when created, but we couldn't tell because
13348      we can't extract the extra string until the location is
13349      resolved.  */
13350   if (b->loc != NULL && b->extra_string == NULL)
13351     error (_("Format string required"));
13352
13353   /* 1 - connect to target 1, that can run breakpoint commands.
13354      2 - create a dprintf, which resolves fine.
13355      3 - disconnect from target 1
13356      4 - connect to target 2, that can NOT run breakpoint commands.
13357
13358      After steps #3/#4, you'll want the dprintf command list to
13359      be updated, because target 1 and 2 may well return different
13360      answers for target_can_run_breakpoint_commands().
13361      Given absence of finer grained resetting, we get to do
13362      it all the time.  */
13363   if (b->extra_string != NULL)
13364     update_dprintf_command_list (b);
13365 }
13366
13367 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13368
13369 static void
13370 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13371 {
13372   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13373                       tp->extra_string);
13374   print_recreate_thread (tp, fp);
13375 }
13376
13377 /* The breakpoint_ops structure to be used on static tracepoints with
13378    markers (`-m').  */
13379
13380 static void
13381 strace_marker_create_sals_from_address (char **arg,
13382                                         struct linespec_result *canonical,
13383                                         enum bptype type_wanted,
13384                                         char *addr_start, char **copy_arg)
13385 {
13386   struct linespec_sals lsal;
13387
13388   lsal.sals = decode_static_tracepoint_spec (arg);
13389
13390   *copy_arg = savestring (addr_start, *arg - addr_start);
13391
13392   canonical->addr_string = xstrdup (*copy_arg);
13393   lsal.canonical = xstrdup (*copy_arg);
13394   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13395 }
13396
13397 static void
13398 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13399                                       struct linespec_result *canonical,
13400                                       struct linespec_sals *lsal,
13401                                       char *cond_string,
13402                                       char *extra_string,
13403                                       enum bptype type_wanted,
13404                                       enum bpdisp disposition,
13405                                       int thread,
13406                                       int task, int ignore_count,
13407                                       const struct breakpoint_ops *ops,
13408                                       int from_tty, int enabled,
13409                                       int internal, unsigned flags)
13410 {
13411   int i;
13412
13413   /* If the user is creating a static tracepoint by marker id
13414      (strace -m MARKER_ID), then store the sals index, so that
13415      breakpoint_re_set can try to match up which of the newly
13416      found markers corresponds to this one, and, don't try to
13417      expand multiple locations for each sal, given than SALS
13418      already should contain all sals for MARKER_ID.  */
13419
13420   for (i = 0; i < lsal->sals.nelts; ++i)
13421     {
13422       struct symtabs_and_lines expanded;
13423       struct tracepoint *tp;
13424       struct cleanup *old_chain;
13425       char *addr_string;
13426
13427       expanded.nelts = 1;
13428       expanded.sals = &lsal->sals.sals[i];
13429
13430       addr_string = xstrdup (canonical->addr_string);
13431       old_chain = make_cleanup (xfree, addr_string);
13432
13433       tp = XCNEW (struct tracepoint);
13434       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13435                            addr_string, NULL,
13436                            cond_string, extra_string,
13437                            type_wanted, disposition,
13438                            thread, task, ignore_count, ops,
13439                            from_tty, enabled, internal, flags,
13440                            canonical->special_display);
13441       /* Given that its possible to have multiple markers with
13442          the same string id, if the user is creating a static
13443          tracepoint by marker id ("strace -m MARKER_ID"), then
13444          store the sals index, so that breakpoint_re_set can
13445          try to match up which of the newly found markers
13446          corresponds to this one  */
13447       tp->static_trace_marker_id_idx = i;
13448
13449       install_breakpoint (internal, &tp->base, 0);
13450
13451       discard_cleanups (old_chain);
13452     }
13453 }
13454
13455 static void
13456 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13457                                struct symtabs_and_lines *sals)
13458 {
13459   struct tracepoint *tp = (struct tracepoint *) b;
13460
13461   *sals = decode_static_tracepoint_spec (s);
13462   if (sals->nelts > tp->static_trace_marker_id_idx)
13463     {
13464       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13465       sals->nelts = 1;
13466     }
13467   else
13468     error (_("marker %s not found"), tp->static_trace_marker_id);
13469 }
13470
13471 static struct breakpoint_ops strace_marker_breakpoint_ops;
13472
13473 static int
13474 strace_marker_p (struct breakpoint *b)
13475 {
13476   return b->ops == &strace_marker_breakpoint_ops;
13477 }
13478
13479 /* Delete a breakpoint and clean up all traces of it in the data
13480    structures.  */
13481
13482 void
13483 delete_breakpoint (struct breakpoint *bpt)
13484 {
13485   struct breakpoint *b;
13486
13487   gdb_assert (bpt != NULL);
13488
13489   /* Has this bp already been deleted?  This can happen because
13490      multiple lists can hold pointers to bp's.  bpstat lists are
13491      especial culprits.
13492
13493      One example of this happening is a watchpoint's scope bp.  When
13494      the scope bp triggers, we notice that the watchpoint is out of
13495      scope, and delete it.  We also delete its scope bp.  But the
13496      scope bp is marked "auto-deleting", and is already on a bpstat.
13497      That bpstat is then checked for auto-deleting bp's, which are
13498      deleted.
13499
13500      A real solution to this problem might involve reference counts in
13501      bp's, and/or giving them pointers back to their referencing
13502      bpstat's, and teaching delete_breakpoint to only free a bp's
13503      storage when no more references were extent.  A cheaper bandaid
13504      was chosen.  */
13505   if (bpt->type == bp_none)
13506     return;
13507
13508   /* At least avoid this stale reference until the reference counting
13509      of breakpoints gets resolved.  */
13510   if (bpt->related_breakpoint != bpt)
13511     {
13512       struct breakpoint *related;
13513       struct watchpoint *w;
13514
13515       if (bpt->type == bp_watchpoint_scope)
13516         w = (struct watchpoint *) bpt->related_breakpoint;
13517       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13518         w = (struct watchpoint *) bpt;
13519       else
13520         w = NULL;
13521       if (w != NULL)
13522         watchpoint_del_at_next_stop (w);
13523
13524       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13525       for (related = bpt; related->related_breakpoint != bpt;
13526            related = related->related_breakpoint);
13527       related->related_breakpoint = bpt->related_breakpoint;
13528       bpt->related_breakpoint = bpt;
13529     }
13530
13531   /* watch_command_1 creates a watchpoint but only sets its number if
13532      update_watchpoint succeeds in creating its bp_locations.  If there's
13533      a problem in that process, we'll be asked to delete the half-created
13534      watchpoint.  In that case, don't announce the deletion.  */
13535   if (bpt->number)
13536     observer_notify_breakpoint_deleted (bpt);
13537
13538   if (breakpoint_chain == bpt)
13539     breakpoint_chain = bpt->next;
13540
13541   ALL_BREAKPOINTS (b)
13542     if (b->next == bpt)
13543     {
13544       b->next = bpt->next;
13545       break;
13546     }
13547
13548   /* Be sure no bpstat's are pointing at the breakpoint after it's
13549      been freed.  */
13550   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13551      in all threads for now.  Note that we cannot just remove bpstats
13552      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13553      commands are associated with the bpstat; if we remove it here,
13554      then the later call to bpstat_do_actions (&stop_bpstat); in
13555      event-top.c won't do anything, and temporary breakpoints with
13556      commands won't work.  */
13557
13558   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13559
13560   /* Now that breakpoint is removed from breakpoint list, update the
13561      global location list.  This will remove locations that used to
13562      belong to this breakpoint.  Do this before freeing the breakpoint
13563      itself, since remove_breakpoint looks at location's owner.  It
13564      might be better design to have location completely
13565      self-contained, but it's not the case now.  */
13566   update_global_location_list (0);
13567
13568   bpt->ops->dtor (bpt);
13569   /* On the chance that someone will soon try again to delete this
13570      same bp, we mark it as deleted before freeing its storage.  */
13571   bpt->type = bp_none;
13572   xfree (bpt);
13573 }
13574
13575 static void
13576 do_delete_breakpoint_cleanup (void *b)
13577 {
13578   delete_breakpoint (b);
13579 }
13580
13581 struct cleanup *
13582 make_cleanup_delete_breakpoint (struct breakpoint *b)
13583 {
13584   return make_cleanup (do_delete_breakpoint_cleanup, b);
13585 }
13586
13587 /* Iterator function to call a user-provided callback function once
13588    for each of B and its related breakpoints.  */
13589
13590 static void
13591 iterate_over_related_breakpoints (struct breakpoint *b,
13592                                   void (*function) (struct breakpoint *,
13593                                                     void *),
13594                                   void *data)
13595 {
13596   struct breakpoint *related;
13597
13598   related = b;
13599   do
13600     {
13601       struct breakpoint *next;
13602
13603       /* FUNCTION may delete RELATED.  */
13604       next = related->related_breakpoint;
13605
13606       if (next == related)
13607         {
13608           /* RELATED is the last ring entry.  */
13609           function (related, data);
13610
13611           /* FUNCTION may have deleted it, so we'd never reach back to
13612              B.  There's nothing left to do anyway, so just break
13613              out.  */
13614           break;
13615         }
13616       else
13617         function (related, data);
13618
13619       related = next;
13620     }
13621   while (related != b);
13622 }
13623
13624 static void
13625 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13626 {
13627   delete_breakpoint (b);
13628 }
13629
13630 /* A callback for map_breakpoint_numbers that calls
13631    delete_breakpoint.  */
13632
13633 static void
13634 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13635 {
13636   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13637 }
13638
13639 void
13640 delete_command (char *arg, int from_tty)
13641 {
13642   struct breakpoint *b, *b_tmp;
13643
13644   dont_repeat ();
13645
13646   if (arg == 0)
13647     {
13648       int breaks_to_delete = 0;
13649
13650       /* Delete all breakpoints if no argument.  Do not delete
13651          internal breakpoints, these have to be deleted with an
13652          explicit breakpoint number argument.  */
13653       ALL_BREAKPOINTS (b)
13654         if (user_breakpoint_p (b))
13655           {
13656             breaks_to_delete = 1;
13657             break;
13658           }
13659
13660       /* Ask user only if there are some breakpoints to delete.  */
13661       if (!from_tty
13662           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13663         {
13664           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13665             if (user_breakpoint_p (b))
13666               delete_breakpoint (b);
13667         }
13668     }
13669   else
13670     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13671 }
13672
13673 static int
13674 all_locations_are_pending (struct bp_location *loc)
13675 {
13676   for (; loc; loc = loc->next)
13677     if (!loc->shlib_disabled
13678         && !loc->pspace->executing_startup)
13679       return 0;
13680   return 1;
13681 }
13682
13683 /* Subroutine of update_breakpoint_locations to simplify it.
13684    Return non-zero if multiple fns in list LOC have the same name.
13685    Null names are ignored.  */
13686
13687 static int
13688 ambiguous_names_p (struct bp_location *loc)
13689 {
13690   struct bp_location *l;
13691   htab_t htab = htab_create_alloc (13, htab_hash_string,
13692                                    (int (*) (const void *, 
13693                                              const void *)) streq,
13694                                    NULL, xcalloc, xfree);
13695
13696   for (l = loc; l != NULL; l = l->next)
13697     {
13698       const char **slot;
13699       const char *name = l->function_name;
13700
13701       /* Allow for some names to be NULL, ignore them.  */
13702       if (name == NULL)
13703         continue;
13704
13705       slot = (const char **) htab_find_slot (htab, (const void *) name,
13706                                              INSERT);
13707       /* NOTE: We can assume slot != NULL here because xcalloc never
13708          returns NULL.  */
13709       if (*slot != NULL)
13710         {
13711           htab_delete (htab);
13712           return 1;
13713         }
13714       *slot = name;
13715     }
13716
13717   htab_delete (htab);
13718   return 0;
13719 }
13720
13721 /* When symbols change, it probably means the sources changed as well,
13722    and it might mean the static tracepoint markers are no longer at
13723    the same address or line numbers they used to be at last we
13724    checked.  Losing your static tracepoints whenever you rebuild is
13725    undesirable.  This function tries to resync/rematch gdb static
13726    tracepoints with the markers on the target, for static tracepoints
13727    that have not been set by marker id.  Static tracepoint that have
13728    been set by marker id are reset by marker id in breakpoint_re_set.
13729    The heuristic is:
13730
13731    1) For a tracepoint set at a specific address, look for a marker at
13732    the old PC.  If one is found there, assume to be the same marker.
13733    If the name / string id of the marker found is different from the
13734    previous known name, assume that means the user renamed the marker
13735    in the sources, and output a warning.
13736
13737    2) For a tracepoint set at a given line number, look for a marker
13738    at the new address of the old line number.  If one is found there,
13739    assume to be the same marker.  If the name / string id of the
13740    marker found is different from the previous known name, assume that
13741    means the user renamed the marker in the sources, and output a
13742    warning.
13743
13744    3) If a marker is no longer found at the same address or line, it
13745    may mean the marker no longer exists.  But it may also just mean
13746    the code changed a bit.  Maybe the user added a few lines of code
13747    that made the marker move up or down (in line number terms).  Ask
13748    the target for info about the marker with the string id as we knew
13749    it.  If found, update line number and address in the matching
13750    static tracepoint.  This will get confused if there's more than one
13751    marker with the same ID (possible in UST, although unadvised
13752    precisely because it confuses tools).  */
13753
13754 static struct symtab_and_line
13755 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13756 {
13757   struct tracepoint *tp = (struct tracepoint *) b;
13758   struct static_tracepoint_marker marker;
13759   CORE_ADDR pc;
13760
13761   pc = sal.pc;
13762   if (sal.line)
13763     find_line_pc (sal.symtab, sal.line, &pc);
13764
13765   if (target_static_tracepoint_marker_at (pc, &marker))
13766     {
13767       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13768         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13769                  b->number,
13770                  tp->static_trace_marker_id, marker.str_id);
13771
13772       xfree (tp->static_trace_marker_id);
13773       tp->static_trace_marker_id = xstrdup (marker.str_id);
13774       release_static_tracepoint_marker (&marker);
13775
13776       return sal;
13777     }
13778
13779   /* Old marker wasn't found on target at lineno.  Try looking it up
13780      by string ID.  */
13781   if (!sal.explicit_pc
13782       && sal.line != 0
13783       && sal.symtab != NULL
13784       && tp->static_trace_marker_id != NULL)
13785     {
13786       VEC(static_tracepoint_marker_p) *markers;
13787
13788       markers
13789         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13790
13791       if (!VEC_empty(static_tracepoint_marker_p, markers))
13792         {
13793           struct symtab_and_line sal2;
13794           struct symbol *sym;
13795           struct static_tracepoint_marker *tpmarker;
13796           struct ui_out *uiout = current_uiout;
13797
13798           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13799
13800           xfree (tp->static_trace_marker_id);
13801           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13802
13803           warning (_("marker for static tracepoint %d (%s) not "
13804                      "found at previous line number"),
13805                    b->number, tp->static_trace_marker_id);
13806
13807           init_sal (&sal2);
13808
13809           sal2.pc = tpmarker->address;
13810
13811           sal2 = find_pc_line (tpmarker->address, 0);
13812           sym = find_pc_sect_function (tpmarker->address, NULL);
13813           ui_out_text (uiout, "Now in ");
13814           if (sym)
13815             {
13816               ui_out_field_string (uiout, "func",
13817                                    SYMBOL_PRINT_NAME (sym));
13818               ui_out_text (uiout, " at ");
13819             }
13820           ui_out_field_string (uiout, "file",
13821                                symtab_to_filename_for_display (sal2.symtab));
13822           ui_out_text (uiout, ":");
13823
13824           if (ui_out_is_mi_like_p (uiout))
13825             {
13826               const char *fullname = symtab_to_fullname (sal2.symtab);
13827
13828               ui_out_field_string (uiout, "fullname", fullname);
13829             }
13830
13831           ui_out_field_int (uiout, "line", sal2.line);
13832           ui_out_text (uiout, "\n");
13833
13834           b->loc->line_number = sal2.line;
13835           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13836
13837           xfree (b->addr_string);
13838           b->addr_string = xstrprintf ("%s:%d",
13839                                    symtab_to_filename_for_display (sal2.symtab),
13840                                        b->loc->line_number);
13841
13842           /* Might be nice to check if function changed, and warn if
13843              so.  */
13844
13845           release_static_tracepoint_marker (tpmarker);
13846         }
13847     }
13848   return sal;
13849 }
13850
13851 /* Returns 1 iff locations A and B are sufficiently same that
13852    we don't need to report breakpoint as changed.  */
13853
13854 static int
13855 locations_are_equal (struct bp_location *a, struct bp_location *b)
13856 {
13857   while (a && b)
13858     {
13859       if (a->address != b->address)
13860         return 0;
13861
13862       if (a->shlib_disabled != b->shlib_disabled)
13863         return 0;
13864
13865       if (a->enabled != b->enabled)
13866         return 0;
13867
13868       a = a->next;
13869       b = b->next;
13870     }
13871
13872   if ((a == NULL) != (b == NULL))
13873     return 0;
13874
13875   return 1;
13876 }
13877
13878 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13879    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13880    a ranged breakpoint.  */
13881
13882 void
13883 update_breakpoint_locations (struct breakpoint *b,
13884                              struct symtabs_and_lines sals,
13885                              struct symtabs_and_lines sals_end)
13886 {
13887   int i;
13888   struct bp_location *existing_locations = b->loc;
13889
13890   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13891     {
13892       /* Ranged breakpoints have only one start location and one end
13893          location.  */
13894       b->enable_state = bp_disabled;
13895       update_global_location_list (1);
13896       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13897                            "multiple locations found\n"),
13898                          b->number);
13899       return;
13900     }
13901
13902   /* If there's no new locations, and all existing locations are
13903      pending, don't do anything.  This optimizes the common case where
13904      all locations are in the same shared library, that was unloaded.
13905      We'd like to retain the location, so that when the library is
13906      loaded again, we don't loose the enabled/disabled status of the
13907      individual locations.  */
13908   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13909     return;
13910
13911   b->loc = NULL;
13912
13913   for (i = 0; i < sals.nelts; ++i)
13914     {
13915       struct bp_location *new_loc;
13916
13917       switch_to_program_space_and_thread (sals.sals[i].pspace);
13918
13919       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13920
13921       /* Reparse conditions, they might contain references to the
13922          old symtab.  */
13923       if (b->cond_string != NULL)
13924         {
13925           const char *s;
13926           volatile struct gdb_exception e;
13927
13928           s = b->cond_string;
13929           TRY_CATCH (e, RETURN_MASK_ERROR)
13930             {
13931               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
13932                                            block_for_pc (sals.sals[i].pc), 
13933                                            0);
13934             }
13935           if (e.reason < 0)
13936             {
13937               warning (_("failed to reevaluate condition "
13938                          "for breakpoint %d: %s"), 
13939                        b->number, e.message);
13940               new_loc->enabled = 0;
13941             }
13942         }
13943
13944       if (sals_end.nelts)
13945         {
13946           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13947
13948           new_loc->length = end - sals.sals[0].pc + 1;
13949         }
13950     }
13951
13952   /* Update locations of permanent breakpoints.  */
13953   if (b->enable_state == bp_permanent)
13954     make_breakpoint_permanent (b);
13955
13956   /* If possible, carry over 'disable' status from existing
13957      breakpoints.  */
13958   {
13959     struct bp_location *e = existing_locations;
13960     /* If there are multiple breakpoints with the same function name,
13961        e.g. for inline functions, comparing function names won't work.
13962        Instead compare pc addresses; this is just a heuristic as things
13963        may have moved, but in practice it gives the correct answer
13964        often enough until a better solution is found.  */
13965     int have_ambiguous_names = ambiguous_names_p (b->loc);
13966
13967     for (; e; e = e->next)
13968       {
13969         if (!e->enabled && e->function_name)
13970           {
13971             struct bp_location *l = b->loc;
13972             if (have_ambiguous_names)
13973               {
13974                 for (; l; l = l->next)
13975                   if (breakpoint_locations_match (e, l))
13976                     {
13977                       l->enabled = 0;
13978                       break;
13979                     }
13980               }
13981             else
13982               {
13983                 for (; l; l = l->next)
13984                   if (l->function_name
13985                       && strcmp (e->function_name, l->function_name) == 0)
13986                     {
13987                       l->enabled = 0;
13988                       break;
13989                     }
13990               }
13991           }
13992       }
13993   }
13994
13995   if (!locations_are_equal (existing_locations, b->loc))
13996     observer_notify_breakpoint_modified (b);
13997
13998   update_global_location_list (1);
13999 }
14000
14001 /* Find the SaL locations corresponding to the given ADDR_STRING.
14002    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14003
14004 static struct symtabs_and_lines
14005 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14006 {
14007   char *s;
14008   struct symtabs_and_lines sals = {0};
14009   volatile struct gdb_exception e;
14010
14011   gdb_assert (b->ops != NULL);
14012   s = addr_string;
14013
14014   TRY_CATCH (e, RETURN_MASK_ERROR)
14015     {
14016       b->ops->decode_linespec (b, &s, &sals);
14017     }
14018   if (e.reason < 0)
14019     {
14020       int not_found_and_ok = 0;
14021       /* For pending breakpoints, it's expected that parsing will
14022          fail until the right shared library is loaded.  User has
14023          already told to create pending breakpoints and don't need
14024          extra messages.  If breakpoint is in bp_shlib_disabled
14025          state, then user already saw the message about that
14026          breakpoint being disabled, and don't want to see more
14027          errors.  */
14028       if (e.error == NOT_FOUND_ERROR
14029           && (b->condition_not_parsed 
14030               || (b->loc && b->loc->shlib_disabled)
14031               || (b->loc && b->loc->pspace->executing_startup)
14032               || b->enable_state == bp_disabled))
14033         not_found_and_ok = 1;
14034
14035       if (!not_found_and_ok)
14036         {
14037           /* We surely don't want to warn about the same breakpoint
14038              10 times.  One solution, implemented here, is disable
14039              the breakpoint on error.  Another solution would be to
14040              have separate 'warning emitted' flag.  Since this
14041              happens only when a binary has changed, I don't know
14042              which approach is better.  */
14043           b->enable_state = bp_disabled;
14044           throw_exception (e);
14045         }
14046     }
14047
14048   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14049     {
14050       int i;
14051
14052       for (i = 0; i < sals.nelts; ++i)
14053         resolve_sal_pc (&sals.sals[i]);
14054       if (b->condition_not_parsed && s && s[0])
14055         {
14056           char *cond_string, *extra_string;
14057           int thread, task;
14058
14059           find_condition_and_thread (s, sals.sals[0].pc,
14060                                      &cond_string, &thread, &task,
14061                                      &extra_string);
14062           if (cond_string)
14063             b->cond_string = cond_string;
14064           b->thread = thread;
14065           b->task = task;
14066           if (extra_string)
14067             b->extra_string = extra_string;
14068           b->condition_not_parsed = 0;
14069         }
14070
14071       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14072         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14073
14074       *found = 1;
14075     }
14076   else
14077     *found = 0;
14078
14079   return sals;
14080 }
14081
14082 /* The default re_set method, for typical hardware or software
14083    breakpoints.  Reevaluate the breakpoint and recreate its
14084    locations.  */
14085
14086 static void
14087 breakpoint_re_set_default (struct breakpoint *b)
14088 {
14089   int found;
14090   struct symtabs_and_lines sals, sals_end;
14091   struct symtabs_and_lines expanded = {0};
14092   struct symtabs_and_lines expanded_end = {0};
14093
14094   sals = addr_string_to_sals (b, b->addr_string, &found);
14095   if (found)
14096     {
14097       make_cleanup (xfree, sals.sals);
14098       expanded = sals;
14099     }
14100
14101   if (b->addr_string_range_end)
14102     {
14103       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14104       if (found)
14105         {
14106           make_cleanup (xfree, sals_end.sals);
14107           expanded_end = sals_end;
14108         }
14109     }
14110
14111   update_breakpoint_locations (b, expanded, expanded_end);
14112 }
14113
14114 /* Default method for creating SALs from an address string.  It basically
14115    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14116
14117 static void
14118 create_sals_from_address_default (char **arg,
14119                                   struct linespec_result *canonical,
14120                                   enum bptype type_wanted,
14121                                   char *addr_start, char **copy_arg)
14122 {
14123   parse_breakpoint_sals (arg, canonical);
14124 }
14125
14126 /* Call create_breakpoints_sal for the given arguments.  This is the default
14127    function for the `create_breakpoints_sal' method of
14128    breakpoint_ops.  */
14129
14130 static void
14131 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14132                                 struct linespec_result *canonical,
14133                                 char *cond_string,
14134                                 char *extra_string,
14135                                 enum bptype type_wanted,
14136                                 enum bpdisp disposition,
14137                                 int thread,
14138                                 int task, int ignore_count,
14139                                 const struct breakpoint_ops *ops,
14140                                 int from_tty, int enabled,
14141                                 int internal, unsigned flags)
14142 {
14143   create_breakpoints_sal (gdbarch, canonical, cond_string,
14144                           extra_string,
14145                           type_wanted, disposition,
14146                           thread, task, ignore_count, ops, from_tty,
14147                           enabled, internal, flags);
14148 }
14149
14150 /* Decode the line represented by S by calling decode_line_full.  This is the
14151    default function for the `decode_linespec' method of breakpoint_ops.  */
14152
14153 static void
14154 decode_linespec_default (struct breakpoint *b, char **s,
14155                          struct symtabs_and_lines *sals)
14156 {
14157   struct linespec_result canonical;
14158
14159   init_linespec_result (&canonical);
14160   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14161                     (struct symtab *) NULL, 0,
14162                     &canonical, multiple_symbols_all,
14163                     b->filter);
14164
14165   /* We should get 0 or 1 resulting SALs.  */
14166   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14167
14168   if (VEC_length (linespec_sals, canonical.sals) > 0)
14169     {
14170       struct linespec_sals *lsal;
14171
14172       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14173       *sals = lsal->sals;
14174       /* Arrange it so the destructor does not free the
14175          contents.  */
14176       lsal->sals.sals = NULL;
14177     }
14178
14179   destroy_linespec_result (&canonical);
14180 }
14181
14182 /* Prepare the global context for a re-set of breakpoint B.  */
14183
14184 static struct cleanup *
14185 prepare_re_set_context (struct breakpoint *b)
14186 {
14187   struct cleanup *cleanups;
14188
14189   input_radix = b->input_radix;
14190   cleanups = save_current_space_and_thread ();
14191   if (b->pspace != NULL)
14192     switch_to_program_space_and_thread (b->pspace);
14193   set_language (b->language);
14194
14195   return cleanups;
14196 }
14197
14198 /* Reset a breakpoint given it's struct breakpoint * BINT.
14199    The value we return ends up being the return value from catch_errors.
14200    Unused in this case.  */
14201
14202 static int
14203 breakpoint_re_set_one (void *bint)
14204 {
14205   /* Get past catch_errs.  */
14206   struct breakpoint *b = (struct breakpoint *) bint;
14207   struct cleanup *cleanups;
14208
14209   cleanups = prepare_re_set_context (b);
14210   b->ops->re_set (b);
14211   do_cleanups (cleanups);
14212   return 0;
14213 }
14214
14215 /* Re-set all breakpoints after symbols have been re-loaded.  */
14216 void
14217 breakpoint_re_set (void)
14218 {
14219   struct breakpoint *b, *b_tmp;
14220   enum language save_language;
14221   int save_input_radix;
14222   struct cleanup *old_chain;
14223
14224   save_language = current_language->la_language;
14225   save_input_radix = input_radix;
14226   old_chain = save_current_program_space ();
14227
14228   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14229   {
14230     /* Format possible error msg.  */
14231     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14232                                 b->number);
14233     struct cleanup *cleanups = make_cleanup (xfree, message);
14234     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14235     do_cleanups (cleanups);
14236   }
14237   set_language (save_language);
14238   input_radix = save_input_radix;
14239
14240   jit_breakpoint_re_set ();
14241
14242   do_cleanups (old_chain);
14243
14244   create_overlay_event_breakpoint ();
14245   create_longjmp_master_breakpoint ();
14246   create_std_terminate_master_breakpoint ();
14247   create_exception_master_breakpoint ();
14248 }
14249 \f
14250 /* Reset the thread number of this breakpoint:
14251
14252    - If the breakpoint is for all threads, leave it as-is.
14253    - Else, reset it to the current thread for inferior_ptid.  */
14254 void
14255 breakpoint_re_set_thread (struct breakpoint *b)
14256 {
14257   if (b->thread != -1)
14258     {
14259       if (in_thread_list (inferior_ptid))
14260         b->thread = pid_to_thread_id (inferior_ptid);
14261
14262       /* We're being called after following a fork.  The new fork is
14263          selected as current, and unless this was a vfork will have a
14264          different program space from the original thread.  Reset that
14265          as well.  */
14266       b->loc->pspace = current_program_space;
14267     }
14268 }
14269
14270 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14271    If from_tty is nonzero, it prints a message to that effect,
14272    which ends with a period (no newline).  */
14273
14274 void
14275 set_ignore_count (int bptnum, int count, int from_tty)
14276 {
14277   struct breakpoint *b;
14278
14279   if (count < 0)
14280     count = 0;
14281
14282   ALL_BREAKPOINTS (b)
14283     if (b->number == bptnum)
14284     {
14285       if (is_tracepoint (b))
14286         {
14287           if (from_tty && count != 0)
14288             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14289                              bptnum);
14290           return;
14291         }
14292       
14293       b->ignore_count = count;
14294       if (from_tty)
14295         {
14296           if (count == 0)
14297             printf_filtered (_("Will stop next time "
14298                                "breakpoint %d is reached."),
14299                              bptnum);
14300           else if (count == 1)
14301             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14302                              bptnum);
14303           else
14304             printf_filtered (_("Will ignore next %d "
14305                                "crossings of breakpoint %d."),
14306                              count, bptnum);
14307         }
14308       observer_notify_breakpoint_modified (b);
14309       return;
14310     }
14311
14312   error (_("No breakpoint number %d."), bptnum);
14313 }
14314
14315 /* Command to set ignore-count of breakpoint N to COUNT.  */
14316
14317 static void
14318 ignore_command (char *args, int from_tty)
14319 {
14320   char *p = args;
14321   int num;
14322
14323   if (p == 0)
14324     error_no_arg (_("a breakpoint number"));
14325
14326   num = get_number (&p);
14327   if (num == 0)
14328     error (_("bad breakpoint number: '%s'"), args);
14329   if (*p == 0)
14330     error (_("Second argument (specified ignore-count) is missing."));
14331
14332   set_ignore_count (num,
14333                     longest_to_int (value_as_long (parse_and_eval (p))),
14334                     from_tty);
14335   if (from_tty)
14336     printf_filtered ("\n");
14337 }
14338 \f
14339 /* Call FUNCTION on each of the breakpoints
14340    whose numbers are given in ARGS.  */
14341
14342 static void
14343 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14344                                                       void *),
14345                         void *data)
14346 {
14347   int num;
14348   struct breakpoint *b, *tmp;
14349   int match;
14350   struct get_number_or_range_state state;
14351
14352   if (args == 0)
14353     error_no_arg (_("one or more breakpoint numbers"));
14354
14355   init_number_or_range (&state, args);
14356
14357   while (!state.finished)
14358     {
14359       char *p = state.string;
14360
14361       match = 0;
14362
14363       num = get_number_or_range (&state);
14364       if (num == 0)
14365         {
14366           warning (_("bad breakpoint number at or near '%s'"), p);
14367         }
14368       else
14369         {
14370           ALL_BREAKPOINTS_SAFE (b, tmp)
14371             if (b->number == num)
14372               {
14373                 match = 1;
14374                 function (b, data);
14375                 break;
14376               }
14377           if (match == 0)
14378             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14379         }
14380     }
14381 }
14382
14383 static struct bp_location *
14384 find_location_by_number (char *number)
14385 {
14386   char *dot = strchr (number, '.');
14387   char *p1;
14388   int bp_num;
14389   int loc_num;
14390   struct breakpoint *b;
14391   struct bp_location *loc;  
14392
14393   *dot = '\0';
14394
14395   p1 = number;
14396   bp_num = get_number (&p1);
14397   if (bp_num == 0)
14398     error (_("Bad breakpoint number '%s'"), number);
14399
14400   ALL_BREAKPOINTS (b)
14401     if (b->number == bp_num)
14402       {
14403         break;
14404       }
14405
14406   if (!b || b->number != bp_num)
14407     error (_("Bad breakpoint number '%s'"), number);
14408   
14409   p1 = dot+1;
14410   loc_num = get_number (&p1);
14411   if (loc_num == 0)
14412     error (_("Bad breakpoint location number '%s'"), number);
14413
14414   --loc_num;
14415   loc = b->loc;
14416   for (;loc_num && loc; --loc_num, loc = loc->next)
14417     ;
14418   if (!loc)
14419     error (_("Bad breakpoint location number '%s'"), dot+1);
14420     
14421   return loc;  
14422 }
14423
14424
14425 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14426    If from_tty is nonzero, it prints a message to that effect,
14427    which ends with a period (no newline).  */
14428
14429 void
14430 disable_breakpoint (struct breakpoint *bpt)
14431 {
14432   /* Never disable a watchpoint scope breakpoint; we want to
14433      hit them when we leave scope so we can delete both the
14434      watchpoint and its scope breakpoint at that time.  */
14435   if (bpt->type == bp_watchpoint_scope)
14436     return;
14437
14438   /* You can't disable permanent breakpoints.  */
14439   if (bpt->enable_state == bp_permanent)
14440     return;
14441
14442   bpt->enable_state = bp_disabled;
14443
14444   /* Mark breakpoint locations modified.  */
14445   mark_breakpoint_modified (bpt);
14446
14447   if (target_supports_enable_disable_tracepoint ()
14448       && current_trace_status ()->running && is_tracepoint (bpt))
14449     {
14450       struct bp_location *location;
14451      
14452       for (location = bpt->loc; location; location = location->next)
14453         target_disable_tracepoint (location);
14454     }
14455
14456   update_global_location_list (0);
14457
14458   observer_notify_breakpoint_modified (bpt);
14459 }
14460
14461 /* A callback for iterate_over_related_breakpoints.  */
14462
14463 static void
14464 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14465 {
14466   disable_breakpoint (b);
14467 }
14468
14469 /* A callback for map_breakpoint_numbers that calls
14470    disable_breakpoint.  */
14471
14472 static void
14473 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14474 {
14475   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14476 }
14477
14478 static void
14479 disable_command (char *args, int from_tty)
14480 {
14481   if (args == 0)
14482     {
14483       struct breakpoint *bpt;
14484
14485       ALL_BREAKPOINTS (bpt)
14486         if (user_breakpoint_p (bpt))
14487           disable_breakpoint (bpt);
14488     }
14489   else if (strchr (args, '.'))
14490     {
14491       struct bp_location *loc = find_location_by_number (args);
14492       if (loc)
14493         {
14494           if (loc->enabled)
14495             {
14496               loc->enabled = 0;
14497               mark_breakpoint_location_modified (loc);
14498             }
14499           if (target_supports_enable_disable_tracepoint ()
14500               && current_trace_status ()->running && loc->owner
14501               && is_tracepoint (loc->owner))
14502             target_disable_tracepoint (loc);
14503         }
14504       update_global_location_list (0);
14505     }
14506   else
14507     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14508 }
14509
14510 static void
14511 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14512                         int count)
14513 {
14514   int target_resources_ok;
14515
14516   if (bpt->type == bp_hardware_breakpoint)
14517     {
14518       int i;
14519       i = hw_breakpoint_used_count ();
14520       target_resources_ok = 
14521         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14522                                             i + 1, 0);
14523       if (target_resources_ok == 0)
14524         error (_("No hardware breakpoint support in the target."));
14525       else if (target_resources_ok < 0)
14526         error (_("Hardware breakpoints used exceeds limit."));
14527     }
14528
14529   if (is_watchpoint (bpt))
14530     {
14531       /* Initialize it just to avoid a GCC false warning.  */
14532       enum enable_state orig_enable_state = 0;
14533       volatile struct gdb_exception e;
14534
14535       TRY_CATCH (e, RETURN_MASK_ALL)
14536         {
14537           struct watchpoint *w = (struct watchpoint *) bpt;
14538
14539           orig_enable_state = bpt->enable_state;
14540           bpt->enable_state = bp_enabled;
14541           update_watchpoint (w, 1 /* reparse */);
14542         }
14543       if (e.reason < 0)
14544         {
14545           bpt->enable_state = orig_enable_state;
14546           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14547                              bpt->number);
14548           return;
14549         }
14550     }
14551
14552   if (bpt->enable_state != bp_permanent)
14553     bpt->enable_state = bp_enabled;
14554
14555   bpt->enable_state = bp_enabled;
14556
14557   /* Mark breakpoint locations modified.  */
14558   mark_breakpoint_modified (bpt);
14559
14560   if (target_supports_enable_disable_tracepoint ()
14561       && current_trace_status ()->running && is_tracepoint (bpt))
14562     {
14563       struct bp_location *location;
14564
14565       for (location = bpt->loc; location; location = location->next)
14566         target_enable_tracepoint (location);
14567     }
14568
14569   bpt->disposition = disposition;
14570   bpt->enable_count = count;
14571   update_global_location_list (1);
14572
14573   observer_notify_breakpoint_modified (bpt);
14574 }
14575
14576
14577 void
14578 enable_breakpoint (struct breakpoint *bpt)
14579 {
14580   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14581 }
14582
14583 static void
14584 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14585 {
14586   enable_breakpoint (bpt);
14587 }
14588
14589 /* A callback for map_breakpoint_numbers that calls
14590    enable_breakpoint.  */
14591
14592 static void
14593 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14594 {
14595   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14596 }
14597
14598 /* The enable command enables the specified breakpoints (or all defined
14599    breakpoints) so they once again become (or continue to be) effective
14600    in stopping the inferior.  */
14601
14602 static void
14603 enable_command (char *args, int from_tty)
14604 {
14605   if (args == 0)
14606     {
14607       struct breakpoint *bpt;
14608
14609       ALL_BREAKPOINTS (bpt)
14610         if (user_breakpoint_p (bpt))
14611           enable_breakpoint (bpt);
14612     }
14613   else if (strchr (args, '.'))
14614     {
14615       struct bp_location *loc = find_location_by_number (args);
14616       if (loc)
14617         {
14618           if (!loc->enabled)
14619             {
14620               loc->enabled = 1;
14621               mark_breakpoint_location_modified (loc);
14622             }
14623           if (target_supports_enable_disable_tracepoint ()
14624               && current_trace_status ()->running && loc->owner
14625               && is_tracepoint (loc->owner))
14626             target_enable_tracepoint (loc);
14627         }
14628       update_global_location_list (1);
14629     }
14630   else
14631     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14632 }
14633
14634 /* This struct packages up disposition data for application to multiple
14635    breakpoints.  */
14636
14637 struct disp_data
14638 {
14639   enum bpdisp disp;
14640   int count;
14641 };
14642
14643 static void
14644 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14645 {
14646   struct disp_data disp_data = *(struct disp_data *) arg;
14647
14648   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14649 }
14650
14651 static void
14652 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14653 {
14654   struct disp_data disp = { disp_disable, 1 };
14655
14656   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14657 }
14658
14659 static void
14660 enable_once_command (char *args, int from_tty)
14661 {
14662   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14663 }
14664
14665 static void
14666 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14667 {
14668   struct disp_data disp = { disp_disable, *(int *) countptr };
14669
14670   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14671 }
14672
14673 static void
14674 enable_count_command (char *args, int from_tty)
14675 {
14676   int count = get_number (&args);
14677
14678   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14679 }
14680
14681 static void
14682 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14683 {
14684   struct disp_data disp = { disp_del, 1 };
14685
14686   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14687 }
14688
14689 static void
14690 enable_delete_command (char *args, int from_tty)
14691 {
14692   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14693 }
14694 \f
14695 static void
14696 set_breakpoint_cmd (char *args, int from_tty)
14697 {
14698 }
14699
14700 static void
14701 show_breakpoint_cmd (char *args, int from_tty)
14702 {
14703 }
14704
14705 /* Invalidate last known value of any hardware watchpoint if
14706    the memory which that value represents has been written to by
14707    GDB itself.  */
14708
14709 static void
14710 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14711                                       CORE_ADDR addr, ssize_t len,
14712                                       const bfd_byte *data)
14713 {
14714   struct breakpoint *bp;
14715
14716   ALL_BREAKPOINTS (bp)
14717     if (bp->enable_state == bp_enabled
14718         && bp->type == bp_hardware_watchpoint)
14719       {
14720         struct watchpoint *wp = (struct watchpoint *) bp;
14721
14722         if (wp->val_valid && wp->val)
14723           {
14724             struct bp_location *loc;
14725
14726             for (loc = bp->loc; loc != NULL; loc = loc->next)
14727               if (loc->loc_type == bp_loc_hardware_watchpoint
14728                   && loc->address + loc->length > addr
14729                   && addr + len > loc->address)
14730                 {
14731                   value_free (wp->val);
14732                   wp->val = NULL;
14733                   wp->val_valid = 0;
14734                 }
14735           }
14736       }
14737 }
14738
14739 /* Create and insert a raw software breakpoint at PC.  Return an
14740    identifier, which should be used to remove the breakpoint later.
14741    In general, places which call this should be using something on the
14742    breakpoint chain instead; this function should be eliminated
14743    someday.  */
14744
14745 void *
14746 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14747                                   struct address_space *aspace, CORE_ADDR pc)
14748 {
14749   struct bp_target_info *bp_tgt;
14750
14751   bp_tgt = XZALLOC (struct bp_target_info);
14752
14753   bp_tgt->placed_address_space = aspace;
14754   bp_tgt->placed_address = pc;
14755
14756   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14757     {
14758       /* Could not insert the breakpoint.  */
14759       xfree (bp_tgt);
14760       return NULL;
14761     }
14762
14763   return bp_tgt;
14764 }
14765
14766 /* Remove a breakpoint BP inserted by
14767    deprecated_insert_raw_breakpoint.  */
14768
14769 int
14770 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14771 {
14772   struct bp_target_info *bp_tgt = bp;
14773   int ret;
14774
14775   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14776   xfree (bp_tgt);
14777
14778   return ret;
14779 }
14780
14781 /* One (or perhaps two) breakpoints used for software single
14782    stepping.  */
14783
14784 static void *single_step_breakpoints[2];
14785 static struct gdbarch *single_step_gdbarch[2];
14786
14787 /* Create and insert a breakpoint for software single step.  */
14788
14789 void
14790 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14791                                struct address_space *aspace, 
14792                                CORE_ADDR next_pc)
14793 {
14794   void **bpt_p;
14795
14796   if (single_step_breakpoints[0] == NULL)
14797     {
14798       bpt_p = &single_step_breakpoints[0];
14799       single_step_gdbarch[0] = gdbarch;
14800     }
14801   else
14802     {
14803       gdb_assert (single_step_breakpoints[1] == NULL);
14804       bpt_p = &single_step_breakpoints[1];
14805       single_step_gdbarch[1] = gdbarch;
14806     }
14807
14808   /* NOTE drow/2006-04-11: A future improvement to this function would
14809      be to only create the breakpoints once, and actually put them on
14810      the breakpoint chain.  That would let us use set_raw_breakpoint.
14811      We could adjust the addresses each time they were needed.  Doing
14812      this requires corresponding changes elsewhere where single step
14813      breakpoints are handled, however.  So, for now, we use this.  */
14814
14815   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14816   if (*bpt_p == NULL)
14817     error (_("Could not insert single-step breakpoint at %s"),
14818              paddress (gdbarch, next_pc));
14819 }
14820
14821 /* Check if the breakpoints used for software single stepping
14822    were inserted or not.  */
14823
14824 int
14825 single_step_breakpoints_inserted (void)
14826 {
14827   return (single_step_breakpoints[0] != NULL
14828           || single_step_breakpoints[1] != NULL);
14829 }
14830
14831 /* Remove and delete any breakpoints used for software single step.  */
14832
14833 void
14834 remove_single_step_breakpoints (void)
14835 {
14836   gdb_assert (single_step_breakpoints[0] != NULL);
14837
14838   /* See insert_single_step_breakpoint for more about this deprecated
14839      call.  */
14840   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14841                                     single_step_breakpoints[0]);
14842   single_step_gdbarch[0] = NULL;
14843   single_step_breakpoints[0] = NULL;
14844
14845   if (single_step_breakpoints[1] != NULL)
14846     {
14847       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14848                                         single_step_breakpoints[1]);
14849       single_step_gdbarch[1] = NULL;
14850       single_step_breakpoints[1] = NULL;
14851     }
14852 }
14853
14854 /* Delete software single step breakpoints without removing them from
14855    the inferior.  This is intended to be used if the inferior's address
14856    space where they were inserted is already gone, e.g. after exit or
14857    exec.  */
14858
14859 void
14860 cancel_single_step_breakpoints (void)
14861 {
14862   int i;
14863
14864   for (i = 0; i < 2; i++)
14865     if (single_step_breakpoints[i])
14866       {
14867         xfree (single_step_breakpoints[i]);
14868         single_step_breakpoints[i] = NULL;
14869         single_step_gdbarch[i] = NULL;
14870       }
14871 }
14872
14873 /* Detach software single-step breakpoints from INFERIOR_PTID without
14874    removing them.  */
14875
14876 static void
14877 detach_single_step_breakpoints (void)
14878 {
14879   int i;
14880
14881   for (i = 0; i < 2; i++)
14882     if (single_step_breakpoints[i])
14883       target_remove_breakpoint (single_step_gdbarch[i],
14884                                 single_step_breakpoints[i]);
14885 }
14886
14887 /* Check whether a software single-step breakpoint is inserted at
14888    PC.  */
14889
14890 static int
14891 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14892                                         CORE_ADDR pc)
14893 {
14894   int i;
14895
14896   for (i = 0; i < 2; i++)
14897     {
14898       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14899       if (bp_tgt
14900           && breakpoint_address_match (bp_tgt->placed_address_space,
14901                                        bp_tgt->placed_address,
14902                                        aspace, pc))
14903         return 1;
14904     }
14905
14906   return 0;
14907 }
14908
14909 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14910    non-zero otherwise.  */
14911 static int
14912 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14913 {
14914   if (syscall_catchpoint_p (bp)
14915       && bp->enable_state != bp_disabled
14916       && bp->enable_state != bp_call_disabled)
14917     return 1;
14918   else
14919     return 0;
14920 }
14921
14922 int
14923 catch_syscall_enabled (void)
14924 {
14925   struct catch_syscall_inferior_data *inf_data
14926     = get_catch_syscall_inferior_data (current_inferior ());
14927
14928   return inf_data->total_syscalls_count != 0;
14929 }
14930
14931 int
14932 catching_syscall_number (int syscall_number)
14933 {
14934   struct breakpoint *bp;
14935
14936   ALL_BREAKPOINTS (bp)
14937     if (is_syscall_catchpoint_enabled (bp))
14938       {
14939         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14940
14941         if (c->syscalls_to_be_caught)
14942           {
14943             int i, iter;
14944             for (i = 0;
14945                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14946                  i++)
14947               if (syscall_number == iter)
14948                 return 1;
14949           }
14950         else
14951           return 1;
14952       }
14953
14954   return 0;
14955 }
14956
14957 /* Complete syscall names.  Used by "catch syscall".  */
14958 static VEC (char_ptr) *
14959 catch_syscall_completer (struct cmd_list_element *cmd,
14960                          const char *text, const char *word)
14961 {
14962   const char **list = get_syscall_names ();
14963   VEC (char_ptr) *retlist
14964     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
14965
14966   xfree (list);
14967   return retlist;
14968 }
14969
14970 /* Tracepoint-specific operations.  */
14971
14972 /* Set tracepoint count to NUM.  */
14973 static void
14974 set_tracepoint_count (int num)
14975 {
14976   tracepoint_count = num;
14977   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14978 }
14979
14980 static void
14981 trace_command (char *arg, int from_tty)
14982 {
14983   struct breakpoint_ops *ops;
14984   const char *arg_cp = arg;
14985
14986   if (arg && probe_linespec_to_ops (&arg_cp))
14987     ops = &tracepoint_probe_breakpoint_ops;
14988   else
14989     ops = &tracepoint_breakpoint_ops;
14990
14991   create_breakpoint (get_current_arch (),
14992                      arg,
14993                      NULL, 0, NULL, 1 /* parse arg */,
14994                      0 /* tempflag */,
14995                      bp_tracepoint /* type_wanted */,
14996                      0 /* Ignore count */,
14997                      pending_break_support,
14998                      ops,
14999                      from_tty,
15000                      1 /* enabled */,
15001                      0 /* internal */, 0);
15002 }
15003
15004 static void
15005 ftrace_command (char *arg, int from_tty)
15006 {
15007   create_breakpoint (get_current_arch (),
15008                      arg,
15009                      NULL, 0, NULL, 1 /* parse arg */,
15010                      0 /* tempflag */,
15011                      bp_fast_tracepoint /* type_wanted */,
15012                      0 /* Ignore count */,
15013                      pending_break_support,
15014                      &tracepoint_breakpoint_ops,
15015                      from_tty,
15016                      1 /* enabled */,
15017                      0 /* internal */, 0);
15018 }
15019
15020 /* strace command implementation.  Creates a static tracepoint.  */
15021
15022 static void
15023 strace_command (char *arg, int from_tty)
15024 {
15025   struct breakpoint_ops *ops;
15026
15027   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15028      or with a normal static tracepoint.  */
15029   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15030     ops = &strace_marker_breakpoint_ops;
15031   else
15032     ops = &tracepoint_breakpoint_ops;
15033
15034   create_breakpoint (get_current_arch (),
15035                      arg,
15036                      NULL, 0, NULL, 1 /* parse arg */,
15037                      0 /* tempflag */,
15038                      bp_static_tracepoint /* type_wanted */,
15039                      0 /* Ignore count */,
15040                      pending_break_support,
15041                      ops,
15042                      from_tty,
15043                      1 /* enabled */,
15044                      0 /* internal */, 0);
15045 }
15046
15047 /* Set up a fake reader function that gets command lines from a linked
15048    list that was acquired during tracepoint uploading.  */
15049
15050 static struct uploaded_tp *this_utp;
15051 static int next_cmd;
15052
15053 static char *
15054 read_uploaded_action (void)
15055 {
15056   char *rslt;
15057
15058   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15059
15060   next_cmd++;
15061
15062   return rslt;
15063 }
15064
15065 /* Given information about a tracepoint as recorded on a target (which
15066    can be either a live system or a trace file), attempt to create an
15067    equivalent GDB tracepoint.  This is not a reliable process, since
15068    the target does not necessarily have all the information used when
15069    the tracepoint was originally defined.  */
15070   
15071 struct tracepoint *
15072 create_tracepoint_from_upload (struct uploaded_tp *utp)
15073 {
15074   char *addr_str, small_buf[100];
15075   struct tracepoint *tp;
15076
15077   if (utp->at_string)
15078     addr_str = utp->at_string;
15079   else
15080     {
15081       /* In the absence of a source location, fall back to raw
15082          address.  Since there is no way to confirm that the address
15083          means the same thing as when the trace was started, warn the
15084          user.  */
15085       warning (_("Uploaded tracepoint %d has no "
15086                  "source location, using raw address"),
15087                utp->number);
15088       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15089       addr_str = small_buf;
15090     }
15091
15092   /* There's not much we can do with a sequence of bytecodes.  */
15093   if (utp->cond && !utp->cond_string)
15094     warning (_("Uploaded tracepoint %d condition "
15095                "has no source form, ignoring it"),
15096              utp->number);
15097
15098   if (!create_breakpoint (get_current_arch (),
15099                           addr_str,
15100                           utp->cond_string, -1, NULL,
15101                           0 /* parse cond/thread */,
15102                           0 /* tempflag */,
15103                           utp->type /* type_wanted */,
15104                           0 /* Ignore count */,
15105                           pending_break_support,
15106                           &tracepoint_breakpoint_ops,
15107                           0 /* from_tty */,
15108                           utp->enabled /* enabled */,
15109                           0 /* internal */,
15110                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15111     return NULL;
15112
15113   /* Get the tracepoint we just created.  */
15114   tp = get_tracepoint (tracepoint_count);
15115   gdb_assert (tp != NULL);
15116
15117   if (utp->pass > 0)
15118     {
15119       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15120                  tp->base.number);
15121
15122       trace_pass_command (small_buf, 0);
15123     }
15124
15125   /* If we have uploaded versions of the original commands, set up a
15126      special-purpose "reader" function and call the usual command line
15127      reader, then pass the result to the breakpoint command-setting
15128      function.  */
15129   if (!VEC_empty (char_ptr, utp->cmd_strings))
15130     {
15131       struct command_line *cmd_list;
15132
15133       this_utp = utp;
15134       next_cmd = 0;
15135
15136       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15137
15138       breakpoint_set_commands (&tp->base, cmd_list);
15139     }
15140   else if (!VEC_empty (char_ptr, utp->actions)
15141            || !VEC_empty (char_ptr, utp->step_actions))
15142     warning (_("Uploaded tracepoint %d actions "
15143                "have no source form, ignoring them"),
15144              utp->number);
15145
15146   /* Copy any status information that might be available.  */
15147   tp->base.hit_count = utp->hit_count;
15148   tp->traceframe_usage = utp->traceframe_usage;
15149
15150   return tp;
15151 }
15152   
15153 /* Print information on tracepoint number TPNUM_EXP, or all if
15154    omitted.  */
15155
15156 static void
15157 tracepoints_info (char *args, int from_tty)
15158 {
15159   struct ui_out *uiout = current_uiout;
15160   int num_printed;
15161
15162   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15163
15164   if (num_printed == 0)
15165     {
15166       if (args == NULL || *args == '\0')
15167         ui_out_message (uiout, 0, "No tracepoints.\n");
15168       else
15169         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15170     }
15171
15172   default_collect_info ();
15173 }
15174
15175 /* The 'enable trace' command enables tracepoints.
15176    Not supported by all targets.  */
15177 static void
15178 enable_trace_command (char *args, int from_tty)
15179 {
15180   enable_command (args, from_tty);
15181 }
15182
15183 /* The 'disable trace' command disables tracepoints.
15184    Not supported by all targets.  */
15185 static void
15186 disable_trace_command (char *args, int from_tty)
15187 {
15188   disable_command (args, from_tty);
15189 }
15190
15191 /* Remove a tracepoint (or all if no argument).  */
15192 static void
15193 delete_trace_command (char *arg, int from_tty)
15194 {
15195   struct breakpoint *b, *b_tmp;
15196
15197   dont_repeat ();
15198
15199   if (arg == 0)
15200     {
15201       int breaks_to_delete = 0;
15202
15203       /* Delete all breakpoints if no argument.
15204          Do not delete internal or call-dummy breakpoints, these
15205          have to be deleted with an explicit breakpoint number 
15206          argument.  */
15207       ALL_TRACEPOINTS (b)
15208         if (is_tracepoint (b) && user_breakpoint_p (b))
15209           {
15210             breaks_to_delete = 1;
15211             break;
15212           }
15213
15214       /* Ask user only if there are some breakpoints to delete.  */
15215       if (!from_tty
15216           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15217         {
15218           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15219             if (is_tracepoint (b) && user_breakpoint_p (b))
15220               delete_breakpoint (b);
15221         }
15222     }
15223   else
15224     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15225 }
15226
15227 /* Helper function for trace_pass_command.  */
15228
15229 static void
15230 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15231 {
15232   tp->pass_count = count;
15233   observer_notify_breakpoint_modified (&tp->base);
15234   if (from_tty)
15235     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15236                      tp->base.number, count);
15237 }
15238
15239 /* Set passcount for tracepoint.
15240
15241    First command argument is passcount, second is tracepoint number.
15242    If tracepoint number omitted, apply to most recently defined.
15243    Also accepts special argument "all".  */
15244
15245 static void
15246 trace_pass_command (char *args, int from_tty)
15247 {
15248   struct tracepoint *t1;
15249   unsigned int count;
15250
15251   if (args == 0 || *args == 0)
15252     error (_("passcount command requires an "
15253              "argument (count + optional TP num)"));
15254
15255   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15256
15257   args = skip_spaces (args);
15258   if (*args && strncasecmp (args, "all", 3) == 0)
15259     {
15260       struct breakpoint *b;
15261
15262       args += 3;                        /* Skip special argument "all".  */
15263       if (*args)
15264         error (_("Junk at end of arguments."));
15265
15266       ALL_TRACEPOINTS (b)
15267       {
15268         t1 = (struct tracepoint *) b;
15269         trace_pass_set_count (t1, count, from_tty);
15270       }
15271     }
15272   else if (*args == '\0')
15273     {
15274       t1 = get_tracepoint_by_number (&args, NULL, 1);
15275       if (t1)
15276         trace_pass_set_count (t1, count, from_tty);
15277     }
15278   else
15279     {
15280       struct get_number_or_range_state state;
15281
15282       init_number_or_range (&state, args);
15283       while (!state.finished)
15284         {
15285           t1 = get_tracepoint_by_number (&args, &state, 1);
15286           if (t1)
15287             trace_pass_set_count (t1, count, from_tty);
15288         }
15289     }
15290 }
15291
15292 struct tracepoint *
15293 get_tracepoint (int num)
15294 {
15295   struct breakpoint *t;
15296
15297   ALL_TRACEPOINTS (t)
15298     if (t->number == num)
15299       return (struct tracepoint *) t;
15300
15301   return NULL;
15302 }
15303
15304 /* Find the tracepoint with the given target-side number (which may be
15305    different from the tracepoint number after disconnecting and
15306    reconnecting).  */
15307
15308 struct tracepoint *
15309 get_tracepoint_by_number_on_target (int num)
15310 {
15311   struct breakpoint *b;
15312
15313   ALL_TRACEPOINTS (b)
15314     {
15315       struct tracepoint *t = (struct tracepoint *) b;
15316
15317       if (t->number_on_target == num)
15318         return t;
15319     }
15320
15321   return NULL;
15322 }
15323
15324 /* Utility: parse a tracepoint number and look it up in the list.
15325    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15326    If OPTIONAL_P is true, then if the argument is missing, the most
15327    recent tracepoint (tracepoint_count) is returned.  */
15328 struct tracepoint *
15329 get_tracepoint_by_number (char **arg,
15330                           struct get_number_or_range_state *state,
15331                           int optional_p)
15332 {
15333   struct breakpoint *t;
15334   int tpnum;
15335   char *instring = arg == NULL ? NULL : *arg;
15336
15337   if (state)
15338     {
15339       gdb_assert (!state->finished);
15340       tpnum = get_number_or_range (state);
15341     }
15342   else if (arg == NULL || *arg == NULL || ! **arg)
15343     {
15344       if (optional_p)
15345         tpnum = tracepoint_count;
15346       else
15347         error_no_arg (_("tracepoint number"));
15348     }
15349   else
15350     tpnum = get_number (arg);
15351
15352   if (tpnum <= 0)
15353     {
15354       if (instring && *instring)
15355         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15356                          instring);
15357       else
15358         printf_filtered (_("Tracepoint argument missing "
15359                            "and no previous tracepoint\n"));
15360       return NULL;
15361     }
15362
15363   ALL_TRACEPOINTS (t)
15364     if (t->number == tpnum)
15365     {
15366       return (struct tracepoint *) t;
15367     }
15368
15369   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15370   return NULL;
15371 }
15372
15373 void
15374 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15375 {
15376   if (b->thread != -1)
15377     fprintf_unfiltered (fp, " thread %d", b->thread);
15378
15379   if (b->task != 0)
15380     fprintf_unfiltered (fp, " task %d", b->task);
15381
15382   fprintf_unfiltered (fp, "\n");
15383 }
15384
15385 /* Save information on user settable breakpoints (watchpoints, etc) to
15386    a new script file named FILENAME.  If FILTER is non-NULL, call it
15387    on each breakpoint and only include the ones for which it returns
15388    non-zero.  */
15389
15390 static void
15391 save_breakpoints (char *filename, int from_tty,
15392                   int (*filter) (const struct breakpoint *))
15393 {
15394   struct breakpoint *tp;
15395   int any = 0;
15396   char *pathname;
15397   struct cleanup *cleanup;
15398   struct ui_file *fp;
15399   int extra_trace_bits = 0;
15400
15401   if (filename == 0 || *filename == 0)
15402     error (_("Argument required (file name in which to save)"));
15403
15404   /* See if we have anything to save.  */
15405   ALL_BREAKPOINTS (tp)
15406   {
15407     /* Skip internal and momentary breakpoints.  */
15408     if (!user_breakpoint_p (tp))
15409       continue;
15410
15411     /* If we have a filter, only save the breakpoints it accepts.  */
15412     if (filter && !filter (tp))
15413       continue;
15414
15415     any = 1;
15416
15417     if (is_tracepoint (tp))
15418       {
15419         extra_trace_bits = 1;
15420
15421         /* We can stop searching.  */
15422         break;
15423       }
15424   }
15425
15426   if (!any)
15427     {
15428       warning (_("Nothing to save."));
15429       return;
15430     }
15431
15432   pathname = tilde_expand (filename);
15433   cleanup = make_cleanup (xfree, pathname);
15434   fp = gdb_fopen (pathname, "w");
15435   if (!fp)
15436     error (_("Unable to open file '%s' for saving (%s)"),
15437            filename, safe_strerror (errno));
15438   make_cleanup_ui_file_delete (fp);
15439
15440   if (extra_trace_bits)
15441     save_trace_state_variables (fp);
15442
15443   ALL_BREAKPOINTS (tp)
15444   {
15445     /* Skip internal and momentary breakpoints.  */
15446     if (!user_breakpoint_p (tp))
15447       continue;
15448
15449     /* If we have a filter, only save the breakpoints it accepts.  */
15450     if (filter && !filter (tp))
15451       continue;
15452
15453     tp->ops->print_recreate (tp, fp);
15454
15455     /* Note, we can't rely on tp->number for anything, as we can't
15456        assume the recreated breakpoint numbers will match.  Use $bpnum
15457        instead.  */
15458
15459     if (tp->cond_string)
15460       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15461
15462     if (tp->ignore_count)
15463       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15464
15465     if (tp->type != bp_dprintf && tp->commands)
15466       {
15467         volatile struct gdb_exception ex;       
15468
15469         fprintf_unfiltered (fp, "  commands\n");
15470         
15471         ui_out_redirect (current_uiout, fp);
15472         TRY_CATCH (ex, RETURN_MASK_ALL)
15473           {
15474             print_command_lines (current_uiout, tp->commands->commands, 2);
15475           }
15476         ui_out_redirect (current_uiout, NULL);
15477
15478         if (ex.reason < 0)
15479           throw_exception (ex);
15480
15481         fprintf_unfiltered (fp, "  end\n");
15482       }
15483
15484     if (tp->enable_state == bp_disabled)
15485       fprintf_unfiltered (fp, "disable\n");
15486
15487     /* If this is a multi-location breakpoint, check if the locations
15488        should be individually disabled.  Watchpoint locations are
15489        special, and not user visible.  */
15490     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15491       {
15492         struct bp_location *loc;
15493         int n = 1;
15494
15495         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15496           if (!loc->enabled)
15497             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15498       }
15499   }
15500
15501   if (extra_trace_bits && *default_collect)
15502     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15503
15504   do_cleanups (cleanup);
15505   if (from_tty)
15506     printf_filtered (_("Saved to file '%s'.\n"), filename);
15507 }
15508
15509 /* The `save breakpoints' command.  */
15510
15511 static void
15512 save_breakpoints_command (char *args, int from_tty)
15513 {
15514   save_breakpoints (args, from_tty, NULL);
15515 }
15516
15517 /* The `save tracepoints' command.  */
15518
15519 static void
15520 save_tracepoints_command (char *args, int from_tty)
15521 {
15522   save_breakpoints (args, from_tty, is_tracepoint);
15523 }
15524
15525 /* Create a vector of all tracepoints.  */
15526
15527 VEC(breakpoint_p) *
15528 all_tracepoints (void)
15529 {
15530   VEC(breakpoint_p) *tp_vec = 0;
15531   struct breakpoint *tp;
15532
15533   ALL_TRACEPOINTS (tp)
15534   {
15535     VEC_safe_push (breakpoint_p, tp_vec, tp);
15536   }
15537
15538   return tp_vec;
15539 }
15540
15541 \f
15542 /* This help string is used for the break, hbreak, tbreak and thbreak
15543    commands.  It is defined as a macro to prevent duplication.
15544    COMMAND should be a string constant containing the name of the
15545    command.  */
15546 #define BREAK_ARGS_HELP(command) \
15547 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15548 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15549 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15550 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15551 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15552 If a line number is specified, break at start of code for that line.\n\
15553 If a function is specified, break at start of code for that function.\n\
15554 If an address is specified, break at that exact address.\n\
15555 With no LOCATION, uses current execution address of the selected\n\
15556 stack frame.  This is useful for breaking on return to a stack frame.\n\
15557 \n\
15558 THREADNUM is the number from \"info threads\".\n\
15559 CONDITION is a boolean expression.\n\
15560 \n\
15561 Multiple breakpoints at one place are permitted, and useful if their\n\
15562 conditions are different.\n\
15563 \n\
15564 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15565
15566 /* List of subcommands for "catch".  */
15567 static struct cmd_list_element *catch_cmdlist;
15568
15569 /* List of subcommands for "tcatch".  */
15570 static struct cmd_list_element *tcatch_cmdlist;
15571
15572 void
15573 add_catch_command (char *name, char *docstring,
15574                    void (*sfunc) (char *args, int from_tty,
15575                                   struct cmd_list_element *command),
15576                    completer_ftype *completer,
15577                    void *user_data_catch,
15578                    void *user_data_tcatch)
15579 {
15580   struct cmd_list_element *command;
15581
15582   command = add_cmd (name, class_breakpoint, NULL, docstring,
15583                      &catch_cmdlist);
15584   set_cmd_sfunc (command, sfunc);
15585   set_cmd_context (command, user_data_catch);
15586   set_cmd_completer (command, completer);
15587
15588   command = add_cmd (name, class_breakpoint, NULL, docstring,
15589                      &tcatch_cmdlist);
15590   set_cmd_sfunc (command, sfunc);
15591   set_cmd_context (command, user_data_tcatch);
15592   set_cmd_completer (command, completer);
15593 }
15594
15595 static void
15596 clear_syscall_counts (struct inferior *inf)
15597 {
15598   struct catch_syscall_inferior_data *inf_data
15599     = get_catch_syscall_inferior_data (inf);
15600
15601   inf_data->total_syscalls_count = 0;
15602   inf_data->any_syscall_count = 0;
15603   VEC_free (int, inf_data->syscalls_counts);
15604 }
15605
15606 static void
15607 save_command (char *arg, int from_tty)
15608 {
15609   printf_unfiltered (_("\"save\" must be followed by "
15610                        "the name of a save subcommand.\n"));
15611   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15612 }
15613
15614 struct breakpoint *
15615 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15616                           void *data)
15617 {
15618   struct breakpoint *b, *b_tmp;
15619
15620   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15621     {
15622       if ((*callback) (b, data))
15623         return b;
15624     }
15625
15626   return NULL;
15627 }
15628
15629 /* Zero if any of the breakpoint's locations could be a location where
15630    functions have been inlined, nonzero otherwise.  */
15631
15632 static int
15633 is_non_inline_function (struct breakpoint *b)
15634 {
15635   /* The shared library event breakpoint is set on the address of a
15636      non-inline function.  */
15637   if (b->type == bp_shlib_event)
15638     return 1;
15639
15640   return 0;
15641 }
15642
15643 /* Nonzero if the specified PC cannot be a location where functions
15644    have been inlined.  */
15645
15646 int
15647 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15648                            const struct target_waitstatus *ws)
15649 {
15650   struct breakpoint *b;
15651   struct bp_location *bl;
15652
15653   ALL_BREAKPOINTS (b)
15654     {
15655       if (!is_non_inline_function (b))
15656         continue;
15657
15658       for (bl = b->loc; bl != NULL; bl = bl->next)
15659         {
15660           if (!bl->shlib_disabled
15661               && bpstat_check_location (bl, aspace, pc, ws))
15662             return 1;
15663         }
15664     }
15665
15666   return 0;
15667 }
15668
15669 /* Remove any references to OBJFILE which is going to be freed.  */
15670
15671 void
15672 breakpoint_free_objfile (struct objfile *objfile)
15673 {
15674   struct bp_location **locp, *loc;
15675
15676   ALL_BP_LOCATIONS (loc, locp)
15677     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15678       loc->symtab = NULL;
15679 }
15680
15681 void
15682 initialize_breakpoint_ops (void)
15683 {
15684   static int initialized = 0;
15685
15686   struct breakpoint_ops *ops;
15687
15688   if (initialized)
15689     return;
15690   initialized = 1;
15691
15692   /* The breakpoint_ops structure to be inherit by all kinds of
15693      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15694      internal and momentary breakpoints, etc.).  */
15695   ops = &bkpt_base_breakpoint_ops;
15696   *ops = base_breakpoint_ops;
15697   ops->re_set = bkpt_re_set;
15698   ops->insert_location = bkpt_insert_location;
15699   ops->remove_location = bkpt_remove_location;
15700   ops->breakpoint_hit = bkpt_breakpoint_hit;
15701   ops->create_sals_from_address = bkpt_create_sals_from_address;
15702   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15703   ops->decode_linespec = bkpt_decode_linespec;
15704
15705   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15706   ops = &bkpt_breakpoint_ops;
15707   *ops = bkpt_base_breakpoint_ops;
15708   ops->re_set = bkpt_re_set;
15709   ops->resources_needed = bkpt_resources_needed;
15710   ops->print_it = bkpt_print_it;
15711   ops->print_mention = bkpt_print_mention;
15712   ops->print_recreate = bkpt_print_recreate;
15713
15714   /* Ranged breakpoints.  */
15715   ops = &ranged_breakpoint_ops;
15716   *ops = bkpt_breakpoint_ops;
15717   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15718   ops->resources_needed = resources_needed_ranged_breakpoint;
15719   ops->print_it = print_it_ranged_breakpoint;
15720   ops->print_one = print_one_ranged_breakpoint;
15721   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15722   ops->print_mention = print_mention_ranged_breakpoint;
15723   ops->print_recreate = print_recreate_ranged_breakpoint;
15724
15725   /* Internal breakpoints.  */
15726   ops = &internal_breakpoint_ops;
15727   *ops = bkpt_base_breakpoint_ops;
15728   ops->re_set = internal_bkpt_re_set;
15729   ops->check_status = internal_bkpt_check_status;
15730   ops->print_it = internal_bkpt_print_it;
15731   ops->print_mention = internal_bkpt_print_mention;
15732
15733   /* Momentary breakpoints.  */
15734   ops = &momentary_breakpoint_ops;
15735   *ops = bkpt_base_breakpoint_ops;
15736   ops->re_set = momentary_bkpt_re_set;
15737   ops->check_status = momentary_bkpt_check_status;
15738   ops->print_it = momentary_bkpt_print_it;
15739   ops->print_mention = momentary_bkpt_print_mention;
15740
15741   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15742   ops = &longjmp_breakpoint_ops;
15743   *ops = momentary_breakpoint_ops;
15744   ops->dtor = longjmp_bkpt_dtor;
15745
15746   /* Probe breakpoints.  */
15747   ops = &bkpt_probe_breakpoint_ops;
15748   *ops = bkpt_breakpoint_ops;
15749   ops->insert_location = bkpt_probe_insert_location;
15750   ops->remove_location = bkpt_probe_remove_location;
15751   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15752   ops->decode_linespec = bkpt_probe_decode_linespec;
15753
15754   /* Watchpoints.  */
15755   ops = &watchpoint_breakpoint_ops;
15756   *ops = base_breakpoint_ops;
15757   ops->dtor = dtor_watchpoint;
15758   ops->re_set = re_set_watchpoint;
15759   ops->insert_location = insert_watchpoint;
15760   ops->remove_location = remove_watchpoint;
15761   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15762   ops->check_status = check_status_watchpoint;
15763   ops->resources_needed = resources_needed_watchpoint;
15764   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15765   ops->print_it = print_it_watchpoint;
15766   ops->print_mention = print_mention_watchpoint;
15767   ops->print_recreate = print_recreate_watchpoint;
15768   ops->explains_signal = explains_signal_watchpoint;
15769
15770   /* Masked watchpoints.  */
15771   ops = &masked_watchpoint_breakpoint_ops;
15772   *ops = watchpoint_breakpoint_ops;
15773   ops->insert_location = insert_masked_watchpoint;
15774   ops->remove_location = remove_masked_watchpoint;
15775   ops->resources_needed = resources_needed_masked_watchpoint;
15776   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15777   ops->print_it = print_it_masked_watchpoint;
15778   ops->print_one_detail = print_one_detail_masked_watchpoint;
15779   ops->print_mention = print_mention_masked_watchpoint;
15780   ops->print_recreate = print_recreate_masked_watchpoint;
15781
15782   /* Tracepoints.  */
15783   ops = &tracepoint_breakpoint_ops;
15784   *ops = base_breakpoint_ops;
15785   ops->re_set = tracepoint_re_set;
15786   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15787   ops->print_one_detail = tracepoint_print_one_detail;
15788   ops->print_mention = tracepoint_print_mention;
15789   ops->print_recreate = tracepoint_print_recreate;
15790   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15791   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15792   ops->decode_linespec = tracepoint_decode_linespec;
15793
15794   /* Probe tracepoints.  */
15795   ops = &tracepoint_probe_breakpoint_ops;
15796   *ops = tracepoint_breakpoint_ops;
15797   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15798   ops->decode_linespec = tracepoint_probe_decode_linespec;
15799
15800   /* Static tracepoints with marker (`-m').  */
15801   ops = &strace_marker_breakpoint_ops;
15802   *ops = tracepoint_breakpoint_ops;
15803   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15804   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15805   ops->decode_linespec = strace_marker_decode_linespec;
15806
15807   /* Fork catchpoints.  */
15808   ops = &catch_fork_breakpoint_ops;
15809   *ops = base_breakpoint_ops;
15810   ops->insert_location = insert_catch_fork;
15811   ops->remove_location = remove_catch_fork;
15812   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15813   ops->print_it = print_it_catch_fork;
15814   ops->print_one = print_one_catch_fork;
15815   ops->print_mention = print_mention_catch_fork;
15816   ops->print_recreate = print_recreate_catch_fork;
15817
15818   /* Vfork catchpoints.  */
15819   ops = &catch_vfork_breakpoint_ops;
15820   *ops = base_breakpoint_ops;
15821   ops->insert_location = insert_catch_vfork;
15822   ops->remove_location = remove_catch_vfork;
15823   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15824   ops->print_it = print_it_catch_vfork;
15825   ops->print_one = print_one_catch_vfork;
15826   ops->print_mention = print_mention_catch_vfork;
15827   ops->print_recreate = print_recreate_catch_vfork;
15828
15829   /* Exec catchpoints.  */
15830   ops = &catch_exec_breakpoint_ops;
15831   *ops = base_breakpoint_ops;
15832   ops->dtor = dtor_catch_exec;
15833   ops->insert_location = insert_catch_exec;
15834   ops->remove_location = remove_catch_exec;
15835   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15836   ops->print_it = print_it_catch_exec;
15837   ops->print_one = print_one_catch_exec;
15838   ops->print_mention = print_mention_catch_exec;
15839   ops->print_recreate = print_recreate_catch_exec;
15840
15841   /* Syscall catchpoints.  */
15842   ops = &catch_syscall_breakpoint_ops;
15843   *ops = base_breakpoint_ops;
15844   ops->dtor = dtor_catch_syscall;
15845   ops->insert_location = insert_catch_syscall;
15846   ops->remove_location = remove_catch_syscall;
15847   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15848   ops->print_it = print_it_catch_syscall;
15849   ops->print_one = print_one_catch_syscall;
15850   ops->print_mention = print_mention_catch_syscall;
15851   ops->print_recreate = print_recreate_catch_syscall;
15852
15853   /* Solib-related catchpoints.  */
15854   ops = &catch_solib_breakpoint_ops;
15855   *ops = base_breakpoint_ops;
15856   ops->dtor = dtor_catch_solib;
15857   ops->insert_location = insert_catch_solib;
15858   ops->remove_location = remove_catch_solib;
15859   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15860   ops->check_status = check_status_catch_solib;
15861   ops->print_it = print_it_catch_solib;
15862   ops->print_one = print_one_catch_solib;
15863   ops->print_mention = print_mention_catch_solib;
15864   ops->print_recreate = print_recreate_catch_solib;
15865
15866   ops = &dprintf_breakpoint_ops;
15867   *ops = bkpt_base_breakpoint_ops;
15868   ops->re_set = dprintf_re_set;
15869   ops->resources_needed = bkpt_resources_needed;
15870   ops->print_it = bkpt_print_it;
15871   ops->print_mention = bkpt_print_mention;
15872   ops->print_recreate = dprintf_print_recreate;
15873 }
15874
15875 /* Chain containing all defined "enable breakpoint" subcommands.  */
15876
15877 static struct cmd_list_element *enablebreaklist = NULL;
15878
15879 void
15880 _initialize_breakpoint (void)
15881 {
15882   struct cmd_list_element *c;
15883
15884   initialize_breakpoint_ops ();
15885
15886   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15887   observer_attach_inferior_exit (clear_syscall_counts);
15888   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15889
15890   breakpoint_objfile_key
15891     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15892
15893   catch_syscall_inferior_data
15894     = register_inferior_data_with_cleanup (NULL,
15895                                            catch_syscall_inferior_data_cleanup);
15896
15897   breakpoint_chain = 0;
15898   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15899      before a breakpoint is set.  */
15900   breakpoint_count = 0;
15901
15902   tracepoint_count = 0;
15903
15904   add_com ("ignore", class_breakpoint, ignore_command, _("\
15905 Set ignore-count of breakpoint number N to COUNT.\n\
15906 Usage is `ignore N COUNT'."));
15907   if (xdb_commands)
15908     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15909
15910   add_com ("commands", class_breakpoint, commands_command, _("\
15911 Set commands to be executed when a breakpoint is hit.\n\
15912 Give breakpoint number as argument after \"commands\".\n\
15913 With no argument, the targeted breakpoint is the last one set.\n\
15914 The commands themselves follow starting on the next line.\n\
15915 Type a line containing \"end\" to indicate the end of them.\n\
15916 Give \"silent\" as the first line to make the breakpoint silent;\n\
15917 then no output is printed when it is hit, except what the commands print."));
15918
15919   c = add_com ("condition", class_breakpoint, condition_command, _("\
15920 Specify breakpoint number N to break only if COND is true.\n\
15921 Usage is `condition N COND', where N is an integer and COND is an\n\
15922 expression to be evaluated whenever breakpoint N is reached."));
15923   set_cmd_completer (c, condition_completer);
15924
15925   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15926 Set a temporary breakpoint.\n\
15927 Like \"break\" except the breakpoint is only temporary,\n\
15928 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15929 by using \"enable delete\" on the breakpoint number.\n\
15930 \n"
15931 BREAK_ARGS_HELP ("tbreak")));
15932   set_cmd_completer (c, location_completer);
15933
15934   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15935 Set a hardware assisted breakpoint.\n\
15936 Like \"break\" except the breakpoint requires hardware support,\n\
15937 some target hardware may not have this support.\n\
15938 \n"
15939 BREAK_ARGS_HELP ("hbreak")));
15940   set_cmd_completer (c, location_completer);
15941
15942   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15943 Set a temporary hardware assisted breakpoint.\n\
15944 Like \"hbreak\" except the breakpoint is only temporary,\n\
15945 so it will be deleted when hit.\n\
15946 \n"
15947 BREAK_ARGS_HELP ("thbreak")));
15948   set_cmd_completer (c, location_completer);
15949
15950   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15951 Enable some breakpoints.\n\
15952 Give breakpoint numbers (separated by spaces) as arguments.\n\
15953 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15954 This is used to cancel the effect of the \"disable\" command.\n\
15955 With a subcommand you can enable temporarily."),
15956                   &enablelist, "enable ", 1, &cmdlist);
15957   if (xdb_commands)
15958     add_com ("ab", class_breakpoint, enable_command, _("\
15959 Enable some breakpoints.\n\
15960 Give breakpoint numbers (separated by spaces) as arguments.\n\
15961 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15962 This is used to cancel the effect of the \"disable\" command.\n\
15963 With a subcommand you can enable temporarily."));
15964
15965   add_com_alias ("en", "enable", class_breakpoint, 1);
15966
15967   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15968 Enable some breakpoints.\n\
15969 Give breakpoint numbers (separated by spaces) as arguments.\n\
15970 This is used to cancel the effect of the \"disable\" command.\n\
15971 May be abbreviated to simply \"enable\".\n"),
15972                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15973
15974   add_cmd ("once", no_class, enable_once_command, _("\
15975 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15976 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15977            &enablebreaklist);
15978
15979   add_cmd ("delete", no_class, enable_delete_command, _("\
15980 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15981 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15982            &enablebreaklist);
15983
15984   add_cmd ("count", no_class, enable_count_command, _("\
15985 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15986 If a breakpoint is hit while enabled in this fashion,\n\
15987 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15988            &enablebreaklist);
15989
15990   add_cmd ("delete", no_class, enable_delete_command, _("\
15991 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15992 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15993            &enablelist);
15994
15995   add_cmd ("once", no_class, enable_once_command, _("\
15996 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15997 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15998            &enablelist);
15999
16000   add_cmd ("count", no_class, enable_count_command, _("\
16001 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16002 If a breakpoint is hit while enabled in this fashion,\n\
16003 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16004            &enablelist);
16005
16006   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16007 Disable some breakpoints.\n\
16008 Arguments are breakpoint numbers with spaces in between.\n\
16009 To disable all breakpoints, give no argument.\n\
16010 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16011                   &disablelist, "disable ", 1, &cmdlist);
16012   add_com_alias ("dis", "disable", class_breakpoint, 1);
16013   add_com_alias ("disa", "disable", class_breakpoint, 1);
16014   if (xdb_commands)
16015     add_com ("sb", class_breakpoint, disable_command, _("\
16016 Disable some breakpoints.\n\
16017 Arguments are breakpoint numbers with spaces in between.\n\
16018 To disable all breakpoints, give no argument.\n\
16019 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16020
16021   add_cmd ("breakpoints", class_alias, disable_command, _("\
16022 Disable some breakpoints.\n\
16023 Arguments are breakpoint numbers with spaces in between.\n\
16024 To disable all breakpoints, give no argument.\n\
16025 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16026 This command may be abbreviated \"disable\"."),
16027            &disablelist);
16028
16029   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16030 Delete some breakpoints or auto-display expressions.\n\
16031 Arguments are breakpoint numbers with spaces in between.\n\
16032 To delete all breakpoints, give no argument.\n\
16033 \n\
16034 Also a prefix command for deletion of other GDB objects.\n\
16035 The \"unset\" command is also an alias for \"delete\"."),
16036                   &deletelist, "delete ", 1, &cmdlist);
16037   add_com_alias ("d", "delete", class_breakpoint, 1);
16038   add_com_alias ("del", "delete", class_breakpoint, 1);
16039   if (xdb_commands)
16040     add_com ("db", class_breakpoint, delete_command, _("\
16041 Delete some breakpoints.\n\
16042 Arguments are breakpoint numbers with spaces in between.\n\
16043 To delete all breakpoints, give no argument.\n"));
16044
16045   add_cmd ("breakpoints", class_alias, delete_command, _("\
16046 Delete some breakpoints or auto-display expressions.\n\
16047 Arguments are breakpoint numbers with spaces in between.\n\
16048 To delete all breakpoints, give no argument.\n\
16049 This command may be abbreviated \"delete\"."),
16050            &deletelist);
16051
16052   add_com ("clear", class_breakpoint, clear_command, _("\
16053 Clear breakpoint at specified line or function.\n\
16054 Argument may be line number, function name, or \"*\" and an address.\n\
16055 If line number is specified, all breakpoints in that line are cleared.\n\
16056 If function is specified, breakpoints at beginning of function are cleared.\n\
16057 If an address is specified, breakpoints at that address are cleared.\n\
16058 \n\
16059 With no argument, clears all breakpoints in the line that the selected frame\n\
16060 is executing in.\n\
16061 \n\
16062 See also the \"delete\" command which clears breakpoints by number."));
16063   add_com_alias ("cl", "clear", class_breakpoint, 1);
16064
16065   c = add_com ("break", class_breakpoint, break_command, _("\
16066 Set breakpoint at specified line or function.\n"
16067 BREAK_ARGS_HELP ("break")));
16068   set_cmd_completer (c, location_completer);
16069
16070   add_com_alias ("b", "break", class_run, 1);
16071   add_com_alias ("br", "break", class_run, 1);
16072   add_com_alias ("bre", "break", class_run, 1);
16073   add_com_alias ("brea", "break", class_run, 1);
16074
16075   if (xdb_commands)
16076    add_com_alias ("ba", "break", class_breakpoint, 1);
16077
16078   if (dbx_commands)
16079     {
16080       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16081 Break in function/address or break at a line in the current file."),
16082                              &stoplist, "stop ", 1, &cmdlist);
16083       add_cmd ("in", class_breakpoint, stopin_command,
16084                _("Break in function or address."), &stoplist);
16085       add_cmd ("at", class_breakpoint, stopat_command,
16086                _("Break at a line in the current file."), &stoplist);
16087       add_com ("status", class_info, breakpoints_info, _("\
16088 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16089 The \"Type\" column indicates one of:\n\
16090 \tbreakpoint     - normal breakpoint\n\
16091 \twatchpoint     - watchpoint\n\
16092 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16093 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16094 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16095 address and file/line number respectively.\n\
16096 \n\
16097 Convenience variable \"$_\" and default examine address for \"x\"\n\
16098 are set to the address of the last breakpoint listed unless the command\n\
16099 is prefixed with \"server \".\n\n\
16100 Convenience variable \"$bpnum\" contains the number of the last\n\
16101 breakpoint set."));
16102     }
16103
16104   add_info ("breakpoints", breakpoints_info, _("\
16105 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16106 The \"Type\" column indicates one of:\n\
16107 \tbreakpoint     - normal breakpoint\n\
16108 \twatchpoint     - watchpoint\n\
16109 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16110 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16111 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16112 address and file/line number respectively.\n\
16113 \n\
16114 Convenience variable \"$_\" and default examine address for \"x\"\n\
16115 are set to the address of the last breakpoint listed unless the command\n\
16116 is prefixed with \"server \".\n\n\
16117 Convenience variable \"$bpnum\" contains the number of the last\n\
16118 breakpoint set."));
16119
16120   add_info_alias ("b", "breakpoints", 1);
16121
16122   if (xdb_commands)
16123     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16124 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16125 The \"Type\" column indicates one of:\n\
16126 \tbreakpoint     - normal breakpoint\n\
16127 \twatchpoint     - watchpoint\n\
16128 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16129 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16130 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16131 address and file/line number respectively.\n\
16132 \n\
16133 Convenience variable \"$_\" and default examine address for \"x\"\n\
16134 are set to the address of the last breakpoint listed unless the command\n\
16135 is prefixed with \"server \".\n\n\
16136 Convenience variable \"$bpnum\" contains the number of the last\n\
16137 breakpoint set."));
16138
16139   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16140 Status of all breakpoints, or breakpoint number NUMBER.\n\
16141 The \"Type\" column indicates one of:\n\
16142 \tbreakpoint     - normal breakpoint\n\
16143 \twatchpoint     - watchpoint\n\
16144 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16145 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16146 \tuntil          - internal breakpoint used by the \"until\" command\n\
16147 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16148 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16149 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16150 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16151 address and file/line number respectively.\n\
16152 \n\
16153 Convenience variable \"$_\" and default examine address for \"x\"\n\
16154 are set to the address of the last breakpoint listed unless the command\n\
16155 is prefixed with \"server \".\n\n\
16156 Convenience variable \"$bpnum\" contains the number of the last\n\
16157 breakpoint set."),
16158            &maintenanceinfolist);
16159
16160   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16161 Set catchpoints to catch events."),
16162                   &catch_cmdlist, "catch ",
16163                   0/*allow-unknown*/, &cmdlist);
16164
16165   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16166 Set temporary catchpoints to catch events."),
16167                   &tcatch_cmdlist, "tcatch ",
16168                   0/*allow-unknown*/, &cmdlist);
16169
16170   add_catch_command ("fork", _("Catch calls to fork."),
16171                      catch_fork_command_1,
16172                      NULL,
16173                      (void *) (uintptr_t) catch_fork_permanent,
16174                      (void *) (uintptr_t) catch_fork_temporary);
16175   add_catch_command ("vfork", _("Catch calls to vfork."),
16176                      catch_fork_command_1,
16177                      NULL,
16178                      (void *) (uintptr_t) catch_vfork_permanent,
16179                      (void *) (uintptr_t) catch_vfork_temporary);
16180   add_catch_command ("exec", _("Catch calls to exec."),
16181                      catch_exec_command_1,
16182                      NULL,
16183                      CATCH_PERMANENT,
16184                      CATCH_TEMPORARY);
16185   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16186 Usage: catch load [REGEX]\n\
16187 If REGEX is given, only stop for libraries matching the regular expression."),
16188                      catch_load_command_1,
16189                      NULL,
16190                      CATCH_PERMANENT,
16191                      CATCH_TEMPORARY);
16192   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16193 Usage: catch unload [REGEX]\n\
16194 If REGEX is given, only stop for libraries matching the regular expression."),
16195                      catch_unload_command_1,
16196                      NULL,
16197                      CATCH_PERMANENT,
16198                      CATCH_TEMPORARY);
16199   add_catch_command ("syscall", _("\
16200 Catch system calls by their names and/or numbers.\n\
16201 Arguments say which system calls to catch.  If no arguments\n\
16202 are given, every system call will be caught.\n\
16203 Arguments, if given, should be one or more system call names\n\
16204 (if your system supports that), or system call numbers."),
16205                      catch_syscall_command_1,
16206                      catch_syscall_completer,
16207                      CATCH_PERMANENT,
16208                      CATCH_TEMPORARY);
16209
16210   c = add_com ("watch", class_breakpoint, watch_command, _("\
16211 Set a watchpoint for an expression.\n\
16212 Usage: watch [-l|-location] EXPRESSION\n\
16213 A watchpoint stops execution of your program whenever the value of\n\
16214 an expression changes.\n\
16215 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16216 the memory to which it refers."));
16217   set_cmd_completer (c, expression_completer);
16218
16219   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16220 Set a read watchpoint for an expression.\n\
16221 Usage: rwatch [-l|-location] EXPRESSION\n\
16222 A watchpoint stops execution of your program whenever the value of\n\
16223 an expression is read.\n\
16224 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16225 the memory to which it refers."));
16226   set_cmd_completer (c, expression_completer);
16227
16228   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16229 Set a watchpoint for an expression.\n\
16230 Usage: awatch [-l|-location] EXPRESSION\n\
16231 A watchpoint stops execution of your program whenever the value of\n\
16232 an expression is either read or written.\n\
16233 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16234 the memory to which it refers."));
16235   set_cmd_completer (c, expression_completer);
16236
16237   add_info ("watchpoints", watchpoints_info, _("\
16238 Status of specified watchpoints (all watchpoints if no argument)."));
16239
16240   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16241      respond to changes - contrary to the description.  */
16242   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16243                             &can_use_hw_watchpoints, _("\
16244 Set debugger's willingness to use watchpoint hardware."), _("\
16245 Show debugger's willingness to use watchpoint hardware."), _("\
16246 If zero, gdb will not use hardware for new watchpoints, even if\n\
16247 such is available.  (However, any hardware watchpoints that were\n\
16248 created before setting this to nonzero, will continue to use watchpoint\n\
16249 hardware.)"),
16250                             NULL,
16251                             show_can_use_hw_watchpoints,
16252                             &setlist, &showlist);
16253
16254   can_use_hw_watchpoints = 1;
16255
16256   /* Tracepoint manipulation commands.  */
16257
16258   c = add_com ("trace", class_breakpoint, trace_command, _("\
16259 Set a tracepoint at specified line or function.\n\
16260 \n"
16261 BREAK_ARGS_HELP ("trace") "\n\
16262 Do \"help tracepoints\" for info on other tracepoint commands."));
16263   set_cmd_completer (c, location_completer);
16264
16265   add_com_alias ("tp", "trace", class_alias, 0);
16266   add_com_alias ("tr", "trace", class_alias, 1);
16267   add_com_alias ("tra", "trace", class_alias, 1);
16268   add_com_alias ("trac", "trace", class_alias, 1);
16269
16270   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16271 Set a fast tracepoint at specified line or function.\n\
16272 \n"
16273 BREAK_ARGS_HELP ("ftrace") "\n\
16274 Do \"help tracepoints\" for info on other tracepoint commands."));
16275   set_cmd_completer (c, location_completer);
16276
16277   c = add_com ("strace", class_breakpoint, strace_command, _("\
16278 Set a static tracepoint at specified line, function or marker.\n\
16279 \n\
16280 strace [LOCATION] [if CONDITION]\n\
16281 LOCATION may be a line number, function name, \"*\" and an address,\n\
16282 or -m MARKER_ID.\n\
16283 If a line number is specified, probe the marker at start of code\n\
16284 for that line.  If a function is specified, probe the marker at start\n\
16285 of code for that function.  If an address is specified, probe the marker\n\
16286 at that exact address.  If a marker id is specified, probe the marker\n\
16287 with that name.  With no LOCATION, uses current execution address of\n\
16288 the selected stack frame.\n\
16289 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16290 This collects arbitrary user data passed in the probe point call to the\n\
16291 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16292 by printing the $_sdata variable like any other convenience variable.\n\
16293 \n\
16294 CONDITION is a boolean expression.\n\
16295 \n\
16296 Multiple tracepoints at one place are permitted, and useful if their\n\
16297 conditions are different.\n\
16298 \n\
16299 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16300 Do \"help tracepoints\" for info on other tracepoint commands."));
16301   set_cmd_completer (c, location_completer);
16302
16303   add_info ("tracepoints", tracepoints_info, _("\
16304 Status of specified tracepoints (all tracepoints if no argument).\n\
16305 Convenience variable \"$tpnum\" contains the number of the\n\
16306 last tracepoint set."));
16307
16308   add_info_alias ("tp", "tracepoints", 1);
16309
16310   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16311 Delete specified tracepoints.\n\
16312 Arguments are tracepoint numbers, separated by spaces.\n\
16313 No argument means delete all tracepoints."),
16314            &deletelist);
16315   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16316
16317   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16318 Disable specified tracepoints.\n\
16319 Arguments are tracepoint numbers, separated by spaces.\n\
16320 No argument means disable all tracepoints."),
16321            &disablelist);
16322   deprecate_cmd (c, "disable");
16323
16324   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16325 Enable specified tracepoints.\n\
16326 Arguments are tracepoint numbers, separated by spaces.\n\
16327 No argument means enable all tracepoints."),
16328            &enablelist);
16329   deprecate_cmd (c, "enable");
16330
16331   add_com ("passcount", class_trace, trace_pass_command, _("\
16332 Set the passcount for a tracepoint.\n\
16333 The trace will end when the tracepoint has been passed 'count' times.\n\
16334 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16335 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16336
16337   add_prefix_cmd ("save", class_breakpoint, save_command,
16338                   _("Save breakpoint definitions as a script."),
16339                   &save_cmdlist, "save ",
16340                   0/*allow-unknown*/, &cmdlist);
16341
16342   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16343 Save current breakpoint definitions as a script.\n\
16344 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16345 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16346 session to restore them."),
16347                &save_cmdlist);
16348   set_cmd_completer (c, filename_completer);
16349
16350   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16351 Save current tracepoint definitions as a script.\n\
16352 Use the 'source' command in another debug session to restore them."),
16353                &save_cmdlist);
16354   set_cmd_completer (c, filename_completer);
16355
16356   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16357   deprecate_cmd (c, "save tracepoints");
16358
16359   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16360 Breakpoint specific settings\n\
16361 Configure various breakpoint-specific variables such as\n\
16362 pending breakpoint behavior"),
16363                   &breakpoint_set_cmdlist, "set breakpoint ",
16364                   0/*allow-unknown*/, &setlist);
16365   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16366 Breakpoint specific settings\n\
16367 Configure various breakpoint-specific variables such as\n\
16368 pending breakpoint behavior"),
16369                   &breakpoint_show_cmdlist, "show breakpoint ",
16370                   0/*allow-unknown*/, &showlist);
16371
16372   add_setshow_auto_boolean_cmd ("pending", no_class,
16373                                 &pending_break_support, _("\
16374 Set debugger's behavior regarding pending breakpoints."), _("\
16375 Show debugger's behavior regarding pending breakpoints."), _("\
16376 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16377 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16378 an error.  If auto, an unrecognized breakpoint location results in a\n\
16379 user-query to see if a pending breakpoint should be created."),
16380                                 NULL,
16381                                 show_pending_break_support,
16382                                 &breakpoint_set_cmdlist,
16383                                 &breakpoint_show_cmdlist);
16384
16385   pending_break_support = AUTO_BOOLEAN_AUTO;
16386
16387   add_setshow_boolean_cmd ("auto-hw", no_class,
16388                            &automatic_hardware_breakpoints, _("\
16389 Set automatic usage of hardware breakpoints."), _("\
16390 Show automatic usage of hardware breakpoints."), _("\
16391 If set, the debugger will automatically use hardware breakpoints for\n\
16392 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16393 a warning will be emitted for such breakpoints."),
16394                            NULL,
16395                            show_automatic_hardware_breakpoints,
16396                            &breakpoint_set_cmdlist,
16397                            &breakpoint_show_cmdlist);
16398
16399   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16400                                 &always_inserted_mode, _("\
16401 Set mode for inserting breakpoints."), _("\
16402 Show mode for inserting breakpoints."), _("\
16403 When this mode is off, breakpoints are inserted in inferior when it is\n\
16404 resumed, and removed when execution stops.  When this mode is on,\n\
16405 breakpoints are inserted immediately and removed only when the user\n\
16406 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16407 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16408 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16409 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16410 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16411                                 NULL,
16412                                 &show_always_inserted_mode,
16413                                 &breakpoint_set_cmdlist,
16414                                 &breakpoint_show_cmdlist);
16415
16416   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16417                         condition_evaluation_enums,
16418                         &condition_evaluation_mode_1, _("\
16419 Set mode of breakpoint condition evaluation."), _("\
16420 Show mode of breakpoint condition evaluation."), _("\
16421 When this is set to \"host\", breakpoint conditions will be\n\
16422 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16423 breakpoint conditions will be downloaded to the target (if the target\n\
16424 supports such feature) and conditions will be evaluated on the target's side.\n\
16425 If this is set to \"auto\" (default), this will be automatically set to\n\
16426 \"target\" if it supports condition evaluation, otherwise it will\n\
16427 be set to \"gdb\""),
16428                            &set_condition_evaluation_mode,
16429                            &show_condition_evaluation_mode,
16430                            &breakpoint_set_cmdlist,
16431                            &breakpoint_show_cmdlist);
16432
16433   add_com ("break-range", class_breakpoint, break_range_command, _("\
16434 Set a breakpoint for an address range.\n\
16435 break-range START-LOCATION, END-LOCATION\n\
16436 where START-LOCATION and END-LOCATION can be one of the following:\n\
16437   LINENUM, for that line in the current file,\n\
16438   FILE:LINENUM, for that line in that file,\n\
16439   +OFFSET, for that number of lines after the current line\n\
16440            or the start of the range\n\
16441   FUNCTION, for the first line in that function,\n\
16442   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16443   *ADDRESS, for the instruction at that address.\n\
16444 \n\
16445 The breakpoint will stop execution of the inferior whenever it executes\n\
16446 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16447 range (including START-LOCATION and END-LOCATION)."));
16448
16449   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16450 Set a dynamic printf at specified line or function.\n\
16451 dprintf location,format string,arg1,arg2,...\n\
16452 location may be a line number, function name, or \"*\" and an address.\n\
16453 If a line number is specified, break at start of code for that line.\n\
16454 If a function is specified, break at start of code for that function."));
16455   set_cmd_completer (c, location_completer);
16456
16457   add_setshow_enum_cmd ("dprintf-style", class_support,
16458                         dprintf_style_enums, &dprintf_style, _("\
16459 Set the style of usage for dynamic printf."), _("\
16460 Show the style of usage for dynamic printf."), _("\
16461 This setting chooses how GDB will do a dynamic printf.\n\
16462 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16463 console, as with the \"printf\" command.\n\
16464 If the value is \"call\", the print is done by calling a function in your\n\
16465 program; by default printf(), but you can choose a different function or\n\
16466 output stream by setting dprintf-function and dprintf-channel."),
16467                         update_dprintf_commands, NULL,
16468                         &setlist, &showlist);
16469
16470   dprintf_function = xstrdup ("printf");
16471   add_setshow_string_cmd ("dprintf-function", class_support,
16472                           &dprintf_function, _("\
16473 Set the function to use for dynamic printf"), _("\
16474 Show the function to use for dynamic printf"), NULL,
16475                           update_dprintf_commands, NULL,
16476                           &setlist, &showlist);
16477
16478   dprintf_channel = xstrdup ("");
16479   add_setshow_string_cmd ("dprintf-channel", class_support,
16480                           &dprintf_channel, _("\
16481 Set the channel to use for dynamic printf"), _("\
16482 Show the channel to use for dynamic printf"), NULL,
16483                           update_dprintf_commands, NULL,
16484                           &setlist, &showlist);
16485
16486   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16487                            &disconnected_dprintf, _("\
16488 Set whether dprintf continues after GDB disconnects."), _("\
16489 Show whether dprintf continues after GDB disconnects."), _("\
16490 Use this to let dprintf commands continue to hit and produce output\n\
16491 even if GDB disconnects or detaches from the target."),
16492                            NULL,
16493                            NULL,
16494                            &setlist, &showlist);
16495
16496   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16497 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16498 (target agent only) This is useful for formatted output in user-defined commands."));
16499
16500   automatic_hardware_breakpoints = 1;
16501
16502   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16503 }