]> Git Repo - binutils.git/blob - gdb/breakpoint.c
Change parameter type of update_global_location_list from boolean to enum
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "exceptions.h"
55 #include "memattr.h"
56 #include "ada-lang.h"
57 #include "top.h"
58 #include "valprint.h"
59 #include "jit.h"
60 #include "xml-syscall.h"
61 #include "parser-defs.h"
62 #include "gdb_regex.h"
63 #include "probe.h"
64 #include "cli/cli-utils.h"
65 #include "continuations.h"
66 #include "stack.h"
67 #include "skip.h"
68 #include "ax-gdb.h"
69 #include "dummy-frame.h"
70
71 #include "format.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82
83 /* Enums for exception-handling support.  */
84 enum exception_event_kind
85 {
86   EX_EVENT_THROW,
87   EX_EVENT_RETHROW,
88   EX_EVENT_CATCH
89 };
90
91 /* Prototypes for local functions.  */
92
93 static void enable_delete_command (char *, int);
94
95 static void enable_once_command (char *, int);
96
97 static void enable_count_command (char *, int);
98
99 static void disable_command (char *, int);
100
101 static void enable_command (char *, int);
102
103 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
104                                                       void *),
105                                     void *);
106
107 static void ignore_command (char *, int);
108
109 static int breakpoint_re_set_one (void *);
110
111 static void breakpoint_re_set_default (struct breakpoint *);
112
113 static void create_sals_from_address_default (char **,
114                                               struct linespec_result *,
115                                               enum bptype, char *,
116                                               char **);
117
118 static void create_breakpoints_sal_default (struct gdbarch *,
119                                             struct linespec_result *,
120                                             char *, char *, enum bptype,
121                                             enum bpdisp, int, int,
122                                             int,
123                                             const struct breakpoint_ops *,
124                                             int, int, int, unsigned);
125
126 static void decode_linespec_default (struct breakpoint *, char **,
127                                      struct symtabs_and_lines *);
128
129 static void clear_command (char *, int);
130
131 static void catch_command (char *, int);
132
133 static int can_use_hardware_watchpoint (struct value *);
134
135 static void break_command_1 (char *, int, int);
136
137 static void mention (struct breakpoint *);
138
139 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
140                                                                enum bptype,
141                                                                const struct breakpoint_ops *);
142 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
143                                                        const struct symtab_and_line *);
144
145 /* This function is used in gdbtk sources and thus can not be made
146    static.  */
147 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
148                                        struct symtab_and_line,
149                                        enum bptype,
150                                        const struct breakpoint_ops *);
151
152 static struct breakpoint *
153   momentary_breakpoint_from_master (struct breakpoint *orig,
154                                     enum bptype type,
155                                     const struct breakpoint_ops *ops,
156                                     int loc_enabled);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int watchpoint_locations_match (struct bp_location *loc1,
169                                        struct bp_location *loc2);
170
171 static int breakpoint_location_address_match (struct bp_location *bl,
172                                               struct address_space *aspace,
173                                               CORE_ADDR addr);
174
175 static void breakpoints_info (char *, int);
176
177 static void watchpoints_info (char *, int);
178
179 static int breakpoint_1 (char *, int, 
180                          int (*) (const struct breakpoint *));
181
182 static int breakpoint_cond_eval (void *);
183
184 static void cleanup_executing_breakpoints (void *);
185
186 static void commands_command (char *, int);
187
188 static void condition_command (char *, int);
189
190 typedef enum
191   {
192     mark_inserted,
193     mark_uninserted
194   }
195 insertion_state_t;
196
197 static int remove_breakpoint (struct bp_location *, insertion_state_t);
198 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
199
200 static enum print_stop_action print_bp_stop_message (bpstat bs);
201
202 static int watchpoint_check (void *);
203
204 static void maintenance_info_breakpoints (char *, int);
205
206 static int hw_breakpoint_used_count (void);
207
208 static int hw_watchpoint_use_count (struct breakpoint *);
209
210 static int hw_watchpoint_used_count_others (struct breakpoint *except,
211                                             enum bptype type,
212                                             int *other_type_used);
213
214 static void hbreak_command (char *, int);
215
216 static void thbreak_command (char *, int);
217
218 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
219                                     int count);
220
221 static void stop_command (char *arg, int from_tty);
222
223 static void stopin_command (char *arg, int from_tty);
224
225 static void stopat_command (char *arg, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int find_single_step_breakpoint (struct address_space *aspace,
232                                         CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 /* update_global_location_list's modes of operation wrt to whether to
241    insert locations now.  */
242 enum ugll_insert_mode
243 {
244   /* Don't insert any breakpoint locations into the inferior, only
245      remove already-inserted locations that no longer should be
246      inserted.  Functions that delete a breakpoint or breakpoints
247      should specify this mode, so that deleting a breakpoint doesn't
248      have the side effect of inserting the locations of other
249      breakpoints that are marked not-inserted, but should_be_inserted
250      returns true on them.
251
252      This behavior is useful is situations close to tear-down -- e.g.,
253      after an exec, while the target still has execution, but
254      breakpoint shadows of the previous executable image should *NOT*
255      be restored to the new image; or before detaching, where the
256      target still has execution and wants to delete breakpoints from
257      GDB's lists, and all breakpoints had already been removed from
258      the inferior.  */
259   UGLL_DONT_INSERT,
260
261   /* May insert breakpoints if breakpoints_always_inserted_mode is
262      true.  */
263   UGLL_MAY_INSERT
264 };
265
266 static void update_global_location_list (enum ugll_insert_mode);
267
268 static void update_global_location_list_nothrow (enum ugll_insert_mode);
269
270 static int is_hardware_watchpoint (const struct breakpoint *bpt);
271
272 static void insert_breakpoint_locations (void);
273
274 static int syscall_catchpoint_p (struct breakpoint *b);
275
276 static void tracepoints_info (char *, int);
277
278 static void delete_trace_command (char *, int);
279
280 static void enable_trace_command (char *, int);
281
282 static void disable_trace_command (char *, int);
283
284 static void trace_pass_command (char *, int);
285
286 static void set_tracepoint_count (int num);
287
288 static int is_masked_watchpoint (const struct breakpoint *b);
289
290 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
291
292 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
293    otherwise.  */
294
295 static int strace_marker_p (struct breakpoint *b);
296
297 /* The abstract base class all breakpoint_ops structures inherit
298    from.  */
299 struct breakpoint_ops base_breakpoint_ops;
300
301 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
302    that are implemented on top of software or hardware breakpoints
303    (user breakpoints, internal and momentary breakpoints, etc.).  */
304 static struct breakpoint_ops bkpt_base_breakpoint_ops;
305
306 /* Internal breakpoints class type.  */
307 static struct breakpoint_ops internal_breakpoint_ops;
308
309 /* Momentary breakpoints class type.  */
310 static struct breakpoint_ops momentary_breakpoint_ops;
311
312 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
313 static struct breakpoint_ops longjmp_breakpoint_ops;
314
315 /* The breakpoint_ops structure to be used in regular user created
316    breakpoints.  */
317 struct breakpoint_ops bkpt_breakpoint_ops;
318
319 /* Breakpoints set on probes.  */
320 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
321
322 /* Dynamic printf class type.  */
323 struct breakpoint_ops dprintf_breakpoint_ops;
324
325 /* One (or perhaps two) breakpoints used for software single
326    stepping.  */
327
328 static void *single_step_breakpoints[2];
329 static struct gdbarch *single_step_gdbarch[2];
330
331 /* The style in which to perform a dynamic printf.  This is a user
332    option because different output options have different tradeoffs;
333    if GDB does the printing, there is better error handling if there
334    is a problem with any of the arguments, but using an inferior
335    function lets you have special-purpose printers and sending of
336    output to the same place as compiled-in print functions.  */
337
338 static const char dprintf_style_gdb[] = "gdb";
339 static const char dprintf_style_call[] = "call";
340 static const char dprintf_style_agent[] = "agent";
341 static const char *const dprintf_style_enums[] = {
342   dprintf_style_gdb,
343   dprintf_style_call,
344   dprintf_style_agent,
345   NULL
346 };
347 static const char *dprintf_style = dprintf_style_gdb;
348
349 /* The function to use for dynamic printf if the preferred style is to
350    call into the inferior.  The value is simply a string that is
351    copied into the command, so it can be anything that GDB can
352    evaluate to a callable address, not necessarily a function name.  */
353
354 static char *dprintf_function = "";
355
356 /* The channel to use for dynamic printf if the preferred style is to
357    call into the inferior; if a nonempty string, it will be passed to
358    the call as the first argument, with the format string as the
359    second.  As with the dprintf function, this can be anything that
360    GDB knows how to evaluate, so in addition to common choices like
361    "stderr", this could be an app-specific expression like
362    "mystreams[curlogger]".  */
363
364 static char *dprintf_channel = "";
365
366 /* True if dprintf commands should continue to operate even if GDB
367    has disconnected.  */
368 static int disconnected_dprintf = 1;
369
370 /* A reference-counted struct command_line.  This lets multiple
371    breakpoints share a single command list.  */
372 struct counted_command_line
373 {
374   /* The reference count.  */
375   int refc;
376
377   /* The command list.  */
378   struct command_line *commands;
379 };
380
381 struct command_line *
382 breakpoint_commands (struct breakpoint *b)
383 {
384   return b->commands ? b->commands->commands : NULL;
385 }
386
387 /* Flag indicating that a command has proceeded the inferior past the
388    current breakpoint.  */
389
390 static int breakpoint_proceeded;
391
392 const char *
393 bpdisp_text (enum bpdisp disp)
394 {
395   /* NOTE: the following values are a part of MI protocol and
396      represent values of 'disp' field returned when inferior stops at
397      a breakpoint.  */
398   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
399
400   return bpdisps[(int) disp];
401 }
402
403 /* Prototypes for exported functions.  */
404 /* If FALSE, gdb will not use hardware support for watchpoints, even
405    if such is available.  */
406 static int can_use_hw_watchpoints;
407
408 static void
409 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
410                              struct cmd_list_element *c,
411                              const char *value)
412 {
413   fprintf_filtered (file,
414                     _("Debugger's willingness to use "
415                       "watchpoint hardware is %s.\n"),
416                     value);
417 }
418
419 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
420    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
421    for unrecognized breakpoint locations.
422    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
423 static enum auto_boolean pending_break_support;
424 static void
425 show_pending_break_support (struct ui_file *file, int from_tty,
426                             struct cmd_list_element *c,
427                             const char *value)
428 {
429   fprintf_filtered (file,
430                     _("Debugger's behavior regarding "
431                       "pending breakpoints is %s.\n"),
432                     value);
433 }
434
435 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
436    set with "break" but falling in read-only memory.
437    If 0, gdb will warn about such breakpoints, but won't automatically
438    use hardware breakpoints.  */
439 static int automatic_hardware_breakpoints;
440 static void
441 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
442                                      struct cmd_list_element *c,
443                                      const char *value)
444 {
445   fprintf_filtered (file,
446                     _("Automatic usage of hardware breakpoints is %s.\n"),
447                     value);
448 }
449
450 /* If on, gdb will keep breakpoints inserted even as inferior is
451    stopped, and immediately insert any new breakpoints.  If off, gdb
452    will insert breakpoints into inferior only when resuming it, and
453    will remove breakpoints upon stop.  If auto, GDB will behave as ON
454    if in non-stop mode, and as OFF if all-stop mode.*/
455
456 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
457
458 static void
459 show_always_inserted_mode (struct ui_file *file, int from_tty,
460                      struct cmd_list_element *c, const char *value)
461 {
462   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
463     fprintf_filtered (file,
464                       _("Always inserted breakpoint "
465                         "mode is %s (currently %s).\n"),
466                       value,
467                       breakpoints_always_inserted_mode () ? "on" : "off");
468   else
469     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
470                       value);
471 }
472
473 int
474 breakpoints_always_inserted_mode (void)
475 {
476   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
477           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
478 }
479
480 static const char condition_evaluation_both[] = "host or target";
481
482 /* Modes for breakpoint condition evaluation.  */
483 static const char condition_evaluation_auto[] = "auto";
484 static const char condition_evaluation_host[] = "host";
485 static const char condition_evaluation_target[] = "target";
486 static const char *const condition_evaluation_enums[] = {
487   condition_evaluation_auto,
488   condition_evaluation_host,
489   condition_evaluation_target,
490   NULL
491 };
492
493 /* Global that holds the current mode for breakpoint condition evaluation.  */
494 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
495
496 /* Global that we use to display information to the user (gets its value from
497    condition_evaluation_mode_1.  */
498 static const char *condition_evaluation_mode = condition_evaluation_auto;
499
500 /* Translate a condition evaluation mode MODE into either "host"
501    or "target".  This is used mostly to translate from "auto" to the
502    real setting that is being used.  It returns the translated
503    evaluation mode.  */
504
505 static const char *
506 translate_condition_evaluation_mode (const char *mode)
507 {
508   if (mode == condition_evaluation_auto)
509     {
510       if (target_supports_evaluation_of_breakpoint_conditions ())
511         return condition_evaluation_target;
512       else
513         return condition_evaluation_host;
514     }
515   else
516     return mode;
517 }
518
519 /* Discovers what condition_evaluation_auto translates to.  */
520
521 static const char *
522 breakpoint_condition_evaluation_mode (void)
523 {
524   return translate_condition_evaluation_mode (condition_evaluation_mode);
525 }
526
527 /* Return true if GDB should evaluate breakpoint conditions or false
528    otherwise.  */
529
530 static int
531 gdb_evaluates_breakpoint_condition_p (void)
532 {
533   const char *mode = breakpoint_condition_evaluation_mode ();
534
535   return (mode == condition_evaluation_host);
536 }
537
538 void _initialize_breakpoint (void);
539
540 /* Are we executing breakpoint commands?  */
541 static int executing_breakpoint_commands;
542
543 /* Are overlay event breakpoints enabled? */
544 static int overlay_events_enabled;
545
546 /* See description in breakpoint.h. */
547 int target_exact_watchpoints = 0;
548
549 /* Walk the following statement or block through all breakpoints.
550    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
551    current breakpoint.  */
552
553 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
554
555 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
556         for (B = breakpoint_chain;      \
557              B ? (TMP=B->next, 1): 0;   \
558              B = TMP)
559
560 /* Similar iterator for the low-level breakpoints.  SAFE variant is
561    not provided so update_global_location_list must not be called
562    while executing the block of ALL_BP_LOCATIONS.  */
563
564 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
565         for (BP_TMP = bp_location;                                      \
566              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
567              BP_TMP++)
568
569 /* Iterates through locations with address ADDRESS for the currently selected
570    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
571    to where the loop should start from.
572    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
573    appropriate location to start with.  */
574
575 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
576         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
577              BP_LOCP_TMP = BP_LOCP_START;                               \
578              BP_LOCP_START                                              \
579              && (BP_LOCP_TMP < bp_location + bp_location_count          \
580              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
581              BP_LOCP_TMP++)
582
583 /* Iterator for tracepoints only.  */
584
585 #define ALL_TRACEPOINTS(B)  \
586   for (B = breakpoint_chain; B; B = B->next)  \
587     if (is_tracepoint (B))
588
589 /* Chains of all breakpoints defined.  */
590
591 struct breakpoint *breakpoint_chain;
592
593 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
594
595 static struct bp_location **bp_location;
596
597 /* Number of elements of BP_LOCATION.  */
598
599 static unsigned bp_location_count;
600
601 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
602    ADDRESS for the current elements of BP_LOCATION which get a valid
603    result from bp_location_has_shadow.  You can use it for roughly
604    limiting the subrange of BP_LOCATION to scan for shadow bytes for
605    an address you need to read.  */
606
607 static CORE_ADDR bp_location_placed_address_before_address_max;
608
609 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
610    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
611    BP_LOCATION which get a valid result from bp_location_has_shadow.
612    You can use it for roughly limiting the subrange of BP_LOCATION to
613    scan for shadow bytes for an address you need to read.  */
614
615 static CORE_ADDR bp_location_shadow_len_after_address_max;
616
617 /* The locations that no longer correspond to any breakpoint, unlinked
618    from bp_location array, but for which a hit may still be reported
619    by a target.  */
620 VEC(bp_location_p) *moribund_locations = NULL;
621
622 /* Number of last breakpoint made.  */
623
624 static int breakpoint_count;
625
626 /* The value of `breakpoint_count' before the last command that
627    created breakpoints.  If the last (break-like) command created more
628    than one breakpoint, then the difference between BREAKPOINT_COUNT
629    and PREV_BREAKPOINT_COUNT is more than one.  */
630 static int prev_breakpoint_count;
631
632 /* Number of last tracepoint made.  */
633
634 static int tracepoint_count;
635
636 static struct cmd_list_element *breakpoint_set_cmdlist;
637 static struct cmd_list_element *breakpoint_show_cmdlist;
638 struct cmd_list_element *save_cmdlist;
639
640 /* Return whether a breakpoint is an active enabled breakpoint.  */
641 static int
642 breakpoint_enabled (struct breakpoint *b)
643 {
644   return (b->enable_state == bp_enabled);
645 }
646
647 /* Set breakpoint count to NUM.  */
648
649 static void
650 set_breakpoint_count (int num)
651 {
652   prev_breakpoint_count = breakpoint_count;
653   breakpoint_count = num;
654   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
655 }
656
657 /* Used by `start_rbreak_breakpoints' below, to record the current
658    breakpoint count before "rbreak" creates any breakpoint.  */
659 static int rbreak_start_breakpoint_count;
660
661 /* Called at the start an "rbreak" command to record the first
662    breakpoint made.  */
663
664 void
665 start_rbreak_breakpoints (void)
666 {
667   rbreak_start_breakpoint_count = breakpoint_count;
668 }
669
670 /* Called at the end of an "rbreak" command to record the last
671    breakpoint made.  */
672
673 void
674 end_rbreak_breakpoints (void)
675 {
676   prev_breakpoint_count = rbreak_start_breakpoint_count;
677 }
678
679 /* Used in run_command to zero the hit count when a new run starts.  */
680
681 void
682 clear_breakpoint_hit_counts (void)
683 {
684   struct breakpoint *b;
685
686   ALL_BREAKPOINTS (b)
687     b->hit_count = 0;
688 }
689
690 /* Allocate a new counted_command_line with reference count of 1.
691    The new structure owns COMMANDS.  */
692
693 static struct counted_command_line *
694 alloc_counted_command_line (struct command_line *commands)
695 {
696   struct counted_command_line *result
697     = xmalloc (sizeof (struct counted_command_line));
698
699   result->refc = 1;
700   result->commands = commands;
701   return result;
702 }
703
704 /* Increment reference count.  This does nothing if CMD is NULL.  */
705
706 static void
707 incref_counted_command_line (struct counted_command_line *cmd)
708 {
709   if (cmd)
710     ++cmd->refc;
711 }
712
713 /* Decrement reference count.  If the reference count reaches 0,
714    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
715    nothing if *CMDP is NULL.  */
716
717 static void
718 decref_counted_command_line (struct counted_command_line **cmdp)
719 {
720   if (*cmdp)
721     {
722       if (--(*cmdp)->refc == 0)
723         {
724           free_command_lines (&(*cmdp)->commands);
725           xfree (*cmdp);
726         }
727       *cmdp = NULL;
728     }
729 }
730
731 /* A cleanup function that calls decref_counted_command_line.  */
732
733 static void
734 do_cleanup_counted_command_line (void *arg)
735 {
736   decref_counted_command_line (arg);
737 }
738
739 /* Create a cleanup that calls decref_counted_command_line on the
740    argument.  */
741
742 static struct cleanup *
743 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
744 {
745   return make_cleanup (do_cleanup_counted_command_line, cmdp);
746 }
747
748 \f
749 /* Return the breakpoint with the specified number, or NULL
750    if the number does not refer to an existing breakpoint.  */
751
752 struct breakpoint *
753 get_breakpoint (int num)
754 {
755   struct breakpoint *b;
756
757   ALL_BREAKPOINTS (b)
758     if (b->number == num)
759       return b;
760   
761   return NULL;
762 }
763
764 \f
765
766 /* Mark locations as "conditions have changed" in case the target supports
767    evaluating conditions on its side.  */
768
769 static void
770 mark_breakpoint_modified (struct breakpoint *b)
771 {
772   struct bp_location *loc;
773
774   /* This is only meaningful if the target is
775      evaluating conditions and if the user has
776      opted for condition evaluation on the target's
777      side.  */
778   if (gdb_evaluates_breakpoint_condition_p ()
779       || !target_supports_evaluation_of_breakpoint_conditions ())
780     return;
781
782   if (!is_breakpoint (b))
783     return;
784
785   for (loc = b->loc; loc; loc = loc->next)
786     loc->condition_changed = condition_modified;
787 }
788
789 /* Mark location as "conditions have changed" in case the target supports
790    evaluating conditions on its side.  */
791
792 static void
793 mark_breakpoint_location_modified (struct bp_location *loc)
794 {
795   /* This is only meaningful if the target is
796      evaluating conditions and if the user has
797      opted for condition evaluation on the target's
798      side.  */
799   if (gdb_evaluates_breakpoint_condition_p ()
800       || !target_supports_evaluation_of_breakpoint_conditions ())
801
802     return;
803
804   if (!is_breakpoint (loc->owner))
805     return;
806
807   loc->condition_changed = condition_modified;
808 }
809
810 /* Sets the condition-evaluation mode using the static global
811    condition_evaluation_mode.  */
812
813 static void
814 set_condition_evaluation_mode (char *args, int from_tty,
815                                struct cmd_list_element *c)
816 {
817   const char *old_mode, *new_mode;
818
819   if ((condition_evaluation_mode_1 == condition_evaluation_target)
820       && !target_supports_evaluation_of_breakpoint_conditions ())
821     {
822       condition_evaluation_mode_1 = condition_evaluation_mode;
823       warning (_("Target does not support breakpoint condition evaluation.\n"
824                  "Using host evaluation mode instead."));
825       return;
826     }
827
828   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
829   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
830
831   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
832      settings was "auto".  */
833   condition_evaluation_mode = condition_evaluation_mode_1;
834
835   /* Only update the mode if the user picked a different one.  */
836   if (new_mode != old_mode)
837     {
838       struct bp_location *loc, **loc_tmp;
839       /* If the user switched to a different evaluation mode, we
840          need to synch the changes with the target as follows:
841
842          "host" -> "target": Send all (valid) conditions to the target.
843          "target" -> "host": Remove all the conditions from the target.
844       */
845
846       if (new_mode == condition_evaluation_target)
847         {
848           /* Mark everything modified and synch conditions with the
849              target.  */
850           ALL_BP_LOCATIONS (loc, loc_tmp)
851             mark_breakpoint_location_modified (loc);
852         }
853       else
854         {
855           /* Manually mark non-duplicate locations to synch conditions
856              with the target.  We do this to remove all the conditions the
857              target knows about.  */
858           ALL_BP_LOCATIONS (loc, loc_tmp)
859             if (is_breakpoint (loc->owner) && loc->inserted)
860               loc->needs_update = 1;
861         }
862
863       /* Do the update.  */
864       update_global_location_list (UGLL_MAY_INSERT);
865     }
866
867   return;
868 }
869
870 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
871    what "auto" is translating to.  */
872
873 static void
874 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
875                                 struct cmd_list_element *c, const char *value)
876 {
877   if (condition_evaluation_mode == condition_evaluation_auto)
878     fprintf_filtered (file,
879                       _("Breakpoint condition evaluation "
880                         "mode is %s (currently %s).\n"),
881                       value,
882                       breakpoint_condition_evaluation_mode ());
883   else
884     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
885                       value);
886 }
887
888 /* A comparison function for bp_location AP and BP that is used by
889    bsearch.  This comparison function only cares about addresses, unlike
890    the more general bp_location_compare function.  */
891
892 static int
893 bp_location_compare_addrs (const void *ap, const void *bp)
894 {
895   struct bp_location *a = *(void **) ap;
896   struct bp_location *b = *(void **) bp;
897
898   if (a->address == b->address)
899     return 0;
900   else
901     return ((a->address > b->address) - (a->address < b->address));
902 }
903
904 /* Helper function to skip all bp_locations with addresses
905    less than ADDRESS.  It returns the first bp_location that
906    is greater than or equal to ADDRESS.  If none is found, just
907    return NULL.  */
908
909 static struct bp_location **
910 get_first_locp_gte_addr (CORE_ADDR address)
911 {
912   struct bp_location dummy_loc;
913   struct bp_location *dummy_locp = &dummy_loc;
914   struct bp_location **locp_found = NULL;
915
916   /* Initialize the dummy location's address field.  */
917   memset (&dummy_loc, 0, sizeof (struct bp_location));
918   dummy_loc.address = address;
919
920   /* Find a close match to the first location at ADDRESS.  */
921   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
922                         sizeof (struct bp_location **),
923                         bp_location_compare_addrs);
924
925   /* Nothing was found, nothing left to do.  */
926   if (locp_found == NULL)
927     return NULL;
928
929   /* We may have found a location that is at ADDRESS but is not the first in the
930      location's list.  Go backwards (if possible) and locate the first one.  */
931   while ((locp_found - 1) >= bp_location
932          && (*(locp_found - 1))->address == address)
933     locp_found--;
934
935   return locp_found;
936 }
937
938 void
939 set_breakpoint_condition (struct breakpoint *b, char *exp,
940                           int from_tty)
941 {
942   xfree (b->cond_string);
943   b->cond_string = NULL;
944
945   if (is_watchpoint (b))
946     {
947       struct watchpoint *w = (struct watchpoint *) b;
948
949       xfree (w->cond_exp);
950       w->cond_exp = NULL;
951     }
952   else
953     {
954       struct bp_location *loc;
955
956       for (loc = b->loc; loc; loc = loc->next)
957         {
958           xfree (loc->cond);
959           loc->cond = NULL;
960
961           /* No need to free the condition agent expression
962              bytecode (if we have one).  We will handle this
963              when we go through update_global_location_list.  */
964         }
965     }
966
967   if (*exp == 0)
968     {
969       if (from_tty)
970         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
971     }
972   else
973     {
974       const char *arg = exp;
975
976       /* I don't know if it matters whether this is the string the user
977          typed in or the decompiled expression.  */
978       b->cond_string = xstrdup (arg);
979       b->condition_not_parsed = 0;
980
981       if (is_watchpoint (b))
982         {
983           struct watchpoint *w = (struct watchpoint *) b;
984
985           innermost_block = NULL;
986           arg = exp;
987           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
988           if (*arg)
989             error (_("Junk at end of expression"));
990           w->cond_exp_valid_block = innermost_block;
991         }
992       else
993         {
994           struct bp_location *loc;
995
996           for (loc = b->loc; loc; loc = loc->next)
997             {
998               arg = exp;
999               loc->cond =
1000                 parse_exp_1 (&arg, loc->address,
1001                              block_for_pc (loc->address), 0);
1002               if (*arg)
1003                 error (_("Junk at end of expression"));
1004             }
1005         }
1006     }
1007   mark_breakpoint_modified (b);
1008
1009   observer_notify_breakpoint_modified (b);
1010 }
1011
1012 /* Completion for the "condition" command.  */
1013
1014 static VEC (char_ptr) *
1015 condition_completer (struct cmd_list_element *cmd,
1016                      const char *text, const char *word)
1017 {
1018   const char *space;
1019
1020   text = skip_spaces_const (text);
1021   space = skip_to_space_const (text);
1022   if (*space == '\0')
1023     {
1024       int len;
1025       struct breakpoint *b;
1026       VEC (char_ptr) *result = NULL;
1027
1028       if (text[0] == '$')
1029         {
1030           /* We don't support completion of history indices.  */
1031           if (isdigit (text[1]))
1032             return NULL;
1033           return complete_internalvar (&text[1]);
1034         }
1035
1036       /* We're completing the breakpoint number.  */
1037       len = strlen (text);
1038
1039       ALL_BREAKPOINTS (b)
1040         {
1041           char number[50];
1042
1043           xsnprintf (number, sizeof (number), "%d", b->number);
1044
1045           if (strncmp (number, text, len) == 0)
1046             VEC_safe_push (char_ptr, result, xstrdup (number));
1047         }
1048
1049       return result;
1050     }
1051
1052   /* We're completing the expression part.  */
1053   text = skip_spaces_const (space);
1054   return expression_completer (cmd, text, word);
1055 }
1056
1057 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1058
1059 static void
1060 condition_command (char *arg, int from_tty)
1061 {
1062   struct breakpoint *b;
1063   char *p;
1064   int bnum;
1065
1066   if (arg == 0)
1067     error_no_arg (_("breakpoint number"));
1068
1069   p = arg;
1070   bnum = get_number (&p);
1071   if (bnum == 0)
1072     error (_("Bad breakpoint argument: '%s'"), arg);
1073
1074   ALL_BREAKPOINTS (b)
1075     if (b->number == bnum)
1076       {
1077         /* Check if this breakpoint has a "stop" method implemented in an
1078            extension language.  This method and conditions entered into GDB
1079            from the CLI are mutually exclusive.  */
1080         const struct extension_language_defn *extlang
1081           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1082
1083         if (extlang != NULL)
1084           {
1085             error (_("Only one stop condition allowed.  There is currently"
1086                      " a %s stop condition defined for this breakpoint."),
1087                    ext_lang_capitalized_name (extlang));
1088           }
1089         set_breakpoint_condition (b, p, from_tty);
1090
1091         if (is_breakpoint (b))
1092           update_global_location_list (UGLL_MAY_INSERT);
1093
1094         return;
1095       }
1096
1097   error (_("No breakpoint number %d."), bnum);
1098 }
1099
1100 /* Check that COMMAND do not contain commands that are suitable
1101    only for tracepoints and not suitable for ordinary breakpoints.
1102    Throw if any such commands is found.  */
1103
1104 static void
1105 check_no_tracepoint_commands (struct command_line *commands)
1106 {
1107   struct command_line *c;
1108
1109   for (c = commands; c; c = c->next)
1110     {
1111       int i;
1112
1113       if (c->control_type == while_stepping_control)
1114         error (_("The 'while-stepping' command can "
1115                  "only be used for tracepoints"));
1116
1117       for (i = 0; i < c->body_count; ++i)
1118         check_no_tracepoint_commands ((c->body_list)[i]);
1119
1120       /* Not that command parsing removes leading whitespace and comment
1121          lines and also empty lines.  So, we only need to check for
1122          command directly.  */
1123       if (strstr (c->line, "collect ") == c->line)
1124         error (_("The 'collect' command can only be used for tracepoints"));
1125
1126       if (strstr (c->line, "teval ") == c->line)
1127         error (_("The 'teval' command can only be used for tracepoints"));
1128     }
1129 }
1130
1131 /* Encapsulate tests for different types of tracepoints.  */
1132
1133 static int
1134 is_tracepoint_type (enum bptype type)
1135 {
1136   return (type == bp_tracepoint
1137           || type == bp_fast_tracepoint
1138           || type == bp_static_tracepoint);
1139 }
1140
1141 int
1142 is_tracepoint (const struct breakpoint *b)
1143 {
1144   return is_tracepoint_type (b->type);
1145 }
1146
1147 /* A helper function that validates that COMMANDS are valid for a
1148    breakpoint.  This function will throw an exception if a problem is
1149    found.  */
1150
1151 static void
1152 validate_commands_for_breakpoint (struct breakpoint *b,
1153                                   struct command_line *commands)
1154 {
1155   if (is_tracepoint (b))
1156     {
1157       struct tracepoint *t = (struct tracepoint *) b;
1158       struct command_line *c;
1159       struct command_line *while_stepping = 0;
1160
1161       /* Reset the while-stepping step count.  The previous commands
1162          might have included a while-stepping action, while the new
1163          ones might not.  */
1164       t->step_count = 0;
1165
1166       /* We need to verify that each top-level element of commands is
1167          valid for tracepoints, that there's at most one
1168          while-stepping element, and that the while-stepping's body
1169          has valid tracing commands excluding nested while-stepping.
1170          We also need to validate the tracepoint action line in the
1171          context of the tracepoint --- validate_actionline actually
1172          has side effects, like setting the tracepoint's
1173          while-stepping STEP_COUNT, in addition to checking if the
1174          collect/teval actions parse and make sense in the
1175          tracepoint's context.  */
1176       for (c = commands; c; c = c->next)
1177         {
1178           if (c->control_type == while_stepping_control)
1179             {
1180               if (b->type == bp_fast_tracepoint)
1181                 error (_("The 'while-stepping' command "
1182                          "cannot be used for fast tracepoint"));
1183               else if (b->type == bp_static_tracepoint)
1184                 error (_("The 'while-stepping' command "
1185                          "cannot be used for static tracepoint"));
1186
1187               if (while_stepping)
1188                 error (_("The 'while-stepping' command "
1189                          "can be used only once"));
1190               else
1191                 while_stepping = c;
1192             }
1193
1194           validate_actionline (c->line, b);
1195         }
1196       if (while_stepping)
1197         {
1198           struct command_line *c2;
1199
1200           gdb_assert (while_stepping->body_count == 1);
1201           c2 = while_stepping->body_list[0];
1202           for (; c2; c2 = c2->next)
1203             {
1204               if (c2->control_type == while_stepping_control)
1205                 error (_("The 'while-stepping' command cannot be nested"));
1206             }
1207         }
1208     }
1209   else
1210     {
1211       check_no_tracepoint_commands (commands);
1212     }
1213 }
1214
1215 /* Return a vector of all the static tracepoints set at ADDR.  The
1216    caller is responsible for releasing the vector.  */
1217
1218 VEC(breakpoint_p) *
1219 static_tracepoints_here (CORE_ADDR addr)
1220 {
1221   struct breakpoint *b;
1222   VEC(breakpoint_p) *found = 0;
1223   struct bp_location *loc;
1224
1225   ALL_BREAKPOINTS (b)
1226     if (b->type == bp_static_tracepoint)
1227       {
1228         for (loc = b->loc; loc; loc = loc->next)
1229           if (loc->address == addr)
1230             VEC_safe_push(breakpoint_p, found, b);
1231       }
1232
1233   return found;
1234 }
1235
1236 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1237    validate that only allowed commands are included.  */
1238
1239 void
1240 breakpoint_set_commands (struct breakpoint *b, 
1241                          struct command_line *commands)
1242 {
1243   validate_commands_for_breakpoint (b, commands);
1244
1245   decref_counted_command_line (&b->commands);
1246   b->commands = alloc_counted_command_line (commands);
1247   observer_notify_breakpoint_modified (b);
1248 }
1249
1250 /* Set the internal `silent' flag on the breakpoint.  Note that this
1251    is not the same as the "silent" that may appear in the breakpoint's
1252    commands.  */
1253
1254 void
1255 breakpoint_set_silent (struct breakpoint *b, int silent)
1256 {
1257   int old_silent = b->silent;
1258
1259   b->silent = silent;
1260   if (old_silent != silent)
1261     observer_notify_breakpoint_modified (b);
1262 }
1263
1264 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1265    breakpoint work for any thread.  */
1266
1267 void
1268 breakpoint_set_thread (struct breakpoint *b, int thread)
1269 {
1270   int old_thread = b->thread;
1271
1272   b->thread = thread;
1273   if (old_thread != thread)
1274     observer_notify_breakpoint_modified (b);
1275 }
1276
1277 /* Set the task for this breakpoint.  If TASK is 0, make the
1278    breakpoint work for any task.  */
1279
1280 void
1281 breakpoint_set_task (struct breakpoint *b, int task)
1282 {
1283   int old_task = b->task;
1284
1285   b->task = task;
1286   if (old_task != task)
1287     observer_notify_breakpoint_modified (b);
1288 }
1289
1290 void
1291 check_tracepoint_command (char *line, void *closure)
1292 {
1293   struct breakpoint *b = closure;
1294
1295   validate_actionline (line, b);
1296 }
1297
1298 /* A structure used to pass information through
1299    map_breakpoint_numbers.  */
1300
1301 struct commands_info
1302 {
1303   /* True if the command was typed at a tty.  */
1304   int from_tty;
1305
1306   /* The breakpoint range spec.  */
1307   char *arg;
1308
1309   /* Non-NULL if the body of the commands are being read from this
1310      already-parsed command.  */
1311   struct command_line *control;
1312
1313   /* The command lines read from the user, or NULL if they have not
1314      yet been read.  */
1315   struct counted_command_line *cmd;
1316 };
1317
1318 /* A callback for map_breakpoint_numbers that sets the commands for
1319    commands_command.  */
1320
1321 static void
1322 do_map_commands_command (struct breakpoint *b, void *data)
1323 {
1324   struct commands_info *info = data;
1325
1326   if (info->cmd == NULL)
1327     {
1328       struct command_line *l;
1329
1330       if (info->control != NULL)
1331         l = copy_command_lines (info->control->body_list[0]);
1332       else
1333         {
1334           struct cleanup *old_chain;
1335           char *str;
1336
1337           str = xstrprintf (_("Type commands for breakpoint(s) "
1338                               "%s, one per line."),
1339                             info->arg);
1340
1341           old_chain = make_cleanup (xfree, str);
1342
1343           l = read_command_lines (str,
1344                                   info->from_tty, 1,
1345                                   (is_tracepoint (b)
1346                                    ? check_tracepoint_command : 0),
1347                                   b);
1348
1349           do_cleanups (old_chain);
1350         }
1351
1352       info->cmd = alloc_counted_command_line (l);
1353     }
1354
1355   /* If a breakpoint was on the list more than once, we don't need to
1356      do anything.  */
1357   if (b->commands != info->cmd)
1358     {
1359       validate_commands_for_breakpoint (b, info->cmd->commands);
1360       incref_counted_command_line (info->cmd);
1361       decref_counted_command_line (&b->commands);
1362       b->commands = info->cmd;
1363       observer_notify_breakpoint_modified (b);
1364     }
1365 }
1366
1367 static void
1368 commands_command_1 (char *arg, int from_tty, 
1369                     struct command_line *control)
1370 {
1371   struct cleanup *cleanups;
1372   struct commands_info info;
1373
1374   info.from_tty = from_tty;
1375   info.control = control;
1376   info.cmd = NULL;
1377   /* If we read command lines from the user, then `info' will hold an
1378      extra reference to the commands that we must clean up.  */
1379   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1380
1381   if (arg == NULL || !*arg)
1382     {
1383       if (breakpoint_count - prev_breakpoint_count > 1)
1384         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1385                           breakpoint_count);
1386       else if (breakpoint_count > 0)
1387         arg = xstrprintf ("%d", breakpoint_count);
1388       else
1389         {
1390           /* So that we don't try to free the incoming non-NULL
1391              argument in the cleanup below.  Mapping breakpoint
1392              numbers will fail in this case.  */
1393           arg = NULL;
1394         }
1395     }
1396   else
1397     /* The command loop has some static state, so we need to preserve
1398        our argument.  */
1399     arg = xstrdup (arg);
1400
1401   if (arg != NULL)
1402     make_cleanup (xfree, arg);
1403
1404   info.arg = arg;
1405
1406   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1407
1408   if (info.cmd == NULL)
1409     error (_("No breakpoints specified."));
1410
1411   do_cleanups (cleanups);
1412 }
1413
1414 static void
1415 commands_command (char *arg, int from_tty)
1416 {
1417   commands_command_1 (arg, from_tty, NULL);
1418 }
1419
1420 /* Like commands_command, but instead of reading the commands from
1421    input stream, takes them from an already parsed command structure.
1422
1423    This is used by cli-script.c to DTRT with breakpoint commands
1424    that are part of if and while bodies.  */
1425 enum command_control_type
1426 commands_from_control_command (char *arg, struct command_line *cmd)
1427 {
1428   commands_command_1 (arg, 0, cmd);
1429   return simple_control;
1430 }
1431
1432 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1433
1434 static int
1435 bp_location_has_shadow (struct bp_location *bl)
1436 {
1437   if (bl->loc_type != bp_loc_software_breakpoint)
1438     return 0;
1439   if (!bl->inserted)
1440     return 0;
1441   if (bl->target_info.shadow_len == 0)
1442     /* BL isn't valid, or doesn't shadow memory.  */
1443     return 0;
1444   return 1;
1445 }
1446
1447 /* Update BUF, which is LEN bytes read from the target address
1448    MEMADDR, by replacing a memory breakpoint with its shadowed
1449    contents.
1450
1451    If READBUF is not NULL, this buffer must not overlap with the of
1452    the breakpoint location's shadow_contents buffer.  Otherwise, a
1453    failed assertion internal error will be raised.  */
1454
1455 static void
1456 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1457                             const gdb_byte *writebuf_org,
1458                             ULONGEST memaddr, LONGEST len,
1459                             struct bp_target_info *target_info,
1460                             struct gdbarch *gdbarch)
1461 {
1462   /* Now do full processing of the found relevant range of elements.  */
1463   CORE_ADDR bp_addr = 0;
1464   int bp_size = 0;
1465   int bptoffset = 0;
1466
1467   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1468                                  current_program_space->aspace, 0))
1469     {
1470       /* The breakpoint is inserted in a different address space.  */
1471       return;
1472     }
1473
1474   /* Addresses and length of the part of the breakpoint that
1475      we need to copy.  */
1476   bp_addr = target_info->placed_address;
1477   bp_size = target_info->shadow_len;
1478
1479   if (bp_addr + bp_size <= memaddr)
1480     {
1481       /* The breakpoint is entirely before the chunk of memory we are
1482          reading.  */
1483       return;
1484     }
1485
1486   if (bp_addr >= memaddr + len)
1487     {
1488       /* The breakpoint is entirely after the chunk of memory we are
1489          reading.  */
1490       return;
1491     }
1492
1493   /* Offset within shadow_contents.  */
1494   if (bp_addr < memaddr)
1495     {
1496       /* Only copy the second part of the breakpoint.  */
1497       bp_size -= memaddr - bp_addr;
1498       bptoffset = memaddr - bp_addr;
1499       bp_addr = memaddr;
1500     }
1501
1502   if (bp_addr + bp_size > memaddr + len)
1503     {
1504       /* Only copy the first part of the breakpoint.  */
1505       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1506     }
1507
1508   if (readbuf != NULL)
1509     {
1510       /* Verify that the readbuf buffer does not overlap with the
1511          shadow_contents buffer.  */
1512       gdb_assert (target_info->shadow_contents >= readbuf + len
1513                   || readbuf >= (target_info->shadow_contents
1514                                  + target_info->shadow_len));
1515
1516       /* Update the read buffer with this inserted breakpoint's
1517          shadow.  */
1518       memcpy (readbuf + bp_addr - memaddr,
1519               target_info->shadow_contents + bptoffset, bp_size);
1520     }
1521   else
1522     {
1523       const unsigned char *bp;
1524       CORE_ADDR placed_address = target_info->placed_address;
1525       int placed_size = target_info->placed_size;
1526
1527       /* Update the shadow with what we want to write to memory.  */
1528       memcpy (target_info->shadow_contents + bptoffset,
1529               writebuf_org + bp_addr - memaddr, bp_size);
1530
1531       /* Determine appropriate breakpoint contents and size for this
1532          address.  */
1533       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1534
1535       /* Update the final write buffer with this inserted
1536          breakpoint's INSN.  */
1537       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1538     }
1539 }
1540
1541 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1542    by replacing any memory breakpoints with their shadowed contents.
1543
1544    If READBUF is not NULL, this buffer must not overlap with any of
1545    the breakpoint location's shadow_contents buffers.  Otherwise,
1546    a failed assertion internal error will be raised.
1547
1548    The range of shadowed area by each bp_location is:
1549      bl->address - bp_location_placed_address_before_address_max
1550      up to bl->address + bp_location_shadow_len_after_address_max
1551    The range we were requested to resolve shadows for is:
1552      memaddr ... memaddr + len
1553    Thus the safe cutoff boundaries for performance optimization are
1554      memaddr + len <= (bl->address
1555                        - bp_location_placed_address_before_address_max)
1556    and:
1557      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1558
1559 void
1560 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1561                         const gdb_byte *writebuf_org,
1562                         ULONGEST memaddr, LONGEST len)
1563 {
1564   /* Left boundary, right boundary and median element of our binary
1565      search.  */
1566   unsigned bc_l, bc_r, bc;
1567   size_t i;
1568
1569   /* Find BC_L which is a leftmost element which may affect BUF
1570      content.  It is safe to report lower value but a failure to
1571      report higher one.  */
1572
1573   bc_l = 0;
1574   bc_r = bp_location_count;
1575   while (bc_l + 1 < bc_r)
1576     {
1577       struct bp_location *bl;
1578
1579       bc = (bc_l + bc_r) / 2;
1580       bl = bp_location[bc];
1581
1582       /* Check first BL->ADDRESS will not overflow due to the added
1583          constant.  Then advance the left boundary only if we are sure
1584          the BC element can in no way affect the BUF content (MEMADDR
1585          to MEMADDR + LEN range).
1586
1587          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1588          offset so that we cannot miss a breakpoint with its shadow
1589          range tail still reaching MEMADDR.  */
1590
1591       if ((bl->address + bp_location_shadow_len_after_address_max
1592            >= bl->address)
1593           && (bl->address + bp_location_shadow_len_after_address_max
1594               <= memaddr))
1595         bc_l = bc;
1596       else
1597         bc_r = bc;
1598     }
1599
1600   /* Due to the binary search above, we need to make sure we pick the
1601      first location that's at BC_L's address.  E.g., if there are
1602      multiple locations at the same address, BC_L may end up pointing
1603      at a duplicate location, and miss the "master"/"inserted"
1604      location.  Say, given locations L1, L2 and L3 at addresses A and
1605      B:
1606
1607       L1@A, L2@A, L3@B, ...
1608
1609      BC_L could end up pointing at location L2, while the "master"
1610      location could be L1.  Since the `loc->inserted' flag is only set
1611      on "master" locations, we'd forget to restore the shadow of L1
1612      and L2.  */
1613   while (bc_l > 0
1614          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1615     bc_l--;
1616
1617   /* Now do full processing of the found relevant range of elements.  */
1618
1619   for (bc = bc_l; bc < bp_location_count; bc++)
1620   {
1621     struct bp_location *bl = bp_location[bc];
1622     CORE_ADDR bp_addr = 0;
1623     int bp_size = 0;
1624     int bptoffset = 0;
1625
1626     /* bp_location array has BL->OWNER always non-NULL.  */
1627     if (bl->owner->type == bp_none)
1628       warning (_("reading through apparently deleted breakpoint #%d?"),
1629                bl->owner->number);
1630
1631     /* Performance optimization: any further element can no longer affect BUF
1632        content.  */
1633
1634     if (bl->address >= bp_location_placed_address_before_address_max
1635         && memaddr + len <= (bl->address
1636                              - bp_location_placed_address_before_address_max))
1637       break;
1638
1639     if (!bp_location_has_shadow (bl))
1640       continue;
1641
1642     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1643                                 memaddr, len, &bl->target_info, bl->gdbarch);
1644   }
1645
1646   /* Now process single-step breakpoints.  These are not found in the
1647      bp_location array.  */
1648   for (i = 0; i < 2; i++)
1649     {
1650       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1651
1652       if (bp_tgt != NULL)
1653         {
1654           struct gdbarch *gdbarch = single_step_gdbarch[i];
1655
1656           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1657                                       memaddr, len, bp_tgt, gdbarch);
1658         }
1659     }
1660 }
1661
1662 \f
1663
1664 /* Return true if BPT is either a software breakpoint or a hardware
1665    breakpoint.  */
1666
1667 int
1668 is_breakpoint (const struct breakpoint *bpt)
1669 {
1670   return (bpt->type == bp_breakpoint
1671           || bpt->type == bp_hardware_breakpoint
1672           || bpt->type == bp_dprintf);
1673 }
1674
1675 /* Return true if BPT is of any hardware watchpoint kind.  */
1676
1677 static int
1678 is_hardware_watchpoint (const struct breakpoint *bpt)
1679 {
1680   return (bpt->type == bp_hardware_watchpoint
1681           || bpt->type == bp_read_watchpoint
1682           || bpt->type == bp_access_watchpoint);
1683 }
1684
1685 /* Return true if BPT is of any watchpoint kind, hardware or
1686    software.  */
1687
1688 int
1689 is_watchpoint (const struct breakpoint *bpt)
1690 {
1691   return (is_hardware_watchpoint (bpt)
1692           || bpt->type == bp_watchpoint);
1693 }
1694
1695 /* Returns true if the current thread and its running state are safe
1696    to evaluate or update watchpoint B.  Watchpoints on local
1697    expressions need to be evaluated in the context of the thread that
1698    was current when the watchpoint was created, and, that thread needs
1699    to be stopped to be able to select the correct frame context.
1700    Watchpoints on global expressions can be evaluated on any thread,
1701    and in any state.  It is presently left to the target allowing
1702    memory accesses when threads are running.  */
1703
1704 static int
1705 watchpoint_in_thread_scope (struct watchpoint *b)
1706 {
1707   return (b->base.pspace == current_program_space
1708           && (ptid_equal (b->watchpoint_thread, null_ptid)
1709               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1710                   && !is_executing (inferior_ptid))));
1711 }
1712
1713 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1714    associated bp_watchpoint_scope breakpoint.  */
1715
1716 static void
1717 watchpoint_del_at_next_stop (struct watchpoint *w)
1718 {
1719   struct breakpoint *b = &w->base;
1720
1721   if (b->related_breakpoint != b)
1722     {
1723       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1724       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1725       b->related_breakpoint->disposition = disp_del_at_next_stop;
1726       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1727       b->related_breakpoint = b;
1728     }
1729   b->disposition = disp_del_at_next_stop;
1730 }
1731
1732 /* Extract a bitfield value from value VAL using the bit parameters contained in
1733    watchpoint W.  */
1734
1735 static struct value *
1736 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1737 {
1738   struct value *bit_val;
1739
1740   if (val == NULL)
1741     return NULL;
1742
1743   bit_val = allocate_value (value_type (val));
1744
1745   unpack_value_bitfield (bit_val,
1746                          w->val_bitpos,
1747                          w->val_bitsize,
1748                          value_contents_for_printing (val),
1749                          value_offset (val),
1750                          val);
1751
1752   return bit_val;
1753 }
1754
1755 /* Assuming that B is a watchpoint:
1756    - Reparse watchpoint expression, if REPARSE is non-zero
1757    - Evaluate expression and store the result in B->val
1758    - Evaluate the condition if there is one, and store the result
1759      in b->loc->cond.
1760    - Update the list of values that must be watched in B->loc.
1761
1762    If the watchpoint disposition is disp_del_at_next_stop, then do
1763    nothing.  If this is local watchpoint that is out of scope, delete
1764    it.
1765
1766    Even with `set breakpoint always-inserted on' the watchpoints are
1767    removed + inserted on each stop here.  Normal breakpoints must
1768    never be removed because they might be missed by a running thread
1769    when debugging in non-stop mode.  On the other hand, hardware
1770    watchpoints (is_hardware_watchpoint; processed here) are specific
1771    to each LWP since they are stored in each LWP's hardware debug
1772    registers.  Therefore, such LWP must be stopped first in order to
1773    be able to modify its hardware watchpoints.
1774
1775    Hardware watchpoints must be reset exactly once after being
1776    presented to the user.  It cannot be done sooner, because it would
1777    reset the data used to present the watchpoint hit to the user.  And
1778    it must not be done later because it could display the same single
1779    watchpoint hit during multiple GDB stops.  Note that the latter is
1780    relevant only to the hardware watchpoint types bp_read_watchpoint
1781    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1782    not user-visible - its hit is suppressed if the memory content has
1783    not changed.
1784
1785    The following constraints influence the location where we can reset
1786    hardware watchpoints:
1787
1788    * target_stopped_by_watchpoint and target_stopped_data_address are
1789      called several times when GDB stops.
1790
1791    [linux] 
1792    * Multiple hardware watchpoints can be hit at the same time,
1793      causing GDB to stop.  GDB only presents one hardware watchpoint
1794      hit at a time as the reason for stopping, and all the other hits
1795      are presented later, one after the other, each time the user
1796      requests the execution to be resumed.  Execution is not resumed
1797      for the threads still having pending hit event stored in
1798      LWP_INFO->STATUS.  While the watchpoint is already removed from
1799      the inferior on the first stop the thread hit event is kept being
1800      reported from its cached value by linux_nat_stopped_data_address
1801      until the real thread resume happens after the watchpoint gets
1802      presented and thus its LWP_INFO->STATUS gets reset.
1803
1804    Therefore the hardware watchpoint hit can get safely reset on the
1805    watchpoint removal from inferior.  */
1806
1807 static void
1808 update_watchpoint (struct watchpoint *b, int reparse)
1809 {
1810   int within_current_scope;
1811   struct frame_id saved_frame_id;
1812   int frame_saved;
1813
1814   /* If this is a local watchpoint, we only want to check if the
1815      watchpoint frame is in scope if the current thread is the thread
1816      that was used to create the watchpoint.  */
1817   if (!watchpoint_in_thread_scope (b))
1818     return;
1819
1820   if (b->base.disposition == disp_del_at_next_stop)
1821     return;
1822  
1823   frame_saved = 0;
1824
1825   /* Determine if the watchpoint is within scope.  */
1826   if (b->exp_valid_block == NULL)
1827     within_current_scope = 1;
1828   else
1829     {
1830       struct frame_info *fi = get_current_frame ();
1831       struct gdbarch *frame_arch = get_frame_arch (fi);
1832       CORE_ADDR frame_pc = get_frame_pc (fi);
1833
1834       /* If we're in a function epilogue, unwinding may not work
1835          properly, so do not attempt to recreate locations at this
1836          point.  See similar comments in watchpoint_check.  */
1837       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1838         return;
1839
1840       /* Save the current frame's ID so we can restore it after
1841          evaluating the watchpoint expression on its own frame.  */
1842       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1843          took a frame parameter, so that we didn't have to change the
1844          selected frame.  */
1845       frame_saved = 1;
1846       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1847
1848       fi = frame_find_by_id (b->watchpoint_frame);
1849       within_current_scope = (fi != NULL);
1850       if (within_current_scope)
1851         select_frame (fi);
1852     }
1853
1854   /* We don't free locations.  They are stored in the bp_location array
1855      and update_global_location_list will eventually delete them and
1856      remove breakpoints if needed.  */
1857   b->base.loc = NULL;
1858
1859   if (within_current_scope && reparse)
1860     {
1861       const char *s;
1862
1863       if (b->exp)
1864         {
1865           xfree (b->exp);
1866           b->exp = NULL;
1867         }
1868       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1869       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1870       /* If the meaning of expression itself changed, the old value is
1871          no longer relevant.  We don't want to report a watchpoint hit
1872          to the user when the old value and the new value may actually
1873          be completely different objects.  */
1874       value_free (b->val);
1875       b->val = NULL;
1876       b->val_valid = 0;
1877
1878       /* Note that unlike with breakpoints, the watchpoint's condition
1879          expression is stored in the breakpoint object, not in the
1880          locations (re)created below.  */
1881       if (b->base.cond_string != NULL)
1882         {
1883           if (b->cond_exp != NULL)
1884             {
1885               xfree (b->cond_exp);
1886               b->cond_exp = NULL;
1887             }
1888
1889           s = b->base.cond_string;
1890           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1891         }
1892     }
1893
1894   /* If we failed to parse the expression, for example because
1895      it refers to a global variable in a not-yet-loaded shared library,
1896      don't try to insert watchpoint.  We don't automatically delete
1897      such watchpoint, though, since failure to parse expression
1898      is different from out-of-scope watchpoint.  */
1899   if (!target_has_execution)
1900     {
1901       /* Without execution, memory can't change.  No use to try and
1902          set watchpoint locations.  The watchpoint will be reset when
1903          the target gains execution, through breakpoint_re_set.  */
1904       if (!can_use_hw_watchpoints)
1905         {
1906           if (b->base.ops->works_in_software_mode (&b->base))
1907             b->base.type = bp_watchpoint;
1908           else
1909             error (_("Can't set read/access watchpoint when "
1910                      "hardware watchpoints are disabled."));
1911         }
1912     }
1913   else if (within_current_scope && b->exp)
1914     {
1915       int pc = 0;
1916       struct value *val_chain, *v, *result, *next;
1917       struct program_space *frame_pspace;
1918
1919       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1920
1921       /* Avoid setting b->val if it's already set.  The meaning of
1922          b->val is 'the last value' user saw, and we should update
1923          it only if we reported that last value to user.  As it
1924          happens, the code that reports it updates b->val directly.
1925          We don't keep track of the memory value for masked
1926          watchpoints.  */
1927       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1928         {
1929           if (b->val_bitsize != 0)
1930             {
1931               v = extract_bitfield_from_watchpoint_value (b, v);
1932               if (v != NULL)
1933                 release_value (v);
1934             }
1935           b->val = v;
1936           b->val_valid = 1;
1937         }
1938
1939       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1940
1941       /* Look at each value on the value chain.  */
1942       for (v = val_chain; v; v = value_next (v))
1943         {
1944           /* If it's a memory location, and GDB actually needed
1945              its contents to evaluate the expression, then we
1946              must watch it.  If the first value returned is
1947              still lazy, that means an error occurred reading it;
1948              watch it anyway in case it becomes readable.  */
1949           if (VALUE_LVAL (v) == lval_memory
1950               && (v == val_chain || ! value_lazy (v)))
1951             {
1952               struct type *vtype = check_typedef (value_type (v));
1953
1954               /* We only watch structs and arrays if user asked
1955                  for it explicitly, never if they just happen to
1956                  appear in the middle of some value chain.  */
1957               if (v == result
1958                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1959                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1960                 {
1961                   CORE_ADDR addr;
1962                   int type;
1963                   struct bp_location *loc, **tmp;
1964                   int bitpos = 0, bitsize = 0;
1965
1966                   if (value_bitsize (v) != 0)
1967                     {
1968                       /* Extract the bit parameters out from the bitfield
1969                          sub-expression.  */
1970                       bitpos = value_bitpos (v);
1971                       bitsize = value_bitsize (v);
1972                     }
1973                   else if (v == result && b->val_bitsize != 0)
1974                     {
1975                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1976                         lvalue whose bit parameters are saved in the fields
1977                         VAL_BITPOS and VAL_BITSIZE.  */
1978                       bitpos = b->val_bitpos;
1979                       bitsize = b->val_bitsize;
1980                     }
1981
1982                   addr = value_address (v);
1983                   if (bitsize != 0)
1984                     {
1985                       /* Skip the bytes that don't contain the bitfield.  */
1986                       addr += bitpos / 8;
1987                     }
1988
1989                   type = hw_write;
1990                   if (b->base.type == bp_read_watchpoint)
1991                     type = hw_read;
1992                   else if (b->base.type == bp_access_watchpoint)
1993                     type = hw_access;
1994
1995                   loc = allocate_bp_location (&b->base);
1996                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1997                     ;
1998                   *tmp = loc;
1999                   loc->gdbarch = get_type_arch (value_type (v));
2000
2001                   loc->pspace = frame_pspace;
2002                   loc->address = addr;
2003
2004                   if (bitsize != 0)
2005                     {
2006                       /* Just cover the bytes that make up the bitfield.  */
2007                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2008                     }
2009                   else
2010                     loc->length = TYPE_LENGTH (value_type (v));
2011
2012                   loc->watchpoint_type = type;
2013                 }
2014             }
2015         }
2016
2017       /* Change the type of breakpoint between hardware assisted or
2018          an ordinary watchpoint depending on the hardware support
2019          and free hardware slots.  REPARSE is set when the inferior
2020          is started.  */
2021       if (reparse)
2022         {
2023           int reg_cnt;
2024           enum bp_loc_type loc_type;
2025           struct bp_location *bl;
2026
2027           reg_cnt = can_use_hardware_watchpoint (val_chain);
2028
2029           if (reg_cnt)
2030             {
2031               int i, target_resources_ok, other_type_used;
2032               enum bptype type;
2033
2034               /* Use an exact watchpoint when there's only one memory region to be
2035                  watched, and only one debug register is needed to watch it.  */
2036               b->exact = target_exact_watchpoints && reg_cnt == 1;
2037
2038               /* We need to determine how many resources are already
2039                  used for all other hardware watchpoints plus this one
2040                  to see if we still have enough resources to also fit
2041                  this watchpoint in as well.  */
2042
2043               /* If this is a software watchpoint, we try to turn it
2044                  to a hardware one -- count resources as if B was of
2045                  hardware watchpoint type.  */
2046               type = b->base.type;
2047               if (type == bp_watchpoint)
2048                 type = bp_hardware_watchpoint;
2049
2050               /* This watchpoint may or may not have been placed on
2051                  the list yet at this point (it won't be in the list
2052                  if we're trying to create it for the first time,
2053                  through watch_command), so always account for it
2054                  manually.  */
2055
2056               /* Count resources used by all watchpoints except B.  */
2057               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2058
2059               /* Add in the resources needed for B.  */
2060               i += hw_watchpoint_use_count (&b->base);
2061
2062               target_resources_ok
2063                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2064               if (target_resources_ok <= 0)
2065                 {
2066                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2067
2068                   if (target_resources_ok == 0 && !sw_mode)
2069                     error (_("Target does not support this type of "
2070                              "hardware watchpoint."));
2071                   else if (target_resources_ok < 0 && !sw_mode)
2072                     error (_("There are not enough available hardware "
2073                              "resources for this watchpoint."));
2074
2075                   /* Downgrade to software watchpoint.  */
2076                   b->base.type = bp_watchpoint;
2077                 }
2078               else
2079                 {
2080                   /* If this was a software watchpoint, we've just
2081                      found we have enough resources to turn it to a
2082                      hardware watchpoint.  Otherwise, this is a
2083                      nop.  */
2084                   b->base.type = type;
2085                 }
2086             }
2087           else if (!b->base.ops->works_in_software_mode (&b->base))
2088             {
2089               if (!can_use_hw_watchpoints)
2090                 error (_("Can't set read/access watchpoint when "
2091                          "hardware watchpoints are disabled."));
2092               else
2093                 error (_("Expression cannot be implemented with "
2094                          "read/access watchpoint."));
2095             }
2096           else
2097             b->base.type = bp_watchpoint;
2098
2099           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2100                       : bp_loc_hardware_watchpoint);
2101           for (bl = b->base.loc; bl; bl = bl->next)
2102             bl->loc_type = loc_type;
2103         }
2104
2105       for (v = val_chain; v; v = next)
2106         {
2107           next = value_next (v);
2108           if (v != b->val)
2109             value_free (v);
2110         }
2111
2112       /* If a software watchpoint is not watching any memory, then the
2113          above left it without any location set up.  But,
2114          bpstat_stop_status requires a location to be able to report
2115          stops, so make sure there's at least a dummy one.  */
2116       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2117         {
2118           struct breakpoint *base = &b->base;
2119           base->loc = allocate_bp_location (base);
2120           base->loc->pspace = frame_pspace;
2121           base->loc->address = -1;
2122           base->loc->length = -1;
2123           base->loc->watchpoint_type = -1;
2124         }
2125     }
2126   else if (!within_current_scope)
2127     {
2128       printf_filtered (_("\
2129 Watchpoint %d deleted because the program has left the block\n\
2130 in which its expression is valid.\n"),
2131                        b->base.number);
2132       watchpoint_del_at_next_stop (b);
2133     }
2134
2135   /* Restore the selected frame.  */
2136   if (frame_saved)
2137     select_frame (frame_find_by_id (saved_frame_id));
2138 }
2139
2140
2141 /* Returns 1 iff breakpoint location should be
2142    inserted in the inferior.  We don't differentiate the type of BL's owner
2143    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2144    breakpoint_ops is not defined, because in insert_bp_location,
2145    tracepoint's insert_location will not be called.  */
2146 static int
2147 should_be_inserted (struct bp_location *bl)
2148 {
2149   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2150     return 0;
2151
2152   if (bl->owner->disposition == disp_del_at_next_stop)
2153     return 0;
2154
2155   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2156     return 0;
2157
2158   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2159     return 0;
2160
2161   /* This is set for example, when we're attached to the parent of a
2162      vfork, and have detached from the child.  The child is running
2163      free, and we expect it to do an exec or exit, at which point the
2164      OS makes the parent schedulable again (and the target reports
2165      that the vfork is done).  Until the child is done with the shared
2166      memory region, do not insert breakpoints in the parent, otherwise
2167      the child could still trip on the parent's breakpoints.  Since
2168      the parent is blocked anyway, it won't miss any breakpoint.  */
2169   if (bl->pspace->breakpoints_not_allowed)
2170     return 0;
2171
2172   /* Don't insert a breakpoint if we're trying to step past its
2173      location.  */
2174   if ((bl->loc_type == bp_loc_software_breakpoint
2175        || bl->loc_type == bp_loc_hardware_breakpoint)
2176       && stepping_past_instruction_at (bl->pspace->aspace,
2177                                        bl->address))
2178     return 0;
2179
2180   return 1;
2181 }
2182
2183 /* Same as should_be_inserted but does the check assuming
2184    that the location is not duplicated.  */
2185
2186 static int
2187 unduplicated_should_be_inserted (struct bp_location *bl)
2188 {
2189   int result;
2190   const int save_duplicate = bl->duplicate;
2191
2192   bl->duplicate = 0;
2193   result = should_be_inserted (bl);
2194   bl->duplicate = save_duplicate;
2195   return result;
2196 }
2197
2198 /* Parses a conditional described by an expression COND into an
2199    agent expression bytecode suitable for evaluation
2200    by the bytecode interpreter.  Return NULL if there was
2201    any error during parsing.  */
2202
2203 static struct agent_expr *
2204 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2205 {
2206   struct agent_expr *aexpr = NULL;
2207   volatile struct gdb_exception ex;
2208
2209   if (!cond)
2210     return NULL;
2211
2212   /* We don't want to stop processing, so catch any errors
2213      that may show up.  */
2214   TRY_CATCH (ex, RETURN_MASK_ERROR)
2215     {
2216       aexpr = gen_eval_for_expr (scope, cond);
2217     }
2218
2219   if (ex.reason < 0)
2220     {
2221       /* If we got here, it means the condition could not be parsed to a valid
2222          bytecode expression and thus can't be evaluated on the target's side.
2223          It's no use iterating through the conditions.  */
2224       return NULL;
2225     }
2226
2227   /* We have a valid agent expression.  */
2228   return aexpr;
2229 }
2230
2231 /* Based on location BL, create a list of breakpoint conditions to be
2232    passed on to the target.  If we have duplicated locations with different
2233    conditions, we will add such conditions to the list.  The idea is that the
2234    target will evaluate the list of conditions and will only notify GDB when
2235    one of them is true.  */
2236
2237 static void
2238 build_target_condition_list (struct bp_location *bl)
2239 {
2240   struct bp_location **locp = NULL, **loc2p;
2241   int null_condition_or_parse_error = 0;
2242   int modified = bl->needs_update;
2243   struct bp_location *loc;
2244
2245   /* Release conditions left over from a previous insert.  */
2246   VEC_free (agent_expr_p, bl->target_info.conditions);
2247
2248   /* This is only meaningful if the target is
2249      evaluating conditions and if the user has
2250      opted for condition evaluation on the target's
2251      side.  */
2252   if (gdb_evaluates_breakpoint_condition_p ()
2253       || !target_supports_evaluation_of_breakpoint_conditions ())
2254     return;
2255
2256   /* Do a first pass to check for locations with no assigned
2257      conditions or conditions that fail to parse to a valid agent expression
2258      bytecode.  If any of these happen, then it's no use to send conditions
2259      to the target since this location will always trigger and generate a
2260      response back to GDB.  */
2261   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2262     {
2263       loc = (*loc2p);
2264       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2265         {
2266           if (modified)
2267             {
2268               struct agent_expr *aexpr;
2269
2270               /* Re-parse the conditions since something changed.  In that
2271                  case we already freed the condition bytecodes (see
2272                  force_breakpoint_reinsertion).  We just
2273                  need to parse the condition to bytecodes again.  */
2274               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2275               loc->cond_bytecode = aexpr;
2276
2277               /* Check if we managed to parse the conditional expression
2278                  correctly.  If not, we will not send this condition
2279                  to the target.  */
2280               if (aexpr)
2281                 continue;
2282             }
2283
2284           /* If we have a NULL bytecode expression, it means something
2285              went wrong or we have a null condition expression.  */
2286           if (!loc->cond_bytecode)
2287             {
2288               null_condition_or_parse_error = 1;
2289               break;
2290             }
2291         }
2292     }
2293
2294   /* If any of these happened, it means we will have to evaluate the conditions
2295      for the location's address on gdb's side.  It is no use keeping bytecodes
2296      for all the other duplicate locations, thus we free all of them here.
2297
2298      This is so we have a finer control over which locations' conditions are
2299      being evaluated by GDB or the remote stub.  */
2300   if (null_condition_or_parse_error)
2301     {
2302       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2303         {
2304           loc = (*loc2p);
2305           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2306             {
2307               /* Only go as far as the first NULL bytecode is
2308                  located.  */
2309               if (!loc->cond_bytecode)
2310                 return;
2311
2312               free_agent_expr (loc->cond_bytecode);
2313               loc->cond_bytecode = NULL;
2314             }
2315         }
2316     }
2317
2318   /* No NULL conditions or failed bytecode generation.  Build a condition list
2319      for this location's address.  */
2320   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2321     {
2322       loc = (*loc2p);
2323       if (loc->cond
2324           && is_breakpoint (loc->owner)
2325           && loc->pspace->num == bl->pspace->num
2326           && loc->owner->enable_state == bp_enabled
2327           && loc->enabled)
2328         /* Add the condition to the vector.  This will be used later to send the
2329            conditions to the target.  */
2330         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2331                        loc->cond_bytecode);
2332     }
2333
2334   return;
2335 }
2336
2337 /* Parses a command described by string CMD into an agent expression
2338    bytecode suitable for evaluation by the bytecode interpreter.
2339    Return NULL if there was any error during parsing.  */
2340
2341 static struct agent_expr *
2342 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2343 {
2344   struct cleanup *old_cleanups = 0;
2345   struct expression *expr, **argvec;
2346   struct agent_expr *aexpr = NULL;
2347   volatile struct gdb_exception ex;
2348   const char *cmdrest;
2349   const char *format_start, *format_end;
2350   struct format_piece *fpieces;
2351   int nargs;
2352   struct gdbarch *gdbarch = get_current_arch ();
2353
2354   if (!cmd)
2355     return NULL;
2356
2357   cmdrest = cmd;
2358
2359   if (*cmdrest == ',')
2360     ++cmdrest;
2361   cmdrest = skip_spaces_const (cmdrest);
2362
2363   if (*cmdrest++ != '"')
2364     error (_("No format string following the location"));
2365
2366   format_start = cmdrest;
2367
2368   fpieces = parse_format_string (&cmdrest);
2369
2370   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2371
2372   format_end = cmdrest;
2373
2374   if (*cmdrest++ != '"')
2375     error (_("Bad format string, non-terminated '\"'."));
2376   
2377   cmdrest = skip_spaces_const (cmdrest);
2378
2379   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2380     error (_("Invalid argument syntax"));
2381
2382   if (*cmdrest == ',')
2383     cmdrest++;
2384   cmdrest = skip_spaces_const (cmdrest);
2385
2386   /* For each argument, make an expression.  */
2387
2388   argvec = (struct expression **) alloca (strlen (cmd)
2389                                          * sizeof (struct expression *));
2390
2391   nargs = 0;
2392   while (*cmdrest != '\0')
2393     {
2394       const char *cmd1;
2395
2396       cmd1 = cmdrest;
2397       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2398       argvec[nargs++] = expr;
2399       cmdrest = cmd1;
2400       if (*cmdrest == ',')
2401         ++cmdrest;
2402     }
2403
2404   /* We don't want to stop processing, so catch any errors
2405      that may show up.  */
2406   TRY_CATCH (ex, RETURN_MASK_ERROR)
2407     {
2408       aexpr = gen_printf (scope, gdbarch, 0, 0,
2409                           format_start, format_end - format_start,
2410                           fpieces, nargs, argvec);
2411     }
2412
2413   do_cleanups (old_cleanups);
2414
2415   if (ex.reason < 0)
2416     {
2417       /* If we got here, it means the command could not be parsed to a valid
2418          bytecode expression and thus can't be evaluated on the target's side.
2419          It's no use iterating through the other commands.  */
2420       return NULL;
2421     }
2422
2423   /* We have a valid agent expression, return it.  */
2424   return aexpr;
2425 }
2426
2427 /* Based on location BL, create a list of breakpoint commands to be
2428    passed on to the target.  If we have duplicated locations with
2429    different commands, we will add any such to the list.  */
2430
2431 static void
2432 build_target_command_list (struct bp_location *bl)
2433 {
2434   struct bp_location **locp = NULL, **loc2p;
2435   int null_command_or_parse_error = 0;
2436   int modified = bl->needs_update;
2437   struct bp_location *loc;
2438
2439   /* Release commands left over from a previous insert.  */
2440   VEC_free (agent_expr_p, bl->target_info.tcommands);
2441
2442   if (!target_can_run_breakpoint_commands ())
2443     return;
2444
2445   /* For now, limit to agent-style dprintf breakpoints.  */
2446   if (dprintf_style != dprintf_style_agent)
2447     return;
2448
2449   /* For now, if we have any duplicate location that isn't a dprintf,
2450      don't install the target-side commands, as that would make the
2451      breakpoint not be reported to the core, and we'd lose
2452      control.  */
2453   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2454     {
2455       loc = (*loc2p);
2456       if (is_breakpoint (loc->owner)
2457           && loc->pspace->num == bl->pspace->num
2458           && loc->owner->type != bp_dprintf)
2459         return;
2460     }
2461
2462   /* Do a first pass to check for locations with no assigned
2463      conditions or conditions that fail to parse to a valid agent expression
2464      bytecode.  If any of these happen, then it's no use to send conditions
2465      to the target since this location will always trigger and generate a
2466      response back to GDB.  */
2467   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2468     {
2469       loc = (*loc2p);
2470       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2471         {
2472           if (modified)
2473             {
2474               struct agent_expr *aexpr;
2475
2476               /* Re-parse the commands since something changed.  In that
2477                  case we already freed the command bytecodes (see
2478                  force_breakpoint_reinsertion).  We just
2479                  need to parse the command to bytecodes again.  */
2480               aexpr = parse_cmd_to_aexpr (bl->address,
2481                                           loc->owner->extra_string);
2482               loc->cmd_bytecode = aexpr;
2483
2484               if (!aexpr)
2485                 continue;
2486             }
2487
2488           /* If we have a NULL bytecode expression, it means something
2489              went wrong or we have a null command expression.  */
2490           if (!loc->cmd_bytecode)
2491             {
2492               null_command_or_parse_error = 1;
2493               break;
2494             }
2495         }
2496     }
2497
2498   /* If anything failed, then we're not doing target-side commands,
2499      and so clean up.  */
2500   if (null_command_or_parse_error)
2501     {
2502       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2503         {
2504           loc = (*loc2p);
2505           if (is_breakpoint (loc->owner)
2506               && loc->pspace->num == bl->pspace->num)
2507             {
2508               /* Only go as far as the first NULL bytecode is
2509                  located.  */
2510               if (loc->cmd_bytecode == NULL)
2511                 return;
2512
2513               free_agent_expr (loc->cmd_bytecode);
2514               loc->cmd_bytecode = NULL;
2515             }
2516         }
2517     }
2518
2519   /* No NULL commands or failed bytecode generation.  Build a command list
2520      for this location's address.  */
2521   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2522     {
2523       loc = (*loc2p);
2524       if (loc->owner->extra_string
2525           && is_breakpoint (loc->owner)
2526           && loc->pspace->num == bl->pspace->num
2527           && loc->owner->enable_state == bp_enabled
2528           && loc->enabled)
2529         /* Add the command to the vector.  This will be used later
2530            to send the commands to the target.  */
2531         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2532                        loc->cmd_bytecode);
2533     }
2534
2535   bl->target_info.persist = 0;
2536   /* Maybe flag this location as persistent.  */
2537   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2538     bl->target_info.persist = 1;
2539 }
2540
2541 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2542    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2543    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2544    Returns 0 for success, 1 if the bp_location type is not supported or
2545    -1 for failure.
2546
2547    NOTE drow/2003-09-09: This routine could be broken down to an
2548    object-style method for each breakpoint or catchpoint type.  */
2549 static int
2550 insert_bp_location (struct bp_location *bl,
2551                     struct ui_file *tmp_error_stream,
2552                     int *disabled_breaks,
2553                     int *hw_breakpoint_error,
2554                     int *hw_bp_error_explained_already)
2555 {
2556   enum errors bp_err = GDB_NO_ERROR;
2557   const char *bp_err_message = NULL;
2558   volatile struct gdb_exception e;
2559
2560   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2561     return 0;
2562
2563   /* Note we don't initialize bl->target_info, as that wipes out
2564      the breakpoint location's shadow_contents if the breakpoint
2565      is still inserted at that location.  This in turn breaks
2566      target_read_memory which depends on these buffers when
2567      a memory read is requested at the breakpoint location:
2568      Once the target_info has been wiped, we fail to see that
2569      we have a breakpoint inserted at that address and thus
2570      read the breakpoint instead of returning the data saved in
2571      the breakpoint location's shadow contents.  */
2572   bl->target_info.placed_address = bl->address;
2573   bl->target_info.placed_address_space = bl->pspace->aspace;
2574   bl->target_info.length = bl->length;
2575
2576   /* When working with target-side conditions, we must pass all the conditions
2577      for the same breakpoint address down to the target since GDB will not
2578      insert those locations.  With a list of breakpoint conditions, the target
2579      can decide when to stop and notify GDB.  */
2580
2581   if (is_breakpoint (bl->owner))
2582     {
2583       build_target_condition_list (bl);
2584       build_target_command_list (bl);
2585       /* Reset the modification marker.  */
2586       bl->needs_update = 0;
2587     }
2588
2589   if (bl->loc_type == bp_loc_software_breakpoint
2590       || bl->loc_type == bp_loc_hardware_breakpoint)
2591     {
2592       if (bl->owner->type != bp_hardware_breakpoint)
2593         {
2594           /* If the explicitly specified breakpoint type
2595              is not hardware breakpoint, check the memory map to see
2596              if the breakpoint address is in read only memory or not.
2597
2598              Two important cases are:
2599              - location type is not hardware breakpoint, memory
2600              is readonly.  We change the type of the location to
2601              hardware breakpoint.
2602              - location type is hardware breakpoint, memory is
2603              read-write.  This means we've previously made the
2604              location hardware one, but then the memory map changed,
2605              so we undo.
2606              
2607              When breakpoints are removed, remove_breakpoints will use
2608              location types we've just set here, the only possible
2609              problem is that memory map has changed during running
2610              program, but it's not going to work anyway with current
2611              gdb.  */
2612           struct mem_region *mr 
2613             = lookup_mem_region (bl->target_info.placed_address);
2614           
2615           if (mr)
2616             {
2617               if (automatic_hardware_breakpoints)
2618                 {
2619                   enum bp_loc_type new_type;
2620                   
2621                   if (mr->attrib.mode != MEM_RW)
2622                     new_type = bp_loc_hardware_breakpoint;
2623                   else 
2624                     new_type = bp_loc_software_breakpoint;
2625                   
2626                   if (new_type != bl->loc_type)
2627                     {
2628                       static int said = 0;
2629
2630                       bl->loc_type = new_type;
2631                       if (!said)
2632                         {
2633                           fprintf_filtered (gdb_stdout,
2634                                             _("Note: automatically using "
2635                                               "hardware breakpoints for "
2636                                               "read-only addresses.\n"));
2637                           said = 1;
2638                         }
2639                     }
2640                 }
2641               else if (bl->loc_type == bp_loc_software_breakpoint
2642                        && mr->attrib.mode != MEM_RW)        
2643                 warning (_("cannot set software breakpoint "
2644                            "at readonly address %s"),
2645                          paddress (bl->gdbarch, bl->address));
2646             }
2647         }
2648         
2649       /* First check to see if we have to handle an overlay.  */
2650       if (overlay_debugging == ovly_off
2651           || bl->section == NULL
2652           || !(section_is_overlay (bl->section)))
2653         {
2654           /* No overlay handling: just set the breakpoint.  */
2655           TRY_CATCH (e, RETURN_MASK_ALL)
2656             {
2657               int val;
2658
2659               val = bl->owner->ops->insert_location (bl);
2660               if (val)
2661                 bp_err = GENERIC_ERROR;
2662             }
2663           if (e.reason < 0)
2664             {
2665               bp_err = e.error;
2666               bp_err_message = e.message;
2667             }
2668         }
2669       else
2670         {
2671           /* This breakpoint is in an overlay section.
2672              Shall we set a breakpoint at the LMA?  */
2673           if (!overlay_events_enabled)
2674             {
2675               /* Yes -- overlay event support is not active, 
2676                  so we must try to set a breakpoint at the LMA.
2677                  This will not work for a hardware breakpoint.  */
2678               if (bl->loc_type == bp_loc_hardware_breakpoint)
2679                 warning (_("hardware breakpoint %d not supported in overlay!"),
2680                          bl->owner->number);
2681               else
2682                 {
2683                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2684                                                              bl->section);
2685                   /* Set a software (trap) breakpoint at the LMA.  */
2686                   bl->overlay_target_info = bl->target_info;
2687                   bl->overlay_target_info.placed_address = addr;
2688
2689                   /* No overlay handling: just set the breakpoint.  */
2690                   TRY_CATCH (e, RETURN_MASK_ALL)
2691                     {
2692                       int val;
2693
2694                       val = target_insert_breakpoint (bl->gdbarch,
2695                                                       &bl->overlay_target_info);
2696                       if (val)
2697                         bp_err = GENERIC_ERROR;
2698                     }
2699                   if (e.reason < 0)
2700                     {
2701                       bp_err = e.error;
2702                       bp_err_message = e.message;
2703                     }
2704
2705                   if (bp_err != GDB_NO_ERROR)
2706                     fprintf_unfiltered (tmp_error_stream,
2707                                         "Overlay breakpoint %d "
2708                                         "failed: in ROM?\n",
2709                                         bl->owner->number);
2710                 }
2711             }
2712           /* Shall we set a breakpoint at the VMA? */
2713           if (section_is_mapped (bl->section))
2714             {
2715               /* Yes.  This overlay section is mapped into memory.  */
2716               TRY_CATCH (e, RETURN_MASK_ALL)
2717                 {
2718                   int val;
2719
2720                   val = bl->owner->ops->insert_location (bl);
2721                   if (val)
2722                     bp_err = GENERIC_ERROR;
2723                 }
2724               if (e.reason < 0)
2725                 {
2726                   bp_err = e.error;
2727                   bp_err_message = e.message;
2728                 }
2729             }
2730           else
2731             {
2732               /* No.  This breakpoint will not be inserted.  
2733                  No error, but do not mark the bp as 'inserted'.  */
2734               return 0;
2735             }
2736         }
2737
2738       if (bp_err != GDB_NO_ERROR)
2739         {
2740           /* Can't set the breakpoint.  */
2741
2742           /* In some cases, we might not be able to insert a
2743              breakpoint in a shared library that has already been
2744              removed, but we have not yet processed the shlib unload
2745              event.  Unfortunately, some targets that implement
2746              breakpoint insertion themselves can't tell why the
2747              breakpoint insertion failed (e.g., the remote target
2748              doesn't define error codes), so we must treat generic
2749              errors as memory errors.  */
2750           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2751               && bl->loc_type == bp_loc_software_breakpoint
2752               && (solib_name_from_address (bl->pspace, bl->address)
2753                   || shared_objfile_contains_address_p (bl->pspace,
2754                                                         bl->address)))
2755             {
2756               /* See also: disable_breakpoints_in_shlibs.  */
2757               bl->shlib_disabled = 1;
2758               observer_notify_breakpoint_modified (bl->owner);
2759               if (!*disabled_breaks)
2760                 {
2761                   fprintf_unfiltered (tmp_error_stream, 
2762                                       "Cannot insert breakpoint %d.\n", 
2763                                       bl->owner->number);
2764                   fprintf_unfiltered (tmp_error_stream, 
2765                                       "Temporarily disabling shared "
2766                                       "library breakpoints:\n");
2767                 }
2768               *disabled_breaks = 1;
2769               fprintf_unfiltered (tmp_error_stream,
2770                                   "breakpoint #%d\n", bl->owner->number);
2771               return 0;
2772             }
2773           else
2774             {
2775               if (bl->loc_type == bp_loc_hardware_breakpoint)
2776                 {
2777                   *hw_breakpoint_error = 1;
2778                   *hw_bp_error_explained_already = bp_err_message != NULL;
2779                   fprintf_unfiltered (tmp_error_stream,
2780                                       "Cannot insert hardware breakpoint %d%s",
2781                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2782                   if (bp_err_message != NULL)
2783                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2784                 }
2785               else
2786                 {
2787                   if (bp_err_message == NULL)
2788                     {
2789                       char *message
2790                         = memory_error_message (TARGET_XFER_E_IO,
2791                                                 bl->gdbarch, bl->address);
2792                       struct cleanup *old_chain = make_cleanup (xfree, message);
2793
2794                       fprintf_unfiltered (tmp_error_stream,
2795                                           "Cannot insert breakpoint %d.\n"
2796                                           "%s\n",
2797                                           bl->owner->number, message);
2798                       do_cleanups (old_chain);
2799                     }
2800                   else
2801                     {
2802                       fprintf_unfiltered (tmp_error_stream,
2803                                           "Cannot insert breakpoint %d: %s\n",
2804                                           bl->owner->number,
2805                                           bp_err_message);
2806                     }
2807                 }
2808               return 1;
2809
2810             }
2811         }
2812       else
2813         bl->inserted = 1;
2814
2815       return 0;
2816     }
2817
2818   else if (bl->loc_type == bp_loc_hardware_watchpoint
2819            /* NOTE drow/2003-09-08: This state only exists for removing
2820               watchpoints.  It's not clear that it's necessary...  */
2821            && bl->owner->disposition != disp_del_at_next_stop)
2822     {
2823       int val;
2824
2825       gdb_assert (bl->owner->ops != NULL
2826                   && bl->owner->ops->insert_location != NULL);
2827
2828       val = bl->owner->ops->insert_location (bl);
2829
2830       /* If trying to set a read-watchpoint, and it turns out it's not
2831          supported, try emulating one with an access watchpoint.  */
2832       if (val == 1 && bl->watchpoint_type == hw_read)
2833         {
2834           struct bp_location *loc, **loc_temp;
2835
2836           /* But don't try to insert it, if there's already another
2837              hw_access location that would be considered a duplicate
2838              of this one.  */
2839           ALL_BP_LOCATIONS (loc, loc_temp)
2840             if (loc != bl
2841                 && loc->watchpoint_type == hw_access
2842                 && watchpoint_locations_match (bl, loc))
2843               {
2844                 bl->duplicate = 1;
2845                 bl->inserted = 1;
2846                 bl->target_info = loc->target_info;
2847                 bl->watchpoint_type = hw_access;
2848                 val = 0;
2849                 break;
2850               }
2851
2852           if (val == 1)
2853             {
2854               bl->watchpoint_type = hw_access;
2855               val = bl->owner->ops->insert_location (bl);
2856
2857               if (val)
2858                 /* Back to the original value.  */
2859                 bl->watchpoint_type = hw_read;
2860             }
2861         }
2862
2863       bl->inserted = (val == 0);
2864     }
2865
2866   else if (bl->owner->type == bp_catchpoint)
2867     {
2868       int val;
2869
2870       gdb_assert (bl->owner->ops != NULL
2871                   && bl->owner->ops->insert_location != NULL);
2872
2873       val = bl->owner->ops->insert_location (bl);
2874       if (val)
2875         {
2876           bl->owner->enable_state = bp_disabled;
2877
2878           if (val == 1)
2879             warning (_("\
2880 Error inserting catchpoint %d: Your system does not support this type\n\
2881 of catchpoint."), bl->owner->number);
2882           else
2883             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2884         }
2885
2886       bl->inserted = (val == 0);
2887
2888       /* We've already printed an error message if there was a problem
2889          inserting this catchpoint, and we've disabled the catchpoint,
2890          so just return success.  */
2891       return 0;
2892     }
2893
2894   return 0;
2895 }
2896
2897 /* This function is called when program space PSPACE is about to be
2898    deleted.  It takes care of updating breakpoints to not reference
2899    PSPACE anymore.  */
2900
2901 void
2902 breakpoint_program_space_exit (struct program_space *pspace)
2903 {
2904   struct breakpoint *b, *b_temp;
2905   struct bp_location *loc, **loc_temp;
2906
2907   /* Remove any breakpoint that was set through this program space.  */
2908   ALL_BREAKPOINTS_SAFE (b, b_temp)
2909     {
2910       if (b->pspace == pspace)
2911         delete_breakpoint (b);
2912     }
2913
2914   /* Breakpoints set through other program spaces could have locations
2915      bound to PSPACE as well.  Remove those.  */
2916   ALL_BP_LOCATIONS (loc, loc_temp)
2917     {
2918       struct bp_location *tmp;
2919
2920       if (loc->pspace == pspace)
2921         {
2922           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2923           if (loc->owner->loc == loc)
2924             loc->owner->loc = loc->next;
2925           else
2926             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2927               if (tmp->next == loc)
2928                 {
2929                   tmp->next = loc->next;
2930                   break;
2931                 }
2932         }
2933     }
2934
2935   /* Now update the global location list to permanently delete the
2936      removed locations above.  */
2937   update_global_location_list (UGLL_DONT_INSERT);
2938 }
2939
2940 /* Make sure all breakpoints are inserted in inferior.
2941    Throws exception on any error.
2942    A breakpoint that is already inserted won't be inserted
2943    again, so calling this function twice is safe.  */
2944 void
2945 insert_breakpoints (void)
2946 {
2947   struct breakpoint *bpt;
2948
2949   ALL_BREAKPOINTS (bpt)
2950     if (is_hardware_watchpoint (bpt))
2951       {
2952         struct watchpoint *w = (struct watchpoint *) bpt;
2953
2954         update_watchpoint (w, 0 /* don't reparse.  */);
2955       }
2956
2957   update_global_location_list (UGLL_MAY_INSERT);
2958
2959   /* update_global_location_list does not insert breakpoints when
2960      always_inserted_mode is not enabled.  Explicitly insert them
2961      now.  */
2962   if (!breakpoints_always_inserted_mode ())
2963     insert_breakpoint_locations ();
2964 }
2965
2966 /* Invoke CALLBACK for each of bp_location.  */
2967
2968 void
2969 iterate_over_bp_locations (walk_bp_location_callback callback)
2970 {
2971   struct bp_location *loc, **loc_tmp;
2972
2973   ALL_BP_LOCATIONS (loc, loc_tmp)
2974     {
2975       callback (loc, NULL);
2976     }
2977 }
2978
2979 /* This is used when we need to synch breakpoint conditions between GDB and the
2980    target.  It is the case with deleting and disabling of breakpoints when using
2981    always-inserted mode.  */
2982
2983 static void
2984 update_inserted_breakpoint_locations (void)
2985 {
2986   struct bp_location *bl, **blp_tmp;
2987   int error_flag = 0;
2988   int val = 0;
2989   int disabled_breaks = 0;
2990   int hw_breakpoint_error = 0;
2991   int hw_bp_details_reported = 0;
2992
2993   struct ui_file *tmp_error_stream = mem_fileopen ();
2994   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2995
2996   /* Explicitly mark the warning -- this will only be printed if
2997      there was an error.  */
2998   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2999
3000   save_current_space_and_thread ();
3001
3002   ALL_BP_LOCATIONS (bl, blp_tmp)
3003     {
3004       /* We only want to update software breakpoints and hardware
3005          breakpoints.  */
3006       if (!is_breakpoint (bl->owner))
3007         continue;
3008
3009       /* We only want to update locations that are already inserted
3010          and need updating.  This is to avoid unwanted insertion during
3011          deletion of breakpoints.  */
3012       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3013         continue;
3014
3015       switch_to_program_space_and_thread (bl->pspace);
3016
3017       /* For targets that support global breakpoints, there's no need
3018          to select an inferior to insert breakpoint to.  In fact, even
3019          if we aren't attached to any process yet, we should still
3020          insert breakpoints.  */
3021       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3022           && ptid_equal (inferior_ptid, null_ptid))
3023         continue;
3024
3025       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3026                                     &hw_breakpoint_error, &hw_bp_details_reported);
3027       if (val)
3028         error_flag = val;
3029     }
3030
3031   if (error_flag)
3032     {
3033       target_terminal_ours_for_output ();
3034       error_stream (tmp_error_stream);
3035     }
3036
3037   do_cleanups (cleanups);
3038 }
3039
3040 /* Used when starting or continuing the program.  */
3041
3042 static void
3043 insert_breakpoint_locations (void)
3044 {
3045   struct breakpoint *bpt;
3046   struct bp_location *bl, **blp_tmp;
3047   int error_flag = 0;
3048   int val = 0;
3049   int disabled_breaks = 0;
3050   int hw_breakpoint_error = 0;
3051   int hw_bp_error_explained_already = 0;
3052
3053   struct ui_file *tmp_error_stream = mem_fileopen ();
3054   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3055   
3056   /* Explicitly mark the warning -- this will only be printed if
3057      there was an error.  */
3058   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3059
3060   save_current_space_and_thread ();
3061
3062   ALL_BP_LOCATIONS (bl, blp_tmp)
3063     {
3064       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3065         continue;
3066
3067       /* There is no point inserting thread-specific breakpoints if
3068          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3069          has BL->OWNER always non-NULL.  */
3070       if (bl->owner->thread != -1
3071           && !valid_thread_id (bl->owner->thread))
3072         continue;
3073
3074       switch_to_program_space_and_thread (bl->pspace);
3075
3076       /* For targets that support global breakpoints, there's no need
3077          to select an inferior to insert breakpoint to.  In fact, even
3078          if we aren't attached to any process yet, we should still
3079          insert breakpoints.  */
3080       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3081           && ptid_equal (inferior_ptid, null_ptid))
3082         continue;
3083
3084       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3085                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3086       if (val)
3087         error_flag = val;
3088     }
3089
3090   /* If we failed to insert all locations of a watchpoint, remove
3091      them, as half-inserted watchpoint is of limited use.  */
3092   ALL_BREAKPOINTS (bpt)  
3093     {
3094       int some_failed = 0;
3095       struct bp_location *loc;
3096
3097       if (!is_hardware_watchpoint (bpt))
3098         continue;
3099
3100       if (!breakpoint_enabled (bpt))
3101         continue;
3102
3103       if (bpt->disposition == disp_del_at_next_stop)
3104         continue;
3105       
3106       for (loc = bpt->loc; loc; loc = loc->next)
3107         if (!loc->inserted && should_be_inserted (loc))
3108           {
3109             some_failed = 1;
3110             break;
3111           }
3112       if (some_failed)
3113         {
3114           for (loc = bpt->loc; loc; loc = loc->next)
3115             if (loc->inserted)
3116               remove_breakpoint (loc, mark_uninserted);
3117
3118           hw_breakpoint_error = 1;
3119           fprintf_unfiltered (tmp_error_stream,
3120                               "Could not insert hardware watchpoint %d.\n", 
3121                               bpt->number);
3122           error_flag = -1;
3123         }
3124     }
3125
3126   if (error_flag)
3127     {
3128       /* If a hardware breakpoint or watchpoint was inserted, add a
3129          message about possibly exhausted resources.  */
3130       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3131         {
3132           fprintf_unfiltered (tmp_error_stream, 
3133                               "Could not insert hardware breakpoints:\n\
3134 You may have requested too many hardware breakpoints/watchpoints.\n");
3135         }
3136       target_terminal_ours_for_output ();
3137       error_stream (tmp_error_stream);
3138     }
3139
3140   do_cleanups (cleanups);
3141 }
3142
3143 /* Used when the program stops.
3144    Returns zero if successful, or non-zero if there was a problem
3145    removing a breakpoint location.  */
3146
3147 int
3148 remove_breakpoints (void)
3149 {
3150   struct bp_location *bl, **blp_tmp;
3151   int val = 0;
3152
3153   ALL_BP_LOCATIONS (bl, blp_tmp)
3154   {
3155     if (bl->inserted && !is_tracepoint (bl->owner))
3156       val |= remove_breakpoint (bl, mark_uninserted);
3157   }
3158   return val;
3159 }
3160
3161 /* When a thread exits, remove breakpoints that are related to
3162    that thread.  */
3163
3164 static void
3165 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3166 {
3167   struct breakpoint *b, *b_tmp;
3168
3169   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3170     {
3171       if (b->thread == tp->num && user_breakpoint_p (b))
3172         {
3173           b->disposition = disp_del_at_next_stop;
3174
3175           printf_filtered (_("\
3176 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3177                           b->number, tp->num);
3178
3179           /* Hide it from the user.  */
3180           b->number = 0;
3181        }
3182     }
3183 }
3184
3185 /* Remove breakpoints of process PID.  */
3186
3187 int
3188 remove_breakpoints_pid (int pid)
3189 {
3190   struct bp_location *bl, **blp_tmp;
3191   int val;
3192   struct inferior *inf = find_inferior_pid (pid);
3193
3194   ALL_BP_LOCATIONS (bl, blp_tmp)
3195   {
3196     if (bl->pspace != inf->pspace)
3197       continue;
3198
3199     if (bl->owner->type == bp_dprintf)
3200       continue;
3201
3202     if (bl->inserted)
3203       {
3204         val = remove_breakpoint (bl, mark_uninserted);
3205         if (val != 0)
3206           return val;
3207       }
3208   }
3209   return 0;
3210 }
3211
3212 int
3213 reattach_breakpoints (int pid)
3214 {
3215   struct cleanup *old_chain;
3216   struct bp_location *bl, **blp_tmp;
3217   int val;
3218   struct ui_file *tmp_error_stream;
3219   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3220   struct inferior *inf;
3221   struct thread_info *tp;
3222
3223   tp = any_live_thread_of_process (pid);
3224   if (tp == NULL)
3225     return 1;
3226
3227   inf = find_inferior_pid (pid);
3228   old_chain = save_inferior_ptid ();
3229
3230   inferior_ptid = tp->ptid;
3231
3232   tmp_error_stream = mem_fileopen ();
3233   make_cleanup_ui_file_delete (tmp_error_stream);
3234
3235   ALL_BP_LOCATIONS (bl, blp_tmp)
3236   {
3237     if (bl->pspace != inf->pspace)
3238       continue;
3239
3240     if (bl->inserted)
3241       {
3242         bl->inserted = 0;
3243         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3244         if (val != 0)
3245           {
3246             do_cleanups (old_chain);
3247             return val;
3248           }
3249       }
3250   }
3251   do_cleanups (old_chain);
3252   return 0;
3253 }
3254
3255 static int internal_breakpoint_number = -1;
3256
3257 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3258    If INTERNAL is non-zero, the breakpoint number will be populated
3259    from internal_breakpoint_number and that variable decremented.
3260    Otherwise the breakpoint number will be populated from
3261    breakpoint_count and that value incremented.  Internal breakpoints
3262    do not set the internal var bpnum.  */
3263 static void
3264 set_breakpoint_number (int internal, struct breakpoint *b)
3265 {
3266   if (internal)
3267     b->number = internal_breakpoint_number--;
3268   else
3269     {
3270       set_breakpoint_count (breakpoint_count + 1);
3271       b->number = breakpoint_count;
3272     }
3273 }
3274
3275 static struct breakpoint *
3276 create_internal_breakpoint (struct gdbarch *gdbarch,
3277                             CORE_ADDR address, enum bptype type,
3278                             const struct breakpoint_ops *ops)
3279 {
3280   struct symtab_and_line sal;
3281   struct breakpoint *b;
3282
3283   init_sal (&sal);              /* Initialize to zeroes.  */
3284
3285   sal.pc = address;
3286   sal.section = find_pc_overlay (sal.pc);
3287   sal.pspace = current_program_space;
3288
3289   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3290   b->number = internal_breakpoint_number--;
3291   b->disposition = disp_donttouch;
3292
3293   return b;
3294 }
3295
3296 static const char *const longjmp_names[] =
3297   {
3298     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3299   };
3300 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3301
3302 /* Per-objfile data private to breakpoint.c.  */
3303 struct breakpoint_objfile_data
3304 {
3305   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3306   struct bound_minimal_symbol overlay_msym;
3307
3308   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3309   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3310
3311   /* True if we have looked for longjmp probes.  */
3312   int longjmp_searched;
3313
3314   /* SystemTap probe points for longjmp (if any).  */
3315   VEC (probe_p) *longjmp_probes;
3316
3317   /* Minimal symbol for "std::terminate()" (if any).  */
3318   struct bound_minimal_symbol terminate_msym;
3319
3320   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3321   struct bound_minimal_symbol exception_msym;
3322
3323   /* True if we have looked for exception probes.  */
3324   int exception_searched;
3325
3326   /* SystemTap probe points for unwinding (if any).  */
3327   VEC (probe_p) *exception_probes;
3328 };
3329
3330 static const struct objfile_data *breakpoint_objfile_key;
3331
3332 /* Minimal symbol not found sentinel.  */
3333 static struct minimal_symbol msym_not_found;
3334
3335 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3336
3337 static int
3338 msym_not_found_p (const struct minimal_symbol *msym)
3339 {
3340   return msym == &msym_not_found;
3341 }
3342
3343 /* Return per-objfile data needed by breakpoint.c.
3344    Allocate the data if necessary.  */
3345
3346 static struct breakpoint_objfile_data *
3347 get_breakpoint_objfile_data (struct objfile *objfile)
3348 {
3349   struct breakpoint_objfile_data *bp_objfile_data;
3350
3351   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3352   if (bp_objfile_data == NULL)
3353     {
3354       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3355                                        sizeof (*bp_objfile_data));
3356
3357       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3358       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3359     }
3360   return bp_objfile_data;
3361 }
3362
3363 static void
3364 free_breakpoint_probes (struct objfile *obj, void *data)
3365 {
3366   struct breakpoint_objfile_data *bp_objfile_data = data;
3367
3368   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3369   VEC_free (probe_p, bp_objfile_data->exception_probes);
3370 }
3371
3372 static void
3373 create_overlay_event_breakpoint (void)
3374 {
3375   struct objfile *objfile;
3376   const char *const func_name = "_ovly_debug_event";
3377
3378   ALL_OBJFILES (objfile)
3379     {
3380       struct breakpoint *b;
3381       struct breakpoint_objfile_data *bp_objfile_data;
3382       CORE_ADDR addr;
3383
3384       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3385
3386       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3387         continue;
3388
3389       if (bp_objfile_data->overlay_msym.minsym == NULL)
3390         {
3391           struct bound_minimal_symbol m;
3392
3393           m = lookup_minimal_symbol_text (func_name, objfile);
3394           if (m.minsym == NULL)
3395             {
3396               /* Avoid future lookups in this objfile.  */
3397               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3398               continue;
3399             }
3400           bp_objfile_data->overlay_msym = m;
3401         }
3402
3403       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3404       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3405                                       bp_overlay_event,
3406                                       &internal_breakpoint_ops);
3407       b->addr_string = xstrdup (func_name);
3408
3409       if (overlay_debugging == ovly_auto)
3410         {
3411           b->enable_state = bp_enabled;
3412           overlay_events_enabled = 1;
3413         }
3414       else
3415        {
3416          b->enable_state = bp_disabled;
3417          overlay_events_enabled = 0;
3418        }
3419     }
3420   update_global_location_list (UGLL_MAY_INSERT);
3421 }
3422
3423 static void
3424 create_longjmp_master_breakpoint (void)
3425 {
3426   struct program_space *pspace;
3427   struct cleanup *old_chain;
3428
3429   old_chain = save_current_program_space ();
3430
3431   ALL_PSPACES (pspace)
3432   {
3433     struct objfile *objfile;
3434
3435     set_current_program_space (pspace);
3436
3437     ALL_OBJFILES (objfile)
3438     {
3439       int i;
3440       struct gdbarch *gdbarch;
3441       struct breakpoint_objfile_data *bp_objfile_data;
3442
3443       gdbarch = get_objfile_arch (objfile);
3444
3445       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3446
3447       if (!bp_objfile_data->longjmp_searched)
3448         {
3449           VEC (probe_p) *ret;
3450
3451           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3452           if (ret != NULL)
3453             {
3454               /* We are only interested in checking one element.  */
3455               struct probe *p = VEC_index (probe_p, ret, 0);
3456
3457               if (!can_evaluate_probe_arguments (p))
3458                 {
3459                   /* We cannot use the probe interface here, because it does
3460                      not know how to evaluate arguments.  */
3461                   VEC_free (probe_p, ret);
3462                   ret = NULL;
3463                 }
3464             }
3465           bp_objfile_data->longjmp_probes = ret;
3466           bp_objfile_data->longjmp_searched = 1;
3467         }
3468
3469       if (bp_objfile_data->longjmp_probes != NULL)
3470         {
3471           int i;
3472           struct probe *probe;
3473           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3474
3475           for (i = 0;
3476                VEC_iterate (probe_p,
3477                             bp_objfile_data->longjmp_probes,
3478                             i, probe);
3479                ++i)
3480             {
3481               struct breakpoint *b;
3482
3483               b = create_internal_breakpoint (gdbarch,
3484                                               get_probe_address (probe,
3485                                                                  objfile),
3486                                               bp_longjmp_master,
3487                                               &internal_breakpoint_ops);
3488               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3489               b->enable_state = bp_disabled;
3490             }
3491
3492           continue;
3493         }
3494
3495       if (!gdbarch_get_longjmp_target_p (gdbarch))
3496         continue;
3497
3498       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3499         {
3500           struct breakpoint *b;
3501           const char *func_name;
3502           CORE_ADDR addr;
3503
3504           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3505             continue;
3506
3507           func_name = longjmp_names[i];
3508           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3509             {
3510               struct bound_minimal_symbol m;
3511
3512               m = lookup_minimal_symbol_text (func_name, objfile);
3513               if (m.minsym == NULL)
3514                 {
3515                   /* Prevent future lookups in this objfile.  */
3516                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3517                   continue;
3518                 }
3519               bp_objfile_data->longjmp_msym[i] = m;
3520             }
3521
3522           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3523           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3524                                           &internal_breakpoint_ops);
3525           b->addr_string = xstrdup (func_name);
3526           b->enable_state = bp_disabled;
3527         }
3528     }
3529   }
3530   update_global_location_list (UGLL_MAY_INSERT);
3531
3532   do_cleanups (old_chain);
3533 }
3534
3535 /* Create a master std::terminate breakpoint.  */
3536 static void
3537 create_std_terminate_master_breakpoint (void)
3538 {
3539   struct program_space *pspace;
3540   struct cleanup *old_chain;
3541   const char *const func_name = "std::terminate()";
3542
3543   old_chain = save_current_program_space ();
3544
3545   ALL_PSPACES (pspace)
3546   {
3547     struct objfile *objfile;
3548     CORE_ADDR addr;
3549
3550     set_current_program_space (pspace);
3551
3552     ALL_OBJFILES (objfile)
3553     {
3554       struct breakpoint *b;
3555       struct breakpoint_objfile_data *bp_objfile_data;
3556
3557       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3558
3559       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3560         continue;
3561
3562       if (bp_objfile_data->terminate_msym.minsym == NULL)
3563         {
3564           struct bound_minimal_symbol m;
3565
3566           m = lookup_minimal_symbol (func_name, NULL, objfile);
3567           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3568                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3569             {
3570               /* Prevent future lookups in this objfile.  */
3571               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3572               continue;
3573             }
3574           bp_objfile_data->terminate_msym = m;
3575         }
3576
3577       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3578       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3579                                       bp_std_terminate_master,
3580                                       &internal_breakpoint_ops);
3581       b->addr_string = xstrdup (func_name);
3582       b->enable_state = bp_disabled;
3583     }
3584   }
3585
3586   update_global_location_list (UGLL_MAY_INSERT);
3587
3588   do_cleanups (old_chain);
3589 }
3590
3591 /* Install a master breakpoint on the unwinder's debug hook.  */
3592
3593 static void
3594 create_exception_master_breakpoint (void)
3595 {
3596   struct objfile *objfile;
3597   const char *const func_name = "_Unwind_DebugHook";
3598
3599   ALL_OBJFILES (objfile)
3600     {
3601       struct breakpoint *b;
3602       struct gdbarch *gdbarch;
3603       struct breakpoint_objfile_data *bp_objfile_data;
3604       CORE_ADDR addr;
3605
3606       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3607
3608       /* We prefer the SystemTap probe point if it exists.  */
3609       if (!bp_objfile_data->exception_searched)
3610         {
3611           VEC (probe_p) *ret;
3612
3613           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3614
3615           if (ret != NULL)
3616             {
3617               /* We are only interested in checking one element.  */
3618               struct probe *p = VEC_index (probe_p, ret, 0);
3619
3620               if (!can_evaluate_probe_arguments (p))
3621                 {
3622                   /* We cannot use the probe interface here, because it does
3623                      not know how to evaluate arguments.  */
3624                   VEC_free (probe_p, ret);
3625                   ret = NULL;
3626                 }
3627             }
3628           bp_objfile_data->exception_probes = ret;
3629           bp_objfile_data->exception_searched = 1;
3630         }
3631
3632       if (bp_objfile_data->exception_probes != NULL)
3633         {
3634           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3635           int i;
3636           struct probe *probe;
3637
3638           for (i = 0;
3639                VEC_iterate (probe_p,
3640                             bp_objfile_data->exception_probes,
3641                             i, probe);
3642                ++i)
3643             {
3644               struct breakpoint *b;
3645
3646               b = create_internal_breakpoint (gdbarch,
3647                                               get_probe_address (probe,
3648                                                                  objfile),
3649                                               bp_exception_master,
3650                                               &internal_breakpoint_ops);
3651               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3652               b->enable_state = bp_disabled;
3653             }
3654
3655           continue;
3656         }
3657
3658       /* Otherwise, try the hook function.  */
3659
3660       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3661         continue;
3662
3663       gdbarch = get_objfile_arch (objfile);
3664
3665       if (bp_objfile_data->exception_msym.minsym == NULL)
3666         {
3667           struct bound_minimal_symbol debug_hook;
3668
3669           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3670           if (debug_hook.minsym == NULL)
3671             {
3672               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3673               continue;
3674             }
3675
3676           bp_objfile_data->exception_msym = debug_hook;
3677         }
3678
3679       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3680       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3681                                                  &current_target);
3682       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3683                                       &internal_breakpoint_ops);
3684       b->addr_string = xstrdup (func_name);
3685       b->enable_state = bp_disabled;
3686     }
3687
3688   update_global_location_list (UGLL_MAY_INSERT);
3689 }
3690
3691 void
3692 update_breakpoints_after_exec (void)
3693 {
3694   struct breakpoint *b, *b_tmp;
3695   struct bp_location *bploc, **bplocp_tmp;
3696
3697   /* We're about to delete breakpoints from GDB's lists.  If the
3698      INSERTED flag is true, GDB will try to lift the breakpoints by
3699      writing the breakpoints' "shadow contents" back into memory.  The
3700      "shadow contents" are NOT valid after an exec, so GDB should not
3701      do that.  Instead, the target is responsible from marking
3702      breakpoints out as soon as it detects an exec.  We don't do that
3703      here instead, because there may be other attempts to delete
3704      breakpoints after detecting an exec and before reaching here.  */
3705   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3706     if (bploc->pspace == current_program_space)
3707       gdb_assert (!bploc->inserted);
3708
3709   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3710   {
3711     if (b->pspace != current_program_space)
3712       continue;
3713
3714     /* Solib breakpoints must be explicitly reset after an exec().  */
3715     if (b->type == bp_shlib_event)
3716       {
3717         delete_breakpoint (b);
3718         continue;
3719       }
3720
3721     /* JIT breakpoints must be explicitly reset after an exec().  */
3722     if (b->type == bp_jit_event)
3723       {
3724         delete_breakpoint (b);
3725         continue;
3726       }
3727
3728     /* Thread event breakpoints must be set anew after an exec(),
3729        as must overlay event and longjmp master breakpoints.  */
3730     if (b->type == bp_thread_event || b->type == bp_overlay_event
3731         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3732         || b->type == bp_exception_master)
3733       {
3734         delete_breakpoint (b);
3735         continue;
3736       }
3737
3738     /* Step-resume breakpoints are meaningless after an exec().  */
3739     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3740       {
3741         delete_breakpoint (b);
3742         continue;
3743       }
3744
3745     /* Longjmp and longjmp-resume breakpoints are also meaningless
3746        after an exec.  */
3747     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3748         || b->type == bp_longjmp_call_dummy
3749         || b->type == bp_exception || b->type == bp_exception_resume)
3750       {
3751         delete_breakpoint (b);
3752         continue;
3753       }
3754
3755     if (b->type == bp_catchpoint)
3756       {
3757         /* For now, none of the bp_catchpoint breakpoints need to
3758            do anything at this point.  In the future, if some of
3759            the catchpoints need to something, we will need to add
3760            a new method, and call this method from here.  */
3761         continue;
3762       }
3763
3764     /* bp_finish is a special case.  The only way we ought to be able
3765        to see one of these when an exec() has happened, is if the user
3766        caught a vfork, and then said "finish".  Ordinarily a finish just
3767        carries them to the call-site of the current callee, by setting
3768        a temporary bp there and resuming.  But in this case, the finish
3769        will carry them entirely through the vfork & exec.
3770
3771        We don't want to allow a bp_finish to remain inserted now.  But
3772        we can't safely delete it, 'cause finish_command has a handle to
3773        the bp on a bpstat, and will later want to delete it.  There's a
3774        chance (and I've seen it happen) that if we delete the bp_finish
3775        here, that its storage will get reused by the time finish_command
3776        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3777        We really must allow finish_command to delete a bp_finish.
3778
3779        In the absence of a general solution for the "how do we know
3780        it's safe to delete something others may have handles to?"
3781        problem, what we'll do here is just uninsert the bp_finish, and
3782        let finish_command delete it.
3783
3784        (We know the bp_finish is "doomed" in the sense that it's
3785        momentary, and will be deleted as soon as finish_command sees
3786        the inferior stopped.  So it doesn't matter that the bp's
3787        address is probably bogus in the new a.out, unlike e.g., the
3788        solib breakpoints.)  */
3789
3790     if (b->type == bp_finish)
3791       {
3792         continue;
3793       }
3794
3795     /* Without a symbolic address, we have little hope of the
3796        pre-exec() address meaning the same thing in the post-exec()
3797        a.out.  */
3798     if (b->addr_string == NULL)
3799       {
3800         delete_breakpoint (b);
3801         continue;
3802       }
3803   }
3804   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3805   create_overlay_event_breakpoint ();
3806   create_longjmp_master_breakpoint ();
3807   create_std_terminate_master_breakpoint ();
3808   create_exception_master_breakpoint ();
3809 }
3810
3811 int
3812 detach_breakpoints (ptid_t ptid)
3813 {
3814   struct bp_location *bl, **blp_tmp;
3815   int val = 0;
3816   struct cleanup *old_chain = save_inferior_ptid ();
3817   struct inferior *inf = current_inferior ();
3818
3819   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3820     error (_("Cannot detach breakpoints of inferior_ptid"));
3821
3822   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3823   inferior_ptid = ptid;
3824   ALL_BP_LOCATIONS (bl, blp_tmp)
3825   {
3826     if (bl->pspace != inf->pspace)
3827       continue;
3828
3829     /* This function must physically remove breakpoints locations
3830        from the specified ptid, without modifying the breakpoint
3831        package's state.  Locations of type bp_loc_other are only
3832        maintained at GDB side.  So, there is no need to remove
3833        these bp_loc_other locations.  Moreover, removing these
3834        would modify the breakpoint package's state.  */
3835     if (bl->loc_type == bp_loc_other)
3836       continue;
3837
3838     if (bl->inserted)
3839       val |= remove_breakpoint_1 (bl, mark_inserted);
3840   }
3841
3842   /* Detach single-step breakpoints as well.  */
3843   detach_single_step_breakpoints ();
3844
3845   do_cleanups (old_chain);
3846   return val;
3847 }
3848
3849 /* Remove the breakpoint location BL from the current address space.
3850    Note that this is used to detach breakpoints from a child fork.
3851    When we get here, the child isn't in the inferior list, and neither
3852    do we have objects to represent its address space --- we should
3853    *not* look at bl->pspace->aspace here.  */
3854
3855 static int
3856 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3857 {
3858   int val;
3859
3860   /* BL is never in moribund_locations by our callers.  */
3861   gdb_assert (bl->owner != NULL);
3862
3863   if (bl->owner->enable_state == bp_permanent)
3864     /* Permanent breakpoints cannot be inserted or removed.  */
3865     return 0;
3866
3867   /* The type of none suggests that owner is actually deleted.
3868      This should not ever happen.  */
3869   gdb_assert (bl->owner->type != bp_none);
3870
3871   if (bl->loc_type == bp_loc_software_breakpoint
3872       || bl->loc_type == bp_loc_hardware_breakpoint)
3873     {
3874       /* "Normal" instruction breakpoint: either the standard
3875          trap-instruction bp (bp_breakpoint), or a
3876          bp_hardware_breakpoint.  */
3877
3878       /* First check to see if we have to handle an overlay.  */
3879       if (overlay_debugging == ovly_off
3880           || bl->section == NULL
3881           || !(section_is_overlay (bl->section)))
3882         {
3883           /* No overlay handling: just remove the breakpoint.  */
3884
3885           /* If we're trying to uninsert a memory breakpoint that we
3886              know is set in a dynamic object that is marked
3887              shlib_disabled, then either the dynamic object was
3888              removed with "remove-symbol-file" or with
3889              "nosharedlibrary".  In the former case, we don't know
3890              whether another dynamic object might have loaded over the
3891              breakpoint's address -- the user might well let us know
3892              about it next with add-symbol-file (the whole point of
3893              add-symbol-file is letting the user manually maintain a
3894              list of dynamically loaded objects).  If we have the
3895              breakpoint's shadow memory, that is, this is a software
3896              breakpoint managed by GDB, check whether the breakpoint
3897              is still inserted in memory, to avoid overwriting wrong
3898              code with stale saved shadow contents.  Note that HW
3899              breakpoints don't have shadow memory, as they're
3900              implemented using a mechanism that is not dependent on
3901              being able to modify the target's memory, and as such
3902              they should always be removed.  */
3903           if (bl->shlib_disabled
3904               && bl->target_info.shadow_len != 0
3905               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3906             val = 0;
3907           else
3908             val = bl->owner->ops->remove_location (bl);
3909         }
3910       else
3911         {
3912           /* This breakpoint is in an overlay section.
3913              Did we set a breakpoint at the LMA?  */
3914           if (!overlay_events_enabled)
3915               {
3916                 /* Yes -- overlay event support is not active, so we
3917                    should have set a breakpoint at the LMA.  Remove it.  
3918                 */
3919                 /* Ignore any failures: if the LMA is in ROM, we will
3920                    have already warned when we failed to insert it.  */
3921                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3922                   target_remove_hw_breakpoint (bl->gdbarch,
3923                                                &bl->overlay_target_info);
3924                 else
3925                   target_remove_breakpoint (bl->gdbarch,
3926                                             &bl->overlay_target_info);
3927               }
3928           /* Did we set a breakpoint at the VMA? 
3929              If so, we will have marked the breakpoint 'inserted'.  */
3930           if (bl->inserted)
3931             {
3932               /* Yes -- remove it.  Previously we did not bother to
3933                  remove the breakpoint if the section had been
3934                  unmapped, but let's not rely on that being safe.  We
3935                  don't know what the overlay manager might do.  */
3936
3937               /* However, we should remove *software* breakpoints only
3938                  if the section is still mapped, or else we overwrite
3939                  wrong code with the saved shadow contents.  */
3940               if (bl->loc_type == bp_loc_hardware_breakpoint
3941                   || section_is_mapped (bl->section))
3942                 val = bl->owner->ops->remove_location (bl);
3943               else
3944                 val = 0;
3945             }
3946           else
3947             {
3948               /* No -- not inserted, so no need to remove.  No error.  */
3949               val = 0;
3950             }
3951         }
3952
3953       /* In some cases, we might not be able to remove a breakpoint in
3954          a shared library that has already been removed, but we have
3955          not yet processed the shlib unload event.  Similarly for an
3956          unloaded add-symbol-file object - the user might not yet have
3957          had the chance to remove-symbol-file it.  shlib_disabled will
3958          be set if the library/object has already been removed, but
3959          the breakpoint hasn't been uninserted yet, e.g., after
3960          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3961          always-inserted mode.  */
3962       if (val
3963           && (bl->loc_type == bp_loc_software_breakpoint
3964               && (bl->shlib_disabled
3965                   || solib_name_from_address (bl->pspace, bl->address)
3966                   || shared_objfile_contains_address_p (bl->pspace,
3967                                                         bl->address))))
3968         val = 0;
3969
3970       if (val)
3971         return val;
3972       bl->inserted = (is == mark_inserted);
3973     }
3974   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3975     {
3976       gdb_assert (bl->owner->ops != NULL
3977                   && bl->owner->ops->remove_location != NULL);
3978
3979       bl->inserted = (is == mark_inserted);
3980       bl->owner->ops->remove_location (bl);
3981
3982       /* Failure to remove any of the hardware watchpoints comes here.  */
3983       if ((is == mark_uninserted) && (bl->inserted))
3984         warning (_("Could not remove hardware watchpoint %d."),
3985                  bl->owner->number);
3986     }
3987   else if (bl->owner->type == bp_catchpoint
3988            && breakpoint_enabled (bl->owner)
3989            && !bl->duplicate)
3990     {
3991       gdb_assert (bl->owner->ops != NULL
3992                   && bl->owner->ops->remove_location != NULL);
3993
3994       val = bl->owner->ops->remove_location (bl);
3995       if (val)
3996         return val;
3997
3998       bl->inserted = (is == mark_inserted);
3999     }
4000
4001   return 0;
4002 }
4003
4004 static int
4005 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4006 {
4007   int ret;
4008   struct cleanup *old_chain;
4009
4010   /* BL is never in moribund_locations by our callers.  */
4011   gdb_assert (bl->owner != NULL);
4012
4013   if (bl->owner->enable_state == bp_permanent)
4014     /* Permanent breakpoints cannot be inserted or removed.  */
4015     return 0;
4016
4017   /* The type of none suggests that owner is actually deleted.
4018      This should not ever happen.  */
4019   gdb_assert (bl->owner->type != bp_none);
4020
4021   old_chain = save_current_space_and_thread ();
4022
4023   switch_to_program_space_and_thread (bl->pspace);
4024
4025   ret = remove_breakpoint_1 (bl, is);
4026
4027   do_cleanups (old_chain);
4028   return ret;
4029 }
4030
4031 /* Clear the "inserted" flag in all breakpoints.  */
4032
4033 void
4034 mark_breakpoints_out (void)
4035 {
4036   struct bp_location *bl, **blp_tmp;
4037
4038   ALL_BP_LOCATIONS (bl, blp_tmp)
4039     if (bl->pspace == current_program_space)
4040       bl->inserted = 0;
4041 }
4042
4043 /* Clear the "inserted" flag in all breakpoints and delete any
4044    breakpoints which should go away between runs of the program.
4045
4046    Plus other such housekeeping that has to be done for breakpoints
4047    between runs.
4048
4049    Note: this function gets called at the end of a run (by
4050    generic_mourn_inferior) and when a run begins (by
4051    init_wait_for_inferior).  */
4052
4053
4054
4055 void
4056 breakpoint_init_inferior (enum inf_context context)
4057 {
4058   struct breakpoint *b, *b_tmp;
4059   struct bp_location *bl, **blp_tmp;
4060   int ix;
4061   struct program_space *pspace = current_program_space;
4062
4063   /* If breakpoint locations are shared across processes, then there's
4064      nothing to do.  */
4065   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4066     return;
4067
4068   ALL_BP_LOCATIONS (bl, blp_tmp)
4069   {
4070     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4071     if (bl->pspace == pspace
4072         && bl->owner->enable_state != bp_permanent)
4073       bl->inserted = 0;
4074   }
4075
4076   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4077   {
4078     if (b->loc && b->loc->pspace != pspace)
4079       continue;
4080
4081     switch (b->type)
4082       {
4083       case bp_call_dummy:
4084       case bp_longjmp_call_dummy:
4085
4086         /* If the call dummy breakpoint is at the entry point it will
4087            cause problems when the inferior is rerun, so we better get
4088            rid of it.  */
4089
4090       case bp_watchpoint_scope:
4091
4092         /* Also get rid of scope breakpoints.  */
4093
4094       case bp_shlib_event:
4095
4096         /* Also remove solib event breakpoints.  Their addresses may
4097            have changed since the last time we ran the program.
4098            Actually we may now be debugging against different target;
4099            and so the solib backend that installed this breakpoint may
4100            not be used in by the target.  E.g.,
4101
4102            (gdb) file prog-linux
4103            (gdb) run               # native linux target
4104            ...
4105            (gdb) kill
4106            (gdb) file prog-win.exe
4107            (gdb) tar rem :9999     # remote Windows gdbserver.
4108         */
4109
4110       case bp_step_resume:
4111
4112         /* Also remove step-resume breakpoints.  */
4113
4114         delete_breakpoint (b);
4115         break;
4116
4117       case bp_watchpoint:
4118       case bp_hardware_watchpoint:
4119       case bp_read_watchpoint:
4120       case bp_access_watchpoint:
4121         {
4122           struct watchpoint *w = (struct watchpoint *) b;
4123
4124           /* Likewise for watchpoints on local expressions.  */
4125           if (w->exp_valid_block != NULL)
4126             delete_breakpoint (b);
4127           else if (context == inf_starting)
4128             {
4129               /* Reset val field to force reread of starting value in
4130                  insert_breakpoints.  */
4131               if (w->val)
4132                 value_free (w->val);
4133               w->val = NULL;
4134               w->val_valid = 0;
4135           }
4136         }
4137         break;
4138       default:
4139         break;
4140       }
4141   }
4142
4143   /* Get rid of the moribund locations.  */
4144   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4145     decref_bp_location (&bl);
4146   VEC_free (bp_location_p, moribund_locations);
4147 }
4148
4149 /* These functions concern about actual breakpoints inserted in the
4150    target --- to e.g. check if we need to do decr_pc adjustment or if
4151    we need to hop over the bkpt --- so we check for address space
4152    match, not program space.  */
4153
4154 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4155    exists at PC.  It returns ordinary_breakpoint_here if it's an
4156    ordinary breakpoint, or permanent_breakpoint_here if it's a
4157    permanent breakpoint.
4158    - When continuing from a location with an ordinary breakpoint, we
4159      actually single step once before calling insert_breakpoints.
4160    - When continuing from a location with a permanent breakpoint, we
4161      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4162      the target, to advance the PC past the breakpoint.  */
4163
4164 enum breakpoint_here
4165 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4166 {
4167   struct bp_location *bl, **blp_tmp;
4168   int any_breakpoint_here = 0;
4169
4170   ALL_BP_LOCATIONS (bl, blp_tmp)
4171     {
4172       if (bl->loc_type != bp_loc_software_breakpoint
4173           && bl->loc_type != bp_loc_hardware_breakpoint)
4174         continue;
4175
4176       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4177       if ((breakpoint_enabled (bl->owner)
4178            || bl->owner->enable_state == bp_permanent)
4179           && breakpoint_location_address_match (bl, aspace, pc))
4180         {
4181           if (overlay_debugging 
4182               && section_is_overlay (bl->section)
4183               && !section_is_mapped (bl->section))
4184             continue;           /* unmapped overlay -- can't be a match */
4185           else if (bl->owner->enable_state == bp_permanent)
4186             return permanent_breakpoint_here;
4187           else
4188             any_breakpoint_here = 1;
4189         }
4190     }
4191
4192   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4193 }
4194
4195 /* Return true if there's a moribund breakpoint at PC.  */
4196
4197 int
4198 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4199 {
4200   struct bp_location *loc;
4201   int ix;
4202
4203   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4204     if (breakpoint_location_address_match (loc, aspace, pc))
4205       return 1;
4206
4207   return 0;
4208 }
4209
4210 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4211    inserted using regular breakpoint_chain / bp_location array
4212    mechanism.  This does not check for single-step breakpoints, which
4213    are inserted and removed using direct target manipulation.  */
4214
4215 int
4216 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4217                                     CORE_ADDR pc)
4218 {
4219   struct bp_location *bl, **blp_tmp;
4220
4221   ALL_BP_LOCATIONS (bl, blp_tmp)
4222     {
4223       if (bl->loc_type != bp_loc_software_breakpoint
4224           && bl->loc_type != bp_loc_hardware_breakpoint)
4225         continue;
4226
4227       if (bl->inserted
4228           && breakpoint_location_address_match (bl, aspace, pc))
4229         {
4230           if (overlay_debugging 
4231               && section_is_overlay (bl->section)
4232               && !section_is_mapped (bl->section))
4233             continue;           /* unmapped overlay -- can't be a match */
4234           else
4235             return 1;
4236         }
4237     }
4238   return 0;
4239 }
4240
4241 /* Returns non-zero iff there's either regular breakpoint
4242    or a single step breakpoint inserted at PC.  */
4243
4244 int
4245 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4246 {
4247   if (regular_breakpoint_inserted_here_p (aspace, pc))
4248     return 1;
4249
4250   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4251     return 1;
4252
4253   return 0;
4254 }
4255
4256 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4257    software breakpoint inserted at PC.  */
4258
4259 static struct bp_location *
4260 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4261                                                 CORE_ADDR pc)
4262 {
4263   struct bp_location *bl, **blp_tmp;
4264
4265   ALL_BP_LOCATIONS (bl, blp_tmp)
4266     {
4267       if (bl->loc_type != bp_loc_software_breakpoint)
4268         continue;
4269
4270       if (bl->inserted
4271           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4272                                        aspace, pc))
4273         {
4274           if (overlay_debugging 
4275               && section_is_overlay (bl->section)
4276               && !section_is_mapped (bl->section))
4277             continue;           /* unmapped overlay -- can't be a match */
4278           else
4279             return bl;
4280         }
4281     }
4282
4283   return NULL;
4284 }
4285
4286 /* This function returns non-zero iff there is a software breakpoint
4287    inserted at PC.  */
4288
4289 int
4290 software_breakpoint_inserted_here_p (struct address_space *aspace,
4291                                      CORE_ADDR pc)
4292 {
4293   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4294     return 1;
4295
4296   /* Also check for software single-step breakpoints.  */
4297   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4298     return 1;
4299
4300   return 0;
4301 }
4302
4303 int
4304 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4305                                        CORE_ADDR addr, ULONGEST len)
4306 {
4307   struct breakpoint *bpt;
4308
4309   ALL_BREAKPOINTS (bpt)
4310     {
4311       struct bp_location *loc;
4312
4313       if (bpt->type != bp_hardware_watchpoint
4314           && bpt->type != bp_access_watchpoint)
4315         continue;
4316
4317       if (!breakpoint_enabled (bpt))
4318         continue;
4319
4320       for (loc = bpt->loc; loc; loc = loc->next)
4321         if (loc->pspace->aspace == aspace && loc->inserted)
4322           {
4323             CORE_ADDR l, h;
4324
4325             /* Check for intersection.  */
4326             l = max (loc->address, addr);
4327             h = min (loc->address + loc->length, addr + len);
4328             if (l < h)
4329               return 1;
4330           }
4331     }
4332   return 0;
4333 }
4334
4335 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4336    PC is valid for process/thread PTID.  */
4337
4338 int
4339 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4340                          ptid_t ptid)
4341 {
4342   struct bp_location *bl, **blp_tmp;
4343   /* The thread and task IDs associated to PTID, computed lazily.  */
4344   int thread = -1;
4345   int task = 0;
4346   
4347   ALL_BP_LOCATIONS (bl, blp_tmp)
4348     {
4349       if (bl->loc_type != bp_loc_software_breakpoint
4350           && bl->loc_type != bp_loc_hardware_breakpoint)
4351         continue;
4352
4353       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4354       if (!breakpoint_enabled (bl->owner)
4355           && bl->owner->enable_state != bp_permanent)
4356         continue;
4357
4358       if (!breakpoint_location_address_match (bl, aspace, pc))
4359         continue;
4360
4361       if (bl->owner->thread != -1)
4362         {
4363           /* This is a thread-specific breakpoint.  Check that ptid
4364              matches that thread.  If thread hasn't been computed yet,
4365              it is now time to do so.  */
4366           if (thread == -1)
4367             thread = pid_to_thread_id (ptid);
4368           if (bl->owner->thread != thread)
4369             continue;
4370         }
4371
4372       if (bl->owner->task != 0)
4373         {
4374           /* This is a task-specific breakpoint.  Check that ptid
4375              matches that task.  If task hasn't been computed yet,
4376              it is now time to do so.  */
4377           if (task == 0)
4378             task = ada_get_task_number (ptid);
4379           if (bl->owner->task != task)
4380             continue;
4381         }
4382
4383       if (overlay_debugging 
4384           && section_is_overlay (bl->section)
4385           && !section_is_mapped (bl->section))
4386         continue;           /* unmapped overlay -- can't be a match */
4387
4388       return 1;
4389     }
4390
4391   return 0;
4392 }
4393 \f
4394
4395 /* bpstat stuff.  External routines' interfaces are documented
4396    in breakpoint.h.  */
4397
4398 int
4399 is_catchpoint (struct breakpoint *ep)
4400 {
4401   return (ep->type == bp_catchpoint);
4402 }
4403
4404 /* Frees any storage that is part of a bpstat.  Does not walk the
4405    'next' chain.  */
4406
4407 static void
4408 bpstat_free (bpstat bs)
4409 {
4410   if (bs->old_val != NULL)
4411     value_free (bs->old_val);
4412   decref_counted_command_line (&bs->commands);
4413   decref_bp_location (&bs->bp_location_at);
4414   xfree (bs);
4415 }
4416
4417 /* Clear a bpstat so that it says we are not at any breakpoint.
4418    Also free any storage that is part of a bpstat.  */
4419
4420 void
4421 bpstat_clear (bpstat *bsp)
4422 {
4423   bpstat p;
4424   bpstat q;
4425
4426   if (bsp == 0)
4427     return;
4428   p = *bsp;
4429   while (p != NULL)
4430     {
4431       q = p->next;
4432       bpstat_free (p);
4433       p = q;
4434     }
4435   *bsp = NULL;
4436 }
4437
4438 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4439    is part of the bpstat is copied as well.  */
4440
4441 bpstat
4442 bpstat_copy (bpstat bs)
4443 {
4444   bpstat p = NULL;
4445   bpstat tmp;
4446   bpstat retval = NULL;
4447
4448   if (bs == NULL)
4449     return bs;
4450
4451   for (; bs != NULL; bs = bs->next)
4452     {
4453       tmp = (bpstat) xmalloc (sizeof (*tmp));
4454       memcpy (tmp, bs, sizeof (*tmp));
4455       incref_counted_command_line (tmp->commands);
4456       incref_bp_location (tmp->bp_location_at);
4457       if (bs->old_val != NULL)
4458         {
4459           tmp->old_val = value_copy (bs->old_val);
4460           release_value (tmp->old_val);
4461         }
4462
4463       if (p == NULL)
4464         /* This is the first thing in the chain.  */
4465         retval = tmp;
4466       else
4467         p->next = tmp;
4468       p = tmp;
4469     }
4470   p->next = NULL;
4471   return retval;
4472 }
4473
4474 /* Find the bpstat associated with this breakpoint.  */
4475
4476 bpstat
4477 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4478 {
4479   if (bsp == NULL)
4480     return NULL;
4481
4482   for (; bsp != NULL; bsp = bsp->next)
4483     {
4484       if (bsp->breakpoint_at == breakpoint)
4485         return bsp;
4486     }
4487   return NULL;
4488 }
4489
4490 /* See breakpoint.h.  */
4491
4492 int
4493 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4494 {
4495   for (; bsp != NULL; bsp = bsp->next)
4496     {
4497       if (bsp->breakpoint_at == NULL)
4498         {
4499           /* A moribund location can never explain a signal other than
4500              GDB_SIGNAL_TRAP.  */
4501           if (sig == GDB_SIGNAL_TRAP)
4502             return 1;
4503         }
4504       else
4505         {
4506           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4507                                                         sig))
4508             return 1;
4509         }
4510     }
4511
4512   return 0;
4513 }
4514
4515 /* Put in *NUM the breakpoint number of the first breakpoint we are
4516    stopped at.  *BSP upon return is a bpstat which points to the
4517    remaining breakpoints stopped at (but which is not guaranteed to be
4518    good for anything but further calls to bpstat_num).
4519
4520    Return 0 if passed a bpstat which does not indicate any breakpoints.
4521    Return -1 if stopped at a breakpoint that has been deleted since
4522    we set it.
4523    Return 1 otherwise.  */
4524
4525 int
4526 bpstat_num (bpstat *bsp, int *num)
4527 {
4528   struct breakpoint *b;
4529
4530   if ((*bsp) == NULL)
4531     return 0;                   /* No more breakpoint values */
4532
4533   /* We assume we'll never have several bpstats that correspond to a
4534      single breakpoint -- otherwise, this function might return the
4535      same number more than once and this will look ugly.  */
4536   b = (*bsp)->breakpoint_at;
4537   *bsp = (*bsp)->next;
4538   if (b == NULL)
4539     return -1;                  /* breakpoint that's been deleted since */
4540
4541   *num = b->number;             /* We have its number */
4542   return 1;
4543 }
4544
4545 /* See breakpoint.h.  */
4546
4547 void
4548 bpstat_clear_actions (void)
4549 {
4550   struct thread_info *tp;
4551   bpstat bs;
4552
4553   if (ptid_equal (inferior_ptid, null_ptid))
4554     return;
4555
4556   tp = find_thread_ptid (inferior_ptid);
4557   if (tp == NULL)
4558     return;
4559
4560   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4561     {
4562       decref_counted_command_line (&bs->commands);
4563
4564       if (bs->old_val != NULL)
4565         {
4566           value_free (bs->old_val);
4567           bs->old_val = NULL;
4568         }
4569     }
4570 }
4571
4572 /* Called when a command is about to proceed the inferior.  */
4573
4574 static void
4575 breakpoint_about_to_proceed (void)
4576 {
4577   if (!ptid_equal (inferior_ptid, null_ptid))
4578     {
4579       struct thread_info *tp = inferior_thread ();
4580
4581       /* Allow inferior function calls in breakpoint commands to not
4582          interrupt the command list.  When the call finishes
4583          successfully, the inferior will be standing at the same
4584          breakpoint as if nothing happened.  */
4585       if (tp->control.in_infcall)
4586         return;
4587     }
4588
4589   breakpoint_proceeded = 1;
4590 }
4591
4592 /* Stub for cleaning up our state if we error-out of a breakpoint
4593    command.  */
4594 static void
4595 cleanup_executing_breakpoints (void *ignore)
4596 {
4597   executing_breakpoint_commands = 0;
4598 }
4599
4600 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4601    or its equivalent.  */
4602
4603 static int
4604 command_line_is_silent (struct command_line *cmd)
4605 {
4606   return cmd && (strcmp ("silent", cmd->line) == 0
4607                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4608 }
4609
4610 /* Execute all the commands associated with all the breakpoints at
4611    this location.  Any of these commands could cause the process to
4612    proceed beyond this point, etc.  We look out for such changes by
4613    checking the global "breakpoint_proceeded" after each command.
4614
4615    Returns true if a breakpoint command resumed the inferior.  In that
4616    case, it is the caller's responsibility to recall it again with the
4617    bpstat of the current thread.  */
4618
4619 static int
4620 bpstat_do_actions_1 (bpstat *bsp)
4621 {
4622   bpstat bs;
4623   struct cleanup *old_chain;
4624   int again = 0;
4625
4626   /* Avoid endless recursion if a `source' command is contained
4627      in bs->commands.  */
4628   if (executing_breakpoint_commands)
4629     return 0;
4630
4631   executing_breakpoint_commands = 1;
4632   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4633
4634   prevent_dont_repeat ();
4635
4636   /* This pointer will iterate over the list of bpstat's.  */
4637   bs = *bsp;
4638
4639   breakpoint_proceeded = 0;
4640   for (; bs != NULL; bs = bs->next)
4641     {
4642       struct counted_command_line *ccmd;
4643       struct command_line *cmd;
4644       struct cleanup *this_cmd_tree_chain;
4645
4646       /* Take ownership of the BSP's command tree, if it has one.
4647
4648          The command tree could legitimately contain commands like
4649          'step' and 'next', which call clear_proceed_status, which
4650          frees stop_bpstat's command tree.  To make sure this doesn't
4651          free the tree we're executing out from under us, we need to
4652          take ownership of the tree ourselves.  Since a given bpstat's
4653          commands are only executed once, we don't need to copy it; we
4654          can clear the pointer in the bpstat, and make sure we free
4655          the tree when we're done.  */
4656       ccmd = bs->commands;
4657       bs->commands = NULL;
4658       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4659       cmd = ccmd ? ccmd->commands : NULL;
4660       if (command_line_is_silent (cmd))
4661         {
4662           /* The action has been already done by bpstat_stop_status.  */
4663           cmd = cmd->next;
4664         }
4665
4666       while (cmd != NULL)
4667         {
4668           execute_control_command (cmd);
4669
4670           if (breakpoint_proceeded)
4671             break;
4672           else
4673             cmd = cmd->next;
4674         }
4675
4676       /* We can free this command tree now.  */
4677       do_cleanups (this_cmd_tree_chain);
4678
4679       if (breakpoint_proceeded)
4680         {
4681           if (target_can_async_p ())
4682             /* If we are in async mode, then the target might be still
4683                running, not stopped at any breakpoint, so nothing for
4684                us to do here -- just return to the event loop.  */
4685             ;
4686           else
4687             /* In sync mode, when execute_control_command returns
4688                we're already standing on the next breakpoint.
4689                Breakpoint commands for that stop were not run, since
4690                execute_command does not run breakpoint commands --
4691                only command_line_handler does, but that one is not
4692                involved in execution of breakpoint commands.  So, we
4693                can now execute breakpoint commands.  It should be
4694                noted that making execute_command do bpstat actions is
4695                not an option -- in this case we'll have recursive
4696                invocation of bpstat for each breakpoint with a
4697                command, and can easily blow up GDB stack.  Instead, we
4698                return true, which will trigger the caller to recall us
4699                with the new stop_bpstat.  */
4700             again = 1;
4701           break;
4702         }
4703     }
4704   do_cleanups (old_chain);
4705   return again;
4706 }
4707
4708 void
4709 bpstat_do_actions (void)
4710 {
4711   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4712
4713   /* Do any commands attached to breakpoint we are stopped at.  */
4714   while (!ptid_equal (inferior_ptid, null_ptid)
4715          && target_has_execution
4716          && !is_exited (inferior_ptid)
4717          && !is_executing (inferior_ptid))
4718     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4719        and only return when it is stopped at the next breakpoint, we
4720        keep doing breakpoint actions until it returns false to
4721        indicate the inferior was not resumed.  */
4722     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4723       break;
4724
4725   discard_cleanups (cleanup_if_error);
4726 }
4727
4728 /* Print out the (old or new) value associated with a watchpoint.  */
4729
4730 static void
4731 watchpoint_value_print (struct value *val, struct ui_file *stream)
4732 {
4733   if (val == NULL)
4734     fprintf_unfiltered (stream, _("<unreadable>"));
4735   else
4736     {
4737       struct value_print_options opts;
4738       get_user_print_options (&opts);
4739       value_print (val, stream, &opts);
4740     }
4741 }
4742
4743 /* Generic routine for printing messages indicating why we
4744    stopped.  The behavior of this function depends on the value
4745    'print_it' in the bpstat structure.  Under some circumstances we
4746    may decide not to print anything here and delegate the task to
4747    normal_stop().  */
4748
4749 static enum print_stop_action
4750 print_bp_stop_message (bpstat bs)
4751 {
4752   switch (bs->print_it)
4753     {
4754     case print_it_noop:
4755       /* Nothing should be printed for this bpstat entry.  */
4756       return PRINT_UNKNOWN;
4757       break;
4758
4759     case print_it_done:
4760       /* We still want to print the frame, but we already printed the
4761          relevant messages.  */
4762       return PRINT_SRC_AND_LOC;
4763       break;
4764
4765     case print_it_normal:
4766       {
4767         struct breakpoint *b = bs->breakpoint_at;
4768
4769         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4770            which has since been deleted.  */
4771         if (b == NULL)
4772           return PRINT_UNKNOWN;
4773
4774         /* Normal case.  Call the breakpoint's print_it method.  */
4775         return b->ops->print_it (bs);
4776       }
4777       break;
4778
4779     default:
4780       internal_error (__FILE__, __LINE__,
4781                       _("print_bp_stop_message: unrecognized enum value"));
4782       break;
4783     }
4784 }
4785
4786 /* A helper function that prints a shared library stopped event.  */
4787
4788 static void
4789 print_solib_event (int is_catchpoint)
4790 {
4791   int any_deleted
4792     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4793   int any_added
4794     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4795
4796   if (!is_catchpoint)
4797     {
4798       if (any_added || any_deleted)
4799         ui_out_text (current_uiout,
4800                      _("Stopped due to shared library event:\n"));
4801       else
4802         ui_out_text (current_uiout,
4803                      _("Stopped due to shared library event (no "
4804                        "libraries added or removed)\n"));
4805     }
4806
4807   if (ui_out_is_mi_like_p (current_uiout))
4808     ui_out_field_string (current_uiout, "reason",
4809                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4810
4811   if (any_deleted)
4812     {
4813       struct cleanup *cleanup;
4814       char *name;
4815       int ix;
4816
4817       ui_out_text (current_uiout, _("  Inferior unloaded "));
4818       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4819                                                     "removed");
4820       for (ix = 0;
4821            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4822                         ix, name);
4823            ++ix)
4824         {
4825           if (ix > 0)
4826             ui_out_text (current_uiout, "    ");
4827           ui_out_field_string (current_uiout, "library", name);
4828           ui_out_text (current_uiout, "\n");
4829         }
4830
4831       do_cleanups (cleanup);
4832     }
4833
4834   if (any_added)
4835     {
4836       struct so_list *iter;
4837       int ix;
4838       struct cleanup *cleanup;
4839
4840       ui_out_text (current_uiout, _("  Inferior loaded "));
4841       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4842                                                     "added");
4843       for (ix = 0;
4844            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4845                         ix, iter);
4846            ++ix)
4847         {
4848           if (ix > 0)
4849             ui_out_text (current_uiout, "    ");
4850           ui_out_field_string (current_uiout, "library", iter->so_name);
4851           ui_out_text (current_uiout, "\n");
4852         }
4853
4854       do_cleanups (cleanup);
4855     }
4856 }
4857
4858 /* Print a message indicating what happened.  This is called from
4859    normal_stop().  The input to this routine is the head of the bpstat
4860    list - a list of the eventpoints that caused this stop.  KIND is
4861    the target_waitkind for the stopping event.  This
4862    routine calls the generic print routine for printing a message
4863    about reasons for stopping.  This will print (for example) the
4864    "Breakpoint n," part of the output.  The return value of this
4865    routine is one of:
4866
4867    PRINT_UNKNOWN: Means we printed nothing.
4868    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4869    code to print the location.  An example is 
4870    "Breakpoint 1, " which should be followed by
4871    the location.
4872    PRINT_SRC_ONLY: Means we printed something, but there is no need
4873    to also print the location part of the message.
4874    An example is the catch/throw messages, which
4875    don't require a location appended to the end.
4876    PRINT_NOTHING: We have done some printing and we don't need any 
4877    further info to be printed.  */
4878
4879 enum print_stop_action
4880 bpstat_print (bpstat bs, int kind)
4881 {
4882   int val;
4883
4884   /* Maybe another breakpoint in the chain caused us to stop.
4885      (Currently all watchpoints go on the bpstat whether hit or not.
4886      That probably could (should) be changed, provided care is taken
4887      with respect to bpstat_explains_signal).  */
4888   for (; bs; bs = bs->next)
4889     {
4890       val = print_bp_stop_message (bs);
4891       if (val == PRINT_SRC_ONLY 
4892           || val == PRINT_SRC_AND_LOC 
4893           || val == PRINT_NOTHING)
4894         return val;
4895     }
4896
4897   /* If we had hit a shared library event breakpoint,
4898      print_bp_stop_message would print out this message.  If we hit an
4899      OS-level shared library event, do the same thing.  */
4900   if (kind == TARGET_WAITKIND_LOADED)
4901     {
4902       print_solib_event (0);
4903       return PRINT_NOTHING;
4904     }
4905
4906   /* We reached the end of the chain, or we got a null BS to start
4907      with and nothing was printed.  */
4908   return PRINT_UNKNOWN;
4909 }
4910
4911 /* Evaluate the expression EXP and return 1 if value is zero.
4912    This returns the inverse of the condition because it is called
4913    from catch_errors which returns 0 if an exception happened, and if an
4914    exception happens we want execution to stop.
4915    The argument is a "struct expression *" that has been cast to a
4916    "void *" to make it pass through catch_errors.  */
4917
4918 static int
4919 breakpoint_cond_eval (void *exp)
4920 {
4921   struct value *mark = value_mark ();
4922   int i = !value_true (evaluate_expression ((struct expression *) exp));
4923
4924   value_free_to_mark (mark);
4925   return i;
4926 }
4927
4928 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4929
4930 static bpstat
4931 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4932 {
4933   bpstat bs;
4934
4935   bs = (bpstat) xmalloc (sizeof (*bs));
4936   bs->next = NULL;
4937   **bs_link_pointer = bs;
4938   *bs_link_pointer = &bs->next;
4939   bs->breakpoint_at = bl->owner;
4940   bs->bp_location_at = bl;
4941   incref_bp_location (bl);
4942   /* If the condition is false, etc., don't do the commands.  */
4943   bs->commands = NULL;
4944   bs->old_val = NULL;
4945   bs->print_it = print_it_normal;
4946   return bs;
4947 }
4948 \f
4949 /* The target has stopped with waitstatus WS.  Check if any hardware
4950    watchpoints have triggered, according to the target.  */
4951
4952 int
4953 watchpoints_triggered (struct target_waitstatus *ws)
4954 {
4955   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4956   CORE_ADDR addr;
4957   struct breakpoint *b;
4958
4959   if (!stopped_by_watchpoint)
4960     {
4961       /* We were not stopped by a watchpoint.  Mark all watchpoints
4962          as not triggered.  */
4963       ALL_BREAKPOINTS (b)
4964         if (is_hardware_watchpoint (b))
4965           {
4966             struct watchpoint *w = (struct watchpoint *) b;
4967
4968             w->watchpoint_triggered = watch_triggered_no;
4969           }
4970
4971       return 0;
4972     }
4973
4974   if (!target_stopped_data_address (&current_target, &addr))
4975     {
4976       /* We were stopped by a watchpoint, but we don't know where.
4977          Mark all watchpoints as unknown.  */
4978       ALL_BREAKPOINTS (b)
4979         if (is_hardware_watchpoint (b))
4980           {
4981             struct watchpoint *w = (struct watchpoint *) b;
4982
4983             w->watchpoint_triggered = watch_triggered_unknown;
4984           }
4985
4986       return 1;
4987     }
4988
4989   /* The target could report the data address.  Mark watchpoints
4990      affected by this data address as triggered, and all others as not
4991      triggered.  */
4992
4993   ALL_BREAKPOINTS (b)
4994     if (is_hardware_watchpoint (b))
4995       {
4996         struct watchpoint *w = (struct watchpoint *) b;
4997         struct bp_location *loc;
4998
4999         w->watchpoint_triggered = watch_triggered_no;
5000         for (loc = b->loc; loc; loc = loc->next)
5001           {
5002             if (is_masked_watchpoint (b))
5003               {
5004                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5005                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5006
5007                 if (newaddr == start)
5008                   {
5009                     w->watchpoint_triggered = watch_triggered_yes;
5010                     break;
5011                   }
5012               }
5013             /* Exact match not required.  Within range is sufficient.  */
5014             else if (target_watchpoint_addr_within_range (&current_target,
5015                                                          addr, loc->address,
5016                                                          loc->length))
5017               {
5018                 w->watchpoint_triggered = watch_triggered_yes;
5019                 break;
5020               }
5021           }
5022       }
5023
5024   return 1;
5025 }
5026
5027 /* Possible return values for watchpoint_check (this can't be an enum
5028    because of check_errors).  */
5029 /* The watchpoint has been deleted.  */
5030 #define WP_DELETED 1
5031 /* The value has changed.  */
5032 #define WP_VALUE_CHANGED 2
5033 /* The value has not changed.  */
5034 #define WP_VALUE_NOT_CHANGED 3
5035 /* Ignore this watchpoint, no matter if the value changed or not.  */
5036 #define WP_IGNORE 4
5037
5038 #define BP_TEMPFLAG 1
5039 #define BP_HARDWAREFLAG 2
5040
5041 /* Evaluate watchpoint condition expression and check if its value
5042    changed.
5043
5044    P should be a pointer to struct bpstat, but is defined as a void *
5045    in order for this function to be usable with catch_errors.  */
5046
5047 static int
5048 watchpoint_check (void *p)
5049 {
5050   bpstat bs = (bpstat) p;
5051   struct watchpoint *b;
5052   struct frame_info *fr;
5053   int within_current_scope;
5054
5055   /* BS is built from an existing struct breakpoint.  */
5056   gdb_assert (bs->breakpoint_at != NULL);
5057   b = (struct watchpoint *) bs->breakpoint_at;
5058
5059   /* If this is a local watchpoint, we only want to check if the
5060      watchpoint frame is in scope if the current thread is the thread
5061      that was used to create the watchpoint.  */
5062   if (!watchpoint_in_thread_scope (b))
5063     return WP_IGNORE;
5064
5065   if (b->exp_valid_block == NULL)
5066     within_current_scope = 1;
5067   else
5068     {
5069       struct frame_info *frame = get_current_frame ();
5070       struct gdbarch *frame_arch = get_frame_arch (frame);
5071       CORE_ADDR frame_pc = get_frame_pc (frame);
5072
5073       /* in_function_epilogue_p() returns a non-zero value if we're
5074          still in the function but the stack frame has already been
5075          invalidated.  Since we can't rely on the values of local
5076          variables after the stack has been destroyed, we are treating
5077          the watchpoint in that state as `not changed' without further
5078          checking.  Don't mark watchpoints as changed if the current
5079          frame is in an epilogue - even if they are in some other
5080          frame, our view of the stack is likely to be wrong and
5081          frame_find_by_id could error out.  */
5082       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5083         return WP_IGNORE;
5084
5085       fr = frame_find_by_id (b->watchpoint_frame);
5086       within_current_scope = (fr != NULL);
5087
5088       /* If we've gotten confused in the unwinder, we might have
5089          returned a frame that can't describe this variable.  */
5090       if (within_current_scope)
5091         {
5092           struct symbol *function;
5093
5094           function = get_frame_function (fr);
5095           if (function == NULL
5096               || !contained_in (b->exp_valid_block,
5097                                 SYMBOL_BLOCK_VALUE (function)))
5098             within_current_scope = 0;
5099         }
5100
5101       if (within_current_scope)
5102         /* If we end up stopping, the current frame will get selected
5103            in normal_stop.  So this call to select_frame won't affect
5104            the user.  */
5105         select_frame (fr);
5106     }
5107
5108   if (within_current_scope)
5109     {
5110       /* We use value_{,free_to_}mark because it could be a *long*
5111          time before we return to the command level and call
5112          free_all_values.  We can't call free_all_values because we
5113          might be in the middle of evaluating a function call.  */
5114
5115       int pc = 0;
5116       struct value *mark;
5117       struct value *new_val;
5118
5119       if (is_masked_watchpoint (&b->base))
5120         /* Since we don't know the exact trigger address (from
5121            stopped_data_address), just tell the user we've triggered
5122            a mask watchpoint.  */
5123         return WP_VALUE_CHANGED;
5124
5125       mark = value_mark ();
5126       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5127
5128       if (b->val_bitsize != 0)
5129         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5130
5131       /* We use value_equal_contents instead of value_equal because
5132          the latter coerces an array to a pointer, thus comparing just
5133          the address of the array instead of its contents.  This is
5134          not what we want.  */
5135       if ((b->val != NULL) != (new_val != NULL)
5136           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5137         {
5138           if (new_val != NULL)
5139             {
5140               release_value (new_val);
5141               value_free_to_mark (mark);
5142             }
5143           bs->old_val = b->val;
5144           b->val = new_val;
5145           b->val_valid = 1;
5146           return WP_VALUE_CHANGED;
5147         }
5148       else
5149         {
5150           /* Nothing changed.  */
5151           value_free_to_mark (mark);
5152           return WP_VALUE_NOT_CHANGED;
5153         }
5154     }
5155   else
5156     {
5157       struct ui_out *uiout = current_uiout;
5158
5159       /* This seems like the only logical thing to do because
5160          if we temporarily ignored the watchpoint, then when
5161          we reenter the block in which it is valid it contains
5162          garbage (in the case of a function, it may have two
5163          garbage values, one before and one after the prologue).
5164          So we can't even detect the first assignment to it and
5165          watch after that (since the garbage may or may not equal
5166          the first value assigned).  */
5167       /* We print all the stop information in
5168          breakpoint_ops->print_it, but in this case, by the time we
5169          call breakpoint_ops->print_it this bp will be deleted
5170          already.  So we have no choice but print the information
5171          here.  */
5172       if (ui_out_is_mi_like_p (uiout))
5173         ui_out_field_string
5174           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5175       ui_out_text (uiout, "\nWatchpoint ");
5176       ui_out_field_int (uiout, "wpnum", b->base.number);
5177       ui_out_text (uiout,
5178                    " deleted because the program has left the block in\n\
5179 which its expression is valid.\n");     
5180
5181       /* Make sure the watchpoint's commands aren't executed.  */
5182       decref_counted_command_line (&b->base.commands);
5183       watchpoint_del_at_next_stop (b);
5184
5185       return WP_DELETED;
5186     }
5187 }
5188
5189 /* Return true if it looks like target has stopped due to hitting
5190    breakpoint location BL.  This function does not check if we should
5191    stop, only if BL explains the stop.  */
5192
5193 static int
5194 bpstat_check_location (const struct bp_location *bl,
5195                        struct address_space *aspace, CORE_ADDR bp_addr,
5196                        const struct target_waitstatus *ws)
5197 {
5198   struct breakpoint *b = bl->owner;
5199
5200   /* BL is from an existing breakpoint.  */
5201   gdb_assert (b != NULL);
5202
5203   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5204 }
5205
5206 /* Determine if the watched values have actually changed, and we
5207    should stop.  If not, set BS->stop to 0.  */
5208
5209 static void
5210 bpstat_check_watchpoint (bpstat bs)
5211 {
5212   const struct bp_location *bl;
5213   struct watchpoint *b;
5214
5215   /* BS is built for existing struct breakpoint.  */
5216   bl = bs->bp_location_at;
5217   gdb_assert (bl != NULL);
5218   b = (struct watchpoint *) bs->breakpoint_at;
5219   gdb_assert (b != NULL);
5220
5221     {
5222       int must_check_value = 0;
5223       
5224       if (b->base.type == bp_watchpoint)
5225         /* For a software watchpoint, we must always check the
5226            watched value.  */
5227         must_check_value = 1;
5228       else if (b->watchpoint_triggered == watch_triggered_yes)
5229         /* We have a hardware watchpoint (read, write, or access)
5230            and the target earlier reported an address watched by
5231            this watchpoint.  */
5232         must_check_value = 1;
5233       else if (b->watchpoint_triggered == watch_triggered_unknown
5234                && b->base.type == bp_hardware_watchpoint)
5235         /* We were stopped by a hardware watchpoint, but the target could
5236            not report the data address.  We must check the watchpoint's
5237            value.  Access and read watchpoints are out of luck; without
5238            a data address, we can't figure it out.  */
5239         must_check_value = 1;
5240
5241       if (must_check_value)
5242         {
5243           char *message
5244             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5245                           b->base.number);
5246           struct cleanup *cleanups = make_cleanup (xfree, message);
5247           int e = catch_errors (watchpoint_check, bs, message,
5248                                 RETURN_MASK_ALL);
5249           do_cleanups (cleanups);
5250           switch (e)
5251             {
5252             case WP_DELETED:
5253               /* We've already printed what needs to be printed.  */
5254               bs->print_it = print_it_done;
5255               /* Stop.  */
5256               break;
5257             case WP_IGNORE:
5258               bs->print_it = print_it_noop;
5259               bs->stop = 0;
5260               break;
5261             case WP_VALUE_CHANGED:
5262               if (b->base.type == bp_read_watchpoint)
5263                 {
5264                   /* There are two cases to consider here:
5265
5266                      1. We're watching the triggered memory for reads.
5267                      In that case, trust the target, and always report
5268                      the watchpoint hit to the user.  Even though
5269                      reads don't cause value changes, the value may
5270                      have changed since the last time it was read, and
5271                      since we're not trapping writes, we will not see
5272                      those, and as such we should ignore our notion of
5273                      old value.
5274
5275                      2. We're watching the triggered memory for both
5276                      reads and writes.  There are two ways this may
5277                      happen:
5278
5279                      2.1. This is a target that can't break on data
5280                      reads only, but can break on accesses (reads or
5281                      writes), such as e.g., x86.  We detect this case
5282                      at the time we try to insert read watchpoints.
5283
5284                      2.2. Otherwise, the target supports read
5285                      watchpoints, but, the user set an access or write
5286                      watchpoint watching the same memory as this read
5287                      watchpoint.
5288
5289                      If we're watching memory writes as well as reads,
5290                      ignore watchpoint hits when we find that the
5291                      value hasn't changed, as reads don't cause
5292                      changes.  This still gives false positives when
5293                      the program writes the same value to memory as
5294                      what there was already in memory (we will confuse
5295                      it for a read), but it's much better than
5296                      nothing.  */
5297
5298                   int other_write_watchpoint = 0;
5299
5300                   if (bl->watchpoint_type == hw_read)
5301                     {
5302                       struct breakpoint *other_b;
5303
5304                       ALL_BREAKPOINTS (other_b)
5305                         if (other_b->type == bp_hardware_watchpoint
5306                             || other_b->type == bp_access_watchpoint)
5307                           {
5308                             struct watchpoint *other_w =
5309                               (struct watchpoint *) other_b;
5310
5311                             if (other_w->watchpoint_triggered
5312                                 == watch_triggered_yes)
5313                               {
5314                                 other_write_watchpoint = 1;
5315                                 break;
5316                               }
5317                           }
5318                     }
5319
5320                   if (other_write_watchpoint
5321                       || bl->watchpoint_type == hw_access)
5322                     {
5323                       /* We're watching the same memory for writes,
5324                          and the value changed since the last time we
5325                          updated it, so this trap must be for a write.
5326                          Ignore it.  */
5327                       bs->print_it = print_it_noop;
5328                       bs->stop = 0;
5329                     }
5330                 }
5331               break;
5332             case WP_VALUE_NOT_CHANGED:
5333               if (b->base.type == bp_hardware_watchpoint
5334                   || b->base.type == bp_watchpoint)
5335                 {
5336                   /* Don't stop: write watchpoints shouldn't fire if
5337                      the value hasn't changed.  */
5338                   bs->print_it = print_it_noop;
5339                   bs->stop = 0;
5340                 }
5341               /* Stop.  */
5342               break;
5343             default:
5344               /* Can't happen.  */
5345             case 0:
5346               /* Error from catch_errors.  */
5347               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5348               watchpoint_del_at_next_stop (b);
5349               /* We've already printed what needs to be printed.  */
5350               bs->print_it = print_it_done;
5351               break;
5352             }
5353         }
5354       else      /* must_check_value == 0 */
5355         {
5356           /* This is a case where some watchpoint(s) triggered, but
5357              not at the address of this watchpoint, or else no
5358              watchpoint triggered after all.  So don't print
5359              anything for this watchpoint.  */
5360           bs->print_it = print_it_noop;
5361           bs->stop = 0;
5362         }
5363     }
5364 }
5365
5366 /* For breakpoints that are currently marked as telling gdb to stop,
5367    check conditions (condition proper, frame, thread and ignore count)
5368    of breakpoint referred to by BS.  If we should not stop for this
5369    breakpoint, set BS->stop to 0.  */
5370
5371 static void
5372 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5373 {
5374   const struct bp_location *bl;
5375   struct breakpoint *b;
5376   int value_is_zero = 0;
5377   struct expression *cond;
5378
5379   gdb_assert (bs->stop);
5380
5381   /* BS is built for existing struct breakpoint.  */
5382   bl = bs->bp_location_at;
5383   gdb_assert (bl != NULL);
5384   b = bs->breakpoint_at;
5385   gdb_assert (b != NULL);
5386
5387   /* Even if the target evaluated the condition on its end and notified GDB, we
5388      need to do so again since GDB does not know if we stopped due to a
5389      breakpoint or a single step breakpoint.  */
5390
5391   if (frame_id_p (b->frame_id)
5392       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5393     {
5394       bs->stop = 0;
5395       return;
5396     }
5397
5398   /* If this is a thread/task-specific breakpoint, don't waste cpu
5399      evaluating the condition if this isn't the specified
5400      thread/task.  */
5401   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5402       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5403
5404     {
5405       bs->stop = 0;
5406       return;
5407     }
5408
5409   /* Evaluate extension language breakpoints that have a "stop" method
5410      implemented.  */
5411   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5412
5413   if (is_watchpoint (b))
5414     {
5415       struct watchpoint *w = (struct watchpoint *) b;
5416
5417       cond = w->cond_exp;
5418     }
5419   else
5420     cond = bl->cond;
5421
5422   if (cond && b->disposition != disp_del_at_next_stop)
5423     {
5424       int within_current_scope = 1;
5425       struct watchpoint * w;
5426
5427       /* We use value_mark and value_free_to_mark because it could
5428          be a long time before we return to the command level and
5429          call free_all_values.  We can't call free_all_values
5430          because we might be in the middle of evaluating a
5431          function call.  */
5432       struct value *mark = value_mark ();
5433
5434       if (is_watchpoint (b))
5435         w = (struct watchpoint *) b;
5436       else
5437         w = NULL;
5438
5439       /* Need to select the frame, with all that implies so that
5440          the conditions will have the right context.  Because we
5441          use the frame, we will not see an inlined function's
5442          variables when we arrive at a breakpoint at the start
5443          of the inlined function; the current frame will be the
5444          call site.  */
5445       if (w == NULL || w->cond_exp_valid_block == NULL)
5446         select_frame (get_current_frame ());
5447       else
5448         {
5449           struct frame_info *frame;
5450
5451           /* For local watchpoint expressions, which particular
5452              instance of a local is being watched matters, so we
5453              keep track of the frame to evaluate the expression
5454              in.  To evaluate the condition however, it doesn't
5455              really matter which instantiation of the function
5456              where the condition makes sense triggers the
5457              watchpoint.  This allows an expression like "watch
5458              global if q > 10" set in `func', catch writes to
5459              global on all threads that call `func', or catch
5460              writes on all recursive calls of `func' by a single
5461              thread.  We simply always evaluate the condition in
5462              the innermost frame that's executing where it makes
5463              sense to evaluate the condition.  It seems
5464              intuitive.  */
5465           frame = block_innermost_frame (w->cond_exp_valid_block);
5466           if (frame != NULL)
5467             select_frame (frame);
5468           else
5469             within_current_scope = 0;
5470         }
5471       if (within_current_scope)
5472         value_is_zero
5473           = catch_errors (breakpoint_cond_eval, cond,
5474                           "Error in testing breakpoint condition:\n",
5475                           RETURN_MASK_ALL);
5476       else
5477         {
5478           warning (_("Watchpoint condition cannot be tested "
5479                      "in the current scope"));
5480           /* If we failed to set the right context for this
5481              watchpoint, unconditionally report it.  */
5482           value_is_zero = 0;
5483         }
5484       /* FIXME-someday, should give breakpoint #.  */
5485       value_free_to_mark (mark);
5486     }
5487
5488   if (cond && value_is_zero)
5489     {
5490       bs->stop = 0;
5491     }
5492   else if (b->ignore_count > 0)
5493     {
5494       b->ignore_count--;
5495       bs->stop = 0;
5496       /* Increase the hit count even though we don't stop.  */
5497       ++(b->hit_count);
5498       observer_notify_breakpoint_modified (b);
5499     }   
5500 }
5501
5502
5503 /* Get a bpstat associated with having just stopped at address
5504    BP_ADDR in thread PTID.
5505
5506    Determine whether we stopped at a breakpoint, etc, or whether we
5507    don't understand this stop.  Result is a chain of bpstat's such
5508    that:
5509
5510    if we don't understand the stop, the result is a null pointer.
5511
5512    if we understand why we stopped, the result is not null.
5513
5514    Each element of the chain refers to a particular breakpoint or
5515    watchpoint at which we have stopped.  (We may have stopped for
5516    several reasons concurrently.)
5517
5518    Each element of the chain has valid next, breakpoint_at,
5519    commands, FIXME??? fields.  */
5520
5521 bpstat
5522 bpstat_stop_status (struct address_space *aspace,
5523                     CORE_ADDR bp_addr, ptid_t ptid,
5524                     const struct target_waitstatus *ws)
5525 {
5526   struct breakpoint *b = NULL;
5527   struct bp_location *bl;
5528   struct bp_location *loc;
5529   /* First item of allocated bpstat's.  */
5530   bpstat bs_head = NULL, *bs_link = &bs_head;
5531   /* Pointer to the last thing in the chain currently.  */
5532   bpstat bs;
5533   int ix;
5534   int need_remove_insert;
5535   int removed_any;
5536
5537   /* First, build the bpstat chain with locations that explain a
5538      target stop, while being careful to not set the target running,
5539      as that may invalidate locations (in particular watchpoint
5540      locations are recreated).  Resuming will happen here with
5541      breakpoint conditions or watchpoint expressions that include
5542      inferior function calls.  */
5543
5544   ALL_BREAKPOINTS (b)
5545     {
5546       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5547         continue;
5548
5549       for (bl = b->loc; bl != NULL; bl = bl->next)
5550         {
5551           /* For hardware watchpoints, we look only at the first
5552              location.  The watchpoint_check function will work on the
5553              entire expression, not the individual locations.  For
5554              read watchpoints, the watchpoints_triggered function has
5555              checked all locations already.  */
5556           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5557             break;
5558
5559           if (!bl->enabled || bl->shlib_disabled)
5560             continue;
5561
5562           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5563             continue;
5564
5565           /* Come here if it's a watchpoint, or if the break address
5566              matches.  */
5567
5568           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5569                                                    explain stop.  */
5570
5571           /* Assume we stop.  Should we find a watchpoint that is not
5572              actually triggered, or if the condition of the breakpoint
5573              evaluates as false, we'll reset 'stop' to 0.  */
5574           bs->stop = 1;
5575           bs->print = 1;
5576
5577           /* If this is a scope breakpoint, mark the associated
5578              watchpoint as triggered so that we will handle the
5579              out-of-scope event.  We'll get to the watchpoint next
5580              iteration.  */
5581           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5582             {
5583               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5584
5585               w->watchpoint_triggered = watch_triggered_yes;
5586             }
5587         }
5588     }
5589
5590   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5591     {
5592       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5593         {
5594           bs = bpstat_alloc (loc, &bs_link);
5595           /* For hits of moribund locations, we should just proceed.  */
5596           bs->stop = 0;
5597           bs->print = 0;
5598           bs->print_it = print_it_noop;
5599         }
5600     }
5601
5602   /* A bit of special processing for shlib breakpoints.  We need to
5603      process solib loading here, so that the lists of loaded and
5604      unloaded libraries are correct before we handle "catch load" and
5605      "catch unload".  */
5606   for (bs = bs_head; bs != NULL; bs = bs->next)
5607     {
5608       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5609         {
5610           handle_solib_event ();
5611           break;
5612         }
5613     }
5614
5615   /* Now go through the locations that caused the target to stop, and
5616      check whether we're interested in reporting this stop to higher
5617      layers, or whether we should resume the target transparently.  */
5618
5619   removed_any = 0;
5620
5621   for (bs = bs_head; bs != NULL; bs = bs->next)
5622     {
5623       if (!bs->stop)
5624         continue;
5625
5626       b = bs->breakpoint_at;
5627       b->ops->check_status (bs);
5628       if (bs->stop)
5629         {
5630           bpstat_check_breakpoint_conditions (bs, ptid);
5631
5632           if (bs->stop)
5633             {
5634               ++(b->hit_count);
5635               observer_notify_breakpoint_modified (b);
5636
5637               /* We will stop here.  */
5638               if (b->disposition == disp_disable)
5639                 {
5640                   --(b->enable_count);
5641                   if (b->enable_count <= 0
5642                       && b->enable_state != bp_permanent)
5643                     b->enable_state = bp_disabled;
5644                   removed_any = 1;
5645                 }
5646               if (b->silent)
5647                 bs->print = 0;
5648               bs->commands = b->commands;
5649               incref_counted_command_line (bs->commands);
5650               if (command_line_is_silent (bs->commands
5651                                           ? bs->commands->commands : NULL))
5652                 bs->print = 0;
5653
5654               b->ops->after_condition_true (bs);
5655             }
5656
5657         }
5658
5659       /* Print nothing for this entry if we don't stop or don't
5660          print.  */
5661       if (!bs->stop || !bs->print)
5662         bs->print_it = print_it_noop;
5663     }
5664
5665   /* If we aren't stopping, the value of some hardware watchpoint may
5666      not have changed, but the intermediate memory locations we are
5667      watching may have.  Don't bother if we're stopping; this will get
5668      done later.  */
5669   need_remove_insert = 0;
5670   if (! bpstat_causes_stop (bs_head))
5671     for (bs = bs_head; bs != NULL; bs = bs->next)
5672       if (!bs->stop
5673           && bs->breakpoint_at
5674           && is_hardware_watchpoint (bs->breakpoint_at))
5675         {
5676           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5677
5678           update_watchpoint (w, 0 /* don't reparse.  */);
5679           need_remove_insert = 1;
5680         }
5681
5682   if (need_remove_insert)
5683     update_global_location_list (UGLL_MAY_INSERT);
5684   else if (removed_any)
5685     update_global_location_list (UGLL_DONT_INSERT);
5686
5687   return bs_head;
5688 }
5689
5690 static void
5691 handle_jit_event (void)
5692 {
5693   struct frame_info *frame;
5694   struct gdbarch *gdbarch;
5695
5696   /* Switch terminal for any messages produced by
5697      breakpoint_re_set.  */
5698   target_terminal_ours_for_output ();
5699
5700   frame = get_current_frame ();
5701   gdbarch = get_frame_arch (frame);
5702
5703   jit_event_handler (gdbarch);
5704
5705   target_terminal_inferior ();
5706 }
5707
5708 /* Prepare WHAT final decision for infrun.  */
5709
5710 /* Decide what infrun needs to do with this bpstat.  */
5711
5712 struct bpstat_what
5713 bpstat_what (bpstat bs_head)
5714 {
5715   struct bpstat_what retval;
5716   int jit_event = 0;
5717   bpstat bs;
5718
5719   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5720   retval.call_dummy = STOP_NONE;
5721   retval.is_longjmp = 0;
5722
5723   for (bs = bs_head; bs != NULL; bs = bs->next)
5724     {
5725       /* Extract this BS's action.  After processing each BS, we check
5726          if its action overrides all we've seem so far.  */
5727       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5728       enum bptype bptype;
5729
5730       if (bs->breakpoint_at == NULL)
5731         {
5732           /* I suspect this can happen if it was a momentary
5733              breakpoint which has since been deleted.  */
5734           bptype = bp_none;
5735         }
5736       else
5737         bptype = bs->breakpoint_at->type;
5738
5739       switch (bptype)
5740         {
5741         case bp_none:
5742           break;
5743         case bp_breakpoint:
5744         case bp_hardware_breakpoint:
5745         case bp_until:
5746         case bp_finish:
5747         case bp_shlib_event:
5748           if (bs->stop)
5749             {
5750               if (bs->print)
5751                 this_action = BPSTAT_WHAT_STOP_NOISY;
5752               else
5753                 this_action = BPSTAT_WHAT_STOP_SILENT;
5754             }
5755           else
5756             this_action = BPSTAT_WHAT_SINGLE;
5757           break;
5758         case bp_watchpoint:
5759         case bp_hardware_watchpoint:
5760         case bp_read_watchpoint:
5761         case bp_access_watchpoint:
5762           if (bs->stop)
5763             {
5764               if (bs->print)
5765                 this_action = BPSTAT_WHAT_STOP_NOISY;
5766               else
5767                 this_action = BPSTAT_WHAT_STOP_SILENT;
5768             }
5769           else
5770             {
5771               /* There was a watchpoint, but we're not stopping.
5772                  This requires no further action.  */
5773             }
5774           break;
5775         case bp_longjmp:
5776         case bp_longjmp_call_dummy:
5777         case bp_exception:
5778           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5779           retval.is_longjmp = bptype != bp_exception;
5780           break;
5781         case bp_longjmp_resume:
5782         case bp_exception_resume:
5783           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5784           retval.is_longjmp = bptype == bp_longjmp_resume;
5785           break;
5786         case bp_step_resume:
5787           if (bs->stop)
5788             this_action = BPSTAT_WHAT_STEP_RESUME;
5789           else
5790             {
5791               /* It is for the wrong frame.  */
5792               this_action = BPSTAT_WHAT_SINGLE;
5793             }
5794           break;
5795         case bp_hp_step_resume:
5796           if (bs->stop)
5797             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5798           else
5799             {
5800               /* It is for the wrong frame.  */
5801               this_action = BPSTAT_WHAT_SINGLE;
5802             }
5803           break;
5804         case bp_watchpoint_scope:
5805         case bp_thread_event:
5806         case bp_overlay_event:
5807         case bp_longjmp_master:
5808         case bp_std_terminate_master:
5809         case bp_exception_master:
5810           this_action = BPSTAT_WHAT_SINGLE;
5811           break;
5812         case bp_catchpoint:
5813           if (bs->stop)
5814             {
5815               if (bs->print)
5816                 this_action = BPSTAT_WHAT_STOP_NOISY;
5817               else
5818                 this_action = BPSTAT_WHAT_STOP_SILENT;
5819             }
5820           else
5821             {
5822               /* There was a catchpoint, but we're not stopping.
5823                  This requires no further action.  */
5824             }
5825           break;
5826         case bp_jit_event:
5827           jit_event = 1;
5828           this_action = BPSTAT_WHAT_SINGLE;
5829           break;
5830         case bp_call_dummy:
5831           /* Make sure the action is stop (silent or noisy),
5832              so infrun.c pops the dummy frame.  */
5833           retval.call_dummy = STOP_STACK_DUMMY;
5834           this_action = BPSTAT_WHAT_STOP_SILENT;
5835           break;
5836         case bp_std_terminate:
5837           /* Make sure the action is stop (silent or noisy),
5838              so infrun.c pops the dummy frame.  */
5839           retval.call_dummy = STOP_STD_TERMINATE;
5840           this_action = BPSTAT_WHAT_STOP_SILENT;
5841           break;
5842         case bp_tracepoint:
5843         case bp_fast_tracepoint:
5844         case bp_static_tracepoint:
5845           /* Tracepoint hits should not be reported back to GDB, and
5846              if one got through somehow, it should have been filtered
5847              out already.  */
5848           internal_error (__FILE__, __LINE__,
5849                           _("bpstat_what: tracepoint encountered"));
5850           break;
5851         case bp_gnu_ifunc_resolver:
5852           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5853           this_action = BPSTAT_WHAT_SINGLE;
5854           break;
5855         case bp_gnu_ifunc_resolver_return:
5856           /* The breakpoint will be removed, execution will restart from the
5857              PC of the former breakpoint.  */
5858           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5859           break;
5860
5861         case bp_dprintf:
5862           if (bs->stop)
5863             this_action = BPSTAT_WHAT_STOP_SILENT;
5864           else
5865             this_action = BPSTAT_WHAT_SINGLE;
5866           break;
5867
5868         default:
5869           internal_error (__FILE__, __LINE__,
5870                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5871         }
5872
5873       retval.main_action = max (retval.main_action, this_action);
5874     }
5875
5876   /* These operations may affect the bs->breakpoint_at state so they are
5877      delayed after MAIN_ACTION is decided above.  */
5878
5879   if (jit_event)
5880     {
5881       if (debug_infrun)
5882         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5883
5884       handle_jit_event ();
5885     }
5886
5887   for (bs = bs_head; bs != NULL; bs = bs->next)
5888     {
5889       struct breakpoint *b = bs->breakpoint_at;
5890
5891       if (b == NULL)
5892         continue;
5893       switch (b->type)
5894         {
5895         case bp_gnu_ifunc_resolver:
5896           gnu_ifunc_resolver_stop (b);
5897           break;
5898         case bp_gnu_ifunc_resolver_return:
5899           gnu_ifunc_resolver_return_stop (b);
5900           break;
5901         }
5902     }
5903
5904   return retval;
5905 }
5906
5907 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5908    without hardware support).  This isn't related to a specific bpstat,
5909    just to things like whether watchpoints are set.  */
5910
5911 int
5912 bpstat_should_step (void)
5913 {
5914   struct breakpoint *b;
5915
5916   ALL_BREAKPOINTS (b)
5917     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5918       return 1;
5919   return 0;
5920 }
5921
5922 int
5923 bpstat_causes_stop (bpstat bs)
5924 {
5925   for (; bs != NULL; bs = bs->next)
5926     if (bs->stop)
5927       return 1;
5928
5929   return 0;
5930 }
5931
5932 \f
5933
5934 /* Compute a string of spaces suitable to indent the next line
5935    so it starts at the position corresponding to the table column
5936    named COL_NAME in the currently active table of UIOUT.  */
5937
5938 static char *
5939 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5940 {
5941   static char wrap_indent[80];
5942   int i, total_width, width, align;
5943   char *text;
5944
5945   total_width = 0;
5946   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5947     {
5948       if (strcmp (text, col_name) == 0)
5949         {
5950           gdb_assert (total_width < sizeof wrap_indent);
5951           memset (wrap_indent, ' ', total_width);
5952           wrap_indent[total_width] = 0;
5953
5954           return wrap_indent;
5955         }
5956
5957       total_width += width + 1;
5958     }
5959
5960   return NULL;
5961 }
5962
5963 /* Determine if the locations of this breakpoint will have their conditions
5964    evaluated by the target, host or a mix of both.  Returns the following:
5965
5966     "host": Host evals condition.
5967     "host or target": Host or Target evals condition.
5968     "target": Target evals condition.
5969 */
5970
5971 static const char *
5972 bp_condition_evaluator (struct breakpoint *b)
5973 {
5974   struct bp_location *bl;
5975   char host_evals = 0;
5976   char target_evals = 0;
5977
5978   if (!b)
5979     return NULL;
5980
5981   if (!is_breakpoint (b))
5982     return NULL;
5983
5984   if (gdb_evaluates_breakpoint_condition_p ()
5985       || !target_supports_evaluation_of_breakpoint_conditions ())
5986     return condition_evaluation_host;
5987
5988   for (bl = b->loc; bl; bl = bl->next)
5989     {
5990       if (bl->cond_bytecode)
5991         target_evals++;
5992       else
5993         host_evals++;
5994     }
5995
5996   if (host_evals && target_evals)
5997     return condition_evaluation_both;
5998   else if (target_evals)
5999     return condition_evaluation_target;
6000   else
6001     return condition_evaluation_host;
6002 }
6003
6004 /* Determine the breakpoint location's condition evaluator.  This is
6005    similar to bp_condition_evaluator, but for locations.  */
6006
6007 static const char *
6008 bp_location_condition_evaluator (struct bp_location *bl)
6009 {
6010   if (bl && !is_breakpoint (bl->owner))
6011     return NULL;
6012
6013   if (gdb_evaluates_breakpoint_condition_p ()
6014       || !target_supports_evaluation_of_breakpoint_conditions ())
6015     return condition_evaluation_host;
6016
6017   if (bl && bl->cond_bytecode)
6018     return condition_evaluation_target;
6019   else
6020     return condition_evaluation_host;
6021 }
6022
6023 /* Print the LOC location out of the list of B->LOC locations.  */
6024
6025 static void
6026 print_breakpoint_location (struct breakpoint *b,
6027                            struct bp_location *loc)
6028 {
6029   struct ui_out *uiout = current_uiout;
6030   struct cleanup *old_chain = save_current_program_space ();
6031
6032   if (loc != NULL && loc->shlib_disabled)
6033     loc = NULL;
6034
6035   if (loc != NULL)
6036     set_current_program_space (loc->pspace);
6037
6038   if (b->display_canonical)
6039     ui_out_field_string (uiout, "what", b->addr_string);
6040   else if (loc && loc->symtab)
6041     {
6042       struct symbol *sym 
6043         = find_pc_sect_function (loc->address, loc->section);
6044       if (sym)
6045         {
6046           ui_out_text (uiout, "in ");
6047           ui_out_field_string (uiout, "func",
6048                                SYMBOL_PRINT_NAME (sym));
6049           ui_out_text (uiout, " ");
6050           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6051           ui_out_text (uiout, "at ");
6052         }
6053       ui_out_field_string (uiout, "file",
6054                            symtab_to_filename_for_display (loc->symtab));
6055       ui_out_text (uiout, ":");
6056
6057       if (ui_out_is_mi_like_p (uiout))
6058         ui_out_field_string (uiout, "fullname",
6059                              symtab_to_fullname (loc->symtab));
6060       
6061       ui_out_field_int (uiout, "line", loc->line_number);
6062     }
6063   else if (loc)
6064     {
6065       struct ui_file *stb = mem_fileopen ();
6066       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6067
6068       print_address_symbolic (loc->gdbarch, loc->address, stb,
6069                               demangle, "");
6070       ui_out_field_stream (uiout, "at", stb);
6071
6072       do_cleanups (stb_chain);
6073     }
6074   else
6075     ui_out_field_string (uiout, "pending", b->addr_string);
6076
6077   if (loc && is_breakpoint (b)
6078       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6079       && bp_condition_evaluator (b) == condition_evaluation_both)
6080     {
6081       ui_out_text (uiout, " (");
6082       ui_out_field_string (uiout, "evaluated-by",
6083                            bp_location_condition_evaluator (loc));
6084       ui_out_text (uiout, ")");
6085     }
6086
6087   do_cleanups (old_chain);
6088 }
6089
6090 static const char *
6091 bptype_string (enum bptype type)
6092 {
6093   struct ep_type_description
6094     {
6095       enum bptype type;
6096       char *description;
6097     };
6098   static struct ep_type_description bptypes[] =
6099   {
6100     {bp_none, "?deleted?"},
6101     {bp_breakpoint, "breakpoint"},
6102     {bp_hardware_breakpoint, "hw breakpoint"},
6103     {bp_until, "until"},
6104     {bp_finish, "finish"},
6105     {bp_watchpoint, "watchpoint"},
6106     {bp_hardware_watchpoint, "hw watchpoint"},
6107     {bp_read_watchpoint, "read watchpoint"},
6108     {bp_access_watchpoint, "acc watchpoint"},
6109     {bp_longjmp, "longjmp"},
6110     {bp_longjmp_resume, "longjmp resume"},
6111     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6112     {bp_exception, "exception"},
6113     {bp_exception_resume, "exception resume"},
6114     {bp_step_resume, "step resume"},
6115     {bp_hp_step_resume, "high-priority step resume"},
6116     {bp_watchpoint_scope, "watchpoint scope"},
6117     {bp_call_dummy, "call dummy"},
6118     {bp_std_terminate, "std::terminate"},
6119     {bp_shlib_event, "shlib events"},
6120     {bp_thread_event, "thread events"},
6121     {bp_overlay_event, "overlay events"},
6122     {bp_longjmp_master, "longjmp master"},
6123     {bp_std_terminate_master, "std::terminate master"},
6124     {bp_exception_master, "exception master"},
6125     {bp_catchpoint, "catchpoint"},
6126     {bp_tracepoint, "tracepoint"},
6127     {bp_fast_tracepoint, "fast tracepoint"},
6128     {bp_static_tracepoint, "static tracepoint"},
6129     {bp_dprintf, "dprintf"},
6130     {bp_jit_event, "jit events"},
6131     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6132     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6133   };
6134
6135   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6136       || ((int) type != bptypes[(int) type].type))
6137     internal_error (__FILE__, __LINE__,
6138                     _("bptypes table does not describe type #%d."),
6139                     (int) type);
6140
6141   return bptypes[(int) type].description;
6142 }
6143
6144 /* For MI, output a field named 'thread-groups' with a list as the value.
6145    For CLI, prefix the list with the string 'inf'. */
6146
6147 static void
6148 output_thread_groups (struct ui_out *uiout,
6149                       const char *field_name,
6150                       VEC(int) *inf_num,
6151                       int mi_only)
6152 {
6153   struct cleanup *back_to;
6154   int is_mi = ui_out_is_mi_like_p (uiout);
6155   int inf;
6156   int i;
6157
6158   /* For backward compatibility, don't display inferiors in CLI unless
6159      there are several.  Always display them for MI. */
6160   if (!is_mi && mi_only)
6161     return;
6162
6163   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6164
6165   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6166     {
6167       if (is_mi)
6168         {
6169           char mi_group[10];
6170
6171           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6172           ui_out_field_string (uiout, NULL, mi_group);
6173         }
6174       else
6175         {
6176           if (i == 0)
6177             ui_out_text (uiout, " inf ");
6178           else
6179             ui_out_text (uiout, ", ");
6180         
6181           ui_out_text (uiout, plongest (inf));
6182         }
6183     }
6184
6185   do_cleanups (back_to);
6186 }
6187
6188 /* Print B to gdb_stdout.  */
6189
6190 static void
6191 print_one_breakpoint_location (struct breakpoint *b,
6192                                struct bp_location *loc,
6193                                int loc_number,
6194                                struct bp_location **last_loc,
6195                                int allflag)
6196 {
6197   struct command_line *l;
6198   static char bpenables[] = "nynny";
6199
6200   struct ui_out *uiout = current_uiout;
6201   int header_of_multiple = 0;
6202   int part_of_multiple = (loc != NULL);
6203   struct value_print_options opts;
6204
6205   get_user_print_options (&opts);
6206
6207   gdb_assert (!loc || loc_number != 0);
6208   /* See comment in print_one_breakpoint concerning treatment of
6209      breakpoints with single disabled location.  */
6210   if (loc == NULL 
6211       && (b->loc != NULL 
6212           && (b->loc->next != NULL || !b->loc->enabled)))
6213     header_of_multiple = 1;
6214   if (loc == NULL)
6215     loc = b->loc;
6216
6217   annotate_record ();
6218
6219   /* 1 */
6220   annotate_field (0);
6221   if (part_of_multiple)
6222     {
6223       char *formatted;
6224       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6225       ui_out_field_string (uiout, "number", formatted);
6226       xfree (formatted);
6227     }
6228   else
6229     {
6230       ui_out_field_int (uiout, "number", b->number);
6231     }
6232
6233   /* 2 */
6234   annotate_field (1);
6235   if (part_of_multiple)
6236     ui_out_field_skip (uiout, "type");
6237   else
6238     ui_out_field_string (uiout, "type", bptype_string (b->type));
6239
6240   /* 3 */
6241   annotate_field (2);
6242   if (part_of_multiple)
6243     ui_out_field_skip (uiout, "disp");
6244   else
6245     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6246
6247
6248   /* 4 */
6249   annotate_field (3);
6250   if (part_of_multiple)
6251     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6252   else
6253     ui_out_field_fmt (uiout, "enabled", "%c", 
6254                       bpenables[(int) b->enable_state]);
6255   ui_out_spaces (uiout, 2);
6256
6257   
6258   /* 5 and 6 */
6259   if (b->ops != NULL && b->ops->print_one != NULL)
6260     {
6261       /* Although the print_one can possibly print all locations,
6262          calling it here is not likely to get any nice result.  So,
6263          make sure there's just one location.  */
6264       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6265       b->ops->print_one (b, last_loc);
6266     }
6267   else
6268     switch (b->type)
6269       {
6270       case bp_none:
6271         internal_error (__FILE__, __LINE__,
6272                         _("print_one_breakpoint: bp_none encountered\n"));
6273         break;
6274
6275       case bp_watchpoint:
6276       case bp_hardware_watchpoint:
6277       case bp_read_watchpoint:
6278       case bp_access_watchpoint:
6279         {
6280           struct watchpoint *w = (struct watchpoint *) b;
6281
6282           /* Field 4, the address, is omitted (which makes the columns
6283              not line up too nicely with the headers, but the effect
6284              is relatively readable).  */
6285           if (opts.addressprint)
6286             ui_out_field_skip (uiout, "addr");
6287           annotate_field (5);
6288           ui_out_field_string (uiout, "what", w->exp_string);
6289         }
6290         break;
6291
6292       case bp_breakpoint:
6293       case bp_hardware_breakpoint:
6294       case bp_until:
6295       case bp_finish:
6296       case bp_longjmp:
6297       case bp_longjmp_resume:
6298       case bp_longjmp_call_dummy:
6299       case bp_exception:
6300       case bp_exception_resume:
6301       case bp_step_resume:
6302       case bp_hp_step_resume:
6303       case bp_watchpoint_scope:
6304       case bp_call_dummy:
6305       case bp_std_terminate:
6306       case bp_shlib_event:
6307       case bp_thread_event:
6308       case bp_overlay_event:
6309       case bp_longjmp_master:
6310       case bp_std_terminate_master:
6311       case bp_exception_master:
6312       case bp_tracepoint:
6313       case bp_fast_tracepoint:
6314       case bp_static_tracepoint:
6315       case bp_dprintf:
6316       case bp_jit_event:
6317       case bp_gnu_ifunc_resolver:
6318       case bp_gnu_ifunc_resolver_return:
6319         if (opts.addressprint)
6320           {
6321             annotate_field (4);
6322             if (header_of_multiple)
6323               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6324             else if (b->loc == NULL || loc->shlib_disabled)
6325               ui_out_field_string (uiout, "addr", "<PENDING>");
6326             else
6327               ui_out_field_core_addr (uiout, "addr",
6328                                       loc->gdbarch, loc->address);
6329           }
6330         annotate_field (5);
6331         if (!header_of_multiple)
6332           print_breakpoint_location (b, loc);
6333         if (b->loc)
6334           *last_loc = b->loc;
6335         break;
6336       }
6337
6338
6339   if (loc != NULL && !header_of_multiple)
6340     {
6341       struct inferior *inf;
6342       VEC(int) *inf_num = NULL;
6343       int mi_only = 1;
6344
6345       ALL_INFERIORS (inf)
6346         {
6347           if (inf->pspace == loc->pspace)
6348             VEC_safe_push (int, inf_num, inf->num);
6349         }
6350
6351         /* For backward compatibility, don't display inferiors in CLI unless
6352            there are several.  Always display for MI. */
6353         if (allflag
6354             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6355                 && (number_of_program_spaces () > 1
6356                     || number_of_inferiors () > 1)
6357                 /* LOC is for existing B, it cannot be in
6358                    moribund_locations and thus having NULL OWNER.  */
6359                 && loc->owner->type != bp_catchpoint))
6360         mi_only = 0;
6361       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6362       VEC_free (int, inf_num);
6363     }
6364
6365   if (!part_of_multiple)
6366     {
6367       if (b->thread != -1)
6368         {
6369           /* FIXME: This seems to be redundant and lost here; see the
6370              "stop only in" line a little further down.  */
6371           ui_out_text (uiout, " thread ");
6372           ui_out_field_int (uiout, "thread", b->thread);
6373         }
6374       else if (b->task != 0)
6375         {
6376           ui_out_text (uiout, " task ");
6377           ui_out_field_int (uiout, "task", b->task);
6378         }
6379     }
6380
6381   ui_out_text (uiout, "\n");
6382
6383   if (!part_of_multiple)
6384     b->ops->print_one_detail (b, uiout);
6385
6386   if (part_of_multiple && frame_id_p (b->frame_id))
6387     {
6388       annotate_field (6);
6389       ui_out_text (uiout, "\tstop only in stack frame at ");
6390       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6391          the frame ID.  */
6392       ui_out_field_core_addr (uiout, "frame",
6393                               b->gdbarch, b->frame_id.stack_addr);
6394       ui_out_text (uiout, "\n");
6395     }
6396   
6397   if (!part_of_multiple && b->cond_string)
6398     {
6399       annotate_field (7);
6400       if (is_tracepoint (b))
6401         ui_out_text (uiout, "\ttrace only if ");
6402       else
6403         ui_out_text (uiout, "\tstop only if ");
6404       ui_out_field_string (uiout, "cond", b->cond_string);
6405
6406       /* Print whether the target is doing the breakpoint's condition
6407          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6408       if (is_breakpoint (b)
6409           && breakpoint_condition_evaluation_mode ()
6410           == condition_evaluation_target)
6411         {
6412           ui_out_text (uiout, " (");
6413           ui_out_field_string (uiout, "evaluated-by",
6414                                bp_condition_evaluator (b));
6415           ui_out_text (uiout, " evals)");
6416         }
6417       ui_out_text (uiout, "\n");
6418     }
6419
6420   if (!part_of_multiple && b->thread != -1)
6421     {
6422       /* FIXME should make an annotation for this.  */
6423       ui_out_text (uiout, "\tstop only in thread ");
6424       ui_out_field_int (uiout, "thread", b->thread);
6425       ui_out_text (uiout, "\n");
6426     }
6427   
6428   if (!part_of_multiple)
6429     {
6430       if (b->hit_count)
6431         {
6432           /* FIXME should make an annotation for this.  */
6433           if (is_catchpoint (b))
6434             ui_out_text (uiout, "\tcatchpoint");
6435           else if (is_tracepoint (b))
6436             ui_out_text (uiout, "\ttracepoint");
6437           else
6438             ui_out_text (uiout, "\tbreakpoint");
6439           ui_out_text (uiout, " already hit ");
6440           ui_out_field_int (uiout, "times", b->hit_count);
6441           if (b->hit_count == 1)
6442             ui_out_text (uiout, " time\n");
6443           else
6444             ui_out_text (uiout, " times\n");
6445         }
6446       else
6447         {
6448           /* Output the count also if it is zero, but only if this is mi.  */
6449           if (ui_out_is_mi_like_p (uiout))
6450             ui_out_field_int (uiout, "times", b->hit_count);
6451         }
6452     }
6453
6454   if (!part_of_multiple && b->ignore_count)
6455     {
6456       annotate_field (8);
6457       ui_out_text (uiout, "\tignore next ");
6458       ui_out_field_int (uiout, "ignore", b->ignore_count);
6459       ui_out_text (uiout, " hits\n");
6460     }
6461
6462   /* Note that an enable count of 1 corresponds to "enable once"
6463      behavior, which is reported by the combination of enablement and
6464      disposition, so we don't need to mention it here.  */
6465   if (!part_of_multiple && b->enable_count > 1)
6466     {
6467       annotate_field (8);
6468       ui_out_text (uiout, "\tdisable after ");
6469       /* Tweak the wording to clarify that ignore and enable counts
6470          are distinct, and have additive effect.  */
6471       if (b->ignore_count)
6472         ui_out_text (uiout, "additional ");
6473       else
6474         ui_out_text (uiout, "next ");
6475       ui_out_field_int (uiout, "enable", b->enable_count);
6476       ui_out_text (uiout, " hits\n");
6477     }
6478
6479   if (!part_of_multiple && is_tracepoint (b))
6480     {
6481       struct tracepoint *tp = (struct tracepoint *) b;
6482
6483       if (tp->traceframe_usage)
6484         {
6485           ui_out_text (uiout, "\ttrace buffer usage ");
6486           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6487           ui_out_text (uiout, " bytes\n");
6488         }
6489     }
6490
6491   l = b->commands ? b->commands->commands : NULL;
6492   if (!part_of_multiple && l)
6493     {
6494       struct cleanup *script_chain;
6495
6496       annotate_field (9);
6497       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6498       print_command_lines (uiout, l, 4);
6499       do_cleanups (script_chain);
6500     }
6501
6502   if (is_tracepoint (b))
6503     {
6504       struct tracepoint *t = (struct tracepoint *) b;
6505
6506       if (!part_of_multiple && t->pass_count)
6507         {
6508           annotate_field (10);
6509           ui_out_text (uiout, "\tpass count ");
6510           ui_out_field_int (uiout, "pass", t->pass_count);
6511           ui_out_text (uiout, " \n");
6512         }
6513
6514       /* Don't display it when tracepoint or tracepoint location is
6515          pending.   */
6516       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6517         {
6518           annotate_field (11);
6519
6520           if (ui_out_is_mi_like_p (uiout))
6521             ui_out_field_string (uiout, "installed",
6522                                  loc->inserted ? "y" : "n");
6523           else
6524             {
6525               if (loc->inserted)
6526                 ui_out_text (uiout, "\t");
6527               else
6528                 ui_out_text (uiout, "\tnot ");
6529               ui_out_text (uiout, "installed on target\n");
6530             }
6531         }
6532     }
6533
6534   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6535     {
6536       if (is_watchpoint (b))
6537         {
6538           struct watchpoint *w = (struct watchpoint *) b;
6539
6540           ui_out_field_string (uiout, "original-location", w->exp_string);
6541         }
6542       else if (b->addr_string)
6543         ui_out_field_string (uiout, "original-location", b->addr_string);
6544     }
6545 }
6546
6547 static void
6548 print_one_breakpoint (struct breakpoint *b,
6549                       struct bp_location **last_loc, 
6550                       int allflag)
6551 {
6552   struct cleanup *bkpt_chain;
6553   struct ui_out *uiout = current_uiout;
6554
6555   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6556
6557   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6558   do_cleanups (bkpt_chain);
6559
6560   /* If this breakpoint has custom print function,
6561      it's already printed.  Otherwise, print individual
6562      locations, if any.  */
6563   if (b->ops == NULL || b->ops->print_one == NULL)
6564     {
6565       /* If breakpoint has a single location that is disabled, we
6566          print it as if it had several locations, since otherwise it's
6567          hard to represent "breakpoint enabled, location disabled"
6568          situation.
6569
6570          Note that while hardware watchpoints have several locations
6571          internally, that's not a property exposed to user.  */
6572       if (b->loc 
6573           && !is_hardware_watchpoint (b)
6574           && (b->loc->next || !b->loc->enabled))
6575         {
6576           struct bp_location *loc;
6577           int n = 1;
6578
6579           for (loc = b->loc; loc; loc = loc->next, ++n)
6580             {
6581               struct cleanup *inner2 =
6582                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6583               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6584               do_cleanups (inner2);
6585             }
6586         }
6587     }
6588 }
6589
6590 static int
6591 breakpoint_address_bits (struct breakpoint *b)
6592 {
6593   int print_address_bits = 0;
6594   struct bp_location *loc;
6595
6596   for (loc = b->loc; loc; loc = loc->next)
6597     {
6598       int addr_bit;
6599
6600       /* Software watchpoints that aren't watching memory don't have
6601          an address to print.  */
6602       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6603         continue;
6604
6605       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6606       if (addr_bit > print_address_bits)
6607         print_address_bits = addr_bit;
6608     }
6609
6610   return print_address_bits;
6611 }
6612
6613 struct captured_breakpoint_query_args
6614   {
6615     int bnum;
6616   };
6617
6618 static int
6619 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6620 {
6621   struct captured_breakpoint_query_args *args = data;
6622   struct breakpoint *b;
6623   struct bp_location *dummy_loc = NULL;
6624
6625   ALL_BREAKPOINTS (b)
6626     {
6627       if (args->bnum == b->number)
6628         {
6629           print_one_breakpoint (b, &dummy_loc, 0);
6630           return GDB_RC_OK;
6631         }
6632     }
6633   return GDB_RC_NONE;
6634 }
6635
6636 enum gdb_rc
6637 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6638                       char **error_message)
6639 {
6640   struct captured_breakpoint_query_args args;
6641
6642   args.bnum = bnum;
6643   /* For the moment we don't trust print_one_breakpoint() to not throw
6644      an error.  */
6645   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6646                                  error_message, RETURN_MASK_ALL) < 0)
6647     return GDB_RC_FAIL;
6648   else
6649     return GDB_RC_OK;
6650 }
6651
6652 /* Return true if this breakpoint was set by the user, false if it is
6653    internal or momentary.  */
6654
6655 int
6656 user_breakpoint_p (struct breakpoint *b)
6657 {
6658   return b->number > 0;
6659 }
6660
6661 /* Print information on user settable breakpoint (watchpoint, etc)
6662    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6663    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6664    FILTER is non-NULL, call it on each breakpoint and only include the
6665    ones for which it returns non-zero.  Return the total number of
6666    breakpoints listed.  */
6667
6668 static int
6669 breakpoint_1 (char *args, int allflag, 
6670               int (*filter) (const struct breakpoint *))
6671 {
6672   struct breakpoint *b;
6673   struct bp_location *last_loc = NULL;
6674   int nr_printable_breakpoints;
6675   struct cleanup *bkpttbl_chain;
6676   struct value_print_options opts;
6677   int print_address_bits = 0;
6678   int print_type_col_width = 14;
6679   struct ui_out *uiout = current_uiout;
6680
6681   get_user_print_options (&opts);
6682
6683   /* Compute the number of rows in the table, as well as the size
6684      required for address fields.  */
6685   nr_printable_breakpoints = 0;
6686   ALL_BREAKPOINTS (b)
6687     {
6688       /* If we have a filter, only list the breakpoints it accepts.  */
6689       if (filter && !filter (b))
6690         continue;
6691
6692       /* If we have an "args" string, it is a list of breakpoints to 
6693          accept.  Skip the others.  */
6694       if (args != NULL && *args != '\0')
6695         {
6696           if (allflag && parse_and_eval_long (args) != b->number)
6697             continue;
6698           if (!allflag && !number_is_in_list (args, b->number))
6699             continue;
6700         }
6701
6702       if (allflag || user_breakpoint_p (b))
6703         {
6704           int addr_bit, type_len;
6705
6706           addr_bit = breakpoint_address_bits (b);
6707           if (addr_bit > print_address_bits)
6708             print_address_bits = addr_bit;
6709
6710           type_len = strlen (bptype_string (b->type));
6711           if (type_len > print_type_col_width)
6712             print_type_col_width = type_len;
6713
6714           nr_printable_breakpoints++;
6715         }
6716     }
6717
6718   if (opts.addressprint)
6719     bkpttbl_chain 
6720       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6721                                              nr_printable_breakpoints,
6722                                              "BreakpointTable");
6723   else
6724     bkpttbl_chain 
6725       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6726                                              nr_printable_breakpoints,
6727                                              "BreakpointTable");
6728
6729   if (nr_printable_breakpoints > 0)
6730     annotate_breakpoints_headers ();
6731   if (nr_printable_breakpoints > 0)
6732     annotate_field (0);
6733   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6734   if (nr_printable_breakpoints > 0)
6735     annotate_field (1);
6736   ui_out_table_header (uiout, print_type_col_width, ui_left,
6737                        "type", "Type");                         /* 2 */
6738   if (nr_printable_breakpoints > 0)
6739     annotate_field (2);
6740   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6741   if (nr_printable_breakpoints > 0)
6742     annotate_field (3);
6743   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6744   if (opts.addressprint)
6745     {
6746       if (nr_printable_breakpoints > 0)
6747         annotate_field (4);
6748       if (print_address_bits <= 32)
6749         ui_out_table_header (uiout, 10, ui_left, 
6750                              "addr", "Address");                /* 5 */
6751       else
6752         ui_out_table_header (uiout, 18, ui_left, 
6753                              "addr", "Address");                /* 5 */
6754     }
6755   if (nr_printable_breakpoints > 0)
6756     annotate_field (5);
6757   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6758   ui_out_table_body (uiout);
6759   if (nr_printable_breakpoints > 0)
6760     annotate_breakpoints_table ();
6761
6762   ALL_BREAKPOINTS (b)
6763     {
6764       QUIT;
6765       /* If we have a filter, only list the breakpoints it accepts.  */
6766       if (filter && !filter (b))
6767         continue;
6768
6769       /* If we have an "args" string, it is a list of breakpoints to 
6770          accept.  Skip the others.  */
6771
6772       if (args != NULL && *args != '\0')
6773         {
6774           if (allflag)  /* maintenance info breakpoint */
6775             {
6776               if (parse_and_eval_long (args) != b->number)
6777                 continue;
6778             }
6779           else          /* all others */
6780             {
6781               if (!number_is_in_list (args, b->number))
6782                 continue;
6783             }
6784         }
6785       /* We only print out user settable breakpoints unless the
6786          allflag is set.  */
6787       if (allflag || user_breakpoint_p (b))
6788         print_one_breakpoint (b, &last_loc, allflag);
6789     }
6790
6791   do_cleanups (bkpttbl_chain);
6792
6793   if (nr_printable_breakpoints == 0)
6794     {
6795       /* If there's a filter, let the caller decide how to report
6796          empty list.  */
6797       if (!filter)
6798         {
6799           if (args == NULL || *args == '\0')
6800             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6801           else
6802             ui_out_message (uiout, 0, 
6803                             "No breakpoint or watchpoint matching '%s'.\n",
6804                             args);
6805         }
6806     }
6807   else
6808     {
6809       if (last_loc && !server_command)
6810         set_next_address (last_loc->gdbarch, last_loc->address);
6811     }
6812
6813   /* FIXME?  Should this be moved up so that it is only called when
6814      there have been breakpoints? */
6815   annotate_breakpoints_table_end ();
6816
6817   return nr_printable_breakpoints;
6818 }
6819
6820 /* Display the value of default-collect in a way that is generally
6821    compatible with the breakpoint list.  */
6822
6823 static void
6824 default_collect_info (void)
6825 {
6826   struct ui_out *uiout = current_uiout;
6827
6828   /* If it has no value (which is frequently the case), say nothing; a
6829      message like "No default-collect." gets in user's face when it's
6830      not wanted.  */
6831   if (!*default_collect)
6832     return;
6833
6834   /* The following phrase lines up nicely with per-tracepoint collect
6835      actions.  */
6836   ui_out_text (uiout, "default collect ");
6837   ui_out_field_string (uiout, "default-collect", default_collect);
6838   ui_out_text (uiout, " \n");
6839 }
6840   
6841 static void
6842 breakpoints_info (char *args, int from_tty)
6843 {
6844   breakpoint_1 (args, 0, NULL);
6845
6846   default_collect_info ();
6847 }
6848
6849 static void
6850 watchpoints_info (char *args, int from_tty)
6851 {
6852   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6853   struct ui_out *uiout = current_uiout;
6854
6855   if (num_printed == 0)
6856     {
6857       if (args == NULL || *args == '\0')
6858         ui_out_message (uiout, 0, "No watchpoints.\n");
6859       else
6860         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6861     }
6862 }
6863
6864 static void
6865 maintenance_info_breakpoints (char *args, int from_tty)
6866 {
6867   breakpoint_1 (args, 1, NULL);
6868
6869   default_collect_info ();
6870 }
6871
6872 static int
6873 breakpoint_has_pc (struct breakpoint *b,
6874                    struct program_space *pspace,
6875                    CORE_ADDR pc, struct obj_section *section)
6876 {
6877   struct bp_location *bl = b->loc;
6878
6879   for (; bl; bl = bl->next)
6880     {
6881       if (bl->pspace == pspace
6882           && bl->address == pc
6883           && (!overlay_debugging || bl->section == section))
6884         return 1;         
6885     }
6886   return 0;
6887 }
6888
6889 /* Print a message describing any user-breakpoints set at PC.  This
6890    concerns with logical breakpoints, so we match program spaces, not
6891    address spaces.  */
6892
6893 static void
6894 describe_other_breakpoints (struct gdbarch *gdbarch,
6895                             struct program_space *pspace, CORE_ADDR pc,
6896                             struct obj_section *section, int thread)
6897 {
6898   int others = 0;
6899   struct breakpoint *b;
6900
6901   ALL_BREAKPOINTS (b)
6902     others += (user_breakpoint_p (b)
6903                && breakpoint_has_pc (b, pspace, pc, section));
6904   if (others > 0)
6905     {
6906       if (others == 1)
6907         printf_filtered (_("Note: breakpoint "));
6908       else /* if (others == ???) */
6909         printf_filtered (_("Note: breakpoints "));
6910       ALL_BREAKPOINTS (b)
6911         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6912           {
6913             others--;
6914             printf_filtered ("%d", b->number);
6915             if (b->thread == -1 && thread != -1)
6916               printf_filtered (" (all threads)");
6917             else if (b->thread != -1)
6918               printf_filtered (" (thread %d)", b->thread);
6919             printf_filtered ("%s%s ",
6920                              ((b->enable_state == bp_disabled
6921                                || b->enable_state == bp_call_disabled)
6922                               ? " (disabled)"
6923                               : b->enable_state == bp_permanent 
6924                               ? " (permanent)"
6925                               : ""),
6926                              (others > 1) ? "," 
6927                              : ((others == 1) ? " and" : ""));
6928           }
6929       printf_filtered (_("also set at pc "));
6930       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6931       printf_filtered (".\n");
6932     }
6933 }
6934 \f
6935
6936 /* Return true iff it is meaningful to use the address member of
6937    BPT.  For some breakpoint types, the address member is irrelevant
6938    and it makes no sense to attempt to compare it to other addresses
6939    (or use it for any other purpose either).
6940
6941    More specifically, each of the following breakpoint types will
6942    always have a zero valued address and we don't want to mark
6943    breakpoints of any of these types to be a duplicate of an actual
6944    breakpoint at address zero:
6945
6946       bp_watchpoint
6947       bp_catchpoint
6948
6949 */
6950
6951 static int
6952 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6953 {
6954   enum bptype type = bpt->type;
6955
6956   return (type != bp_watchpoint && type != bp_catchpoint);
6957 }
6958
6959 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6960    true if LOC1 and LOC2 represent the same watchpoint location.  */
6961
6962 static int
6963 watchpoint_locations_match (struct bp_location *loc1, 
6964                             struct bp_location *loc2)
6965 {
6966   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6967   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6968
6969   /* Both of them must exist.  */
6970   gdb_assert (w1 != NULL);
6971   gdb_assert (w2 != NULL);
6972
6973   /* If the target can evaluate the condition expression in hardware,
6974      then we we need to insert both watchpoints even if they are at
6975      the same place.  Otherwise the watchpoint will only trigger when
6976      the condition of whichever watchpoint was inserted evaluates to
6977      true, not giving a chance for GDB to check the condition of the
6978      other watchpoint.  */
6979   if ((w1->cond_exp
6980        && target_can_accel_watchpoint_condition (loc1->address, 
6981                                                  loc1->length,
6982                                                  loc1->watchpoint_type,
6983                                                  w1->cond_exp))
6984       || (w2->cond_exp
6985           && target_can_accel_watchpoint_condition (loc2->address, 
6986                                                     loc2->length,
6987                                                     loc2->watchpoint_type,
6988                                                     w2->cond_exp)))
6989     return 0;
6990
6991   /* Note that this checks the owner's type, not the location's.  In
6992      case the target does not support read watchpoints, but does
6993      support access watchpoints, we'll have bp_read_watchpoint
6994      watchpoints with hw_access locations.  Those should be considered
6995      duplicates of hw_read locations.  The hw_read locations will
6996      become hw_access locations later.  */
6997   return (loc1->owner->type == loc2->owner->type
6998           && loc1->pspace->aspace == loc2->pspace->aspace
6999           && loc1->address == loc2->address
7000           && loc1->length == loc2->length);
7001 }
7002
7003 /* See breakpoint.h.  */
7004
7005 int
7006 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7007                           struct address_space *aspace2, CORE_ADDR addr2)
7008 {
7009   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7010            || aspace1 == aspace2)
7011           && addr1 == addr2);
7012 }
7013
7014 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7015    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7016    matches ASPACE2.  On targets that have global breakpoints, the address
7017    space doesn't really matter.  */
7018
7019 static int
7020 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7021                                 int len1, struct address_space *aspace2,
7022                                 CORE_ADDR addr2)
7023 {
7024   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7025            || aspace1 == aspace2)
7026           && addr2 >= addr1 && addr2 < addr1 + len1);
7027 }
7028
7029 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7030    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7031    matches the breakpoint's address space.  On targets that have global
7032    breakpoints, the address space doesn't really matter.  */
7033
7034 static int
7035 breakpoint_location_address_match (struct bp_location *bl,
7036                                    struct address_space *aspace,
7037                                    CORE_ADDR addr)
7038 {
7039   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7040                                     aspace, addr)
7041           || (bl->length
7042               && breakpoint_address_match_range (bl->pspace->aspace,
7043                                                  bl->address, bl->length,
7044                                                  aspace, addr)));
7045 }
7046
7047 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7048    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7049    true, otherwise returns false.  */
7050
7051 static int
7052 tracepoint_locations_match (struct bp_location *loc1,
7053                             struct bp_location *loc2)
7054 {
7055   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7056     /* Since tracepoint locations are never duplicated with others', tracepoint
7057        locations at the same address of different tracepoints are regarded as
7058        different locations.  */
7059     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7060   else
7061     return 0;
7062 }
7063
7064 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7065    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7066    represent the same location.  */
7067
7068 static int
7069 breakpoint_locations_match (struct bp_location *loc1, 
7070                             struct bp_location *loc2)
7071 {
7072   int hw_point1, hw_point2;
7073
7074   /* Both of them must not be in moribund_locations.  */
7075   gdb_assert (loc1->owner != NULL);
7076   gdb_assert (loc2->owner != NULL);
7077
7078   hw_point1 = is_hardware_watchpoint (loc1->owner);
7079   hw_point2 = is_hardware_watchpoint (loc2->owner);
7080
7081   if (hw_point1 != hw_point2)
7082     return 0;
7083   else if (hw_point1)
7084     return watchpoint_locations_match (loc1, loc2);
7085   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7086     return tracepoint_locations_match (loc1, loc2);
7087   else
7088     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7089     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7090                                      loc2->pspace->aspace, loc2->address)
7091             && loc1->length == loc2->length);
7092 }
7093
7094 static void
7095 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7096                                int bnum, int have_bnum)
7097 {
7098   /* The longest string possibly returned by hex_string_custom
7099      is 50 chars.  These must be at least that big for safety.  */
7100   char astr1[64];
7101   char astr2[64];
7102
7103   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7104   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7105   if (have_bnum)
7106     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7107              bnum, astr1, astr2);
7108   else
7109     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7110 }
7111
7112 /* Adjust a breakpoint's address to account for architectural
7113    constraints on breakpoint placement.  Return the adjusted address.
7114    Note: Very few targets require this kind of adjustment.  For most
7115    targets, this function is simply the identity function.  */
7116
7117 static CORE_ADDR
7118 adjust_breakpoint_address (struct gdbarch *gdbarch,
7119                            CORE_ADDR bpaddr, enum bptype bptype)
7120 {
7121   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7122     {
7123       /* Very few targets need any kind of breakpoint adjustment.  */
7124       return bpaddr;
7125     }
7126   else if (bptype == bp_watchpoint
7127            || bptype == bp_hardware_watchpoint
7128            || bptype == bp_read_watchpoint
7129            || bptype == bp_access_watchpoint
7130            || bptype == bp_catchpoint)
7131     {
7132       /* Watchpoints and the various bp_catch_* eventpoints should not
7133          have their addresses modified.  */
7134       return bpaddr;
7135     }
7136   else
7137     {
7138       CORE_ADDR adjusted_bpaddr;
7139
7140       /* Some targets have architectural constraints on the placement
7141          of breakpoint instructions.  Obtain the adjusted address.  */
7142       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7143
7144       /* An adjusted breakpoint address can significantly alter
7145          a user's expectations.  Print a warning if an adjustment
7146          is required.  */
7147       if (adjusted_bpaddr != bpaddr)
7148         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7149
7150       return adjusted_bpaddr;
7151     }
7152 }
7153
7154 void
7155 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7156                   struct breakpoint *owner)
7157 {
7158   memset (loc, 0, sizeof (*loc));
7159
7160   gdb_assert (ops != NULL);
7161
7162   loc->ops = ops;
7163   loc->owner = owner;
7164   loc->cond = NULL;
7165   loc->cond_bytecode = NULL;
7166   loc->shlib_disabled = 0;
7167   loc->enabled = 1;
7168
7169   switch (owner->type)
7170     {
7171     case bp_breakpoint:
7172     case bp_until:
7173     case bp_finish:
7174     case bp_longjmp:
7175     case bp_longjmp_resume:
7176     case bp_longjmp_call_dummy:
7177     case bp_exception:
7178     case bp_exception_resume:
7179     case bp_step_resume:
7180     case bp_hp_step_resume:
7181     case bp_watchpoint_scope:
7182     case bp_call_dummy:
7183     case bp_std_terminate:
7184     case bp_shlib_event:
7185     case bp_thread_event:
7186     case bp_overlay_event:
7187     case bp_jit_event:
7188     case bp_longjmp_master:
7189     case bp_std_terminate_master:
7190     case bp_exception_master:
7191     case bp_gnu_ifunc_resolver:
7192     case bp_gnu_ifunc_resolver_return:
7193     case bp_dprintf:
7194       loc->loc_type = bp_loc_software_breakpoint;
7195       mark_breakpoint_location_modified (loc);
7196       break;
7197     case bp_hardware_breakpoint:
7198       loc->loc_type = bp_loc_hardware_breakpoint;
7199       mark_breakpoint_location_modified (loc);
7200       break;
7201     case bp_hardware_watchpoint:
7202     case bp_read_watchpoint:
7203     case bp_access_watchpoint:
7204       loc->loc_type = bp_loc_hardware_watchpoint;
7205       break;
7206     case bp_watchpoint:
7207     case bp_catchpoint:
7208     case bp_tracepoint:
7209     case bp_fast_tracepoint:
7210     case bp_static_tracepoint:
7211       loc->loc_type = bp_loc_other;
7212       break;
7213     default:
7214       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7215     }
7216
7217   loc->refc = 1;
7218 }
7219
7220 /* Allocate a struct bp_location.  */
7221
7222 static struct bp_location *
7223 allocate_bp_location (struct breakpoint *bpt)
7224 {
7225   return bpt->ops->allocate_location (bpt);
7226 }
7227
7228 static void
7229 free_bp_location (struct bp_location *loc)
7230 {
7231   loc->ops->dtor (loc);
7232   xfree (loc);
7233 }
7234
7235 /* Increment reference count.  */
7236
7237 static void
7238 incref_bp_location (struct bp_location *bl)
7239 {
7240   ++bl->refc;
7241 }
7242
7243 /* Decrement reference count.  If the reference count reaches 0,
7244    destroy the bp_location.  Sets *BLP to NULL.  */
7245
7246 static void
7247 decref_bp_location (struct bp_location **blp)
7248 {
7249   gdb_assert ((*blp)->refc > 0);
7250
7251   if (--(*blp)->refc == 0)
7252     free_bp_location (*blp);
7253   *blp = NULL;
7254 }
7255
7256 /* Add breakpoint B at the end of the global breakpoint chain.  */
7257
7258 static void
7259 add_to_breakpoint_chain (struct breakpoint *b)
7260 {
7261   struct breakpoint *b1;
7262
7263   /* Add this breakpoint to the end of the chain so that a list of
7264      breakpoints will come out in order of increasing numbers.  */
7265
7266   b1 = breakpoint_chain;
7267   if (b1 == 0)
7268     breakpoint_chain = b;
7269   else
7270     {
7271       while (b1->next)
7272         b1 = b1->next;
7273       b1->next = b;
7274     }
7275 }
7276
7277 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7278
7279 static void
7280 init_raw_breakpoint_without_location (struct breakpoint *b,
7281                                       struct gdbarch *gdbarch,
7282                                       enum bptype bptype,
7283                                       const struct breakpoint_ops *ops)
7284 {
7285   memset (b, 0, sizeof (*b));
7286
7287   gdb_assert (ops != NULL);
7288
7289   b->ops = ops;
7290   b->type = bptype;
7291   b->gdbarch = gdbarch;
7292   b->language = current_language->la_language;
7293   b->input_radix = input_radix;
7294   b->thread = -1;
7295   b->enable_state = bp_enabled;
7296   b->next = 0;
7297   b->silent = 0;
7298   b->ignore_count = 0;
7299   b->commands = NULL;
7300   b->frame_id = null_frame_id;
7301   b->condition_not_parsed = 0;
7302   b->py_bp_object = NULL;
7303   b->related_breakpoint = b;
7304 }
7305
7306 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7307    that has type BPTYPE and has no locations as yet.  */
7308
7309 static struct breakpoint *
7310 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7311                                      enum bptype bptype,
7312                                      const struct breakpoint_ops *ops)
7313 {
7314   struct breakpoint *b = XNEW (struct breakpoint);
7315
7316   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7317   add_to_breakpoint_chain (b);
7318   return b;
7319 }
7320
7321 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7322    resolutions should be made as the user specified the location explicitly
7323    enough.  */
7324
7325 static void
7326 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7327 {
7328   gdb_assert (loc->owner != NULL);
7329
7330   if (loc->owner->type == bp_breakpoint
7331       || loc->owner->type == bp_hardware_breakpoint
7332       || is_tracepoint (loc->owner))
7333     {
7334       int is_gnu_ifunc;
7335       const char *function_name;
7336       CORE_ADDR func_addr;
7337
7338       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7339                                           &func_addr, NULL, &is_gnu_ifunc);
7340
7341       if (is_gnu_ifunc && !explicit_loc)
7342         {
7343           struct breakpoint *b = loc->owner;
7344
7345           gdb_assert (loc->pspace == current_program_space);
7346           if (gnu_ifunc_resolve_name (function_name,
7347                                       &loc->requested_address))
7348             {
7349               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7350               loc->address = adjust_breakpoint_address (loc->gdbarch,
7351                                                         loc->requested_address,
7352                                                         b->type);
7353             }
7354           else if (b->type == bp_breakpoint && b->loc == loc
7355                    && loc->next == NULL && b->related_breakpoint == b)
7356             {
7357               /* Create only the whole new breakpoint of this type but do not
7358                  mess more complicated breakpoints with multiple locations.  */
7359               b->type = bp_gnu_ifunc_resolver;
7360               /* Remember the resolver's address for use by the return
7361                  breakpoint.  */
7362               loc->related_address = func_addr;
7363             }
7364         }
7365
7366       if (function_name)
7367         loc->function_name = xstrdup (function_name);
7368     }
7369 }
7370
7371 /* Attempt to determine architecture of location identified by SAL.  */
7372 struct gdbarch *
7373 get_sal_arch (struct symtab_and_line sal)
7374 {
7375   if (sal.section)
7376     return get_objfile_arch (sal.section->objfile);
7377   if (sal.symtab)
7378     return get_objfile_arch (sal.symtab->objfile);
7379
7380   return NULL;
7381 }
7382
7383 /* Low level routine for partially initializing a breakpoint of type
7384    BPTYPE.  The newly created breakpoint's address, section, source
7385    file name, and line number are provided by SAL.
7386
7387    It is expected that the caller will complete the initialization of
7388    the newly created breakpoint struct as well as output any status
7389    information regarding the creation of a new breakpoint.  */
7390
7391 static void
7392 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7393                      struct symtab_and_line sal, enum bptype bptype,
7394                      const struct breakpoint_ops *ops)
7395 {
7396   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7397
7398   add_location_to_breakpoint (b, &sal);
7399
7400   if (bptype != bp_catchpoint)
7401     gdb_assert (sal.pspace != NULL);
7402
7403   /* Store the program space that was used to set the breakpoint,
7404      except for ordinary breakpoints, which are independent of the
7405      program space.  */
7406   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7407     b->pspace = sal.pspace;
7408 }
7409
7410 /* set_raw_breakpoint is a low level routine for allocating and
7411    partially initializing a breakpoint of type BPTYPE.  The newly
7412    created breakpoint's address, section, source file name, and line
7413    number are provided by SAL.  The newly created and partially
7414    initialized breakpoint is added to the breakpoint chain and
7415    is also returned as the value of this function.
7416
7417    It is expected that the caller will complete the initialization of
7418    the newly created breakpoint struct as well as output any status
7419    information regarding the creation of a new breakpoint.  In
7420    particular, set_raw_breakpoint does NOT set the breakpoint
7421    number!  Care should be taken to not allow an error to occur
7422    prior to completing the initialization of the breakpoint.  If this
7423    should happen, a bogus breakpoint will be left on the chain.  */
7424
7425 struct breakpoint *
7426 set_raw_breakpoint (struct gdbarch *gdbarch,
7427                     struct symtab_and_line sal, enum bptype bptype,
7428                     const struct breakpoint_ops *ops)
7429 {
7430   struct breakpoint *b = XNEW (struct breakpoint);
7431
7432   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7433   add_to_breakpoint_chain (b);
7434   return b;
7435 }
7436
7437
7438 /* Note that the breakpoint object B describes a permanent breakpoint
7439    instruction, hard-wired into the inferior's code.  */
7440 void
7441 make_breakpoint_permanent (struct breakpoint *b)
7442 {
7443   struct bp_location *bl;
7444
7445   b->enable_state = bp_permanent;
7446
7447   /* By definition, permanent breakpoints are already present in the
7448      code.  Mark all locations as inserted.  For now,
7449      make_breakpoint_permanent is called in just one place, so it's
7450      hard to say if it's reasonable to have permanent breakpoint with
7451      multiple locations or not, but it's easy to implement.  */
7452   for (bl = b->loc; bl; bl = bl->next)
7453     bl->inserted = 1;
7454 }
7455
7456 /* Call this routine when stepping and nexting to enable a breakpoint
7457    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7458    initiated the operation.  */
7459
7460 void
7461 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7462 {
7463   struct breakpoint *b, *b_tmp;
7464   int thread = tp->num;
7465
7466   /* To avoid having to rescan all objfile symbols at every step,
7467      we maintain a list of continually-inserted but always disabled
7468      longjmp "master" breakpoints.  Here, we simply create momentary
7469      clones of those and enable them for the requested thread.  */
7470   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7471     if (b->pspace == current_program_space
7472         && (b->type == bp_longjmp_master
7473             || b->type == bp_exception_master))
7474       {
7475         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7476         struct breakpoint *clone;
7477
7478         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7479            after their removal.  */
7480         clone = momentary_breakpoint_from_master (b, type,
7481                                                   &longjmp_breakpoint_ops, 1);
7482         clone->thread = thread;
7483       }
7484
7485   tp->initiating_frame = frame;
7486 }
7487
7488 /* Delete all longjmp breakpoints from THREAD.  */
7489 void
7490 delete_longjmp_breakpoint (int thread)
7491 {
7492   struct breakpoint *b, *b_tmp;
7493
7494   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7495     if (b->type == bp_longjmp || b->type == bp_exception)
7496       {
7497         if (b->thread == thread)
7498           delete_breakpoint (b);
7499       }
7500 }
7501
7502 void
7503 delete_longjmp_breakpoint_at_next_stop (int thread)
7504 {
7505   struct breakpoint *b, *b_tmp;
7506
7507   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7508     if (b->type == bp_longjmp || b->type == bp_exception)
7509       {
7510         if (b->thread == thread)
7511           b->disposition = disp_del_at_next_stop;
7512       }
7513 }
7514
7515 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7516    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7517    pointer to any of them.  Return NULL if this system cannot place longjmp
7518    breakpoints.  */
7519
7520 struct breakpoint *
7521 set_longjmp_breakpoint_for_call_dummy (void)
7522 {
7523   struct breakpoint *b, *retval = NULL;
7524
7525   ALL_BREAKPOINTS (b)
7526     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7527       {
7528         struct breakpoint *new_b;
7529
7530         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7531                                                   &momentary_breakpoint_ops,
7532                                                   1);
7533         new_b->thread = pid_to_thread_id (inferior_ptid);
7534
7535         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7536
7537         gdb_assert (new_b->related_breakpoint == new_b);
7538         if (retval == NULL)
7539           retval = new_b;
7540         new_b->related_breakpoint = retval;
7541         while (retval->related_breakpoint != new_b->related_breakpoint)
7542           retval = retval->related_breakpoint;
7543         retval->related_breakpoint = new_b;
7544       }
7545
7546   return retval;
7547 }
7548
7549 /* Verify all existing dummy frames and their associated breakpoints for
7550    TP.  Remove those which can no longer be found in the current frame
7551    stack.
7552
7553    You should call this function only at places where it is safe to currently
7554    unwind the whole stack.  Failed stack unwind would discard live dummy
7555    frames.  */
7556
7557 void
7558 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7559 {
7560   struct breakpoint *b, *b_tmp;
7561
7562   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7563     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7564       {
7565         struct breakpoint *dummy_b = b->related_breakpoint;
7566
7567         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7568           dummy_b = dummy_b->related_breakpoint;
7569         if (dummy_b->type != bp_call_dummy
7570             || frame_find_by_id (dummy_b->frame_id) != NULL)
7571           continue;
7572         
7573         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7574
7575         while (b->related_breakpoint != b)
7576           {
7577             if (b_tmp == b->related_breakpoint)
7578               b_tmp = b->related_breakpoint->next;
7579             delete_breakpoint (b->related_breakpoint);
7580           }
7581         delete_breakpoint (b);
7582       }
7583 }
7584
7585 void
7586 enable_overlay_breakpoints (void)
7587 {
7588   struct breakpoint *b;
7589
7590   ALL_BREAKPOINTS (b)
7591     if (b->type == bp_overlay_event)
7592     {
7593       b->enable_state = bp_enabled;
7594       update_global_location_list (UGLL_MAY_INSERT);
7595       overlay_events_enabled = 1;
7596     }
7597 }
7598
7599 void
7600 disable_overlay_breakpoints (void)
7601 {
7602   struct breakpoint *b;
7603
7604   ALL_BREAKPOINTS (b)
7605     if (b->type == bp_overlay_event)
7606     {
7607       b->enable_state = bp_disabled;
7608       update_global_location_list (UGLL_DONT_INSERT);
7609       overlay_events_enabled = 0;
7610     }
7611 }
7612
7613 /* Set an active std::terminate breakpoint for each std::terminate
7614    master breakpoint.  */
7615 void
7616 set_std_terminate_breakpoint (void)
7617 {
7618   struct breakpoint *b, *b_tmp;
7619
7620   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7621     if (b->pspace == current_program_space
7622         && b->type == bp_std_terminate_master)
7623       {
7624         momentary_breakpoint_from_master (b, bp_std_terminate,
7625                                           &momentary_breakpoint_ops, 1);
7626       }
7627 }
7628
7629 /* Delete all the std::terminate breakpoints.  */
7630 void
7631 delete_std_terminate_breakpoint (void)
7632 {
7633   struct breakpoint *b, *b_tmp;
7634
7635   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7636     if (b->type == bp_std_terminate)
7637       delete_breakpoint (b);
7638 }
7639
7640 struct breakpoint *
7641 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7642 {
7643   struct breakpoint *b;
7644
7645   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7646                                   &internal_breakpoint_ops);
7647
7648   b->enable_state = bp_enabled;
7649   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7650   b->addr_string
7651     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7652
7653   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7654
7655   return b;
7656 }
7657
7658 void
7659 remove_thread_event_breakpoints (void)
7660 {
7661   struct breakpoint *b, *b_tmp;
7662
7663   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7664     if (b->type == bp_thread_event
7665         && b->loc->pspace == current_program_space)
7666       delete_breakpoint (b);
7667 }
7668
7669 struct lang_and_radix
7670   {
7671     enum language lang;
7672     int radix;
7673   };
7674
7675 /* Create a breakpoint for JIT code registration and unregistration.  */
7676
7677 struct breakpoint *
7678 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7679 {
7680   struct breakpoint *b;
7681
7682   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7683                                   &internal_breakpoint_ops);
7684   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7685   return b;
7686 }
7687
7688 /* Remove JIT code registration and unregistration breakpoint(s).  */
7689
7690 void
7691 remove_jit_event_breakpoints (void)
7692 {
7693   struct breakpoint *b, *b_tmp;
7694
7695   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7696     if (b->type == bp_jit_event
7697         && b->loc->pspace == current_program_space)
7698       delete_breakpoint (b);
7699 }
7700
7701 void
7702 remove_solib_event_breakpoints (void)
7703 {
7704   struct breakpoint *b, *b_tmp;
7705
7706   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7707     if (b->type == bp_shlib_event
7708         && b->loc->pspace == current_program_space)
7709       delete_breakpoint (b);
7710 }
7711
7712 /* See breakpoint.h.  */
7713
7714 void
7715 remove_solib_event_breakpoints_at_next_stop (void)
7716 {
7717   struct breakpoint *b, *b_tmp;
7718
7719   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7720     if (b->type == bp_shlib_event
7721         && b->loc->pspace == current_program_space)
7722       b->disposition = disp_del_at_next_stop;
7723 }
7724
7725 struct breakpoint *
7726 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7727 {
7728   struct breakpoint *b;
7729
7730   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7731                                   &internal_breakpoint_ops);
7732   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7733   return b;
7734 }
7735
7736 /* See breakpoint.h.  */
7737
7738 struct breakpoint *
7739 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7740 {
7741   struct breakpoint *b;
7742
7743   b = create_solib_event_breakpoint (gdbarch, address);
7744   if (!breakpoints_always_inserted_mode ())
7745     insert_breakpoint_locations ();
7746   if (!b->loc->inserted)
7747     {
7748       delete_breakpoint (b);
7749       return NULL;
7750     }
7751   return b;
7752 }
7753
7754 /* Disable any breakpoints that are on code in shared libraries.  Only
7755    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7756
7757 void
7758 disable_breakpoints_in_shlibs (void)
7759 {
7760   struct bp_location *loc, **locp_tmp;
7761
7762   ALL_BP_LOCATIONS (loc, locp_tmp)
7763   {
7764     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7765     struct breakpoint *b = loc->owner;
7766
7767     /* We apply the check to all breakpoints, including disabled for
7768        those with loc->duplicate set.  This is so that when breakpoint
7769        becomes enabled, or the duplicate is removed, gdb will try to
7770        insert all breakpoints.  If we don't set shlib_disabled here,
7771        we'll try to insert those breakpoints and fail.  */
7772     if (((b->type == bp_breakpoint)
7773          || (b->type == bp_jit_event)
7774          || (b->type == bp_hardware_breakpoint)
7775          || (is_tracepoint (b)))
7776         && loc->pspace == current_program_space
7777         && !loc->shlib_disabled
7778         && solib_name_from_address (loc->pspace, loc->address)
7779         )
7780       {
7781         loc->shlib_disabled = 1;
7782       }
7783   }
7784 }
7785
7786 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7787    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7788    disabled ones can just stay disabled.  */
7789
7790 static void
7791 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7792 {
7793   struct bp_location *loc, **locp_tmp;
7794   int disabled_shlib_breaks = 0;
7795
7796   /* SunOS a.out shared libraries are always mapped, so do not
7797      disable breakpoints; they will only be reported as unloaded
7798      through clear_solib when GDB discards its shared library
7799      list.  See clear_solib for more information.  */
7800   if (exec_bfd != NULL
7801       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7802     return;
7803
7804   ALL_BP_LOCATIONS (loc, locp_tmp)
7805   {
7806     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7807     struct breakpoint *b = loc->owner;
7808
7809     if (solib->pspace == loc->pspace
7810         && !loc->shlib_disabled
7811         && (((b->type == bp_breakpoint
7812               || b->type == bp_jit_event
7813               || b->type == bp_hardware_breakpoint)
7814              && (loc->loc_type == bp_loc_hardware_breakpoint
7815                  || loc->loc_type == bp_loc_software_breakpoint))
7816             || is_tracepoint (b))
7817         && solib_contains_address_p (solib, loc->address))
7818       {
7819         loc->shlib_disabled = 1;
7820         /* At this point, we cannot rely on remove_breakpoint
7821            succeeding so we must mark the breakpoint as not inserted
7822            to prevent future errors occurring in remove_breakpoints.  */
7823         loc->inserted = 0;
7824
7825         /* This may cause duplicate notifications for the same breakpoint.  */
7826         observer_notify_breakpoint_modified (b);
7827
7828         if (!disabled_shlib_breaks)
7829           {
7830             target_terminal_ours_for_output ();
7831             warning (_("Temporarily disabling breakpoints "
7832                        "for unloaded shared library \"%s\""),
7833                      solib->so_name);
7834           }
7835         disabled_shlib_breaks = 1;
7836       }
7837   }
7838 }
7839
7840 /* Disable any breakpoints and tracepoints in OBJFILE upon
7841    notification of free_objfile.  Only apply to enabled breakpoints,
7842    disabled ones can just stay disabled.  */
7843
7844 static void
7845 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7846 {
7847   struct breakpoint *b;
7848
7849   if (objfile == NULL)
7850     return;
7851
7852   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7853      managed by the user with add-symbol-file/remove-symbol-file.
7854      Similarly to how breakpoints in shared libraries are handled in
7855      response to "nosharedlibrary", mark breakpoints in such modules
7856      shlib_disabled so they end up uninserted on the next global
7857      location list update.  Shared libraries not loaded by the user
7858      aren't handled here -- they're already handled in
7859      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7860      solib_unloaded observer.  We skip objfiles that are not
7861      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7862      main objfile).  */
7863   if ((objfile->flags & OBJF_SHARED) == 0
7864       || (objfile->flags & OBJF_USERLOADED) == 0)
7865     return;
7866
7867   ALL_BREAKPOINTS (b)
7868     {
7869       struct bp_location *loc;
7870       int bp_modified = 0;
7871
7872       if (!is_breakpoint (b) && !is_tracepoint (b))
7873         continue;
7874
7875       for (loc = b->loc; loc != NULL; loc = loc->next)
7876         {
7877           CORE_ADDR loc_addr = loc->address;
7878
7879           if (loc->loc_type != bp_loc_hardware_breakpoint
7880               && loc->loc_type != bp_loc_software_breakpoint)
7881             continue;
7882
7883           if (loc->shlib_disabled != 0)
7884             continue;
7885
7886           if (objfile->pspace != loc->pspace)
7887             continue;
7888
7889           if (loc->loc_type != bp_loc_hardware_breakpoint
7890               && loc->loc_type != bp_loc_software_breakpoint)
7891             continue;
7892
7893           if (is_addr_in_objfile (loc_addr, objfile))
7894             {
7895               loc->shlib_disabled = 1;
7896               /* At this point, we don't know whether the object was
7897                  unmapped from the inferior or not, so leave the
7898                  inserted flag alone.  We'll handle failure to
7899                  uninsert quietly, in case the object was indeed
7900                  unmapped.  */
7901
7902               mark_breakpoint_location_modified (loc);
7903
7904               bp_modified = 1;
7905             }
7906         }
7907
7908       if (bp_modified)
7909         observer_notify_breakpoint_modified (b);
7910     }
7911 }
7912
7913 /* FORK & VFORK catchpoints.  */
7914
7915 /* An instance of this type is used to represent a fork or vfork
7916    catchpoint.  It includes a "struct breakpoint" as a kind of base
7917    class; users downcast to "struct breakpoint *" when needed.  A
7918    breakpoint is really of this type iff its ops pointer points to
7919    CATCH_FORK_BREAKPOINT_OPS.  */
7920
7921 struct fork_catchpoint
7922 {
7923   /* The base class.  */
7924   struct breakpoint base;
7925
7926   /* Process id of a child process whose forking triggered this
7927      catchpoint.  This field is only valid immediately after this
7928      catchpoint has triggered.  */
7929   ptid_t forked_inferior_pid;
7930 };
7931
7932 /* Implement the "insert" breakpoint_ops method for fork
7933    catchpoints.  */
7934
7935 static int
7936 insert_catch_fork (struct bp_location *bl)
7937 {
7938   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7939 }
7940
7941 /* Implement the "remove" breakpoint_ops method for fork
7942    catchpoints.  */
7943
7944 static int
7945 remove_catch_fork (struct bp_location *bl)
7946 {
7947   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7948 }
7949
7950 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7951    catchpoints.  */
7952
7953 static int
7954 breakpoint_hit_catch_fork (const struct bp_location *bl,
7955                            struct address_space *aspace, CORE_ADDR bp_addr,
7956                            const struct target_waitstatus *ws)
7957 {
7958   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7959
7960   if (ws->kind != TARGET_WAITKIND_FORKED)
7961     return 0;
7962
7963   c->forked_inferior_pid = ws->value.related_pid;
7964   return 1;
7965 }
7966
7967 /* Implement the "print_it" breakpoint_ops method for fork
7968    catchpoints.  */
7969
7970 static enum print_stop_action
7971 print_it_catch_fork (bpstat bs)
7972 {
7973   struct ui_out *uiout = current_uiout;
7974   struct breakpoint *b = bs->breakpoint_at;
7975   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7976
7977   annotate_catchpoint (b->number);
7978   if (b->disposition == disp_del)
7979     ui_out_text (uiout, "\nTemporary catchpoint ");
7980   else
7981     ui_out_text (uiout, "\nCatchpoint ");
7982   if (ui_out_is_mi_like_p (uiout))
7983     {
7984       ui_out_field_string (uiout, "reason",
7985                            async_reason_lookup (EXEC_ASYNC_FORK));
7986       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7987     }
7988   ui_out_field_int (uiout, "bkptno", b->number);
7989   ui_out_text (uiout, " (forked process ");
7990   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7991   ui_out_text (uiout, "), ");
7992   return PRINT_SRC_AND_LOC;
7993 }
7994
7995 /* Implement the "print_one" breakpoint_ops method for fork
7996    catchpoints.  */
7997
7998 static void
7999 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8000 {
8001   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8002   struct value_print_options opts;
8003   struct ui_out *uiout = current_uiout;
8004
8005   get_user_print_options (&opts);
8006
8007   /* Field 4, the address, is omitted (which makes the columns not
8008      line up too nicely with the headers, but the effect is relatively
8009      readable).  */
8010   if (opts.addressprint)
8011     ui_out_field_skip (uiout, "addr");
8012   annotate_field (5);
8013   ui_out_text (uiout, "fork");
8014   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8015     {
8016       ui_out_text (uiout, ", process ");
8017       ui_out_field_int (uiout, "what",
8018                         ptid_get_pid (c->forked_inferior_pid));
8019       ui_out_spaces (uiout, 1);
8020     }
8021
8022   if (ui_out_is_mi_like_p (uiout))
8023     ui_out_field_string (uiout, "catch-type", "fork");
8024 }
8025
8026 /* Implement the "print_mention" breakpoint_ops method for fork
8027    catchpoints.  */
8028
8029 static void
8030 print_mention_catch_fork (struct breakpoint *b)
8031 {
8032   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8033 }
8034
8035 /* Implement the "print_recreate" breakpoint_ops method for fork
8036    catchpoints.  */
8037
8038 static void
8039 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8040 {
8041   fprintf_unfiltered (fp, "catch fork");
8042   print_recreate_thread (b, fp);
8043 }
8044
8045 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8046
8047 static struct breakpoint_ops catch_fork_breakpoint_ops;
8048
8049 /* Implement the "insert" breakpoint_ops method for vfork
8050    catchpoints.  */
8051
8052 static int
8053 insert_catch_vfork (struct bp_location *bl)
8054 {
8055   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8056 }
8057
8058 /* Implement the "remove" breakpoint_ops method for vfork
8059    catchpoints.  */
8060
8061 static int
8062 remove_catch_vfork (struct bp_location *bl)
8063 {
8064   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8065 }
8066
8067 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8068    catchpoints.  */
8069
8070 static int
8071 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8072                             struct address_space *aspace, CORE_ADDR bp_addr,
8073                             const struct target_waitstatus *ws)
8074 {
8075   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8076
8077   if (ws->kind != TARGET_WAITKIND_VFORKED)
8078     return 0;
8079
8080   c->forked_inferior_pid = ws->value.related_pid;
8081   return 1;
8082 }
8083
8084 /* Implement the "print_it" breakpoint_ops method for vfork
8085    catchpoints.  */
8086
8087 static enum print_stop_action
8088 print_it_catch_vfork (bpstat bs)
8089 {
8090   struct ui_out *uiout = current_uiout;
8091   struct breakpoint *b = bs->breakpoint_at;
8092   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8093
8094   annotate_catchpoint (b->number);
8095   if (b->disposition == disp_del)
8096     ui_out_text (uiout, "\nTemporary catchpoint ");
8097   else
8098     ui_out_text (uiout, "\nCatchpoint ");
8099   if (ui_out_is_mi_like_p (uiout))
8100     {
8101       ui_out_field_string (uiout, "reason",
8102                            async_reason_lookup (EXEC_ASYNC_VFORK));
8103       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8104     }
8105   ui_out_field_int (uiout, "bkptno", b->number);
8106   ui_out_text (uiout, " (vforked process ");
8107   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8108   ui_out_text (uiout, "), ");
8109   return PRINT_SRC_AND_LOC;
8110 }
8111
8112 /* Implement the "print_one" breakpoint_ops method for vfork
8113    catchpoints.  */
8114
8115 static void
8116 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8117 {
8118   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8119   struct value_print_options opts;
8120   struct ui_out *uiout = current_uiout;
8121
8122   get_user_print_options (&opts);
8123   /* Field 4, the address, is omitted (which makes the columns not
8124      line up too nicely with the headers, but the effect is relatively
8125      readable).  */
8126   if (opts.addressprint)
8127     ui_out_field_skip (uiout, "addr");
8128   annotate_field (5);
8129   ui_out_text (uiout, "vfork");
8130   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8131     {
8132       ui_out_text (uiout, ", process ");
8133       ui_out_field_int (uiout, "what",
8134                         ptid_get_pid (c->forked_inferior_pid));
8135       ui_out_spaces (uiout, 1);
8136     }
8137
8138   if (ui_out_is_mi_like_p (uiout))
8139     ui_out_field_string (uiout, "catch-type", "vfork");
8140 }
8141
8142 /* Implement the "print_mention" breakpoint_ops method for vfork
8143    catchpoints.  */
8144
8145 static void
8146 print_mention_catch_vfork (struct breakpoint *b)
8147 {
8148   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8149 }
8150
8151 /* Implement the "print_recreate" breakpoint_ops method for vfork
8152    catchpoints.  */
8153
8154 static void
8155 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8156 {
8157   fprintf_unfiltered (fp, "catch vfork");
8158   print_recreate_thread (b, fp);
8159 }
8160
8161 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8162
8163 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8164
8165 /* An instance of this type is used to represent an solib catchpoint.
8166    It includes a "struct breakpoint" as a kind of base class; users
8167    downcast to "struct breakpoint *" when needed.  A breakpoint is
8168    really of this type iff its ops pointer points to
8169    CATCH_SOLIB_BREAKPOINT_OPS.  */
8170
8171 struct solib_catchpoint
8172 {
8173   /* The base class.  */
8174   struct breakpoint base;
8175
8176   /* True for "catch load", false for "catch unload".  */
8177   unsigned char is_load;
8178
8179   /* Regular expression to match, if any.  COMPILED is only valid when
8180      REGEX is non-NULL.  */
8181   char *regex;
8182   regex_t compiled;
8183 };
8184
8185 static void
8186 dtor_catch_solib (struct breakpoint *b)
8187 {
8188   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8189
8190   if (self->regex)
8191     regfree (&self->compiled);
8192   xfree (self->regex);
8193
8194   base_breakpoint_ops.dtor (b);
8195 }
8196
8197 static int
8198 insert_catch_solib (struct bp_location *ignore)
8199 {
8200   return 0;
8201 }
8202
8203 static int
8204 remove_catch_solib (struct bp_location *ignore)
8205 {
8206   return 0;
8207 }
8208
8209 static int
8210 breakpoint_hit_catch_solib (const struct bp_location *bl,
8211                             struct address_space *aspace,
8212                             CORE_ADDR bp_addr,
8213                             const struct target_waitstatus *ws)
8214 {
8215   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8216   struct breakpoint *other;
8217
8218   if (ws->kind == TARGET_WAITKIND_LOADED)
8219     return 1;
8220
8221   ALL_BREAKPOINTS (other)
8222   {
8223     struct bp_location *other_bl;
8224
8225     if (other == bl->owner)
8226       continue;
8227
8228     if (other->type != bp_shlib_event)
8229       continue;
8230
8231     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8232       continue;
8233
8234     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8235       {
8236         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8237           return 1;
8238       }
8239   }
8240
8241   return 0;
8242 }
8243
8244 static void
8245 check_status_catch_solib (struct bpstats *bs)
8246 {
8247   struct solib_catchpoint *self
8248     = (struct solib_catchpoint *) bs->breakpoint_at;
8249   int ix;
8250
8251   if (self->is_load)
8252     {
8253       struct so_list *iter;
8254
8255       for (ix = 0;
8256            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8257                         ix, iter);
8258            ++ix)
8259         {
8260           if (!self->regex
8261               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8262             return;
8263         }
8264     }
8265   else
8266     {
8267       char *iter;
8268
8269       for (ix = 0;
8270            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8271                         ix, iter);
8272            ++ix)
8273         {
8274           if (!self->regex
8275               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8276             return;
8277         }
8278     }
8279
8280   bs->stop = 0;
8281   bs->print_it = print_it_noop;
8282 }
8283
8284 static enum print_stop_action
8285 print_it_catch_solib (bpstat bs)
8286 {
8287   struct breakpoint *b = bs->breakpoint_at;
8288   struct ui_out *uiout = current_uiout;
8289
8290   annotate_catchpoint (b->number);
8291   if (b->disposition == disp_del)
8292     ui_out_text (uiout, "\nTemporary catchpoint ");
8293   else
8294     ui_out_text (uiout, "\nCatchpoint ");
8295   ui_out_field_int (uiout, "bkptno", b->number);
8296   ui_out_text (uiout, "\n");
8297   if (ui_out_is_mi_like_p (uiout))
8298     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8299   print_solib_event (1);
8300   return PRINT_SRC_AND_LOC;
8301 }
8302
8303 static void
8304 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8305 {
8306   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8307   struct value_print_options opts;
8308   struct ui_out *uiout = current_uiout;
8309   char *msg;
8310
8311   get_user_print_options (&opts);
8312   /* Field 4, the address, is omitted (which makes the columns not
8313      line up too nicely with the headers, but the effect is relatively
8314      readable).  */
8315   if (opts.addressprint)
8316     {
8317       annotate_field (4);
8318       ui_out_field_skip (uiout, "addr");
8319     }
8320
8321   annotate_field (5);
8322   if (self->is_load)
8323     {
8324       if (self->regex)
8325         msg = xstrprintf (_("load of library matching %s"), self->regex);
8326       else
8327         msg = xstrdup (_("load of library"));
8328     }
8329   else
8330     {
8331       if (self->regex)
8332         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8333       else
8334         msg = xstrdup (_("unload of library"));
8335     }
8336   ui_out_field_string (uiout, "what", msg);
8337   xfree (msg);
8338
8339   if (ui_out_is_mi_like_p (uiout))
8340     ui_out_field_string (uiout, "catch-type",
8341                          self->is_load ? "load" : "unload");
8342 }
8343
8344 static void
8345 print_mention_catch_solib (struct breakpoint *b)
8346 {
8347   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8348
8349   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8350                    self->is_load ? "load" : "unload");
8351 }
8352
8353 static void
8354 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8355 {
8356   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8357
8358   fprintf_unfiltered (fp, "%s %s",
8359                       b->disposition == disp_del ? "tcatch" : "catch",
8360                       self->is_load ? "load" : "unload");
8361   if (self->regex)
8362     fprintf_unfiltered (fp, " %s", self->regex);
8363   fprintf_unfiltered (fp, "\n");
8364 }
8365
8366 static struct breakpoint_ops catch_solib_breakpoint_ops;
8367
8368 /* Shared helper function (MI and CLI) for creating and installing
8369    a shared object event catchpoint.  If IS_LOAD is non-zero then
8370    the events to be caught are load events, otherwise they are
8371    unload events.  If IS_TEMP is non-zero the catchpoint is a
8372    temporary one.  If ENABLED is non-zero the catchpoint is
8373    created in an enabled state.  */
8374
8375 void
8376 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8377 {
8378   struct solib_catchpoint *c;
8379   struct gdbarch *gdbarch = get_current_arch ();
8380   struct cleanup *cleanup;
8381
8382   if (!arg)
8383     arg = "";
8384   arg = skip_spaces (arg);
8385
8386   c = XCNEW (struct solib_catchpoint);
8387   cleanup = make_cleanup (xfree, c);
8388
8389   if (*arg != '\0')
8390     {
8391       int errcode;
8392
8393       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8394       if (errcode != 0)
8395         {
8396           char *err = get_regcomp_error (errcode, &c->compiled);
8397
8398           make_cleanup (xfree, err);
8399           error (_("Invalid regexp (%s): %s"), err, arg);
8400         }
8401       c->regex = xstrdup (arg);
8402     }
8403
8404   c->is_load = is_load;
8405   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8406                    &catch_solib_breakpoint_ops);
8407
8408   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8409
8410   discard_cleanups (cleanup);
8411   install_breakpoint (0, &c->base, 1);
8412 }
8413
8414 /* A helper function that does all the work for "catch load" and
8415    "catch unload".  */
8416
8417 static void
8418 catch_load_or_unload (char *arg, int from_tty, int is_load,
8419                       struct cmd_list_element *command)
8420 {
8421   int tempflag;
8422   const int enabled = 1;
8423
8424   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8425
8426   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8427 }
8428
8429 static void
8430 catch_load_command_1 (char *arg, int from_tty,
8431                       struct cmd_list_element *command)
8432 {
8433   catch_load_or_unload (arg, from_tty, 1, command);
8434 }
8435
8436 static void
8437 catch_unload_command_1 (char *arg, int from_tty,
8438                         struct cmd_list_element *command)
8439 {
8440   catch_load_or_unload (arg, from_tty, 0, command);
8441 }
8442
8443 /* An instance of this type is used to represent a syscall 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_SYSCALL_BREAKPOINT_OPS.  */
8448
8449 struct syscall_catchpoint
8450 {
8451   /* The base class.  */
8452   struct breakpoint base;
8453
8454   /* Syscall numbers used for the 'catch syscall' feature.  If no
8455      syscall has been specified for filtering, its value is NULL.
8456      Otherwise, it holds a list of all syscalls to be caught.  The
8457      list elements are allocated with xmalloc.  */
8458   VEC(int) *syscalls_to_be_caught;
8459 };
8460
8461 /* Implement the "dtor" breakpoint_ops method for syscall
8462    catchpoints.  */
8463
8464 static void
8465 dtor_catch_syscall (struct breakpoint *b)
8466 {
8467   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8468
8469   VEC_free (int, c->syscalls_to_be_caught);
8470
8471   base_breakpoint_ops.dtor (b);
8472 }
8473
8474 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8475
8476 struct catch_syscall_inferior_data
8477 {
8478   /* We keep a count of the number of times the user has requested a
8479      particular syscall to be tracked, and pass this information to the
8480      target.  This lets capable targets implement filtering directly.  */
8481
8482   /* Number of times that "any" syscall is requested.  */
8483   int any_syscall_count;
8484
8485   /* Count of each system call.  */
8486   VEC(int) *syscalls_counts;
8487
8488   /* This counts all syscall catch requests, so we can readily determine
8489      if any catching is necessary.  */
8490   int total_syscalls_count;
8491 };
8492
8493 static struct catch_syscall_inferior_data*
8494 get_catch_syscall_inferior_data (struct inferior *inf)
8495 {
8496   struct catch_syscall_inferior_data *inf_data;
8497
8498   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8499   if (inf_data == NULL)
8500     {
8501       inf_data = XCNEW (struct catch_syscall_inferior_data);
8502       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8503     }
8504
8505   return inf_data;
8506 }
8507
8508 static void
8509 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8510 {
8511   xfree (arg);
8512 }
8513
8514
8515 /* Implement the "insert" breakpoint_ops method for syscall
8516    catchpoints.  */
8517
8518 static int
8519 insert_catch_syscall (struct bp_location *bl)
8520 {
8521   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8522   struct inferior *inf = current_inferior ();
8523   struct catch_syscall_inferior_data *inf_data
8524     = get_catch_syscall_inferior_data (inf);
8525
8526   ++inf_data->total_syscalls_count;
8527   if (!c->syscalls_to_be_caught)
8528     ++inf_data->any_syscall_count;
8529   else
8530     {
8531       int i, iter;
8532
8533       for (i = 0;
8534            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8535            i++)
8536         {
8537           int elem;
8538
8539           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8540             {
8541               int old_size = VEC_length (int, inf_data->syscalls_counts);
8542               uintptr_t vec_addr_offset
8543                 = old_size * ((uintptr_t) sizeof (int));
8544               uintptr_t vec_addr;
8545               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8546               vec_addr = ((uintptr_t) VEC_address (int,
8547                                                   inf_data->syscalls_counts)
8548                           + vec_addr_offset);
8549               memset ((void *) vec_addr, 0,
8550                       (iter + 1 - old_size) * sizeof (int));
8551             }
8552           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8553           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8554         }
8555     }
8556
8557   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8558                                         inf_data->total_syscalls_count != 0,
8559                                         inf_data->any_syscall_count,
8560                                         VEC_length (int,
8561                                                     inf_data->syscalls_counts),
8562                                         VEC_address (int,
8563                                                      inf_data->syscalls_counts));
8564 }
8565
8566 /* Implement the "remove" breakpoint_ops method for syscall
8567    catchpoints.  */
8568
8569 static int
8570 remove_catch_syscall (struct bp_location *bl)
8571 {
8572   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8573   struct inferior *inf = current_inferior ();
8574   struct catch_syscall_inferior_data *inf_data
8575     = get_catch_syscall_inferior_data (inf);
8576
8577   --inf_data->total_syscalls_count;
8578   if (!c->syscalls_to_be_caught)
8579     --inf_data->any_syscall_count;
8580   else
8581     {
8582       int i, iter;
8583
8584       for (i = 0;
8585            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8586            i++)
8587         {
8588           int elem;
8589           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8590             /* Shouldn't happen.  */
8591             continue;
8592           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8593           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8594         }
8595     }
8596
8597   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8598                                         inf_data->total_syscalls_count != 0,
8599                                         inf_data->any_syscall_count,
8600                                         VEC_length (int,
8601                                                     inf_data->syscalls_counts),
8602                                         VEC_address (int,
8603                                                      inf_data->syscalls_counts));
8604 }
8605
8606 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8607    catchpoints.  */
8608
8609 static int
8610 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8611                               struct address_space *aspace, CORE_ADDR bp_addr,
8612                               const struct target_waitstatus *ws)
8613 {
8614   /* We must check if we are catching specific syscalls in this
8615      breakpoint.  If we are, then we must guarantee that the called
8616      syscall is the same syscall we are catching.  */
8617   int syscall_number = 0;
8618   const struct syscall_catchpoint *c
8619     = (const struct syscall_catchpoint *) bl->owner;
8620
8621   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8622       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8623     return 0;
8624
8625   syscall_number = ws->value.syscall_number;
8626
8627   /* Now, checking if the syscall is the same.  */
8628   if (c->syscalls_to_be_caught)
8629     {
8630       int i, iter;
8631
8632       for (i = 0;
8633            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8634            i++)
8635         if (syscall_number == iter)
8636           return 1;
8637
8638       return 0;
8639     }
8640
8641   return 1;
8642 }
8643
8644 /* Implement the "print_it" breakpoint_ops method for syscall
8645    catchpoints.  */
8646
8647 static enum print_stop_action
8648 print_it_catch_syscall (bpstat bs)
8649 {
8650   struct ui_out *uiout = current_uiout;
8651   struct breakpoint *b = bs->breakpoint_at;
8652   /* These are needed because we want to know in which state a
8653      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8654      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8655      must print "called syscall" or "returned from syscall".  */
8656   ptid_t ptid;
8657   struct target_waitstatus last;
8658   struct syscall s;
8659
8660   get_last_target_status (&ptid, &last);
8661
8662   get_syscall_by_number (last.value.syscall_number, &s);
8663
8664   annotate_catchpoint (b->number);
8665
8666   if (b->disposition == disp_del)
8667     ui_out_text (uiout, "\nTemporary catchpoint ");
8668   else
8669     ui_out_text (uiout, "\nCatchpoint ");
8670   if (ui_out_is_mi_like_p (uiout))
8671     {
8672       ui_out_field_string (uiout, "reason",
8673                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8674                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8675                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8676       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8677     }
8678   ui_out_field_int (uiout, "bkptno", b->number);
8679
8680   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8681     ui_out_text (uiout, " (call to syscall ");
8682   else
8683     ui_out_text (uiout, " (returned from syscall ");
8684
8685   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8686     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8687   if (s.name != NULL)
8688     ui_out_field_string (uiout, "syscall-name", s.name);
8689
8690   ui_out_text (uiout, "), ");
8691
8692   return PRINT_SRC_AND_LOC;
8693 }
8694
8695 /* Implement the "print_one" breakpoint_ops method for syscall
8696    catchpoints.  */
8697
8698 static void
8699 print_one_catch_syscall (struct breakpoint *b,
8700                          struct bp_location **last_loc)
8701 {
8702   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8703   struct value_print_options opts;
8704   struct ui_out *uiout = current_uiout;
8705
8706   get_user_print_options (&opts);
8707   /* Field 4, the address, is omitted (which makes the columns not
8708      line up too nicely with the headers, but the effect is relatively
8709      readable).  */
8710   if (opts.addressprint)
8711     ui_out_field_skip (uiout, "addr");
8712   annotate_field (5);
8713
8714   if (c->syscalls_to_be_caught
8715       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8716     ui_out_text (uiout, "syscalls \"");
8717   else
8718     ui_out_text (uiout, "syscall \"");
8719
8720   if (c->syscalls_to_be_caught)
8721     {
8722       int i, iter;
8723       char *text = xstrprintf ("%s", "");
8724
8725       for (i = 0;
8726            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8727            i++)
8728         {
8729           char *x = text;
8730           struct syscall s;
8731           get_syscall_by_number (iter, &s);
8732
8733           if (s.name != NULL)
8734             text = xstrprintf ("%s%s, ", text, s.name);
8735           else
8736             text = xstrprintf ("%s%d, ", text, iter);
8737
8738           /* We have to xfree the last 'text' (now stored at 'x')
8739              because xstrprintf dynamically allocates new space for it
8740              on every call.  */
8741           xfree (x);
8742         }
8743       /* Remove the last comma.  */
8744       text[strlen (text) - 2] = '\0';
8745       ui_out_field_string (uiout, "what", text);
8746     }
8747   else
8748     ui_out_field_string (uiout, "what", "<any syscall>");
8749   ui_out_text (uiout, "\" ");
8750
8751   if (ui_out_is_mi_like_p (uiout))
8752     ui_out_field_string (uiout, "catch-type", "syscall");
8753 }
8754
8755 /* Implement the "print_mention" breakpoint_ops method for syscall
8756    catchpoints.  */
8757
8758 static void
8759 print_mention_catch_syscall (struct breakpoint *b)
8760 {
8761   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8762
8763   if (c->syscalls_to_be_caught)
8764     {
8765       int i, iter;
8766
8767       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8768         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8769       else
8770         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8771
8772       for (i = 0;
8773            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8774            i++)
8775         {
8776           struct syscall s;
8777           get_syscall_by_number (iter, &s);
8778
8779           if (s.name)
8780             printf_filtered (" '%s' [%d]", s.name, s.number);
8781           else
8782             printf_filtered (" %d", s.number);
8783         }
8784       printf_filtered (")");
8785     }
8786   else
8787     printf_filtered (_("Catchpoint %d (any syscall)"),
8788                      b->number);
8789 }
8790
8791 /* Implement the "print_recreate" breakpoint_ops method for syscall
8792    catchpoints.  */
8793
8794 static void
8795 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8796 {
8797   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8798
8799   fprintf_unfiltered (fp, "catch syscall");
8800
8801   if (c->syscalls_to_be_caught)
8802     {
8803       int i, iter;
8804
8805       for (i = 0;
8806            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8807            i++)
8808         {
8809           struct syscall s;
8810
8811           get_syscall_by_number (iter, &s);
8812           if (s.name)
8813             fprintf_unfiltered (fp, " %s", s.name);
8814           else
8815             fprintf_unfiltered (fp, " %d", s.number);
8816         }
8817     }
8818   print_recreate_thread (b, fp);
8819 }
8820
8821 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8822
8823 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8824
8825 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8826
8827 static int
8828 syscall_catchpoint_p (struct breakpoint *b)
8829 {
8830   return (b->ops == &catch_syscall_breakpoint_ops);
8831 }
8832
8833 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8834    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8835    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8836    the breakpoint_ops structure associated to the catchpoint.  */
8837
8838 void
8839 init_catchpoint (struct breakpoint *b,
8840                  struct gdbarch *gdbarch, int tempflag,
8841                  char *cond_string,
8842                  const struct breakpoint_ops *ops)
8843 {
8844   struct symtab_and_line sal;
8845
8846   init_sal (&sal);
8847   sal.pspace = current_program_space;
8848
8849   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8850
8851   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8852   b->disposition = tempflag ? disp_del : disp_donttouch;
8853 }
8854
8855 void
8856 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8857 {
8858   add_to_breakpoint_chain (b);
8859   set_breakpoint_number (internal, b);
8860   if (is_tracepoint (b))
8861     set_tracepoint_count (breakpoint_count);
8862   if (!internal)
8863     mention (b);
8864   observer_notify_breakpoint_created (b);
8865
8866   if (update_gll)
8867     update_global_location_list (UGLL_MAY_INSERT);
8868 }
8869
8870 static void
8871 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8872                                     int tempflag, char *cond_string,
8873                                     const struct breakpoint_ops *ops)
8874 {
8875   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8876
8877   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8878
8879   c->forked_inferior_pid = null_ptid;
8880
8881   install_breakpoint (0, &c->base, 1);
8882 }
8883
8884 /* Exec catchpoints.  */
8885
8886 /* An instance of this type is used to represent an exec catchpoint.
8887    It includes a "struct breakpoint" as a kind of base class; users
8888    downcast to "struct breakpoint *" when needed.  A breakpoint is
8889    really of this type iff its ops pointer points to
8890    CATCH_EXEC_BREAKPOINT_OPS.  */
8891
8892 struct exec_catchpoint
8893 {
8894   /* The base class.  */
8895   struct breakpoint base;
8896
8897   /* Filename of a program whose exec triggered this catchpoint.
8898      This field is only valid immediately after this catchpoint has
8899      triggered.  */
8900   char *exec_pathname;
8901 };
8902
8903 /* Implement the "dtor" breakpoint_ops method for exec
8904    catchpoints.  */
8905
8906 static void
8907 dtor_catch_exec (struct breakpoint *b)
8908 {
8909   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8910
8911   xfree (c->exec_pathname);
8912
8913   base_breakpoint_ops.dtor (b);
8914 }
8915
8916 static int
8917 insert_catch_exec (struct bp_location *bl)
8918 {
8919   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8920 }
8921
8922 static int
8923 remove_catch_exec (struct bp_location *bl)
8924 {
8925   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8926 }
8927
8928 static int
8929 breakpoint_hit_catch_exec (const struct bp_location *bl,
8930                            struct address_space *aspace, CORE_ADDR bp_addr,
8931                            const struct target_waitstatus *ws)
8932 {
8933   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8934
8935   if (ws->kind != TARGET_WAITKIND_EXECD)
8936     return 0;
8937
8938   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8939   return 1;
8940 }
8941
8942 static enum print_stop_action
8943 print_it_catch_exec (bpstat bs)
8944 {
8945   struct ui_out *uiout = current_uiout;
8946   struct breakpoint *b = bs->breakpoint_at;
8947   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8948
8949   annotate_catchpoint (b->number);
8950   if (b->disposition == disp_del)
8951     ui_out_text (uiout, "\nTemporary catchpoint ");
8952   else
8953     ui_out_text (uiout, "\nCatchpoint ");
8954   if (ui_out_is_mi_like_p (uiout))
8955     {
8956       ui_out_field_string (uiout, "reason",
8957                            async_reason_lookup (EXEC_ASYNC_EXEC));
8958       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8959     }
8960   ui_out_field_int (uiout, "bkptno", b->number);
8961   ui_out_text (uiout, " (exec'd ");
8962   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8963   ui_out_text (uiout, "), ");
8964
8965   return PRINT_SRC_AND_LOC;
8966 }
8967
8968 static void
8969 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8970 {
8971   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8972   struct value_print_options opts;
8973   struct ui_out *uiout = current_uiout;
8974
8975   get_user_print_options (&opts);
8976
8977   /* Field 4, the address, is omitted (which makes the columns
8978      not line up too nicely with the headers, but the effect
8979      is relatively readable).  */
8980   if (opts.addressprint)
8981     ui_out_field_skip (uiout, "addr");
8982   annotate_field (5);
8983   ui_out_text (uiout, "exec");
8984   if (c->exec_pathname != NULL)
8985     {
8986       ui_out_text (uiout, ", program \"");
8987       ui_out_field_string (uiout, "what", c->exec_pathname);
8988       ui_out_text (uiout, "\" ");
8989     }
8990
8991   if (ui_out_is_mi_like_p (uiout))
8992     ui_out_field_string (uiout, "catch-type", "exec");
8993 }
8994
8995 static void
8996 print_mention_catch_exec (struct breakpoint *b)
8997 {
8998   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8999 }
9000
9001 /* Implement the "print_recreate" breakpoint_ops method for exec
9002    catchpoints.  */
9003
9004 static void
9005 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9006 {
9007   fprintf_unfiltered (fp, "catch exec");
9008   print_recreate_thread (b, fp);
9009 }
9010
9011 static struct breakpoint_ops catch_exec_breakpoint_ops;
9012
9013 static void
9014 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9015                                  const struct breakpoint_ops *ops)
9016 {
9017   struct syscall_catchpoint *c;
9018   struct gdbarch *gdbarch = get_current_arch ();
9019
9020   c = XNEW (struct syscall_catchpoint);
9021   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9022   c->syscalls_to_be_caught = filter;
9023
9024   install_breakpoint (0, &c->base, 1);
9025 }
9026
9027 static int
9028 hw_breakpoint_used_count (void)
9029 {
9030   int i = 0;
9031   struct breakpoint *b;
9032   struct bp_location *bl;
9033
9034   ALL_BREAKPOINTS (b)
9035   {
9036     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9037       for (bl = b->loc; bl; bl = bl->next)
9038         {
9039           /* Special types of hardware breakpoints may use more than
9040              one register.  */
9041           i += b->ops->resources_needed (bl);
9042         }
9043   }
9044
9045   return i;
9046 }
9047
9048 /* Returns the resources B would use if it were a hardware
9049    watchpoint.  */
9050
9051 static int
9052 hw_watchpoint_use_count (struct breakpoint *b)
9053 {
9054   int i = 0;
9055   struct bp_location *bl;
9056
9057   if (!breakpoint_enabled (b))
9058     return 0;
9059
9060   for (bl = b->loc; bl; bl = bl->next)
9061     {
9062       /* Special types of hardware watchpoints may use more than
9063          one register.  */
9064       i += b->ops->resources_needed (bl);
9065     }
9066
9067   return i;
9068 }
9069
9070 /* Returns the sum the used resources of all hardware watchpoints of
9071    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9072    the sum of the used resources of all hardware watchpoints of other
9073    types _not_ TYPE.  */
9074
9075 static int
9076 hw_watchpoint_used_count_others (struct breakpoint *except,
9077                                  enum bptype type, int *other_type_used)
9078 {
9079   int i = 0;
9080   struct breakpoint *b;
9081
9082   *other_type_used = 0;
9083   ALL_BREAKPOINTS (b)
9084     {
9085       if (b == except)
9086         continue;
9087       if (!breakpoint_enabled (b))
9088         continue;
9089
9090       if (b->type == type)
9091         i += hw_watchpoint_use_count (b);
9092       else if (is_hardware_watchpoint (b))
9093         *other_type_used = 1;
9094     }
9095
9096   return i;
9097 }
9098
9099 void
9100 disable_watchpoints_before_interactive_call_start (void)
9101 {
9102   struct breakpoint *b;
9103
9104   ALL_BREAKPOINTS (b)
9105   {
9106     if (is_watchpoint (b) && breakpoint_enabled (b))
9107       {
9108         b->enable_state = bp_call_disabled;
9109         update_global_location_list (UGLL_DONT_INSERT);
9110       }
9111   }
9112 }
9113
9114 void
9115 enable_watchpoints_after_interactive_call_stop (void)
9116 {
9117   struct breakpoint *b;
9118
9119   ALL_BREAKPOINTS (b)
9120   {
9121     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9122       {
9123         b->enable_state = bp_enabled;
9124         update_global_location_list (UGLL_MAY_INSERT);
9125       }
9126   }
9127 }
9128
9129 void
9130 disable_breakpoints_before_startup (void)
9131 {
9132   current_program_space->executing_startup = 1;
9133   update_global_location_list (UGLL_DONT_INSERT);
9134 }
9135
9136 void
9137 enable_breakpoints_after_startup (void)
9138 {
9139   current_program_space->executing_startup = 0;
9140   breakpoint_re_set ();
9141 }
9142
9143
9144 /* Set a breakpoint that will evaporate an end of command
9145    at address specified by SAL.
9146    Restrict it to frame FRAME if FRAME is nonzero.  */
9147
9148 struct breakpoint *
9149 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9150                           struct frame_id frame_id, enum bptype type)
9151 {
9152   struct breakpoint *b;
9153
9154   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9155      tail-called one.  */
9156   gdb_assert (!frame_id_artificial_p (frame_id));
9157
9158   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9159   b->enable_state = bp_enabled;
9160   b->disposition = disp_donttouch;
9161   b->frame_id = frame_id;
9162
9163   /* If we're debugging a multi-threaded program, then we want
9164      momentary breakpoints to be active in only a single thread of
9165      control.  */
9166   if (in_thread_list (inferior_ptid))
9167     b->thread = pid_to_thread_id (inferior_ptid);
9168
9169   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9170
9171   return b;
9172 }
9173
9174 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9175    The new breakpoint will have type TYPE, use OPS as its
9176    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9177
9178 static struct breakpoint *
9179 momentary_breakpoint_from_master (struct breakpoint *orig,
9180                                   enum bptype type,
9181                                   const struct breakpoint_ops *ops,
9182                                   int loc_enabled)
9183 {
9184   struct breakpoint *copy;
9185
9186   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9187   copy->loc = allocate_bp_location (copy);
9188   set_breakpoint_location_function (copy->loc, 1);
9189
9190   copy->loc->gdbarch = orig->loc->gdbarch;
9191   copy->loc->requested_address = orig->loc->requested_address;
9192   copy->loc->address = orig->loc->address;
9193   copy->loc->section = orig->loc->section;
9194   copy->loc->pspace = orig->loc->pspace;
9195   copy->loc->probe = orig->loc->probe;
9196   copy->loc->line_number = orig->loc->line_number;
9197   copy->loc->symtab = orig->loc->symtab;
9198   copy->loc->enabled = loc_enabled;
9199   copy->frame_id = orig->frame_id;
9200   copy->thread = orig->thread;
9201   copy->pspace = orig->pspace;
9202
9203   copy->enable_state = bp_enabled;
9204   copy->disposition = disp_donttouch;
9205   copy->number = internal_breakpoint_number--;
9206
9207   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9208   return copy;
9209 }
9210
9211 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9212    ORIG is NULL.  */
9213
9214 struct breakpoint *
9215 clone_momentary_breakpoint (struct breakpoint *orig)
9216 {
9217   /* If there's nothing to clone, then return nothing.  */
9218   if (orig == NULL)
9219     return NULL;
9220
9221   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9222 }
9223
9224 struct breakpoint *
9225 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9226                                 enum bptype type)
9227 {
9228   struct symtab_and_line sal;
9229
9230   sal = find_pc_line (pc, 0);
9231   sal.pc = pc;
9232   sal.section = find_pc_overlay (pc);
9233   sal.explicit_pc = 1;
9234
9235   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9236 }
9237 \f
9238
9239 /* Tell the user we have just set a breakpoint B.  */
9240
9241 static void
9242 mention (struct breakpoint *b)
9243 {
9244   b->ops->print_mention (b);
9245   if (ui_out_is_mi_like_p (current_uiout))
9246     return;
9247   printf_filtered ("\n");
9248 }
9249 \f
9250
9251 static struct bp_location *
9252 add_location_to_breakpoint (struct breakpoint *b,
9253                             const struct symtab_and_line *sal)
9254 {
9255   struct bp_location *loc, **tmp;
9256   CORE_ADDR adjusted_address;
9257   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9258
9259   if (loc_gdbarch == NULL)
9260     loc_gdbarch = b->gdbarch;
9261
9262   /* Adjust the breakpoint's address prior to allocating a location.
9263      Once we call allocate_bp_location(), that mostly uninitialized
9264      location will be placed on the location chain.  Adjustment of the
9265      breakpoint may cause target_read_memory() to be called and we do
9266      not want its scan of the location chain to find a breakpoint and
9267      location that's only been partially initialized.  */
9268   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9269                                                 sal->pc, b->type);
9270
9271   /* Sort the locations by their ADDRESS.  */
9272   loc = allocate_bp_location (b);
9273   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9274        tmp = &((*tmp)->next))
9275     ;
9276   loc->next = *tmp;
9277   *tmp = loc;
9278
9279   loc->requested_address = sal->pc;
9280   loc->address = adjusted_address;
9281   loc->pspace = sal->pspace;
9282   loc->probe.probe = sal->probe;
9283   loc->probe.objfile = sal->objfile;
9284   gdb_assert (loc->pspace != NULL);
9285   loc->section = sal->section;
9286   loc->gdbarch = loc_gdbarch;
9287   loc->line_number = sal->line;
9288   loc->symtab = sal->symtab;
9289
9290   set_breakpoint_location_function (loc,
9291                                     sal->explicit_pc || sal->explicit_line);
9292   return loc;
9293 }
9294 \f
9295
9296 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9297    return 0 otherwise.  */
9298
9299 static int
9300 bp_loc_is_permanent (struct bp_location *loc)
9301 {
9302   int len;
9303   CORE_ADDR addr;
9304   const gdb_byte *bpoint;
9305   gdb_byte *target_mem;
9306   struct cleanup *cleanup;
9307   int retval = 0;
9308
9309   gdb_assert (loc != NULL);
9310
9311   addr = loc->address;
9312   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9313
9314   /* Software breakpoints unsupported?  */
9315   if (bpoint == NULL)
9316     return 0;
9317
9318   target_mem = alloca (len);
9319
9320   /* Enable the automatic memory restoration from breakpoints while
9321      we read the memory.  Otherwise we could say about our temporary
9322      breakpoints they are permanent.  */
9323   cleanup = save_current_space_and_thread ();
9324
9325   switch_to_program_space_and_thread (loc->pspace);
9326   make_show_memory_breakpoints_cleanup (0);
9327
9328   if (target_read_memory (loc->address, target_mem, len) == 0
9329       && memcmp (target_mem, bpoint, len) == 0)
9330     retval = 1;
9331
9332   do_cleanups (cleanup);
9333
9334   return retval;
9335 }
9336
9337 /* Build a command list for the dprintf corresponding to the current
9338    settings of the dprintf style options.  */
9339
9340 static void
9341 update_dprintf_command_list (struct breakpoint *b)
9342 {
9343   char *dprintf_args = b->extra_string;
9344   char *printf_line = NULL;
9345
9346   if (!dprintf_args)
9347     return;
9348
9349   dprintf_args = skip_spaces (dprintf_args);
9350
9351   /* Allow a comma, as it may have terminated a location, but don't
9352      insist on it.  */
9353   if (*dprintf_args == ',')
9354     ++dprintf_args;
9355   dprintf_args = skip_spaces (dprintf_args);
9356
9357   if (*dprintf_args != '"')
9358     error (_("Bad format string, missing '\"'."));
9359
9360   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9361     printf_line = xstrprintf ("printf %s", dprintf_args);
9362   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9363     {
9364       if (!dprintf_function)
9365         error (_("No function supplied for dprintf call"));
9366
9367       if (dprintf_channel && strlen (dprintf_channel) > 0)
9368         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9369                                   dprintf_function,
9370                                   dprintf_channel,
9371                                   dprintf_args);
9372       else
9373         printf_line = xstrprintf ("call (void) %s (%s)",
9374                                   dprintf_function,
9375                                   dprintf_args);
9376     }
9377   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9378     {
9379       if (target_can_run_breakpoint_commands ())
9380         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9381       else
9382         {
9383           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9384           printf_line = xstrprintf ("printf %s", dprintf_args);
9385         }
9386     }
9387   else
9388     internal_error (__FILE__, __LINE__,
9389                     _("Invalid dprintf style."));
9390
9391   gdb_assert (printf_line != NULL);
9392   /* Manufacture a printf sequence.  */
9393   {
9394     struct command_line *printf_cmd_line
9395       = xmalloc (sizeof (struct command_line));
9396
9397     printf_cmd_line = xmalloc (sizeof (struct command_line));
9398     printf_cmd_line->control_type = simple_control;
9399     printf_cmd_line->body_count = 0;
9400     printf_cmd_line->body_list = NULL;
9401     printf_cmd_line->next = NULL;
9402     printf_cmd_line->line = printf_line;
9403
9404     breakpoint_set_commands (b, printf_cmd_line);
9405   }
9406 }
9407
9408 /* Update all dprintf commands, making their command lists reflect
9409    current style settings.  */
9410
9411 static void
9412 update_dprintf_commands (char *args, int from_tty,
9413                          struct cmd_list_element *c)
9414 {
9415   struct breakpoint *b;
9416
9417   ALL_BREAKPOINTS (b)
9418     {
9419       if (b->type == bp_dprintf)
9420         update_dprintf_command_list (b);
9421     }
9422 }
9423
9424 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9425    as textual description of the location, and COND_STRING
9426    as condition expression.  */
9427
9428 static void
9429 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9430                      struct symtabs_and_lines sals, char *addr_string,
9431                      char *filter, char *cond_string,
9432                      char *extra_string,
9433                      enum bptype type, enum bpdisp disposition,
9434                      int thread, int task, int ignore_count,
9435                      const struct breakpoint_ops *ops, int from_tty,
9436                      int enabled, int internal, unsigned flags,
9437                      int display_canonical)
9438 {
9439   int i;
9440
9441   if (type == bp_hardware_breakpoint)
9442     {
9443       int target_resources_ok;
9444
9445       i = hw_breakpoint_used_count ();
9446       target_resources_ok =
9447         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9448                                             i + 1, 0);
9449       if (target_resources_ok == 0)
9450         error (_("No hardware breakpoint support in the target."));
9451       else if (target_resources_ok < 0)
9452         error (_("Hardware breakpoints used exceeds limit."));
9453     }
9454
9455   gdb_assert (sals.nelts > 0);
9456
9457   for (i = 0; i < sals.nelts; ++i)
9458     {
9459       struct symtab_and_line sal = sals.sals[i];
9460       struct bp_location *loc;
9461
9462       if (from_tty)
9463         {
9464           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9465           if (!loc_gdbarch)
9466             loc_gdbarch = gdbarch;
9467
9468           describe_other_breakpoints (loc_gdbarch,
9469                                       sal.pspace, sal.pc, sal.section, thread);
9470         }
9471
9472       if (i == 0)
9473         {
9474           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9475           b->thread = thread;
9476           b->task = task;
9477
9478           b->cond_string = cond_string;
9479           b->extra_string = extra_string;
9480           b->ignore_count = ignore_count;
9481           b->enable_state = enabled ? bp_enabled : bp_disabled;
9482           b->disposition = disposition;
9483
9484           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9485             b->loc->inserted = 1;
9486
9487           if (type == bp_static_tracepoint)
9488             {
9489               struct tracepoint *t = (struct tracepoint *) b;
9490               struct static_tracepoint_marker marker;
9491
9492               if (strace_marker_p (b))
9493                 {
9494                   /* We already know the marker exists, otherwise, we
9495                      wouldn't see a sal for it.  */
9496                   char *p = &addr_string[3];
9497                   char *endp;
9498                   char *marker_str;
9499
9500                   p = skip_spaces (p);
9501
9502                   endp = skip_to_space (p);
9503
9504                   marker_str = savestring (p, endp - p);
9505                   t->static_trace_marker_id = marker_str;
9506
9507                   printf_filtered (_("Probed static tracepoint "
9508                                      "marker \"%s\"\n"),
9509                                    t->static_trace_marker_id);
9510                 }
9511               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9512                 {
9513                   t->static_trace_marker_id = xstrdup (marker.str_id);
9514                   release_static_tracepoint_marker (&marker);
9515
9516                   printf_filtered (_("Probed static tracepoint "
9517                                      "marker \"%s\"\n"),
9518                                    t->static_trace_marker_id);
9519                 }
9520               else
9521                 warning (_("Couldn't determine the static "
9522                            "tracepoint marker to probe"));
9523             }
9524
9525           loc = b->loc;
9526         }
9527       else
9528         {
9529           loc = add_location_to_breakpoint (b, &sal);
9530           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9531             loc->inserted = 1;
9532         }
9533
9534       if (bp_loc_is_permanent (loc))
9535         make_breakpoint_permanent (b);
9536
9537       if (b->cond_string)
9538         {
9539           const char *arg = b->cond_string;
9540
9541           loc->cond = parse_exp_1 (&arg, loc->address,
9542                                    block_for_pc (loc->address), 0);
9543           if (*arg)
9544               error (_("Garbage '%s' follows condition"), arg);
9545         }
9546
9547       /* Dynamic printf requires and uses additional arguments on the
9548          command line, otherwise it's an error.  */
9549       if (type == bp_dprintf)
9550         {
9551           if (b->extra_string)
9552             update_dprintf_command_list (b);
9553           else
9554             error (_("Format string required"));
9555         }
9556       else if (b->extra_string)
9557         error (_("Garbage '%s' at end of command"), b->extra_string);
9558     }
9559
9560   b->display_canonical = display_canonical;
9561   if (addr_string)
9562     b->addr_string = addr_string;
9563   else
9564     /* addr_string has to be used or breakpoint_re_set will delete
9565        me.  */
9566     b->addr_string
9567       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9568   b->filter = filter;
9569 }
9570
9571 static void
9572 create_breakpoint_sal (struct gdbarch *gdbarch,
9573                        struct symtabs_and_lines sals, char *addr_string,
9574                        char *filter, char *cond_string,
9575                        char *extra_string,
9576                        enum bptype type, enum bpdisp disposition,
9577                        int thread, int task, int ignore_count,
9578                        const struct breakpoint_ops *ops, int from_tty,
9579                        int enabled, int internal, unsigned flags,
9580                        int display_canonical)
9581 {
9582   struct breakpoint *b;
9583   struct cleanup *old_chain;
9584
9585   if (is_tracepoint_type (type))
9586     {
9587       struct tracepoint *t;
9588
9589       t = XCNEW (struct tracepoint);
9590       b = &t->base;
9591     }
9592   else
9593     b = XNEW (struct breakpoint);
9594
9595   old_chain = make_cleanup (xfree, b);
9596
9597   init_breakpoint_sal (b, gdbarch,
9598                        sals, addr_string,
9599                        filter, cond_string, extra_string,
9600                        type, disposition,
9601                        thread, task, ignore_count,
9602                        ops, from_tty,
9603                        enabled, internal, flags,
9604                        display_canonical);
9605   discard_cleanups (old_chain);
9606
9607   install_breakpoint (internal, b, 0);
9608 }
9609
9610 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9611    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9612    value.  COND_STRING, if not NULL, specified the condition to be
9613    used for all breakpoints.  Essentially the only case where
9614    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9615    function.  In that case, it's still not possible to specify
9616    separate conditions for different overloaded functions, so
9617    we take just a single condition string.
9618    
9619    NOTE: If the function succeeds, the caller is expected to cleanup
9620    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9621    array contents).  If the function fails (error() is called), the
9622    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9623    COND and SALS arrays and each of those arrays contents.  */
9624
9625 static void
9626 create_breakpoints_sal (struct gdbarch *gdbarch,
9627                         struct linespec_result *canonical,
9628                         char *cond_string, char *extra_string,
9629                         enum bptype type, enum bpdisp disposition,
9630                         int thread, int task, int ignore_count,
9631                         const struct breakpoint_ops *ops, int from_tty,
9632                         int enabled, int internal, unsigned flags)
9633 {
9634   int i;
9635   struct linespec_sals *lsal;
9636
9637   if (canonical->pre_expanded)
9638     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9639
9640   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9641     {
9642       /* Note that 'addr_string' can be NULL in the case of a plain
9643          'break', without arguments.  */
9644       char *addr_string = (canonical->addr_string
9645                            ? xstrdup (canonical->addr_string)
9646                            : NULL);
9647       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9648       struct cleanup *inner = make_cleanup (xfree, addr_string);
9649
9650       make_cleanup (xfree, filter_string);
9651       create_breakpoint_sal (gdbarch, lsal->sals,
9652                              addr_string,
9653                              filter_string,
9654                              cond_string, extra_string,
9655                              type, disposition,
9656                              thread, task, ignore_count, ops,
9657                              from_tty, enabled, internal, flags,
9658                              canonical->special_display);
9659       discard_cleanups (inner);
9660     }
9661 }
9662
9663 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9664    followed by conditionals.  On return, SALS contains an array of SAL
9665    addresses found.  ADDR_STRING contains a vector of (canonical)
9666    address strings.  ADDRESS points to the end of the SAL.
9667
9668    The array and the line spec strings are allocated on the heap, it is
9669    the caller's responsibility to free them.  */
9670
9671 static void
9672 parse_breakpoint_sals (char **address,
9673                        struct linespec_result *canonical)
9674 {
9675   /* If no arg given, or if first arg is 'if ', use the default
9676      breakpoint.  */
9677   if ((*address) == NULL
9678       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9679     {
9680       /* The last displayed codepoint, if it's valid, is our default breakpoint
9681          address.  */
9682       if (last_displayed_sal_is_valid ())
9683         {
9684           struct linespec_sals lsal;
9685           struct symtab_and_line sal;
9686           CORE_ADDR pc;
9687
9688           init_sal (&sal);              /* Initialize to zeroes.  */
9689           lsal.sals.sals = (struct symtab_and_line *)
9690             xmalloc (sizeof (struct symtab_and_line));
9691
9692           /* Set sal's pspace, pc, symtab, and line to the values
9693              corresponding to the last call to print_frame_info.
9694              Be sure to reinitialize LINE with NOTCURRENT == 0
9695              as the breakpoint line number is inappropriate otherwise.
9696              find_pc_line would adjust PC, re-set it back.  */
9697           get_last_displayed_sal (&sal);
9698           pc = sal.pc;
9699           sal = find_pc_line (pc, 0);
9700
9701           /* "break" without arguments is equivalent to "break *PC"
9702              where PC is the last displayed codepoint's address.  So
9703              make sure to set sal.explicit_pc to prevent GDB from
9704              trying to expand the list of sals to include all other
9705              instances with the same symtab and line.  */
9706           sal.pc = pc;
9707           sal.explicit_pc = 1;
9708
9709           lsal.sals.sals[0] = sal;
9710           lsal.sals.nelts = 1;
9711           lsal.canonical = NULL;
9712
9713           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9714         }
9715       else
9716         error (_("No default breakpoint address now."));
9717     }
9718   else
9719     {
9720       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9721
9722       /* Force almost all breakpoints to be in terms of the
9723          current_source_symtab (which is decode_line_1's default).
9724          This should produce the results we want almost all of the
9725          time while leaving default_breakpoint_* alone.
9726
9727          ObjC: However, don't match an Objective-C method name which
9728          may have a '+' or '-' succeeded by a '['.  */
9729       if (last_displayed_sal_is_valid ()
9730           && (!cursal.symtab
9731               || ((strchr ("+-", (*address)[0]) != NULL)
9732                   && ((*address)[1] != '['))))
9733         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9734                           get_last_displayed_symtab (),
9735                           get_last_displayed_line (),
9736                           canonical, NULL, NULL);
9737       else
9738         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9739                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9740     }
9741 }
9742
9743
9744 /* Convert each SAL into a real PC.  Verify that the PC can be
9745    inserted as a breakpoint.  If it can't throw an error.  */
9746
9747 static void
9748 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9749 {    
9750   int i;
9751
9752   for (i = 0; i < sals->nelts; i++)
9753     resolve_sal_pc (&sals->sals[i]);
9754 }
9755
9756 /* Fast tracepoints may have restrictions on valid locations.  For
9757    instance, a fast tracepoint using a jump instead of a trap will
9758    likely have to overwrite more bytes than a trap would, and so can
9759    only be placed where the instruction is longer than the jump, or a
9760    multi-instruction sequence does not have a jump into the middle of
9761    it, etc.  */
9762
9763 static void
9764 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9765                             struct symtabs_and_lines *sals)
9766 {
9767   int i, rslt;
9768   struct symtab_and_line *sal;
9769   char *msg;
9770   struct cleanup *old_chain;
9771
9772   for (i = 0; i < sals->nelts; i++)
9773     {
9774       struct gdbarch *sarch;
9775
9776       sal = &sals->sals[i];
9777
9778       sarch = get_sal_arch (*sal);
9779       /* We fall back to GDBARCH if there is no architecture
9780          associated with SAL.  */
9781       if (sarch == NULL)
9782         sarch = gdbarch;
9783       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9784                                                NULL, &msg);
9785       old_chain = make_cleanup (xfree, msg);
9786
9787       if (!rslt)
9788         error (_("May not have a fast tracepoint at 0x%s%s"),
9789                paddress (sarch, sal->pc), (msg ? msg : ""));
9790
9791       do_cleanups (old_chain);
9792     }
9793 }
9794
9795 /* Issue an invalid thread ID error.  */
9796
9797 static void ATTRIBUTE_NORETURN
9798 invalid_thread_id_error (int id)
9799 {
9800   error (_("Unknown thread %d."), id);
9801 }
9802
9803 /* Given TOK, a string specification of condition and thread, as
9804    accepted by the 'break' command, extract the condition
9805    string and thread number and set *COND_STRING and *THREAD.
9806    PC identifies the context at which the condition should be parsed.
9807    If no condition is found, *COND_STRING is set to NULL.
9808    If no thread is found, *THREAD is set to -1.  */
9809
9810 static void
9811 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9812                            char **cond_string, int *thread, int *task,
9813                            char **rest)
9814 {
9815   *cond_string = NULL;
9816   *thread = -1;
9817   *task = 0;
9818   *rest = NULL;
9819
9820   while (tok && *tok)
9821     {
9822       const char *end_tok;
9823       int toklen;
9824       const char *cond_start = NULL;
9825       const char *cond_end = NULL;
9826
9827       tok = skip_spaces_const (tok);
9828
9829       if ((*tok == '"' || *tok == ',') && rest)
9830         {
9831           *rest = savestring (tok, strlen (tok));
9832           return;
9833         }
9834
9835       end_tok = skip_to_space_const (tok);
9836
9837       toklen = end_tok - tok;
9838
9839       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9840         {
9841           struct expression *expr;
9842
9843           tok = cond_start = end_tok + 1;
9844           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9845           xfree (expr);
9846           cond_end = tok;
9847           *cond_string = savestring (cond_start, cond_end - cond_start);
9848         }
9849       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9850         {
9851           char *tmptok;
9852
9853           tok = end_tok + 1;
9854           *thread = strtol (tok, &tmptok, 0);
9855           if (tok == tmptok)
9856             error (_("Junk after thread keyword."));
9857           if (!valid_thread_id (*thread))
9858             invalid_thread_id_error (*thread);
9859           tok = tmptok;
9860         }
9861       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9862         {
9863           char *tmptok;
9864
9865           tok = end_tok + 1;
9866           *task = strtol (tok, &tmptok, 0);
9867           if (tok == tmptok)
9868             error (_("Junk after task keyword."));
9869           if (!valid_task_id (*task))
9870             error (_("Unknown task %d."), *task);
9871           tok = tmptok;
9872         }
9873       else if (rest)
9874         {
9875           *rest = savestring (tok, strlen (tok));
9876           return;
9877         }
9878       else
9879         error (_("Junk at end of arguments."));
9880     }
9881 }
9882
9883 /* Decode a static tracepoint marker spec.  */
9884
9885 static struct symtabs_and_lines
9886 decode_static_tracepoint_spec (char **arg_p)
9887 {
9888   VEC(static_tracepoint_marker_p) *markers = NULL;
9889   struct symtabs_and_lines sals;
9890   struct cleanup *old_chain;
9891   char *p = &(*arg_p)[3];
9892   char *endp;
9893   char *marker_str;
9894   int i;
9895
9896   p = skip_spaces (p);
9897
9898   endp = skip_to_space (p);
9899
9900   marker_str = savestring (p, endp - p);
9901   old_chain = make_cleanup (xfree, marker_str);
9902
9903   markers = target_static_tracepoint_markers_by_strid (marker_str);
9904   if (VEC_empty(static_tracepoint_marker_p, markers))
9905     error (_("No known static tracepoint marker named %s"), marker_str);
9906
9907   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9908   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9909
9910   for (i = 0; i < sals.nelts; i++)
9911     {
9912       struct static_tracepoint_marker *marker;
9913
9914       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9915
9916       init_sal (&sals.sals[i]);
9917
9918       sals.sals[i] = find_pc_line (marker->address, 0);
9919       sals.sals[i].pc = marker->address;
9920
9921       release_static_tracepoint_marker (marker);
9922     }
9923
9924   do_cleanups (old_chain);
9925
9926   *arg_p = endp;
9927   return sals;
9928 }
9929
9930 /* Set a breakpoint.  This function is shared between CLI and MI
9931    functions for setting a breakpoint.  This function has two major
9932    modes of operations, selected by the PARSE_ARG parameter.  If
9933    non-zero, the function will parse ARG, extracting location,
9934    condition, thread and extra string.  Otherwise, ARG is just the
9935    breakpoint's location, with condition, thread, and extra string
9936    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9937    If INTERNAL is non-zero, the breakpoint number will be allocated
9938    from the internal breakpoint count.  Returns true if any breakpoint
9939    was created; false otherwise.  */
9940
9941 int
9942 create_breakpoint (struct gdbarch *gdbarch,
9943                    char *arg, char *cond_string,
9944                    int thread, char *extra_string,
9945                    int parse_arg,
9946                    int tempflag, enum bptype type_wanted,
9947                    int ignore_count,
9948                    enum auto_boolean pending_break_support,
9949                    const struct breakpoint_ops *ops,
9950                    int from_tty, int enabled, int internal,
9951                    unsigned flags)
9952 {
9953   volatile struct gdb_exception e;
9954   char *copy_arg = NULL;
9955   char *addr_start = arg;
9956   struct linespec_result canonical;
9957   struct cleanup *old_chain;
9958   struct cleanup *bkpt_chain = NULL;
9959   int pending = 0;
9960   int task = 0;
9961   int prev_bkpt_count = breakpoint_count;
9962
9963   gdb_assert (ops != NULL);
9964
9965   init_linespec_result (&canonical);
9966
9967   TRY_CATCH (e, RETURN_MASK_ALL)
9968     {
9969       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9970                                      addr_start, &copy_arg);
9971     }
9972
9973   /* If caller is interested in rc value from parse, set value.  */
9974   switch (e.reason)
9975     {
9976     case GDB_NO_ERROR:
9977       if (VEC_empty (linespec_sals, canonical.sals))
9978         return 0;
9979       break;
9980     case RETURN_ERROR:
9981       switch (e.error)
9982         {
9983         case NOT_FOUND_ERROR:
9984
9985           /* If pending breakpoint support is turned off, throw
9986              error.  */
9987
9988           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9989             throw_exception (e);
9990
9991           exception_print (gdb_stderr, e);
9992
9993           /* If pending breakpoint support is auto query and the user
9994              selects no, then simply return the error code.  */
9995           if (pending_break_support == AUTO_BOOLEAN_AUTO
9996               && !nquery (_("Make %s pending on future shared library load? "),
9997                           bptype_string (type_wanted)))
9998             return 0;
9999
10000           /* At this point, either the user was queried about setting
10001              a pending breakpoint and selected yes, or pending
10002              breakpoint behavior is on and thus a pending breakpoint
10003              is defaulted on behalf of the user.  */
10004           {
10005             struct linespec_sals lsal;
10006
10007             copy_arg = xstrdup (addr_start);
10008             lsal.canonical = xstrdup (copy_arg);
10009             lsal.sals.nelts = 1;
10010             lsal.sals.sals = XNEW (struct symtab_and_line);
10011             init_sal (&lsal.sals.sals[0]);
10012             pending = 1;
10013             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10014           }
10015           break;
10016         default:
10017           throw_exception (e);
10018         }
10019       break;
10020     default:
10021       throw_exception (e);
10022     }
10023
10024   /* Create a chain of things that always need to be cleaned up.  */
10025   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10026
10027   /* ----------------------------- SNIP -----------------------------
10028      Anything added to the cleanup chain beyond this point is assumed
10029      to be part of a breakpoint.  If the breakpoint create succeeds
10030      then the memory is not reclaimed.  */
10031   bkpt_chain = make_cleanup (null_cleanup, 0);
10032
10033   /* Resolve all line numbers to PC's and verify that the addresses
10034      are ok for the target.  */
10035   if (!pending)
10036     {
10037       int ix;
10038       struct linespec_sals *iter;
10039
10040       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10041         breakpoint_sals_to_pc (&iter->sals);
10042     }
10043
10044   /* Fast tracepoints may have additional restrictions on location.  */
10045   if (!pending && type_wanted == bp_fast_tracepoint)
10046     {
10047       int ix;
10048       struct linespec_sals *iter;
10049
10050       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10051         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10052     }
10053
10054   /* Verify that condition can be parsed, before setting any
10055      breakpoints.  Allocate a separate condition expression for each
10056      breakpoint.  */
10057   if (!pending)
10058     {
10059       if (parse_arg)
10060         {
10061           char *rest;
10062           struct linespec_sals *lsal;
10063
10064           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10065
10066           /* Here we only parse 'arg' to separate condition
10067              from thread number, so parsing in context of first
10068              sal is OK.  When setting the breakpoint we'll
10069              re-parse it in context of each sal.  */
10070
10071           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10072                                      &thread, &task, &rest);
10073           if (cond_string)
10074             make_cleanup (xfree, cond_string);
10075           if (rest)
10076             make_cleanup (xfree, rest);
10077           if (rest)
10078             extra_string = rest;
10079         }
10080       else
10081         {
10082           if (*arg != '\0')
10083             error (_("Garbage '%s' at end of location"), arg);
10084
10085           /* Create a private copy of condition string.  */
10086           if (cond_string)
10087             {
10088               cond_string = xstrdup (cond_string);
10089               make_cleanup (xfree, cond_string);
10090             }
10091           /* Create a private copy of any extra string.  */
10092           if (extra_string)
10093             {
10094               extra_string = xstrdup (extra_string);
10095               make_cleanup (xfree, extra_string);
10096             }
10097         }
10098
10099       ops->create_breakpoints_sal (gdbarch, &canonical,
10100                                    cond_string, extra_string, type_wanted,
10101                                    tempflag ? disp_del : disp_donttouch,
10102                                    thread, task, ignore_count, ops,
10103                                    from_tty, enabled, internal, flags);
10104     }
10105   else
10106     {
10107       struct breakpoint *b;
10108
10109       make_cleanup (xfree, copy_arg);
10110
10111       if (is_tracepoint_type (type_wanted))
10112         {
10113           struct tracepoint *t;
10114
10115           t = XCNEW (struct tracepoint);
10116           b = &t->base;
10117         }
10118       else
10119         b = XNEW (struct breakpoint);
10120
10121       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10122
10123       b->addr_string = copy_arg;
10124       if (parse_arg)
10125         b->cond_string = NULL;
10126       else
10127         {
10128           /* Create a private copy of condition string.  */
10129           if (cond_string)
10130             {
10131               cond_string = xstrdup (cond_string);
10132               make_cleanup (xfree, cond_string);
10133             }
10134           b->cond_string = cond_string;
10135         }
10136       b->extra_string = NULL;
10137       b->ignore_count = ignore_count;
10138       b->disposition = tempflag ? disp_del : disp_donttouch;
10139       b->condition_not_parsed = 1;
10140       b->enable_state = enabled ? bp_enabled : bp_disabled;
10141       if ((type_wanted != bp_breakpoint
10142            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10143         b->pspace = current_program_space;
10144
10145       install_breakpoint (internal, b, 0);
10146     }
10147   
10148   if (VEC_length (linespec_sals, canonical.sals) > 1)
10149     {
10150       warning (_("Multiple breakpoints were set.\nUse the "
10151                  "\"delete\" command to delete unwanted breakpoints."));
10152       prev_breakpoint_count = prev_bkpt_count;
10153     }
10154
10155   /* That's it.  Discard the cleanups for data inserted into the
10156      breakpoint.  */
10157   discard_cleanups (bkpt_chain);
10158   /* But cleanup everything else.  */
10159   do_cleanups (old_chain);
10160
10161   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10162   update_global_location_list (UGLL_MAY_INSERT);
10163
10164   return 1;
10165 }
10166
10167 /* Set a breakpoint.
10168    ARG is a string describing breakpoint address,
10169    condition, and thread.
10170    FLAG specifies if a breakpoint is hardware on,
10171    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10172    and BP_TEMPFLAG.  */
10173
10174 static void
10175 break_command_1 (char *arg, int flag, int from_tty)
10176 {
10177   int tempflag = flag & BP_TEMPFLAG;
10178   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10179                              ? bp_hardware_breakpoint
10180                              : bp_breakpoint);
10181   struct breakpoint_ops *ops;
10182   const char *arg_cp = arg;
10183
10184   /* Matching breakpoints on probes.  */
10185   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10186     ops = &bkpt_probe_breakpoint_ops;
10187   else
10188     ops = &bkpt_breakpoint_ops;
10189
10190   create_breakpoint (get_current_arch (),
10191                      arg,
10192                      NULL, 0, NULL, 1 /* parse arg */,
10193                      tempflag, type_wanted,
10194                      0 /* Ignore count */,
10195                      pending_break_support,
10196                      ops,
10197                      from_tty,
10198                      1 /* enabled */,
10199                      0 /* internal */,
10200                      0);
10201 }
10202
10203 /* Helper function for break_command_1 and disassemble_command.  */
10204
10205 void
10206 resolve_sal_pc (struct symtab_and_line *sal)
10207 {
10208   CORE_ADDR pc;
10209
10210   if (sal->pc == 0 && sal->symtab != NULL)
10211     {
10212       if (!find_line_pc (sal->symtab, sal->line, &pc))
10213         error (_("No line %d in file \"%s\"."),
10214                sal->line, symtab_to_filename_for_display (sal->symtab));
10215       sal->pc = pc;
10216
10217       /* If this SAL corresponds to a breakpoint inserted using a line
10218          number, then skip the function prologue if necessary.  */
10219       if (sal->explicit_line)
10220         skip_prologue_sal (sal);
10221     }
10222
10223   if (sal->section == 0 && sal->symtab != NULL)
10224     {
10225       const struct blockvector *bv;
10226       const struct block *b;
10227       struct symbol *sym;
10228
10229       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10230       if (bv != NULL)
10231         {
10232           sym = block_linkage_function (b);
10233           if (sym != NULL)
10234             {
10235               fixup_symbol_section (sym, sal->symtab->objfile);
10236               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10237             }
10238           else
10239             {
10240               /* It really is worthwhile to have the section, so we'll
10241                  just have to look harder. This case can be executed
10242                  if we have line numbers but no functions (as can
10243                  happen in assembly source).  */
10244
10245               struct bound_minimal_symbol msym;
10246               struct cleanup *old_chain = save_current_space_and_thread ();
10247
10248               switch_to_program_space_and_thread (sal->pspace);
10249
10250               msym = lookup_minimal_symbol_by_pc (sal->pc);
10251               if (msym.minsym)
10252                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10253
10254               do_cleanups (old_chain);
10255             }
10256         }
10257     }
10258 }
10259
10260 void
10261 break_command (char *arg, int from_tty)
10262 {
10263   break_command_1 (arg, 0, from_tty);
10264 }
10265
10266 void
10267 tbreak_command (char *arg, int from_tty)
10268 {
10269   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10270 }
10271
10272 static void
10273 hbreak_command (char *arg, int from_tty)
10274 {
10275   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10276 }
10277
10278 static void
10279 thbreak_command (char *arg, int from_tty)
10280 {
10281   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10282 }
10283
10284 static void
10285 stop_command (char *arg, int from_tty)
10286 {
10287   printf_filtered (_("Specify the type of breakpoint to set.\n\
10288 Usage: stop in <function | address>\n\
10289        stop at <line>\n"));
10290 }
10291
10292 static void
10293 stopin_command (char *arg, int from_tty)
10294 {
10295   int badInput = 0;
10296
10297   if (arg == (char *) NULL)
10298     badInput = 1;
10299   else if (*arg != '*')
10300     {
10301       char *argptr = arg;
10302       int hasColon = 0;
10303
10304       /* Look for a ':'.  If this is a line number specification, then
10305          say it is bad, otherwise, it should be an address or
10306          function/method name.  */
10307       while (*argptr && !hasColon)
10308         {
10309           hasColon = (*argptr == ':');
10310           argptr++;
10311         }
10312
10313       if (hasColon)
10314         badInput = (*argptr != ':');    /* Not a class::method */
10315       else
10316         badInput = isdigit (*arg);      /* a simple line number */
10317     }
10318
10319   if (badInput)
10320     printf_filtered (_("Usage: stop in <function | address>\n"));
10321   else
10322     break_command_1 (arg, 0, from_tty);
10323 }
10324
10325 static void
10326 stopat_command (char *arg, int from_tty)
10327 {
10328   int badInput = 0;
10329
10330   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10331     badInput = 1;
10332   else
10333     {
10334       char *argptr = arg;
10335       int hasColon = 0;
10336
10337       /* Look for a ':'.  If there is a '::' then get out, otherwise
10338          it is probably a line number.  */
10339       while (*argptr && !hasColon)
10340         {
10341           hasColon = (*argptr == ':');
10342           argptr++;
10343         }
10344
10345       if (hasColon)
10346         badInput = (*argptr == ':');    /* we have class::method */
10347       else
10348         badInput = !isdigit (*arg);     /* not a line number */
10349     }
10350
10351   if (badInput)
10352     printf_filtered (_("Usage: stop at <line>\n"));
10353   else
10354     break_command_1 (arg, 0, from_tty);
10355 }
10356
10357 /* The dynamic printf command is mostly like a regular breakpoint, but
10358    with a prewired command list consisting of a single output command,
10359    built from extra arguments supplied on the dprintf command
10360    line.  */
10361
10362 static void
10363 dprintf_command (char *arg, int from_tty)
10364 {
10365   create_breakpoint (get_current_arch (),
10366                      arg,
10367                      NULL, 0, NULL, 1 /* parse arg */,
10368                      0, bp_dprintf,
10369                      0 /* Ignore count */,
10370                      pending_break_support,
10371                      &dprintf_breakpoint_ops,
10372                      from_tty,
10373                      1 /* enabled */,
10374                      0 /* internal */,
10375                      0);
10376 }
10377
10378 static void
10379 agent_printf_command (char *arg, int from_tty)
10380 {
10381   error (_("May only run agent-printf on the target"));
10382 }
10383
10384 /* Implement the "breakpoint_hit" breakpoint_ops method for
10385    ranged breakpoints.  */
10386
10387 static int
10388 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10389                                   struct address_space *aspace,
10390                                   CORE_ADDR bp_addr,
10391                                   const struct target_waitstatus *ws)
10392 {
10393   if (ws->kind != TARGET_WAITKIND_STOPPED
10394       || ws->value.sig != GDB_SIGNAL_TRAP)
10395     return 0;
10396
10397   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10398                                          bl->length, aspace, bp_addr);
10399 }
10400
10401 /* Implement the "resources_needed" breakpoint_ops method for
10402    ranged breakpoints.  */
10403
10404 static int
10405 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10406 {
10407   return target_ranged_break_num_registers ();
10408 }
10409
10410 /* Implement the "print_it" breakpoint_ops method for
10411    ranged breakpoints.  */
10412
10413 static enum print_stop_action
10414 print_it_ranged_breakpoint (bpstat bs)
10415 {
10416   struct breakpoint *b = bs->breakpoint_at;
10417   struct bp_location *bl = b->loc;
10418   struct ui_out *uiout = current_uiout;
10419
10420   gdb_assert (b->type == bp_hardware_breakpoint);
10421
10422   /* Ranged breakpoints have only one location.  */
10423   gdb_assert (bl && bl->next == NULL);
10424
10425   annotate_breakpoint (b->number);
10426   if (b->disposition == disp_del)
10427     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10428   else
10429     ui_out_text (uiout, "\nRanged breakpoint ");
10430   if (ui_out_is_mi_like_p (uiout))
10431     {
10432       ui_out_field_string (uiout, "reason",
10433                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10434       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10435     }
10436   ui_out_field_int (uiout, "bkptno", b->number);
10437   ui_out_text (uiout, ", ");
10438
10439   return PRINT_SRC_AND_LOC;
10440 }
10441
10442 /* Implement the "print_one" breakpoint_ops method for
10443    ranged breakpoints.  */
10444
10445 static void
10446 print_one_ranged_breakpoint (struct breakpoint *b,
10447                              struct bp_location **last_loc)
10448 {
10449   struct bp_location *bl = b->loc;
10450   struct value_print_options opts;
10451   struct ui_out *uiout = current_uiout;
10452
10453   /* Ranged breakpoints have only one location.  */
10454   gdb_assert (bl && bl->next == NULL);
10455
10456   get_user_print_options (&opts);
10457
10458   if (opts.addressprint)
10459     /* We don't print the address range here, it will be printed later
10460        by print_one_detail_ranged_breakpoint.  */
10461     ui_out_field_skip (uiout, "addr");
10462   annotate_field (5);
10463   print_breakpoint_location (b, bl);
10464   *last_loc = bl;
10465 }
10466
10467 /* Implement the "print_one_detail" breakpoint_ops method for
10468    ranged breakpoints.  */
10469
10470 static void
10471 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10472                                     struct ui_out *uiout)
10473 {
10474   CORE_ADDR address_start, address_end;
10475   struct bp_location *bl = b->loc;
10476   struct ui_file *stb = mem_fileopen ();
10477   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10478
10479   gdb_assert (bl);
10480
10481   address_start = bl->address;
10482   address_end = address_start + bl->length - 1;
10483
10484   ui_out_text (uiout, "\taddress range: ");
10485   fprintf_unfiltered (stb, "[%s, %s]",
10486                       print_core_address (bl->gdbarch, address_start),
10487                       print_core_address (bl->gdbarch, address_end));
10488   ui_out_field_stream (uiout, "addr", stb);
10489   ui_out_text (uiout, "\n");
10490
10491   do_cleanups (cleanup);
10492 }
10493
10494 /* Implement the "print_mention" breakpoint_ops method for
10495    ranged breakpoints.  */
10496
10497 static void
10498 print_mention_ranged_breakpoint (struct breakpoint *b)
10499 {
10500   struct bp_location *bl = b->loc;
10501   struct ui_out *uiout = current_uiout;
10502
10503   gdb_assert (bl);
10504   gdb_assert (b->type == bp_hardware_breakpoint);
10505
10506   if (ui_out_is_mi_like_p (uiout))
10507     return;
10508
10509   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10510                    b->number, paddress (bl->gdbarch, bl->address),
10511                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10512 }
10513
10514 /* Implement the "print_recreate" breakpoint_ops method for
10515    ranged breakpoints.  */
10516
10517 static void
10518 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10519 {
10520   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10521                       b->addr_string_range_end);
10522   print_recreate_thread (b, fp);
10523 }
10524
10525 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10526
10527 static struct breakpoint_ops ranged_breakpoint_ops;
10528
10529 /* Find the address where the end of the breakpoint range should be
10530    placed, given the SAL of the end of the range.  This is so that if
10531    the user provides a line number, the end of the range is set to the
10532    last instruction of the given line.  */
10533
10534 static CORE_ADDR
10535 find_breakpoint_range_end (struct symtab_and_line sal)
10536 {
10537   CORE_ADDR end;
10538
10539   /* If the user provided a PC value, use it.  Otherwise,
10540      find the address of the end of the given location.  */
10541   if (sal.explicit_pc)
10542     end = sal.pc;
10543   else
10544     {
10545       int ret;
10546       CORE_ADDR start;
10547
10548       ret = find_line_pc_range (sal, &start, &end);
10549       if (!ret)
10550         error (_("Could not find location of the end of the range."));
10551
10552       /* find_line_pc_range returns the start of the next line.  */
10553       end--;
10554     }
10555
10556   return end;
10557 }
10558
10559 /* Implement the "break-range" CLI command.  */
10560
10561 static void
10562 break_range_command (char *arg, int from_tty)
10563 {
10564   char *arg_start, *addr_string_start, *addr_string_end;
10565   struct linespec_result canonical_start, canonical_end;
10566   int bp_count, can_use_bp, length;
10567   CORE_ADDR end;
10568   struct breakpoint *b;
10569   struct symtab_and_line sal_start, sal_end;
10570   struct cleanup *cleanup_bkpt;
10571   struct linespec_sals *lsal_start, *lsal_end;
10572
10573   /* We don't support software ranged breakpoints.  */
10574   if (target_ranged_break_num_registers () < 0)
10575     error (_("This target does not support hardware ranged breakpoints."));
10576
10577   bp_count = hw_breakpoint_used_count ();
10578   bp_count += target_ranged_break_num_registers ();
10579   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10580                                                    bp_count, 0);
10581   if (can_use_bp < 0)
10582     error (_("Hardware breakpoints used exceeds limit."));
10583
10584   arg = skip_spaces (arg);
10585   if (arg == NULL || arg[0] == '\0')
10586     error(_("No address range specified."));
10587
10588   init_linespec_result (&canonical_start);
10589
10590   arg_start = arg;
10591   parse_breakpoint_sals (&arg, &canonical_start);
10592
10593   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10594
10595   if (arg[0] != ',')
10596     error (_("Too few arguments."));
10597   else if (VEC_empty (linespec_sals, canonical_start.sals))
10598     error (_("Could not find location of the beginning of the range."));
10599
10600   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10601
10602   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10603       || lsal_start->sals.nelts != 1)
10604     error (_("Cannot create a ranged breakpoint with multiple locations."));
10605
10606   sal_start = lsal_start->sals.sals[0];
10607   addr_string_start = savestring (arg_start, arg - arg_start);
10608   make_cleanup (xfree, addr_string_start);
10609
10610   arg++;        /* Skip the comma.  */
10611   arg = skip_spaces (arg);
10612
10613   /* Parse the end location.  */
10614
10615   init_linespec_result (&canonical_end);
10616   arg_start = arg;
10617
10618   /* We call decode_line_full directly here instead of using
10619      parse_breakpoint_sals because we need to specify the start location's
10620      symtab and line as the default symtab and line for the end of the
10621      range.  This makes it possible to have ranges like "foo.c:27, +14",
10622      where +14 means 14 lines from the start location.  */
10623   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10624                     sal_start.symtab, sal_start.line,
10625                     &canonical_end, NULL, NULL);
10626
10627   make_cleanup_destroy_linespec_result (&canonical_end);
10628
10629   if (VEC_empty (linespec_sals, canonical_end.sals))
10630     error (_("Could not find location of the end of the range."));
10631
10632   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10633   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10634       || lsal_end->sals.nelts != 1)
10635     error (_("Cannot create a ranged breakpoint with multiple locations."));
10636
10637   sal_end = lsal_end->sals.sals[0];
10638   addr_string_end = savestring (arg_start, arg - arg_start);
10639   make_cleanup (xfree, addr_string_end);
10640
10641   end = find_breakpoint_range_end (sal_end);
10642   if (sal_start.pc > end)
10643     error (_("Invalid address range, end precedes start."));
10644
10645   length = end - sal_start.pc + 1;
10646   if (length < 0)
10647     /* Length overflowed.  */
10648     error (_("Address range too large."));
10649   else if (length == 1)
10650     {
10651       /* This range is simple enough to be handled by
10652          the `hbreak' command.  */
10653       hbreak_command (addr_string_start, 1);
10654
10655       do_cleanups (cleanup_bkpt);
10656
10657       return;
10658     }
10659
10660   /* Now set up the breakpoint.  */
10661   b = set_raw_breakpoint (get_current_arch (), sal_start,
10662                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10663   set_breakpoint_count (breakpoint_count + 1);
10664   b->number = breakpoint_count;
10665   b->disposition = disp_donttouch;
10666   b->addr_string = xstrdup (addr_string_start);
10667   b->addr_string_range_end = xstrdup (addr_string_end);
10668   b->loc->length = length;
10669
10670   do_cleanups (cleanup_bkpt);
10671
10672   mention (b);
10673   observer_notify_breakpoint_created (b);
10674   update_global_location_list (UGLL_MAY_INSERT);
10675 }
10676
10677 /*  Return non-zero if EXP is verified as constant.  Returned zero
10678     means EXP is variable.  Also the constant detection may fail for
10679     some constant expressions and in such case still falsely return
10680     zero.  */
10681
10682 static int
10683 watchpoint_exp_is_const (const struct expression *exp)
10684 {
10685   int i = exp->nelts;
10686
10687   while (i > 0)
10688     {
10689       int oplenp, argsp;
10690
10691       /* We are only interested in the descriptor of each element.  */
10692       operator_length (exp, i, &oplenp, &argsp);
10693       i -= oplenp;
10694
10695       switch (exp->elts[i].opcode)
10696         {
10697         case BINOP_ADD:
10698         case BINOP_SUB:
10699         case BINOP_MUL:
10700         case BINOP_DIV:
10701         case BINOP_REM:
10702         case BINOP_MOD:
10703         case BINOP_LSH:
10704         case BINOP_RSH:
10705         case BINOP_LOGICAL_AND:
10706         case BINOP_LOGICAL_OR:
10707         case BINOP_BITWISE_AND:
10708         case BINOP_BITWISE_IOR:
10709         case BINOP_BITWISE_XOR:
10710         case BINOP_EQUAL:
10711         case BINOP_NOTEQUAL:
10712         case BINOP_LESS:
10713         case BINOP_GTR:
10714         case BINOP_LEQ:
10715         case BINOP_GEQ:
10716         case BINOP_REPEAT:
10717         case BINOP_COMMA:
10718         case BINOP_EXP:
10719         case BINOP_MIN:
10720         case BINOP_MAX:
10721         case BINOP_INTDIV:
10722         case BINOP_CONCAT:
10723         case TERNOP_COND:
10724         case TERNOP_SLICE:
10725
10726         case OP_LONG:
10727         case OP_DOUBLE:
10728         case OP_DECFLOAT:
10729         case OP_LAST:
10730         case OP_COMPLEX:
10731         case OP_STRING:
10732         case OP_ARRAY:
10733         case OP_TYPE:
10734         case OP_TYPEOF:
10735         case OP_DECLTYPE:
10736         case OP_TYPEID:
10737         case OP_NAME:
10738         case OP_OBJC_NSSTRING:
10739
10740         case UNOP_NEG:
10741         case UNOP_LOGICAL_NOT:
10742         case UNOP_COMPLEMENT:
10743         case UNOP_ADDR:
10744         case UNOP_HIGH:
10745         case UNOP_CAST:
10746
10747         case UNOP_CAST_TYPE:
10748         case UNOP_REINTERPRET_CAST:
10749         case UNOP_DYNAMIC_CAST:
10750           /* Unary, binary and ternary operators: We have to check
10751              their operands.  If they are constant, then so is the
10752              result of that operation.  For instance, if A and B are
10753              determined to be constants, then so is "A + B".
10754
10755              UNOP_IND is one exception to the rule above, because the
10756              value of *ADDR is not necessarily a constant, even when
10757              ADDR is.  */
10758           break;
10759
10760         case OP_VAR_VALUE:
10761           /* Check whether the associated symbol is a constant.
10762
10763              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10764              possible that a buggy compiler could mark a variable as
10765              constant even when it is not, and TYPE_CONST would return
10766              true in this case, while SYMBOL_CLASS wouldn't.
10767
10768              We also have to check for function symbols because they
10769              are always constant.  */
10770           {
10771             struct symbol *s = exp->elts[i + 2].symbol;
10772
10773             if (SYMBOL_CLASS (s) != LOC_BLOCK
10774                 && SYMBOL_CLASS (s) != LOC_CONST
10775                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10776               return 0;
10777             break;
10778           }
10779
10780         /* The default action is to return 0 because we are using
10781            the optimistic approach here: If we don't know something,
10782            then it is not a constant.  */
10783         default:
10784           return 0;
10785         }
10786     }
10787
10788   return 1;
10789 }
10790
10791 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10792
10793 static void
10794 dtor_watchpoint (struct breakpoint *self)
10795 {
10796   struct watchpoint *w = (struct watchpoint *) self;
10797
10798   xfree (w->cond_exp);
10799   xfree (w->exp);
10800   xfree (w->exp_string);
10801   xfree (w->exp_string_reparse);
10802   value_free (w->val);
10803
10804   base_breakpoint_ops.dtor (self);
10805 }
10806
10807 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10808
10809 static void
10810 re_set_watchpoint (struct breakpoint *b)
10811 {
10812   struct watchpoint *w = (struct watchpoint *) b;
10813
10814   /* Watchpoint can be either on expression using entirely global
10815      variables, or it can be on local variables.
10816
10817      Watchpoints of the first kind are never auto-deleted, and even
10818      persist across program restarts.  Since they can use variables
10819      from shared libraries, we need to reparse expression as libraries
10820      are loaded and unloaded.
10821
10822      Watchpoints on local variables can also change meaning as result
10823      of solib event.  For example, if a watchpoint uses both a local
10824      and a global variables in expression, it's a local watchpoint,
10825      but unloading of a shared library will make the expression
10826      invalid.  This is not a very common use case, but we still
10827      re-evaluate expression, to avoid surprises to the user.
10828
10829      Note that for local watchpoints, we re-evaluate it only if
10830      watchpoints frame id is still valid.  If it's not, it means the
10831      watchpoint is out of scope and will be deleted soon.  In fact,
10832      I'm not sure we'll ever be called in this case.
10833
10834      If a local watchpoint's frame id is still valid, then
10835      w->exp_valid_block is likewise valid, and we can safely use it.
10836
10837      Don't do anything about disabled watchpoints, since they will be
10838      reevaluated again when enabled.  */
10839   update_watchpoint (w, 1 /* reparse */);
10840 }
10841
10842 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10843
10844 static int
10845 insert_watchpoint (struct bp_location *bl)
10846 {
10847   struct watchpoint *w = (struct watchpoint *) bl->owner;
10848   int length = w->exact ? 1 : bl->length;
10849
10850   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10851                                    w->cond_exp);
10852 }
10853
10854 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10855
10856 static int
10857 remove_watchpoint (struct bp_location *bl)
10858 {
10859   struct watchpoint *w = (struct watchpoint *) bl->owner;
10860   int length = w->exact ? 1 : bl->length;
10861
10862   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10863                                    w->cond_exp);
10864 }
10865
10866 static int
10867 breakpoint_hit_watchpoint (const struct bp_location *bl,
10868                            struct address_space *aspace, CORE_ADDR bp_addr,
10869                            const struct target_waitstatus *ws)
10870 {
10871   struct breakpoint *b = bl->owner;
10872   struct watchpoint *w = (struct watchpoint *) b;
10873
10874   /* Continuable hardware watchpoints are treated as non-existent if the
10875      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10876      some data address).  Otherwise gdb won't stop on a break instruction
10877      in the code (not from a breakpoint) when a hardware watchpoint has
10878      been defined.  Also skip watchpoints which we know did not trigger
10879      (did not match the data address).  */
10880   if (is_hardware_watchpoint (b)
10881       && w->watchpoint_triggered == watch_triggered_no)
10882     return 0;
10883
10884   return 1;
10885 }
10886
10887 static void
10888 check_status_watchpoint (bpstat bs)
10889 {
10890   gdb_assert (is_watchpoint (bs->breakpoint_at));
10891
10892   bpstat_check_watchpoint (bs);
10893 }
10894
10895 /* Implement the "resources_needed" breakpoint_ops method for
10896    hardware watchpoints.  */
10897
10898 static int
10899 resources_needed_watchpoint (const struct bp_location *bl)
10900 {
10901   struct watchpoint *w = (struct watchpoint *) bl->owner;
10902   int length = w->exact? 1 : bl->length;
10903
10904   return target_region_ok_for_hw_watchpoint (bl->address, length);
10905 }
10906
10907 /* Implement the "works_in_software_mode" breakpoint_ops method for
10908    hardware watchpoints.  */
10909
10910 static int
10911 works_in_software_mode_watchpoint (const struct breakpoint *b)
10912 {
10913   /* Read and access watchpoints only work with hardware support.  */
10914   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10915 }
10916
10917 static enum print_stop_action
10918 print_it_watchpoint (bpstat bs)
10919 {
10920   struct cleanup *old_chain;
10921   struct breakpoint *b;
10922   struct ui_file *stb;
10923   enum print_stop_action result;
10924   struct watchpoint *w;
10925   struct ui_out *uiout = current_uiout;
10926
10927   gdb_assert (bs->bp_location_at != NULL);
10928
10929   b = bs->breakpoint_at;
10930   w = (struct watchpoint *) b;
10931
10932   stb = mem_fileopen ();
10933   old_chain = make_cleanup_ui_file_delete (stb);
10934
10935   switch (b->type)
10936     {
10937     case bp_watchpoint:
10938     case bp_hardware_watchpoint:
10939       annotate_watchpoint (b->number);
10940       if (ui_out_is_mi_like_p (uiout))
10941         ui_out_field_string
10942           (uiout, "reason",
10943            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10944       mention (b);
10945       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10946       ui_out_text (uiout, "\nOld value = ");
10947       watchpoint_value_print (bs->old_val, stb);
10948       ui_out_field_stream (uiout, "old", stb);
10949       ui_out_text (uiout, "\nNew value = ");
10950       watchpoint_value_print (w->val, stb);
10951       ui_out_field_stream (uiout, "new", stb);
10952       ui_out_text (uiout, "\n");
10953       /* More than one watchpoint may have been triggered.  */
10954       result = PRINT_UNKNOWN;
10955       break;
10956
10957     case bp_read_watchpoint:
10958       if (ui_out_is_mi_like_p (uiout))
10959         ui_out_field_string
10960           (uiout, "reason",
10961            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10962       mention (b);
10963       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10964       ui_out_text (uiout, "\nValue = ");
10965       watchpoint_value_print (w->val, stb);
10966       ui_out_field_stream (uiout, "value", stb);
10967       ui_out_text (uiout, "\n");
10968       result = PRINT_UNKNOWN;
10969       break;
10970
10971     case bp_access_watchpoint:
10972       if (bs->old_val != NULL)
10973         {
10974           annotate_watchpoint (b->number);
10975           if (ui_out_is_mi_like_p (uiout))
10976             ui_out_field_string
10977               (uiout, "reason",
10978                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10979           mention (b);
10980           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10981           ui_out_text (uiout, "\nOld value = ");
10982           watchpoint_value_print (bs->old_val, stb);
10983           ui_out_field_stream (uiout, "old", stb);
10984           ui_out_text (uiout, "\nNew value = ");
10985         }
10986       else
10987         {
10988           mention (b);
10989           if (ui_out_is_mi_like_p (uiout))
10990             ui_out_field_string
10991               (uiout, "reason",
10992                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10993           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10994           ui_out_text (uiout, "\nValue = ");
10995         }
10996       watchpoint_value_print (w->val, stb);
10997       ui_out_field_stream (uiout, "new", stb);
10998       ui_out_text (uiout, "\n");
10999       result = PRINT_UNKNOWN;
11000       break;
11001     default:
11002       result = PRINT_UNKNOWN;
11003     }
11004
11005   do_cleanups (old_chain);
11006   return result;
11007 }
11008
11009 /* Implement the "print_mention" breakpoint_ops method for hardware
11010    watchpoints.  */
11011
11012 static void
11013 print_mention_watchpoint (struct breakpoint *b)
11014 {
11015   struct cleanup *ui_out_chain;
11016   struct watchpoint *w = (struct watchpoint *) b;
11017   struct ui_out *uiout = current_uiout;
11018
11019   switch (b->type)
11020     {
11021     case bp_watchpoint:
11022       ui_out_text (uiout, "Watchpoint ");
11023       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11024       break;
11025     case bp_hardware_watchpoint:
11026       ui_out_text (uiout, "Hardware watchpoint ");
11027       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11028       break;
11029     case bp_read_watchpoint:
11030       ui_out_text (uiout, "Hardware read watchpoint ");
11031       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11032       break;
11033     case bp_access_watchpoint:
11034       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11035       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11036       break;
11037     default:
11038       internal_error (__FILE__, __LINE__,
11039                       _("Invalid hardware watchpoint type."));
11040     }
11041
11042   ui_out_field_int (uiout, "number", b->number);
11043   ui_out_text (uiout, ": ");
11044   ui_out_field_string (uiout, "exp", w->exp_string);
11045   do_cleanups (ui_out_chain);
11046 }
11047
11048 /* Implement the "print_recreate" breakpoint_ops method for
11049    watchpoints.  */
11050
11051 static void
11052 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11053 {
11054   struct watchpoint *w = (struct watchpoint *) b;
11055
11056   switch (b->type)
11057     {
11058     case bp_watchpoint:
11059     case bp_hardware_watchpoint:
11060       fprintf_unfiltered (fp, "watch");
11061       break;
11062     case bp_read_watchpoint:
11063       fprintf_unfiltered (fp, "rwatch");
11064       break;
11065     case bp_access_watchpoint:
11066       fprintf_unfiltered (fp, "awatch");
11067       break;
11068     default:
11069       internal_error (__FILE__, __LINE__,
11070                       _("Invalid watchpoint type."));
11071     }
11072
11073   fprintf_unfiltered (fp, " %s", w->exp_string);
11074   print_recreate_thread (b, fp);
11075 }
11076
11077 /* Implement the "explains_signal" breakpoint_ops method for
11078    watchpoints.  */
11079
11080 static int
11081 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11082 {
11083   /* A software watchpoint cannot cause a signal other than
11084      GDB_SIGNAL_TRAP.  */
11085   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11086     return 0;
11087
11088   return 1;
11089 }
11090
11091 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11092
11093 static struct breakpoint_ops watchpoint_breakpoint_ops;
11094
11095 /* Implement the "insert" breakpoint_ops method for
11096    masked hardware watchpoints.  */
11097
11098 static int
11099 insert_masked_watchpoint (struct bp_location *bl)
11100 {
11101   struct watchpoint *w = (struct watchpoint *) bl->owner;
11102
11103   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11104                                         bl->watchpoint_type);
11105 }
11106
11107 /* Implement the "remove" breakpoint_ops method for
11108    masked hardware watchpoints.  */
11109
11110 static int
11111 remove_masked_watchpoint (struct bp_location *bl)
11112 {
11113   struct watchpoint *w = (struct watchpoint *) bl->owner;
11114
11115   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11116                                         bl->watchpoint_type);
11117 }
11118
11119 /* Implement the "resources_needed" breakpoint_ops method for
11120    masked hardware watchpoints.  */
11121
11122 static int
11123 resources_needed_masked_watchpoint (const struct bp_location *bl)
11124 {
11125   struct watchpoint *w = (struct watchpoint *) bl->owner;
11126
11127   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11128 }
11129
11130 /* Implement the "works_in_software_mode" breakpoint_ops method for
11131    masked hardware watchpoints.  */
11132
11133 static int
11134 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11135 {
11136   return 0;
11137 }
11138
11139 /* Implement the "print_it" breakpoint_ops method for
11140    masked hardware watchpoints.  */
11141
11142 static enum print_stop_action
11143 print_it_masked_watchpoint (bpstat bs)
11144 {
11145   struct breakpoint *b = bs->breakpoint_at;
11146   struct ui_out *uiout = current_uiout;
11147
11148   /* Masked watchpoints have only one location.  */
11149   gdb_assert (b->loc && b->loc->next == NULL);
11150
11151   switch (b->type)
11152     {
11153     case bp_hardware_watchpoint:
11154       annotate_watchpoint (b->number);
11155       if (ui_out_is_mi_like_p (uiout))
11156         ui_out_field_string
11157           (uiout, "reason",
11158            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11159       break;
11160
11161     case bp_read_watchpoint:
11162       if (ui_out_is_mi_like_p (uiout))
11163         ui_out_field_string
11164           (uiout, "reason",
11165            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11166       break;
11167
11168     case bp_access_watchpoint:
11169       if (ui_out_is_mi_like_p (uiout))
11170         ui_out_field_string
11171           (uiout, "reason",
11172            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11173       break;
11174     default:
11175       internal_error (__FILE__, __LINE__,
11176                       _("Invalid hardware watchpoint type."));
11177     }
11178
11179   mention (b);
11180   ui_out_text (uiout, _("\n\
11181 Check the underlying instruction at PC for the memory\n\
11182 address and value which triggered this watchpoint.\n"));
11183   ui_out_text (uiout, "\n");
11184
11185   /* More than one watchpoint may have been triggered.  */
11186   return PRINT_UNKNOWN;
11187 }
11188
11189 /* Implement the "print_one_detail" breakpoint_ops method for
11190    masked hardware watchpoints.  */
11191
11192 static void
11193 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11194                                     struct ui_out *uiout)
11195 {
11196   struct watchpoint *w = (struct watchpoint *) b;
11197
11198   /* Masked watchpoints have only one location.  */
11199   gdb_assert (b->loc && b->loc->next == NULL);
11200
11201   ui_out_text (uiout, "\tmask ");
11202   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11203   ui_out_text (uiout, "\n");
11204 }
11205
11206 /* Implement the "print_mention" breakpoint_ops method for
11207    masked hardware watchpoints.  */
11208
11209 static void
11210 print_mention_masked_watchpoint (struct breakpoint *b)
11211 {
11212   struct watchpoint *w = (struct watchpoint *) b;
11213   struct ui_out *uiout = current_uiout;
11214   struct cleanup *ui_out_chain;
11215
11216   switch (b->type)
11217     {
11218     case bp_hardware_watchpoint:
11219       ui_out_text (uiout, "Masked hardware watchpoint ");
11220       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11221       break;
11222     case bp_read_watchpoint:
11223       ui_out_text (uiout, "Masked hardware read watchpoint ");
11224       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11225       break;
11226     case bp_access_watchpoint:
11227       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11228       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11229       break;
11230     default:
11231       internal_error (__FILE__, __LINE__,
11232                       _("Invalid hardware watchpoint type."));
11233     }
11234
11235   ui_out_field_int (uiout, "number", b->number);
11236   ui_out_text (uiout, ": ");
11237   ui_out_field_string (uiout, "exp", w->exp_string);
11238   do_cleanups (ui_out_chain);
11239 }
11240
11241 /* Implement the "print_recreate" breakpoint_ops method for
11242    masked hardware watchpoints.  */
11243
11244 static void
11245 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11246 {
11247   struct watchpoint *w = (struct watchpoint *) b;
11248   char tmp[40];
11249
11250   switch (b->type)
11251     {
11252     case bp_hardware_watchpoint:
11253       fprintf_unfiltered (fp, "watch");
11254       break;
11255     case bp_read_watchpoint:
11256       fprintf_unfiltered (fp, "rwatch");
11257       break;
11258     case bp_access_watchpoint:
11259       fprintf_unfiltered (fp, "awatch");
11260       break;
11261     default:
11262       internal_error (__FILE__, __LINE__,
11263                       _("Invalid hardware watchpoint type."));
11264     }
11265
11266   sprintf_vma (tmp, w->hw_wp_mask);
11267   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11268   print_recreate_thread (b, fp);
11269 }
11270
11271 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11272
11273 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11274
11275 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11276
11277 static int
11278 is_masked_watchpoint (const struct breakpoint *b)
11279 {
11280   return b->ops == &masked_watchpoint_breakpoint_ops;
11281 }
11282
11283 /* accessflag:  hw_write:  watch write, 
11284                 hw_read:   watch read, 
11285                 hw_access: watch access (read or write) */
11286 static void
11287 watch_command_1 (const char *arg, int accessflag, int from_tty,
11288                  int just_location, int internal)
11289 {
11290   volatile struct gdb_exception e;
11291   struct breakpoint *b, *scope_breakpoint = NULL;
11292   struct expression *exp;
11293   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11294   struct value *val, *mark, *result;
11295   int saved_bitpos = 0, saved_bitsize = 0;
11296   struct frame_info *frame;
11297   const char *exp_start = NULL;
11298   const char *exp_end = NULL;
11299   const char *tok, *end_tok;
11300   int toklen = -1;
11301   const char *cond_start = NULL;
11302   const char *cond_end = NULL;
11303   enum bptype bp_type;
11304   int thread = -1;
11305   int pc = 0;
11306   /* Flag to indicate whether we are going to use masks for
11307      the hardware watchpoint.  */
11308   int use_mask = 0;
11309   CORE_ADDR mask = 0;
11310   struct watchpoint *w;
11311   char *expression;
11312   struct cleanup *back_to;
11313
11314   /* Make sure that we actually have parameters to parse.  */
11315   if (arg != NULL && arg[0] != '\0')
11316     {
11317       const char *value_start;
11318
11319       exp_end = arg + strlen (arg);
11320
11321       /* Look for "parameter value" pairs at the end
11322          of the arguments string.  */
11323       for (tok = exp_end - 1; tok > arg; tok--)
11324         {
11325           /* Skip whitespace at the end of the argument list.  */
11326           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11327             tok--;
11328
11329           /* Find the beginning of the last token.
11330              This is the value of the parameter.  */
11331           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11332             tok--;
11333           value_start = tok + 1;
11334
11335           /* Skip whitespace.  */
11336           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11337             tok--;
11338
11339           end_tok = tok;
11340
11341           /* Find the beginning of the second to last token.
11342              This is the parameter itself.  */
11343           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11344             tok--;
11345           tok++;
11346           toklen = end_tok - tok + 1;
11347
11348           if (toklen == 6 && !strncmp (tok, "thread", 6))
11349             {
11350               /* At this point we've found a "thread" token, which means
11351                  the user is trying to set a watchpoint that triggers
11352                  only in a specific thread.  */
11353               char *endp;
11354
11355               if (thread != -1)
11356                 error(_("You can specify only one thread."));
11357
11358               /* Extract the thread ID from the next token.  */
11359               thread = strtol (value_start, &endp, 0);
11360
11361               /* Check if the user provided a valid numeric value for the
11362                  thread ID.  */
11363               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11364                 error (_("Invalid thread ID specification %s."), value_start);
11365
11366               /* Check if the thread actually exists.  */
11367               if (!valid_thread_id (thread))
11368                 invalid_thread_id_error (thread);
11369             }
11370           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11371             {
11372               /* We've found a "mask" token, which means the user wants to
11373                  create a hardware watchpoint that is going to have the mask
11374                  facility.  */
11375               struct value *mask_value, *mark;
11376
11377               if (use_mask)
11378                 error(_("You can specify only one mask."));
11379
11380               use_mask = just_location = 1;
11381
11382               mark = value_mark ();
11383               mask_value = parse_to_comma_and_eval (&value_start);
11384               mask = value_as_address (mask_value);
11385               value_free_to_mark (mark);
11386             }
11387           else
11388             /* We didn't recognize what we found.  We should stop here.  */
11389             break;
11390
11391           /* Truncate the string and get rid of the "parameter value" pair before
11392              the arguments string is parsed by the parse_exp_1 function.  */
11393           exp_end = tok;
11394         }
11395     }
11396   else
11397     exp_end = arg;
11398
11399   /* Parse the rest of the arguments.  From here on out, everything
11400      is in terms of a newly allocated string instead of the original
11401      ARG.  */
11402   innermost_block = NULL;
11403   expression = savestring (arg, exp_end - arg);
11404   back_to = make_cleanup (xfree, expression);
11405   exp_start = arg = expression;
11406   exp = parse_exp_1 (&arg, 0, 0, 0);
11407   exp_end = arg;
11408   /* Remove trailing whitespace from the expression before saving it.
11409      This makes the eventual display of the expression string a bit
11410      prettier.  */
11411   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11412     --exp_end;
11413
11414   /* Checking if the expression is not constant.  */
11415   if (watchpoint_exp_is_const (exp))
11416     {
11417       int len;
11418
11419       len = exp_end - exp_start;
11420       while (len > 0 && isspace (exp_start[len - 1]))
11421         len--;
11422       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11423     }
11424
11425   exp_valid_block = innermost_block;
11426   mark = value_mark ();
11427   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11428
11429   if (val != NULL && just_location)
11430     {
11431       saved_bitpos = value_bitpos (val);
11432       saved_bitsize = value_bitsize (val);
11433     }
11434
11435   if (just_location)
11436     {
11437       int ret;
11438
11439       exp_valid_block = NULL;
11440       val = value_addr (result);
11441       release_value (val);
11442       value_free_to_mark (mark);
11443
11444       if (use_mask)
11445         {
11446           ret = target_masked_watch_num_registers (value_as_address (val),
11447                                                    mask);
11448           if (ret == -1)
11449             error (_("This target does not support masked watchpoints."));
11450           else if (ret == -2)
11451             error (_("Invalid mask or memory region."));
11452         }
11453     }
11454   else if (val != NULL)
11455     release_value (val);
11456
11457   tok = skip_spaces_const (arg);
11458   end_tok = skip_to_space_const (tok);
11459
11460   toklen = end_tok - tok;
11461   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11462     {
11463       struct expression *cond;
11464
11465       innermost_block = NULL;
11466       tok = cond_start = end_tok + 1;
11467       cond = parse_exp_1 (&tok, 0, 0, 0);
11468
11469       /* The watchpoint expression may not be local, but the condition
11470          may still be.  E.g.: `watch global if local > 0'.  */
11471       cond_exp_valid_block = innermost_block;
11472
11473       xfree (cond);
11474       cond_end = tok;
11475     }
11476   if (*tok)
11477     error (_("Junk at end of command."));
11478
11479   frame = block_innermost_frame (exp_valid_block);
11480
11481   /* If the expression is "local", then set up a "watchpoint scope"
11482      breakpoint at the point where we've left the scope of the watchpoint
11483      expression.  Create the scope breakpoint before the watchpoint, so
11484      that we will encounter it first in bpstat_stop_status.  */
11485   if (exp_valid_block && frame)
11486     {
11487       if (frame_id_p (frame_unwind_caller_id (frame)))
11488         {
11489           scope_breakpoint
11490             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11491                                           frame_unwind_caller_pc (frame),
11492                                           bp_watchpoint_scope,
11493                                           &momentary_breakpoint_ops);
11494
11495           scope_breakpoint->enable_state = bp_enabled;
11496
11497           /* Automatically delete the breakpoint when it hits.  */
11498           scope_breakpoint->disposition = disp_del;
11499
11500           /* Only break in the proper frame (help with recursion).  */
11501           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11502
11503           /* Set the address at which we will stop.  */
11504           scope_breakpoint->loc->gdbarch
11505             = frame_unwind_caller_arch (frame);
11506           scope_breakpoint->loc->requested_address
11507             = frame_unwind_caller_pc (frame);
11508           scope_breakpoint->loc->address
11509             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11510                                          scope_breakpoint->loc->requested_address,
11511                                          scope_breakpoint->type);
11512         }
11513     }
11514
11515   /* Now set up the breakpoint.  We create all watchpoints as hardware
11516      watchpoints here even if hardware watchpoints are turned off, a call
11517      to update_watchpoint later in this function will cause the type to
11518      drop back to bp_watchpoint (software watchpoint) if required.  */
11519
11520   if (accessflag == hw_read)
11521     bp_type = bp_read_watchpoint;
11522   else if (accessflag == hw_access)
11523     bp_type = bp_access_watchpoint;
11524   else
11525     bp_type = bp_hardware_watchpoint;
11526
11527   w = XCNEW (struct watchpoint);
11528   b = &w->base;
11529   if (use_mask)
11530     init_raw_breakpoint_without_location (b, NULL, bp_type,
11531                                           &masked_watchpoint_breakpoint_ops);
11532   else
11533     init_raw_breakpoint_without_location (b, NULL, bp_type,
11534                                           &watchpoint_breakpoint_ops);
11535   b->thread = thread;
11536   b->disposition = disp_donttouch;
11537   b->pspace = current_program_space;
11538   w->exp = exp;
11539   w->exp_valid_block = exp_valid_block;
11540   w->cond_exp_valid_block = cond_exp_valid_block;
11541   if (just_location)
11542     {
11543       struct type *t = value_type (val);
11544       CORE_ADDR addr = value_as_address (val);
11545       char *name;
11546
11547       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11548       name = type_to_string (t);
11549
11550       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11551                                           core_addr_to_string (addr));
11552       xfree (name);
11553
11554       w->exp_string = xstrprintf ("-location %.*s",
11555                                   (int) (exp_end - exp_start), exp_start);
11556
11557       /* The above expression is in C.  */
11558       b->language = language_c;
11559     }
11560   else
11561     w->exp_string = savestring (exp_start, exp_end - exp_start);
11562
11563   if (use_mask)
11564     {
11565       w->hw_wp_mask = mask;
11566     }
11567   else
11568     {
11569       w->val = val;
11570       w->val_bitpos = saved_bitpos;
11571       w->val_bitsize = saved_bitsize;
11572       w->val_valid = 1;
11573     }
11574
11575   if (cond_start)
11576     b->cond_string = savestring (cond_start, cond_end - cond_start);
11577   else
11578     b->cond_string = 0;
11579
11580   if (frame)
11581     {
11582       w->watchpoint_frame = get_frame_id (frame);
11583       w->watchpoint_thread = inferior_ptid;
11584     }
11585   else
11586     {
11587       w->watchpoint_frame = null_frame_id;
11588       w->watchpoint_thread = null_ptid;
11589     }
11590
11591   if (scope_breakpoint != NULL)
11592     {
11593       /* The scope breakpoint is related to the watchpoint.  We will
11594          need to act on them together.  */
11595       b->related_breakpoint = scope_breakpoint;
11596       scope_breakpoint->related_breakpoint = b;
11597     }
11598
11599   if (!just_location)
11600     value_free_to_mark (mark);
11601
11602   TRY_CATCH (e, RETURN_MASK_ALL)
11603     {
11604       /* Finally update the new watchpoint.  This creates the locations
11605          that should be inserted.  */
11606       update_watchpoint (w, 1);
11607     }
11608   if (e.reason < 0)
11609     {
11610       delete_breakpoint (b);
11611       throw_exception (e);
11612     }
11613
11614   install_breakpoint (internal, b, 1);
11615   do_cleanups (back_to);
11616 }
11617
11618 /* Return count of debug registers needed to watch the given expression.
11619    If the watchpoint cannot be handled in hardware return zero.  */
11620
11621 static int
11622 can_use_hardware_watchpoint (struct value *v)
11623 {
11624   int found_memory_cnt = 0;
11625   struct value *head = v;
11626
11627   /* Did the user specifically forbid us to use hardware watchpoints? */
11628   if (!can_use_hw_watchpoints)
11629     return 0;
11630
11631   /* Make sure that the value of the expression depends only upon
11632      memory contents, and values computed from them within GDB.  If we
11633      find any register references or function calls, we can't use a
11634      hardware watchpoint.
11635
11636      The idea here is that evaluating an expression generates a series
11637      of values, one holding the value of every subexpression.  (The
11638      expression a*b+c has five subexpressions: a, b, a*b, c, and
11639      a*b+c.)  GDB's values hold almost enough information to establish
11640      the criteria given above --- they identify memory lvalues,
11641      register lvalues, computed values, etcetera.  So we can evaluate
11642      the expression, and then scan the chain of values that leaves
11643      behind to decide whether we can detect any possible change to the
11644      expression's final value using only hardware watchpoints.
11645
11646      However, I don't think that the values returned by inferior
11647      function calls are special in any way.  So this function may not
11648      notice that an expression involving an inferior function call
11649      can't be watched with hardware watchpoints.  FIXME.  */
11650   for (; v; v = value_next (v))
11651     {
11652       if (VALUE_LVAL (v) == lval_memory)
11653         {
11654           if (v != head && value_lazy (v))
11655             /* A lazy memory lvalue in the chain is one that GDB never
11656                needed to fetch; we either just used its address (e.g.,
11657                `a' in `a.b') or we never needed it at all (e.g., `a'
11658                in `a,b').  This doesn't apply to HEAD; if that is
11659                lazy then it was not readable, but watch it anyway.  */
11660             ;
11661           else
11662             {
11663               /* Ahh, memory we actually used!  Check if we can cover
11664                  it with hardware watchpoints.  */
11665               struct type *vtype = check_typedef (value_type (v));
11666
11667               /* We only watch structs and arrays if user asked for it
11668                  explicitly, never if they just happen to appear in a
11669                  middle of some value chain.  */
11670               if (v == head
11671                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11672                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11673                 {
11674                   CORE_ADDR vaddr = value_address (v);
11675                   int len;
11676                   int num_regs;
11677
11678                   len = (target_exact_watchpoints
11679                          && is_scalar_type_recursive (vtype))?
11680                     1 : TYPE_LENGTH (value_type (v));
11681
11682                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11683                   if (!num_regs)
11684                     return 0;
11685                   else
11686                     found_memory_cnt += num_regs;
11687                 }
11688             }
11689         }
11690       else if (VALUE_LVAL (v) != not_lval
11691                && deprecated_value_modifiable (v) == 0)
11692         return 0;       /* These are values from the history (e.g., $1).  */
11693       else if (VALUE_LVAL (v) == lval_register)
11694         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11695     }
11696
11697   /* The expression itself looks suitable for using a hardware
11698      watchpoint, but give the target machine a chance to reject it.  */
11699   return found_memory_cnt;
11700 }
11701
11702 void
11703 watch_command_wrapper (char *arg, int from_tty, int internal)
11704 {
11705   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11706 }
11707
11708 /* A helper function that looks for the "-location" argument and then
11709    calls watch_command_1.  */
11710
11711 static void
11712 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11713 {
11714   int just_location = 0;
11715
11716   if (arg
11717       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11718           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11719     {
11720       arg = skip_spaces (arg);
11721       just_location = 1;
11722     }
11723
11724   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11725 }
11726
11727 static void
11728 watch_command (char *arg, int from_tty)
11729 {
11730   watch_maybe_just_location (arg, hw_write, from_tty);
11731 }
11732
11733 void
11734 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11735 {
11736   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11737 }
11738
11739 static void
11740 rwatch_command (char *arg, int from_tty)
11741 {
11742   watch_maybe_just_location (arg, hw_read, from_tty);
11743 }
11744
11745 void
11746 awatch_command_wrapper (char *arg, int from_tty, int internal)
11747 {
11748   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11749 }
11750
11751 static void
11752 awatch_command (char *arg, int from_tty)
11753 {
11754   watch_maybe_just_location (arg, hw_access, from_tty);
11755 }
11756 \f
11757
11758 /* Helper routines for the until_command routine in infcmd.c.  Here
11759    because it uses the mechanisms of breakpoints.  */
11760
11761 struct until_break_command_continuation_args
11762 {
11763   struct breakpoint *breakpoint;
11764   struct breakpoint *breakpoint2;
11765   int thread_num;
11766 };
11767
11768 /* This function is called by fetch_inferior_event via the
11769    cmd_continuation pointer, to complete the until command.  It takes
11770    care of cleaning up the temporary breakpoints set up by the until
11771    command.  */
11772 static void
11773 until_break_command_continuation (void *arg, int err)
11774 {
11775   struct until_break_command_continuation_args *a = arg;
11776
11777   delete_breakpoint (a->breakpoint);
11778   if (a->breakpoint2)
11779     delete_breakpoint (a->breakpoint2);
11780   delete_longjmp_breakpoint (a->thread_num);
11781 }
11782
11783 void
11784 until_break_command (char *arg, int from_tty, int anywhere)
11785 {
11786   struct symtabs_and_lines sals;
11787   struct symtab_and_line sal;
11788   struct frame_info *frame;
11789   struct gdbarch *frame_gdbarch;
11790   struct frame_id stack_frame_id;
11791   struct frame_id caller_frame_id;
11792   struct breakpoint *breakpoint;
11793   struct breakpoint *breakpoint2 = NULL;
11794   struct cleanup *old_chain;
11795   int thread;
11796   struct thread_info *tp;
11797
11798   clear_proceed_status (0);
11799
11800   /* Set a breakpoint where the user wants it and at return from
11801      this function.  */
11802
11803   if (last_displayed_sal_is_valid ())
11804     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11805                           get_last_displayed_symtab (),
11806                           get_last_displayed_line ());
11807   else
11808     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11809                           (struct symtab *) NULL, 0);
11810
11811   if (sals.nelts != 1)
11812     error (_("Couldn't get information on specified line."));
11813
11814   sal = sals.sals[0];
11815   xfree (sals.sals);    /* malloc'd, so freed.  */
11816
11817   if (*arg)
11818     error (_("Junk at end of arguments."));
11819
11820   resolve_sal_pc (&sal);
11821
11822   tp = inferior_thread ();
11823   thread = tp->num;
11824
11825   old_chain = make_cleanup (null_cleanup, NULL);
11826
11827   /* Note linespec handling above invalidates the frame chain.
11828      Installing a breakpoint also invalidates the frame chain (as it
11829      may need to switch threads), so do any frame handling before
11830      that.  */
11831
11832   frame = get_selected_frame (NULL);
11833   frame_gdbarch = get_frame_arch (frame);
11834   stack_frame_id = get_stack_frame_id (frame);
11835   caller_frame_id = frame_unwind_caller_id (frame);
11836
11837   /* Keep within the current frame, or in frames called by the current
11838      one.  */
11839
11840   if (frame_id_p (caller_frame_id))
11841     {
11842       struct symtab_and_line sal2;
11843
11844       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11845       sal2.pc = frame_unwind_caller_pc (frame);
11846       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11847                                               sal2,
11848                                               caller_frame_id,
11849                                               bp_until);
11850       make_cleanup_delete_breakpoint (breakpoint2);
11851
11852       set_longjmp_breakpoint (tp, caller_frame_id);
11853       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11854     }
11855
11856   /* set_momentary_breakpoint could invalidate FRAME.  */
11857   frame = NULL;
11858
11859   if (anywhere)
11860     /* If the user told us to continue until a specified location,
11861        we don't specify a frame at which we need to stop.  */
11862     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11863                                            null_frame_id, bp_until);
11864   else
11865     /* Otherwise, specify the selected frame, because we want to stop
11866        only at the very same frame.  */
11867     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11868                                            stack_frame_id, bp_until);
11869   make_cleanup_delete_breakpoint (breakpoint);
11870
11871   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11872
11873   /* If we are running asynchronously, and proceed call above has
11874      actually managed to start the target, arrange for breakpoints to
11875      be deleted when the target stops.  Otherwise, we're already
11876      stopped and delete breakpoints via cleanup chain.  */
11877
11878   if (target_can_async_p () && is_running (inferior_ptid))
11879     {
11880       struct until_break_command_continuation_args *args;
11881       args = xmalloc (sizeof (*args));
11882
11883       args->breakpoint = breakpoint;
11884       args->breakpoint2 = breakpoint2;
11885       args->thread_num = thread;
11886
11887       discard_cleanups (old_chain);
11888       add_continuation (inferior_thread (),
11889                         until_break_command_continuation, args,
11890                         xfree);
11891     }
11892   else
11893     do_cleanups (old_chain);
11894 }
11895
11896 /* This function attempts to parse an optional "if <cond>" clause
11897    from the arg string.  If one is not found, it returns NULL.
11898
11899    Else, it returns a pointer to the condition string.  (It does not
11900    attempt to evaluate the string against a particular block.)  And,
11901    it updates arg to point to the first character following the parsed
11902    if clause in the arg string.  */
11903
11904 char *
11905 ep_parse_optional_if_clause (char **arg)
11906 {
11907   char *cond_string;
11908
11909   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11910     return NULL;
11911
11912   /* Skip the "if" keyword.  */
11913   (*arg) += 2;
11914
11915   /* Skip any extra leading whitespace, and record the start of the
11916      condition string.  */
11917   *arg = skip_spaces (*arg);
11918   cond_string = *arg;
11919
11920   /* Assume that the condition occupies the remainder of the arg
11921      string.  */
11922   (*arg) += strlen (cond_string);
11923
11924   return cond_string;
11925 }
11926
11927 /* Commands to deal with catching events, such as signals, exceptions,
11928    process start/exit, etc.  */
11929
11930 typedef enum
11931 {
11932   catch_fork_temporary, catch_vfork_temporary,
11933   catch_fork_permanent, catch_vfork_permanent
11934 }
11935 catch_fork_kind;
11936
11937 static void
11938 catch_fork_command_1 (char *arg, int from_tty, 
11939                       struct cmd_list_element *command)
11940 {
11941   struct gdbarch *gdbarch = get_current_arch ();
11942   char *cond_string = NULL;
11943   catch_fork_kind fork_kind;
11944   int tempflag;
11945
11946   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11947   tempflag = (fork_kind == catch_fork_temporary
11948               || fork_kind == catch_vfork_temporary);
11949
11950   if (!arg)
11951     arg = "";
11952   arg = skip_spaces (arg);
11953
11954   /* The allowed syntax is:
11955      catch [v]fork
11956      catch [v]fork if <cond>
11957
11958      First, check if there's an if clause.  */
11959   cond_string = ep_parse_optional_if_clause (&arg);
11960
11961   if ((*arg != '\0') && !isspace (*arg))
11962     error (_("Junk at end of arguments."));
11963
11964   /* If this target supports it, create a fork or vfork catchpoint
11965      and enable reporting of such events.  */
11966   switch (fork_kind)
11967     {
11968     case catch_fork_temporary:
11969     case catch_fork_permanent:
11970       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11971                                           &catch_fork_breakpoint_ops);
11972       break;
11973     case catch_vfork_temporary:
11974     case catch_vfork_permanent:
11975       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11976                                           &catch_vfork_breakpoint_ops);
11977       break;
11978     default:
11979       error (_("unsupported or unknown fork kind; cannot catch it"));
11980       break;
11981     }
11982 }
11983
11984 static void
11985 catch_exec_command_1 (char *arg, int from_tty, 
11986                       struct cmd_list_element *command)
11987 {
11988   struct exec_catchpoint *c;
11989   struct gdbarch *gdbarch = get_current_arch ();
11990   int tempflag;
11991   char *cond_string = NULL;
11992
11993   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11994
11995   if (!arg)
11996     arg = "";
11997   arg = skip_spaces (arg);
11998
11999   /* The allowed syntax is:
12000      catch exec
12001      catch exec if <cond>
12002
12003      First, check if there's an if clause.  */
12004   cond_string = ep_parse_optional_if_clause (&arg);
12005
12006   if ((*arg != '\0') && !isspace (*arg))
12007     error (_("Junk at end of arguments."));
12008
12009   c = XNEW (struct exec_catchpoint);
12010   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12011                    &catch_exec_breakpoint_ops);
12012   c->exec_pathname = NULL;
12013
12014   install_breakpoint (0, &c->base, 1);
12015 }
12016
12017 void
12018 init_ada_exception_breakpoint (struct breakpoint *b,
12019                                struct gdbarch *gdbarch,
12020                                struct symtab_and_line sal,
12021                                char *addr_string,
12022                                const struct breakpoint_ops *ops,
12023                                int tempflag,
12024                                int enabled,
12025                                int from_tty)
12026 {
12027   if (from_tty)
12028     {
12029       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12030       if (!loc_gdbarch)
12031         loc_gdbarch = gdbarch;
12032
12033       describe_other_breakpoints (loc_gdbarch,
12034                                   sal.pspace, sal.pc, sal.section, -1);
12035       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12036          version for exception catchpoints, because two catchpoints
12037          used for different exception names will use the same address.
12038          In this case, a "breakpoint ... also set at..." warning is
12039          unproductive.  Besides, the warning phrasing is also a bit
12040          inappropriate, we should use the word catchpoint, and tell
12041          the user what type of catchpoint it is.  The above is good
12042          enough for now, though.  */
12043     }
12044
12045   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12046
12047   b->enable_state = enabled ? bp_enabled : bp_disabled;
12048   b->disposition = tempflag ? disp_del : disp_donttouch;
12049   b->addr_string = addr_string;
12050   b->language = language_ada;
12051 }
12052
12053 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12054    filter list, or NULL if no filtering is required.  */
12055 static VEC(int) *
12056 catch_syscall_split_args (char *arg)
12057 {
12058   VEC(int) *result = NULL;
12059   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12060
12061   while (*arg != '\0')
12062     {
12063       int i, syscall_number;
12064       char *endptr;
12065       char cur_name[128];
12066       struct syscall s;
12067
12068       /* Skip whitespace.  */
12069       arg = skip_spaces (arg);
12070
12071       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12072         cur_name[i] = arg[i];
12073       cur_name[i] = '\0';
12074       arg += i;
12075
12076       /* Check if the user provided a syscall name or a number.  */
12077       syscall_number = (int) strtol (cur_name, &endptr, 0);
12078       if (*endptr == '\0')
12079         get_syscall_by_number (syscall_number, &s);
12080       else
12081         {
12082           /* We have a name.  Let's check if it's valid and convert it
12083              to a number.  */
12084           get_syscall_by_name (cur_name, &s);
12085
12086           if (s.number == UNKNOWN_SYSCALL)
12087             /* Here we have to issue an error instead of a warning,
12088                because GDB cannot do anything useful if there's no
12089                syscall number to be caught.  */
12090             error (_("Unknown syscall name '%s'."), cur_name);
12091         }
12092
12093       /* Ok, it's valid.  */
12094       VEC_safe_push (int, result, s.number);
12095     }
12096
12097   discard_cleanups (cleanup);
12098   return result;
12099 }
12100
12101 /* Implement the "catch syscall" command.  */
12102
12103 static void
12104 catch_syscall_command_1 (char *arg, int from_tty, 
12105                          struct cmd_list_element *command)
12106 {
12107   int tempflag;
12108   VEC(int) *filter;
12109   struct syscall s;
12110   struct gdbarch *gdbarch = get_current_arch ();
12111
12112   /* Checking if the feature if supported.  */
12113   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12114     error (_("The feature 'catch syscall' is not supported on \
12115 this architecture yet."));
12116
12117   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12118
12119   arg = skip_spaces (arg);
12120
12121   /* We need to do this first "dummy" translation in order
12122      to get the syscall XML file loaded or, most important,
12123      to display a warning to the user if there's no XML file
12124      for his/her architecture.  */
12125   get_syscall_by_number (0, &s);
12126
12127   /* The allowed syntax is:
12128      catch syscall
12129      catch syscall <name | number> [<name | number> ... <name | number>]
12130
12131      Let's check if there's a syscall name.  */
12132
12133   if (arg != NULL)
12134     filter = catch_syscall_split_args (arg);
12135   else
12136     filter = NULL;
12137
12138   create_syscall_event_catchpoint (tempflag, filter,
12139                                    &catch_syscall_breakpoint_ops);
12140 }
12141
12142 static void
12143 catch_command (char *arg, int from_tty)
12144 {
12145   error (_("Catch requires an event name."));
12146 }
12147 \f
12148
12149 static void
12150 tcatch_command (char *arg, int from_tty)
12151 {
12152   error (_("Catch requires an event name."));
12153 }
12154
12155 /* A qsort comparison function that sorts breakpoints in order.  */
12156
12157 static int
12158 compare_breakpoints (const void *a, const void *b)
12159 {
12160   const breakpoint_p *ba = a;
12161   uintptr_t ua = (uintptr_t) *ba;
12162   const breakpoint_p *bb = b;
12163   uintptr_t ub = (uintptr_t) *bb;
12164
12165   if ((*ba)->number < (*bb)->number)
12166     return -1;
12167   else if ((*ba)->number > (*bb)->number)
12168     return 1;
12169
12170   /* Now sort by address, in case we see, e..g, two breakpoints with
12171      the number 0.  */
12172   if (ua < ub)
12173     return -1;
12174   return ua > ub ? 1 : 0;
12175 }
12176
12177 /* Delete breakpoints by address or line.  */
12178
12179 static void
12180 clear_command (char *arg, int from_tty)
12181 {
12182   struct breakpoint *b, *prev;
12183   VEC(breakpoint_p) *found = 0;
12184   int ix;
12185   int default_match;
12186   struct symtabs_and_lines sals;
12187   struct symtab_and_line sal;
12188   int i;
12189   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12190
12191   if (arg)
12192     {
12193       sals = decode_line_with_current_source (arg,
12194                                               (DECODE_LINE_FUNFIRSTLINE
12195                                                | DECODE_LINE_LIST_MODE));
12196       make_cleanup (xfree, sals.sals);
12197       default_match = 0;
12198     }
12199   else
12200     {
12201       sals.sals = (struct symtab_and_line *)
12202         xmalloc (sizeof (struct symtab_and_line));
12203       make_cleanup (xfree, sals.sals);
12204       init_sal (&sal);          /* Initialize to zeroes.  */
12205
12206       /* Set sal's line, symtab, pc, and pspace to the values
12207          corresponding to the last call to print_frame_info.  If the
12208          codepoint is not valid, this will set all the fields to 0.  */
12209       get_last_displayed_sal (&sal);
12210       if (sal.symtab == 0)
12211         error (_("No source file specified."));
12212
12213       sals.sals[0] = sal;
12214       sals.nelts = 1;
12215
12216       default_match = 1;
12217     }
12218
12219   /* We don't call resolve_sal_pc here.  That's not as bad as it
12220      seems, because all existing breakpoints typically have both
12221      file/line and pc set.  So, if clear is given file/line, we can
12222      match this to existing breakpoint without obtaining pc at all.
12223
12224      We only support clearing given the address explicitly 
12225      present in breakpoint table.  Say, we've set breakpoint 
12226      at file:line.  There were several PC values for that file:line,
12227      due to optimization, all in one block.
12228
12229      We've picked one PC value.  If "clear" is issued with another
12230      PC corresponding to the same file:line, the breakpoint won't
12231      be cleared.  We probably can still clear the breakpoint, but 
12232      since the other PC value is never presented to user, user
12233      can only find it by guessing, and it does not seem important
12234      to support that.  */
12235
12236   /* For each line spec given, delete bps which correspond to it.  Do
12237      it in two passes, solely to preserve the current behavior that
12238      from_tty is forced true if we delete more than one
12239      breakpoint.  */
12240
12241   found = NULL;
12242   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12243   for (i = 0; i < sals.nelts; i++)
12244     {
12245       const char *sal_fullname;
12246
12247       /* If exact pc given, clear bpts at that pc.
12248          If line given (pc == 0), clear all bpts on specified line.
12249          If defaulting, clear all bpts on default line
12250          or at default pc.
12251
12252          defaulting    sal.pc != 0    tests to do
12253
12254          0              1             pc
12255          1              1             pc _and_ line
12256          0              0             line
12257          1              0             <can't happen> */
12258
12259       sal = sals.sals[i];
12260       sal_fullname = (sal.symtab == NULL
12261                       ? NULL : symtab_to_fullname (sal.symtab));
12262
12263       /* Find all matching breakpoints and add them to 'found'.  */
12264       ALL_BREAKPOINTS (b)
12265         {
12266           int match = 0;
12267           /* Are we going to delete b?  */
12268           if (b->type != bp_none && !is_watchpoint (b))
12269             {
12270               struct bp_location *loc = b->loc;
12271               for (; loc; loc = loc->next)
12272                 {
12273                   /* If the user specified file:line, don't allow a PC
12274                      match.  This matches historical gdb behavior.  */
12275                   int pc_match = (!sal.explicit_line
12276                                   && sal.pc
12277                                   && (loc->pspace == sal.pspace)
12278                                   && (loc->address == sal.pc)
12279                                   && (!section_is_overlay (loc->section)
12280                                       || loc->section == sal.section));
12281                   int line_match = 0;
12282
12283                   if ((default_match || sal.explicit_line)
12284                       && loc->symtab != NULL
12285                       && sal_fullname != NULL
12286                       && sal.pspace == loc->pspace
12287                       && loc->line_number == sal.line
12288                       && filename_cmp (symtab_to_fullname (loc->symtab),
12289                                        sal_fullname) == 0)
12290                     line_match = 1;
12291
12292                   if (pc_match || line_match)
12293                     {
12294                       match = 1;
12295                       break;
12296                     }
12297                 }
12298             }
12299
12300           if (match)
12301             VEC_safe_push(breakpoint_p, found, b);
12302         }
12303     }
12304
12305   /* Now go thru the 'found' chain and delete them.  */
12306   if (VEC_empty(breakpoint_p, found))
12307     {
12308       if (arg)
12309         error (_("No breakpoint at %s."), arg);
12310       else
12311         error (_("No breakpoint at this line."));
12312     }
12313
12314   /* Remove duplicates from the vec.  */
12315   qsort (VEC_address (breakpoint_p, found),
12316          VEC_length (breakpoint_p, found),
12317          sizeof (breakpoint_p),
12318          compare_breakpoints);
12319   prev = VEC_index (breakpoint_p, found, 0);
12320   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12321     {
12322       if (b == prev)
12323         {
12324           VEC_ordered_remove (breakpoint_p, found, ix);
12325           --ix;
12326         }
12327     }
12328
12329   if (VEC_length(breakpoint_p, found) > 1)
12330     from_tty = 1;       /* Always report if deleted more than one.  */
12331   if (from_tty)
12332     {
12333       if (VEC_length(breakpoint_p, found) == 1)
12334         printf_unfiltered (_("Deleted breakpoint "));
12335       else
12336         printf_unfiltered (_("Deleted breakpoints "));
12337     }
12338
12339   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12340     {
12341       if (from_tty)
12342         printf_unfiltered ("%d ", b->number);
12343       delete_breakpoint (b);
12344     }
12345   if (from_tty)
12346     putchar_unfiltered ('\n');
12347
12348   do_cleanups (cleanups);
12349 }
12350 \f
12351 /* Delete breakpoint in BS if they are `delete' breakpoints and
12352    all breakpoints that are marked for deletion, whether hit or not.
12353    This is called after any breakpoint is hit, or after errors.  */
12354
12355 void
12356 breakpoint_auto_delete (bpstat bs)
12357 {
12358   struct breakpoint *b, *b_tmp;
12359
12360   for (; bs; bs = bs->next)
12361     if (bs->breakpoint_at
12362         && bs->breakpoint_at->disposition == disp_del
12363         && bs->stop)
12364       delete_breakpoint (bs->breakpoint_at);
12365
12366   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12367   {
12368     if (b->disposition == disp_del_at_next_stop)
12369       delete_breakpoint (b);
12370   }
12371 }
12372
12373 /* A comparison function for bp_location AP and BP being interfaced to
12374    qsort.  Sort elements primarily by their ADDRESS (no matter what
12375    does breakpoint_address_is_meaningful say for its OWNER),
12376    secondarily by ordering first bp_permanent OWNERed elements and
12377    terciarily just ensuring the array is sorted stable way despite
12378    qsort being an unstable algorithm.  */
12379
12380 static int
12381 bp_location_compare (const void *ap, const void *bp)
12382 {
12383   struct bp_location *a = *(void **) ap;
12384   struct bp_location *b = *(void **) bp;
12385   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12386   int a_perm = a->owner->enable_state == bp_permanent;
12387   int b_perm = b->owner->enable_state == bp_permanent;
12388
12389   if (a->address != b->address)
12390     return (a->address > b->address) - (a->address < b->address);
12391
12392   /* Sort locations at the same address by their pspace number, keeping
12393      locations of the same inferior (in a multi-inferior environment)
12394      grouped.  */
12395
12396   if (a->pspace->num != b->pspace->num)
12397     return ((a->pspace->num > b->pspace->num)
12398             - (a->pspace->num < b->pspace->num));
12399
12400   /* Sort permanent breakpoints first.  */
12401   if (a_perm != b_perm)
12402     return (a_perm < b_perm) - (a_perm > b_perm);
12403
12404   /* Make the internal GDB representation stable across GDB runs
12405      where A and B memory inside GDB can differ.  Breakpoint locations of
12406      the same type at the same address can be sorted in arbitrary order.  */
12407
12408   if (a->owner->number != b->owner->number)
12409     return ((a->owner->number > b->owner->number)
12410             - (a->owner->number < b->owner->number));
12411
12412   return (a > b) - (a < b);
12413 }
12414
12415 /* Set bp_location_placed_address_before_address_max and
12416    bp_location_shadow_len_after_address_max according to the current
12417    content of the bp_location array.  */
12418
12419 static void
12420 bp_location_target_extensions_update (void)
12421 {
12422   struct bp_location *bl, **blp_tmp;
12423
12424   bp_location_placed_address_before_address_max = 0;
12425   bp_location_shadow_len_after_address_max = 0;
12426
12427   ALL_BP_LOCATIONS (bl, blp_tmp)
12428     {
12429       CORE_ADDR start, end, addr;
12430
12431       if (!bp_location_has_shadow (bl))
12432         continue;
12433
12434       start = bl->target_info.placed_address;
12435       end = start + bl->target_info.shadow_len;
12436
12437       gdb_assert (bl->address >= start);
12438       addr = bl->address - start;
12439       if (addr > bp_location_placed_address_before_address_max)
12440         bp_location_placed_address_before_address_max = addr;
12441
12442       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12443
12444       gdb_assert (bl->address < end);
12445       addr = end - bl->address;
12446       if (addr > bp_location_shadow_len_after_address_max)
12447         bp_location_shadow_len_after_address_max = addr;
12448     }
12449 }
12450
12451 /* Download tracepoint locations if they haven't been.  */
12452
12453 static void
12454 download_tracepoint_locations (void)
12455 {
12456   struct breakpoint *b;
12457   struct cleanup *old_chain;
12458
12459   if (!target_can_download_tracepoint ())
12460     return;
12461
12462   old_chain = save_current_space_and_thread ();
12463
12464   ALL_TRACEPOINTS (b)
12465     {
12466       struct bp_location *bl;
12467       struct tracepoint *t;
12468       int bp_location_downloaded = 0;
12469
12470       if ((b->type == bp_fast_tracepoint
12471            ? !may_insert_fast_tracepoints
12472            : !may_insert_tracepoints))
12473         continue;
12474
12475       for (bl = b->loc; bl; bl = bl->next)
12476         {
12477           /* In tracepoint, locations are _never_ duplicated, so
12478              should_be_inserted is equivalent to
12479              unduplicated_should_be_inserted.  */
12480           if (!should_be_inserted (bl) || bl->inserted)
12481             continue;
12482
12483           switch_to_program_space_and_thread (bl->pspace);
12484
12485           target_download_tracepoint (bl);
12486
12487           bl->inserted = 1;
12488           bp_location_downloaded = 1;
12489         }
12490       t = (struct tracepoint *) b;
12491       t->number_on_target = b->number;
12492       if (bp_location_downloaded)
12493         observer_notify_breakpoint_modified (b);
12494     }
12495
12496   do_cleanups (old_chain);
12497 }
12498
12499 /* Swap the insertion/duplication state between two locations.  */
12500
12501 static void
12502 swap_insertion (struct bp_location *left, struct bp_location *right)
12503 {
12504   const int left_inserted = left->inserted;
12505   const int left_duplicate = left->duplicate;
12506   const int left_needs_update = left->needs_update;
12507   const struct bp_target_info left_target_info = left->target_info;
12508
12509   /* Locations of tracepoints can never be duplicated.  */
12510   if (is_tracepoint (left->owner))
12511     gdb_assert (!left->duplicate);
12512   if (is_tracepoint (right->owner))
12513     gdb_assert (!right->duplicate);
12514
12515   left->inserted = right->inserted;
12516   left->duplicate = right->duplicate;
12517   left->needs_update = right->needs_update;
12518   left->target_info = right->target_info;
12519   right->inserted = left_inserted;
12520   right->duplicate = left_duplicate;
12521   right->needs_update = left_needs_update;
12522   right->target_info = left_target_info;
12523 }
12524
12525 /* Force the re-insertion of the locations at ADDRESS.  This is called
12526    once a new/deleted/modified duplicate location is found and we are evaluating
12527    conditions on the target's side.  Such conditions need to be updated on
12528    the target.  */
12529
12530 static void
12531 force_breakpoint_reinsertion (struct bp_location *bl)
12532 {
12533   struct bp_location **locp = NULL, **loc2p;
12534   struct bp_location *loc;
12535   CORE_ADDR address = 0;
12536   int pspace_num;
12537
12538   address = bl->address;
12539   pspace_num = bl->pspace->num;
12540
12541   /* This is only meaningful if the target is
12542      evaluating conditions and if the user has
12543      opted for condition evaluation on the target's
12544      side.  */
12545   if (gdb_evaluates_breakpoint_condition_p ()
12546       || !target_supports_evaluation_of_breakpoint_conditions ())
12547     return;
12548
12549   /* Flag all breakpoint locations with this address and
12550      the same program space as the location
12551      as "its condition has changed".  We need to
12552      update the conditions on the target's side.  */
12553   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12554     {
12555       loc = *loc2p;
12556
12557       if (!is_breakpoint (loc->owner)
12558           || pspace_num != loc->pspace->num)
12559         continue;
12560
12561       /* Flag the location appropriately.  We use a different state to
12562          let everyone know that we already updated the set of locations
12563          with addr bl->address and program space bl->pspace.  This is so
12564          we don't have to keep calling these functions just to mark locations
12565          that have already been marked.  */
12566       loc->condition_changed = condition_updated;
12567
12568       /* Free the agent expression bytecode as well.  We will compute
12569          it later on.  */
12570       if (loc->cond_bytecode)
12571         {
12572           free_agent_expr (loc->cond_bytecode);
12573           loc->cond_bytecode = NULL;
12574         }
12575     }
12576 }
12577 /* Called whether new breakpoints are created, or existing breakpoints
12578    deleted, to update the global location list and recompute which
12579    locations are duplicate of which.
12580
12581    The INSERT_MODE flag determines whether locations may or may not be
12582    inserted now.  See 'enum ugll_insert_mode' for more info.  */
12583
12584 static void
12585 update_global_location_list (enum ugll_insert_mode insert_mode)
12586 {
12587   struct breakpoint *b;
12588   struct bp_location **locp, *loc;
12589   struct cleanup *cleanups;
12590   /* Last breakpoint location address that was marked for update.  */
12591   CORE_ADDR last_addr = 0;
12592   /* Last breakpoint location program space that was marked for update.  */
12593   int last_pspace_num = -1;
12594
12595   /* Used in the duplicates detection below.  When iterating over all
12596      bp_locations, points to the first bp_location of a given address.
12597      Breakpoints and watchpoints of different types are never
12598      duplicates of each other.  Keep one pointer for each type of
12599      breakpoint/watchpoint, so we only need to loop over all locations
12600      once.  */
12601   struct bp_location *bp_loc_first;  /* breakpoint */
12602   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12603   struct bp_location *awp_loc_first; /* access watchpoint */
12604   struct bp_location *rwp_loc_first; /* read watchpoint */
12605
12606   /* Saved former bp_location array which we compare against the newly
12607      built bp_location from the current state of ALL_BREAKPOINTS.  */
12608   struct bp_location **old_location, **old_locp;
12609   unsigned old_location_count;
12610
12611   old_location = bp_location;
12612   old_location_count = bp_location_count;
12613   bp_location = NULL;
12614   bp_location_count = 0;
12615   cleanups = make_cleanup (xfree, old_location);
12616
12617   ALL_BREAKPOINTS (b)
12618     for (loc = b->loc; loc; loc = loc->next)
12619       bp_location_count++;
12620
12621   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12622   locp = bp_location;
12623   ALL_BREAKPOINTS (b)
12624     for (loc = b->loc; loc; loc = loc->next)
12625       *locp++ = loc;
12626   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12627          bp_location_compare);
12628
12629   bp_location_target_extensions_update ();
12630
12631   /* Identify bp_location instances that are no longer present in the
12632      new list, and therefore should be freed.  Note that it's not
12633      necessary that those locations should be removed from inferior --
12634      if there's another location at the same address (previously
12635      marked as duplicate), we don't need to remove/insert the
12636      location.
12637      
12638      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12639      and former bp_location array state respectively.  */
12640
12641   locp = bp_location;
12642   for (old_locp = old_location; old_locp < old_location + old_location_count;
12643        old_locp++)
12644     {
12645       struct bp_location *old_loc = *old_locp;
12646       struct bp_location **loc2p;
12647
12648       /* Tells if 'old_loc' is found among the new locations.  If
12649          not, we have to free it.  */
12650       int found_object = 0;
12651       /* Tells if the location should remain inserted in the target.  */
12652       int keep_in_target = 0;
12653       int removed = 0;
12654
12655       /* Skip LOCP entries which will definitely never be needed.
12656          Stop either at or being the one matching OLD_LOC.  */
12657       while (locp < bp_location + bp_location_count
12658              && (*locp)->address < old_loc->address)
12659         locp++;
12660
12661       for (loc2p = locp;
12662            (loc2p < bp_location + bp_location_count
12663             && (*loc2p)->address == old_loc->address);
12664            loc2p++)
12665         {
12666           /* Check if this is a new/duplicated location or a duplicated
12667              location that had its condition modified.  If so, we want to send
12668              its condition to the target if evaluation of conditions is taking
12669              place there.  */
12670           if ((*loc2p)->condition_changed == condition_modified
12671               && (last_addr != old_loc->address
12672                   || last_pspace_num != old_loc->pspace->num))
12673             {
12674               force_breakpoint_reinsertion (*loc2p);
12675               last_pspace_num = old_loc->pspace->num;
12676             }
12677
12678           if (*loc2p == old_loc)
12679             found_object = 1;
12680         }
12681
12682       /* We have already handled this address, update it so that we don't
12683          have to go through updates again.  */
12684       last_addr = old_loc->address;
12685
12686       /* Target-side condition evaluation: Handle deleted locations.  */
12687       if (!found_object)
12688         force_breakpoint_reinsertion (old_loc);
12689
12690       /* If this location is no longer present, and inserted, look if
12691          there's maybe a new location at the same address.  If so,
12692          mark that one inserted, and don't remove this one.  This is
12693          needed so that we don't have a time window where a breakpoint
12694          at certain location is not inserted.  */
12695
12696       if (old_loc->inserted)
12697         {
12698           /* If the location is inserted now, we might have to remove
12699              it.  */
12700
12701           if (found_object && should_be_inserted (old_loc))
12702             {
12703               /* The location is still present in the location list,
12704                  and still should be inserted.  Don't do anything.  */
12705               keep_in_target = 1;
12706             }
12707           else
12708             {
12709               /* This location still exists, but it won't be kept in the
12710                  target since it may have been disabled.  We proceed to
12711                  remove its target-side condition.  */
12712
12713               /* The location is either no longer present, or got
12714                  disabled.  See if there's another location at the
12715                  same address, in which case we don't need to remove
12716                  this one from the target.  */
12717
12718               /* OLD_LOC comes from existing struct breakpoint.  */
12719               if (breakpoint_address_is_meaningful (old_loc->owner))
12720                 {
12721                   for (loc2p = locp;
12722                        (loc2p < bp_location + bp_location_count
12723                         && (*loc2p)->address == old_loc->address);
12724                        loc2p++)
12725                     {
12726                       struct bp_location *loc2 = *loc2p;
12727
12728                       if (breakpoint_locations_match (loc2, old_loc))
12729                         {
12730                           /* Read watchpoint locations are switched to
12731                              access watchpoints, if the former are not
12732                              supported, but the latter are.  */
12733                           if (is_hardware_watchpoint (old_loc->owner))
12734                             {
12735                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12736                               loc2->watchpoint_type = old_loc->watchpoint_type;
12737                             }
12738
12739                           /* loc2 is a duplicated location. We need to check
12740                              if it should be inserted in case it will be
12741                              unduplicated.  */
12742                           if (loc2 != old_loc
12743                               && unduplicated_should_be_inserted (loc2))
12744                             {
12745                               swap_insertion (old_loc, loc2);
12746                               keep_in_target = 1;
12747                               break;
12748                             }
12749                         }
12750                     }
12751                 }
12752             }
12753
12754           if (!keep_in_target)
12755             {
12756               if (remove_breakpoint (old_loc, mark_uninserted))
12757                 {
12758                   /* This is just about all we can do.  We could keep
12759                      this location on the global list, and try to
12760                      remove it next time, but there's no particular
12761                      reason why we will succeed next time.
12762                      
12763                      Note that at this point, old_loc->owner is still
12764                      valid, as delete_breakpoint frees the breakpoint
12765                      only after calling us.  */
12766                   printf_filtered (_("warning: Error removing "
12767                                      "breakpoint %d\n"), 
12768                                    old_loc->owner->number);
12769                 }
12770               removed = 1;
12771             }
12772         }
12773
12774       if (!found_object)
12775         {
12776           if (removed && non_stop
12777               && breakpoint_address_is_meaningful (old_loc->owner)
12778               && !is_hardware_watchpoint (old_loc->owner))
12779             {
12780               /* This location was removed from the target.  In
12781                  non-stop mode, a race condition is possible where
12782                  we've removed a breakpoint, but stop events for that
12783                  breakpoint are already queued and will arrive later.
12784                  We apply an heuristic to be able to distinguish such
12785                  SIGTRAPs from other random SIGTRAPs: we keep this
12786                  breakpoint location for a bit, and will retire it
12787                  after we see some number of events.  The theory here
12788                  is that reporting of events should, "on the average",
12789                  be fair, so after a while we'll see events from all
12790                  threads that have anything of interest, and no longer
12791                  need to keep this breakpoint location around.  We
12792                  don't hold locations forever so to reduce chances of
12793                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12794                  SIGTRAP.
12795
12796                  The heuristic failing can be disastrous on
12797                  decr_pc_after_break targets.
12798
12799                  On decr_pc_after_break targets, like e.g., x86-linux,
12800                  if we fail to recognize a late breakpoint SIGTRAP,
12801                  because events_till_retirement has reached 0 too
12802                  soon, we'll fail to do the PC adjustment, and report
12803                  a random SIGTRAP to the user.  When the user resumes
12804                  the inferior, it will most likely immediately crash
12805                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12806                  corrupted, because of being resumed e.g., in the
12807                  middle of a multi-byte instruction, or skipped a
12808                  one-byte instruction.  This was actually seen happen
12809                  on native x86-linux, and should be less rare on
12810                  targets that do not support new thread events, like
12811                  remote, due to the heuristic depending on
12812                  thread_count.
12813
12814                  Mistaking a random SIGTRAP for a breakpoint trap
12815                  causes similar symptoms (PC adjustment applied when
12816                  it shouldn't), but then again, playing with SIGTRAPs
12817                  behind the debugger's back is asking for trouble.
12818
12819                  Since hardware watchpoint traps are always
12820                  distinguishable from other traps, so we don't need to
12821                  apply keep hardware watchpoint moribund locations
12822                  around.  We simply always ignore hardware watchpoint
12823                  traps we can no longer explain.  */
12824
12825               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12826               old_loc->owner = NULL;
12827
12828               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12829             }
12830           else
12831             {
12832               old_loc->owner = NULL;
12833               decref_bp_location (&old_loc);
12834             }
12835         }
12836     }
12837
12838   /* Rescan breakpoints at the same address and section, marking the
12839      first one as "first" and any others as "duplicates".  This is so
12840      that the bpt instruction is only inserted once.  If we have a
12841      permanent breakpoint at the same place as BPT, make that one the
12842      official one, and the rest as duplicates.  Permanent breakpoints
12843      are sorted first for the same address.
12844
12845      Do the same for hardware watchpoints, but also considering the
12846      watchpoint's type (regular/access/read) and length.  */
12847
12848   bp_loc_first = NULL;
12849   wp_loc_first = NULL;
12850   awp_loc_first = NULL;
12851   rwp_loc_first = NULL;
12852   ALL_BP_LOCATIONS (loc, locp)
12853     {
12854       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12855          non-NULL.  */
12856       struct bp_location **loc_first_p;
12857       b = loc->owner;
12858
12859       if (!unduplicated_should_be_inserted (loc)
12860           || !breakpoint_address_is_meaningful (b)
12861           /* Don't detect duplicate for tracepoint locations because they are
12862            never duplicated.  See the comments in field `duplicate' of
12863            `struct bp_location'.  */
12864           || is_tracepoint (b))
12865         {
12866           /* Clear the condition modification flag.  */
12867           loc->condition_changed = condition_unchanged;
12868           continue;
12869         }
12870
12871       /* Permanent breakpoint should always be inserted.  */
12872       if (b->enable_state == bp_permanent && ! loc->inserted)
12873         internal_error (__FILE__, __LINE__,
12874                         _("allegedly permanent breakpoint is not "
12875                         "actually inserted"));
12876
12877       if (b->type == bp_hardware_watchpoint)
12878         loc_first_p = &wp_loc_first;
12879       else if (b->type == bp_read_watchpoint)
12880         loc_first_p = &rwp_loc_first;
12881       else if (b->type == bp_access_watchpoint)
12882         loc_first_p = &awp_loc_first;
12883       else
12884         loc_first_p = &bp_loc_first;
12885
12886       if (*loc_first_p == NULL
12887           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12888           || !breakpoint_locations_match (loc, *loc_first_p))
12889         {
12890           *loc_first_p = loc;
12891           loc->duplicate = 0;
12892
12893           if (is_breakpoint (loc->owner) && loc->condition_changed)
12894             {
12895               loc->needs_update = 1;
12896               /* Clear the condition modification flag.  */
12897               loc->condition_changed = condition_unchanged;
12898             }
12899           continue;
12900         }
12901
12902
12903       /* This and the above ensure the invariant that the first location
12904          is not duplicated, and is the inserted one.
12905          All following are marked as duplicated, and are not inserted.  */
12906       if (loc->inserted)
12907         swap_insertion (loc, *loc_first_p);
12908       loc->duplicate = 1;
12909
12910       /* Clear the condition modification flag.  */
12911       loc->condition_changed = condition_unchanged;
12912
12913       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12914           && b->enable_state != bp_permanent)
12915         internal_error (__FILE__, __LINE__,
12916                         _("another breakpoint was inserted on top of "
12917                         "a permanent breakpoint"));
12918     }
12919
12920   if (breakpoints_always_inserted_mode ()
12921       && (have_live_inferiors ()
12922           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12923     {
12924       if (insert_mode == UGLL_MAY_INSERT)
12925         insert_breakpoint_locations ();
12926       else
12927         {
12928           /* Even though the caller told us to not insert new
12929              locations, we may still need to update conditions on the
12930              target's side of breakpoints that were already inserted
12931              if the target is evaluating breakpoint conditions.  We
12932              only update conditions for locations that are marked
12933              "needs_update".  */
12934           update_inserted_breakpoint_locations ();
12935         }
12936     }
12937
12938   if (insert_mode == UGLL_MAY_INSERT)
12939     download_tracepoint_locations ();
12940
12941   do_cleanups (cleanups);
12942 }
12943
12944 void
12945 breakpoint_retire_moribund (void)
12946 {
12947   struct bp_location *loc;
12948   int ix;
12949
12950   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12951     if (--(loc->events_till_retirement) == 0)
12952       {
12953         decref_bp_location (&loc);
12954         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12955         --ix;
12956       }
12957 }
12958
12959 static void
12960 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12961 {
12962   volatile struct gdb_exception e;
12963
12964   TRY_CATCH (e, RETURN_MASK_ERROR)
12965     update_global_location_list (insert_mode);
12966 }
12967
12968 /* Clear BKP from a BPS.  */
12969
12970 static void
12971 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12972 {
12973   bpstat bs;
12974
12975   for (bs = bps; bs; bs = bs->next)
12976     if (bs->breakpoint_at == bpt)
12977       {
12978         bs->breakpoint_at = NULL;
12979         bs->old_val = NULL;
12980         /* bs->commands will be freed later.  */
12981       }
12982 }
12983
12984 /* Callback for iterate_over_threads.  */
12985 static int
12986 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12987 {
12988   struct breakpoint *bpt = data;
12989
12990   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12991   return 0;
12992 }
12993
12994 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12995    callbacks.  */
12996
12997 static void
12998 say_where (struct breakpoint *b)
12999 {
13000   struct value_print_options opts;
13001
13002   get_user_print_options (&opts);
13003
13004   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13005      single string.  */
13006   if (b->loc == NULL)
13007     {
13008       printf_filtered (_(" (%s) pending."), b->addr_string);
13009     }
13010   else
13011     {
13012       if (opts.addressprint || b->loc->symtab == NULL)
13013         {
13014           printf_filtered (" at ");
13015           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13016                           gdb_stdout);
13017         }
13018       if (b->loc->symtab != NULL)
13019         {
13020           /* If there is a single location, we can print the location
13021              more nicely.  */
13022           if (b->loc->next == NULL)
13023             printf_filtered (": file %s, line %d.",
13024                              symtab_to_filename_for_display (b->loc->symtab),
13025                              b->loc->line_number);
13026           else
13027             /* This is not ideal, but each location may have a
13028                different file name, and this at least reflects the
13029                real situation somewhat.  */
13030             printf_filtered (": %s.", b->addr_string);
13031         }
13032
13033       if (b->loc->next)
13034         {
13035           struct bp_location *loc = b->loc;
13036           int n = 0;
13037           for (; loc; loc = loc->next)
13038             ++n;
13039           printf_filtered (" (%d locations)", n);
13040         }
13041     }
13042 }
13043
13044 /* Default bp_location_ops methods.  */
13045
13046 static void
13047 bp_location_dtor (struct bp_location *self)
13048 {
13049   xfree (self->cond);
13050   if (self->cond_bytecode)
13051     free_agent_expr (self->cond_bytecode);
13052   xfree (self->function_name);
13053
13054   VEC_free (agent_expr_p, self->target_info.conditions);
13055   VEC_free (agent_expr_p, self->target_info.tcommands);
13056 }
13057
13058 static const struct bp_location_ops bp_location_ops =
13059 {
13060   bp_location_dtor
13061 };
13062
13063 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13064    inherit from.  */
13065
13066 static void
13067 base_breakpoint_dtor (struct breakpoint *self)
13068 {
13069   decref_counted_command_line (&self->commands);
13070   xfree (self->cond_string);
13071   xfree (self->extra_string);
13072   xfree (self->addr_string);
13073   xfree (self->filter);
13074   xfree (self->addr_string_range_end);
13075 }
13076
13077 static struct bp_location *
13078 base_breakpoint_allocate_location (struct breakpoint *self)
13079 {
13080   struct bp_location *loc;
13081
13082   loc = XNEW (struct bp_location);
13083   init_bp_location (loc, &bp_location_ops, self);
13084   return loc;
13085 }
13086
13087 static void
13088 base_breakpoint_re_set (struct breakpoint *b)
13089 {
13090   /* Nothing to re-set. */
13091 }
13092
13093 #define internal_error_pure_virtual_called() \
13094   gdb_assert_not_reached ("pure virtual function called")
13095
13096 static int
13097 base_breakpoint_insert_location (struct bp_location *bl)
13098 {
13099   internal_error_pure_virtual_called ();
13100 }
13101
13102 static int
13103 base_breakpoint_remove_location (struct bp_location *bl)
13104 {
13105   internal_error_pure_virtual_called ();
13106 }
13107
13108 static int
13109 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13110                                 struct address_space *aspace,
13111                                 CORE_ADDR bp_addr,
13112                                 const struct target_waitstatus *ws)
13113 {
13114   internal_error_pure_virtual_called ();
13115 }
13116
13117 static void
13118 base_breakpoint_check_status (bpstat bs)
13119 {
13120   /* Always stop.   */
13121 }
13122
13123 /* A "works_in_software_mode" breakpoint_ops method that just internal
13124    errors.  */
13125
13126 static int
13127 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13128 {
13129   internal_error_pure_virtual_called ();
13130 }
13131
13132 /* A "resources_needed" breakpoint_ops method that just internal
13133    errors.  */
13134
13135 static int
13136 base_breakpoint_resources_needed (const struct bp_location *bl)
13137 {
13138   internal_error_pure_virtual_called ();
13139 }
13140
13141 static enum print_stop_action
13142 base_breakpoint_print_it (bpstat bs)
13143 {
13144   internal_error_pure_virtual_called ();
13145 }
13146
13147 static void
13148 base_breakpoint_print_one_detail (const struct breakpoint *self,
13149                                   struct ui_out *uiout)
13150 {
13151   /* nothing */
13152 }
13153
13154 static void
13155 base_breakpoint_print_mention (struct breakpoint *b)
13156 {
13157   internal_error_pure_virtual_called ();
13158 }
13159
13160 static void
13161 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13162 {
13163   internal_error_pure_virtual_called ();
13164 }
13165
13166 static void
13167 base_breakpoint_create_sals_from_address (char **arg,
13168                                           struct linespec_result *canonical,
13169                                           enum bptype type_wanted,
13170                                           char *addr_start,
13171                                           char **copy_arg)
13172 {
13173   internal_error_pure_virtual_called ();
13174 }
13175
13176 static void
13177 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13178                                         struct linespec_result *c,
13179                                         char *cond_string,
13180                                         char *extra_string,
13181                                         enum bptype type_wanted,
13182                                         enum bpdisp disposition,
13183                                         int thread,
13184                                         int task, int ignore_count,
13185                                         const struct breakpoint_ops *o,
13186                                         int from_tty, int enabled,
13187                                         int internal, unsigned flags)
13188 {
13189   internal_error_pure_virtual_called ();
13190 }
13191
13192 static void
13193 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13194                                  struct symtabs_and_lines *sals)
13195 {
13196   internal_error_pure_virtual_called ();
13197 }
13198
13199 /* The default 'explains_signal' method.  */
13200
13201 static int
13202 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13203 {
13204   return 1;
13205 }
13206
13207 /* The default "after_condition_true" method.  */
13208
13209 static void
13210 base_breakpoint_after_condition_true (struct bpstats *bs)
13211 {
13212   /* Nothing to do.   */
13213 }
13214
13215 struct breakpoint_ops base_breakpoint_ops =
13216 {
13217   base_breakpoint_dtor,
13218   base_breakpoint_allocate_location,
13219   base_breakpoint_re_set,
13220   base_breakpoint_insert_location,
13221   base_breakpoint_remove_location,
13222   base_breakpoint_breakpoint_hit,
13223   base_breakpoint_check_status,
13224   base_breakpoint_resources_needed,
13225   base_breakpoint_works_in_software_mode,
13226   base_breakpoint_print_it,
13227   NULL,
13228   base_breakpoint_print_one_detail,
13229   base_breakpoint_print_mention,
13230   base_breakpoint_print_recreate,
13231   base_breakpoint_create_sals_from_address,
13232   base_breakpoint_create_breakpoints_sal,
13233   base_breakpoint_decode_linespec,
13234   base_breakpoint_explains_signal,
13235   base_breakpoint_after_condition_true,
13236 };
13237
13238 /* Default breakpoint_ops methods.  */
13239
13240 static void
13241 bkpt_re_set (struct breakpoint *b)
13242 {
13243   /* FIXME: is this still reachable?  */
13244   if (b->addr_string == NULL)
13245     {
13246       /* Anything without a string can't be re-set.  */
13247       delete_breakpoint (b);
13248       return;
13249     }
13250
13251   breakpoint_re_set_default (b);
13252 }
13253
13254 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13255    inserted DEST, so we can remove it later, in case SRC is removed
13256    first.  */
13257
13258 static void
13259 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13260                                      const struct bp_target_info *src)
13261 {
13262   dest->shadow_len = src->shadow_len;
13263   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13264   dest->placed_size = src->placed_size;
13265 }
13266
13267 static int
13268 bkpt_insert_location (struct bp_location *bl)
13269 {
13270   if (bl->loc_type == bp_loc_hardware_breakpoint)
13271     return target_insert_hw_breakpoint (bl->gdbarch,
13272                                         &bl->target_info);
13273   else
13274     {
13275       struct bp_target_info *bp_tgt = &bl->target_info;
13276       int ret;
13277       int sss_slot;
13278
13279       /* There is no need to insert a breakpoint if an unconditional
13280          raw/sss breakpoint is already inserted at that location.  */
13281       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13282                                               bp_tgt->placed_address);
13283       if (sss_slot >= 0)
13284         {
13285           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13286
13287           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13288           return 0;
13289         }
13290
13291       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13292     }
13293 }
13294
13295 static int
13296 bkpt_remove_location (struct bp_location *bl)
13297 {
13298   if (bl->loc_type == bp_loc_hardware_breakpoint)
13299     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13300   else
13301     {
13302       struct bp_target_info *bp_tgt = &bl->target_info;
13303       struct address_space *aspace = bp_tgt->placed_address_space;
13304       CORE_ADDR address = bp_tgt->placed_address;
13305
13306       /* Only remove the breakpoint if there is no raw/sss breakpoint
13307          still inserted at this location.  Otherwise, we would be
13308          effectively disabling the raw/sss breakpoint.  */
13309       if (single_step_breakpoint_inserted_here_p (aspace, address))
13310         return 0;
13311
13312       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13313     }
13314 }
13315
13316 static int
13317 bkpt_breakpoint_hit (const struct bp_location *bl,
13318                      struct address_space *aspace, CORE_ADDR bp_addr,
13319                      const struct target_waitstatus *ws)
13320 {
13321   if (ws->kind != TARGET_WAITKIND_STOPPED
13322       || ws->value.sig != GDB_SIGNAL_TRAP)
13323     return 0;
13324
13325   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13326                                  aspace, bp_addr))
13327     return 0;
13328
13329   if (overlay_debugging         /* unmapped overlay section */
13330       && section_is_overlay (bl->section)
13331       && !section_is_mapped (bl->section))
13332     return 0;
13333
13334   return 1;
13335 }
13336
13337 static int
13338 dprintf_breakpoint_hit (const struct bp_location *bl,
13339                         struct address_space *aspace, CORE_ADDR bp_addr,
13340                         const struct target_waitstatus *ws)
13341 {
13342   if (dprintf_style == dprintf_style_agent
13343       && target_can_run_breakpoint_commands ())
13344     {
13345       /* An agent-style dprintf never causes a stop.  If we see a trap
13346          for this address it must be for a breakpoint that happens to
13347          be set at the same address.  */
13348       return 0;
13349     }
13350
13351   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13352 }
13353
13354 static int
13355 bkpt_resources_needed (const struct bp_location *bl)
13356 {
13357   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13358
13359   return 1;
13360 }
13361
13362 static enum print_stop_action
13363 bkpt_print_it (bpstat bs)
13364 {
13365   struct breakpoint *b;
13366   const struct bp_location *bl;
13367   int bp_temp;
13368   struct ui_out *uiout = current_uiout;
13369
13370   gdb_assert (bs->bp_location_at != NULL);
13371
13372   bl = bs->bp_location_at;
13373   b = bs->breakpoint_at;
13374
13375   bp_temp = b->disposition == disp_del;
13376   if (bl->address != bl->requested_address)
13377     breakpoint_adjustment_warning (bl->requested_address,
13378                                    bl->address,
13379                                    b->number, 1);
13380   annotate_breakpoint (b->number);
13381   if (bp_temp)
13382     ui_out_text (uiout, "\nTemporary breakpoint ");
13383   else
13384     ui_out_text (uiout, "\nBreakpoint ");
13385   if (ui_out_is_mi_like_p (uiout))
13386     {
13387       ui_out_field_string (uiout, "reason",
13388                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13389       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13390     }
13391   ui_out_field_int (uiout, "bkptno", b->number);
13392   ui_out_text (uiout, ", ");
13393
13394   return PRINT_SRC_AND_LOC;
13395 }
13396
13397 static void
13398 bkpt_print_mention (struct breakpoint *b)
13399 {
13400   if (ui_out_is_mi_like_p (current_uiout))
13401     return;
13402
13403   switch (b->type)
13404     {
13405     case bp_breakpoint:
13406     case bp_gnu_ifunc_resolver:
13407       if (b->disposition == disp_del)
13408         printf_filtered (_("Temporary breakpoint"));
13409       else
13410         printf_filtered (_("Breakpoint"));
13411       printf_filtered (_(" %d"), b->number);
13412       if (b->type == bp_gnu_ifunc_resolver)
13413         printf_filtered (_(" at gnu-indirect-function resolver"));
13414       break;
13415     case bp_hardware_breakpoint:
13416       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13417       break;
13418     case bp_dprintf:
13419       printf_filtered (_("Dprintf %d"), b->number);
13420       break;
13421     }
13422
13423   say_where (b);
13424 }
13425
13426 static void
13427 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13428 {
13429   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13430     fprintf_unfiltered (fp, "tbreak");
13431   else if (tp->type == bp_breakpoint)
13432     fprintf_unfiltered (fp, "break");
13433   else if (tp->type == bp_hardware_breakpoint
13434            && tp->disposition == disp_del)
13435     fprintf_unfiltered (fp, "thbreak");
13436   else if (tp->type == bp_hardware_breakpoint)
13437     fprintf_unfiltered (fp, "hbreak");
13438   else
13439     internal_error (__FILE__, __LINE__,
13440                     _("unhandled breakpoint type %d"), (int) tp->type);
13441
13442   fprintf_unfiltered (fp, " %s", tp->addr_string);
13443   print_recreate_thread (tp, fp);
13444 }
13445
13446 static void
13447 bkpt_create_sals_from_address (char **arg,
13448                                struct linespec_result *canonical,
13449                                enum bptype type_wanted,
13450                                char *addr_start, char **copy_arg)
13451 {
13452   create_sals_from_address_default (arg, canonical, type_wanted,
13453                                     addr_start, copy_arg);
13454 }
13455
13456 static void
13457 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13458                              struct linespec_result *canonical,
13459                              char *cond_string,
13460                              char *extra_string,
13461                              enum bptype type_wanted,
13462                              enum bpdisp disposition,
13463                              int thread,
13464                              int task, int ignore_count,
13465                              const struct breakpoint_ops *ops,
13466                              int from_tty, int enabled,
13467                              int internal, unsigned flags)
13468 {
13469   create_breakpoints_sal_default (gdbarch, canonical,
13470                                   cond_string, extra_string,
13471                                   type_wanted,
13472                                   disposition, thread, task,
13473                                   ignore_count, ops, from_tty,
13474                                   enabled, internal, flags);
13475 }
13476
13477 static void
13478 bkpt_decode_linespec (struct breakpoint *b, char **s,
13479                       struct symtabs_and_lines *sals)
13480 {
13481   decode_linespec_default (b, s, sals);
13482 }
13483
13484 /* Virtual table for internal breakpoints.  */
13485
13486 static void
13487 internal_bkpt_re_set (struct breakpoint *b)
13488 {
13489   switch (b->type)
13490     {
13491       /* Delete overlay event and longjmp master breakpoints; they
13492          will be reset later by breakpoint_re_set.  */
13493     case bp_overlay_event:
13494     case bp_longjmp_master:
13495     case bp_std_terminate_master:
13496     case bp_exception_master:
13497       delete_breakpoint (b);
13498       break;
13499
13500       /* This breakpoint is special, it's set up when the inferior
13501          starts and we really don't want to touch it.  */
13502     case bp_shlib_event:
13503
13504       /* Like bp_shlib_event, this breakpoint type is special.  Once
13505          it is set up, we do not want to touch it.  */
13506     case bp_thread_event:
13507       break;
13508     }
13509 }
13510
13511 static void
13512 internal_bkpt_check_status (bpstat bs)
13513 {
13514   if (bs->breakpoint_at->type == bp_shlib_event)
13515     {
13516       /* If requested, stop when the dynamic linker notifies GDB of
13517          events.  This allows the user to get control and place
13518          breakpoints in initializer routines for dynamically loaded
13519          objects (among other things).  */
13520       bs->stop = stop_on_solib_events;
13521       bs->print = stop_on_solib_events;
13522     }
13523   else
13524     bs->stop = 0;
13525 }
13526
13527 static enum print_stop_action
13528 internal_bkpt_print_it (bpstat bs)
13529 {
13530   struct breakpoint *b;
13531
13532   b = bs->breakpoint_at;
13533
13534   switch (b->type)
13535     {
13536     case bp_shlib_event:
13537       /* Did we stop because the user set the stop_on_solib_events
13538          variable?  (If so, we report this as a generic, "Stopped due
13539          to shlib event" message.) */
13540       print_solib_event (0);
13541       break;
13542
13543     case bp_thread_event:
13544       /* Not sure how we will get here.
13545          GDB should not stop for these breakpoints.  */
13546       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13547       break;
13548
13549     case bp_overlay_event:
13550       /* By analogy with the thread event, GDB should not stop for these.  */
13551       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13552       break;
13553
13554     case bp_longjmp_master:
13555       /* These should never be enabled.  */
13556       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13557       break;
13558
13559     case bp_std_terminate_master:
13560       /* These should never be enabled.  */
13561       printf_filtered (_("std::terminate Master Breakpoint: "
13562                          "gdb should not stop!\n"));
13563       break;
13564
13565     case bp_exception_master:
13566       /* These should never be enabled.  */
13567       printf_filtered (_("Exception Master Breakpoint: "
13568                          "gdb should not stop!\n"));
13569       break;
13570     }
13571
13572   return PRINT_NOTHING;
13573 }
13574
13575 static void
13576 internal_bkpt_print_mention (struct breakpoint *b)
13577 {
13578   /* Nothing to mention.  These breakpoints are internal.  */
13579 }
13580
13581 /* Virtual table for momentary breakpoints  */
13582
13583 static void
13584 momentary_bkpt_re_set (struct breakpoint *b)
13585 {
13586   /* Keep temporary breakpoints, which can be encountered when we step
13587      over a dlopen call and solib_add is resetting the breakpoints.
13588      Otherwise these should have been blown away via the cleanup chain
13589      or by breakpoint_init_inferior when we rerun the executable.  */
13590 }
13591
13592 static void
13593 momentary_bkpt_check_status (bpstat bs)
13594 {
13595   /* Nothing.  The point of these breakpoints is causing a stop.  */
13596 }
13597
13598 static enum print_stop_action
13599 momentary_bkpt_print_it (bpstat bs)
13600 {
13601   struct ui_out *uiout = current_uiout;
13602
13603   if (ui_out_is_mi_like_p (uiout))
13604     {
13605       struct breakpoint *b = bs->breakpoint_at;
13606
13607       switch (b->type)
13608         {
13609         case bp_finish:
13610           ui_out_field_string
13611             (uiout, "reason",
13612              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13613           break;
13614
13615         case bp_until:
13616           ui_out_field_string
13617             (uiout, "reason",
13618              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13619           break;
13620         }
13621     }
13622
13623   return PRINT_UNKNOWN;
13624 }
13625
13626 static void
13627 momentary_bkpt_print_mention (struct breakpoint *b)
13628 {
13629   /* Nothing to mention.  These breakpoints are internal.  */
13630 }
13631
13632 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13633
13634    It gets cleared already on the removal of the first one of such placed
13635    breakpoints.  This is OK as they get all removed altogether.  */
13636
13637 static void
13638 longjmp_bkpt_dtor (struct breakpoint *self)
13639 {
13640   struct thread_info *tp = find_thread_id (self->thread);
13641
13642   if (tp)
13643     tp->initiating_frame = null_frame_id;
13644
13645   momentary_breakpoint_ops.dtor (self);
13646 }
13647
13648 /* Specific methods for probe breakpoints.  */
13649
13650 static int
13651 bkpt_probe_insert_location (struct bp_location *bl)
13652 {
13653   int v = bkpt_insert_location (bl);
13654
13655   if (v == 0)
13656     {
13657       /* The insertion was successful, now let's set the probe's semaphore
13658          if needed.  */
13659       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13660                                             bl->probe.objfile,
13661                                             bl->gdbarch);
13662     }
13663
13664   return v;
13665 }
13666
13667 static int
13668 bkpt_probe_remove_location (struct bp_location *bl)
13669 {
13670   /* Let's clear the semaphore before removing the location.  */
13671   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13672                                           bl->probe.objfile,
13673                                           bl->gdbarch);
13674
13675   return bkpt_remove_location (bl);
13676 }
13677
13678 static void
13679 bkpt_probe_create_sals_from_address (char **arg,
13680                                      struct linespec_result *canonical,
13681                                      enum bptype type_wanted,
13682                                      char *addr_start, char **copy_arg)
13683 {
13684   struct linespec_sals lsal;
13685
13686   lsal.sals = parse_probes (arg, canonical);
13687
13688   *copy_arg = xstrdup (canonical->addr_string);
13689   lsal.canonical = xstrdup (*copy_arg);
13690
13691   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13692 }
13693
13694 static void
13695 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13696                             struct symtabs_and_lines *sals)
13697 {
13698   *sals = parse_probes (s, NULL);
13699   if (!sals->sals)
13700     error (_("probe not found"));
13701 }
13702
13703 /* The breakpoint_ops structure to be used in tracepoints.  */
13704
13705 static void
13706 tracepoint_re_set (struct breakpoint *b)
13707 {
13708   breakpoint_re_set_default (b);
13709 }
13710
13711 static int
13712 tracepoint_breakpoint_hit (const struct bp_location *bl,
13713                            struct address_space *aspace, CORE_ADDR bp_addr,
13714                            const struct target_waitstatus *ws)
13715 {
13716   /* By definition, the inferior does not report stops at
13717      tracepoints.  */
13718   return 0;
13719 }
13720
13721 static void
13722 tracepoint_print_one_detail (const struct breakpoint *self,
13723                              struct ui_out *uiout)
13724 {
13725   struct tracepoint *tp = (struct tracepoint *) self;
13726   if (tp->static_trace_marker_id)
13727     {
13728       gdb_assert (self->type == bp_static_tracepoint);
13729
13730       ui_out_text (uiout, "\tmarker id is ");
13731       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13732                            tp->static_trace_marker_id);
13733       ui_out_text (uiout, "\n");
13734     }
13735 }
13736
13737 static void
13738 tracepoint_print_mention (struct breakpoint *b)
13739 {
13740   if (ui_out_is_mi_like_p (current_uiout))
13741     return;
13742
13743   switch (b->type)
13744     {
13745     case bp_tracepoint:
13746       printf_filtered (_("Tracepoint"));
13747       printf_filtered (_(" %d"), b->number);
13748       break;
13749     case bp_fast_tracepoint:
13750       printf_filtered (_("Fast tracepoint"));
13751       printf_filtered (_(" %d"), b->number);
13752       break;
13753     case bp_static_tracepoint:
13754       printf_filtered (_("Static tracepoint"));
13755       printf_filtered (_(" %d"), b->number);
13756       break;
13757     default:
13758       internal_error (__FILE__, __LINE__,
13759                       _("unhandled tracepoint type %d"), (int) b->type);
13760     }
13761
13762   say_where (b);
13763 }
13764
13765 static void
13766 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13767 {
13768   struct tracepoint *tp = (struct tracepoint *) self;
13769
13770   if (self->type == bp_fast_tracepoint)
13771     fprintf_unfiltered (fp, "ftrace");
13772   if (self->type == bp_static_tracepoint)
13773     fprintf_unfiltered (fp, "strace");
13774   else if (self->type == bp_tracepoint)
13775     fprintf_unfiltered (fp, "trace");
13776   else
13777     internal_error (__FILE__, __LINE__,
13778                     _("unhandled tracepoint type %d"), (int) self->type);
13779
13780   fprintf_unfiltered (fp, " %s", self->addr_string);
13781   print_recreate_thread (self, fp);
13782
13783   if (tp->pass_count)
13784     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13785 }
13786
13787 static void
13788 tracepoint_create_sals_from_address (char **arg,
13789                                      struct linespec_result *canonical,
13790                                      enum bptype type_wanted,
13791                                      char *addr_start, char **copy_arg)
13792 {
13793   create_sals_from_address_default (arg, canonical, type_wanted,
13794                                     addr_start, copy_arg);
13795 }
13796
13797 static void
13798 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13799                                    struct linespec_result *canonical,
13800                                    char *cond_string,
13801                                    char *extra_string,
13802                                    enum bptype type_wanted,
13803                                    enum bpdisp disposition,
13804                                    int thread,
13805                                    int task, int ignore_count,
13806                                    const struct breakpoint_ops *ops,
13807                                    int from_tty, int enabled,
13808                                    int internal, unsigned flags)
13809 {
13810   create_breakpoints_sal_default (gdbarch, canonical,
13811                                   cond_string, extra_string,
13812                                   type_wanted,
13813                                   disposition, thread, task,
13814                                   ignore_count, ops, from_tty,
13815                                   enabled, internal, flags);
13816 }
13817
13818 static void
13819 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13820                             struct symtabs_and_lines *sals)
13821 {
13822   decode_linespec_default (b, s, sals);
13823 }
13824
13825 struct breakpoint_ops tracepoint_breakpoint_ops;
13826
13827 /* The breakpoint_ops structure to be use on tracepoints placed in a
13828    static probe.  */
13829
13830 static void
13831 tracepoint_probe_create_sals_from_address (char **arg,
13832                                            struct linespec_result *canonical,
13833                                            enum bptype type_wanted,
13834                                            char *addr_start, char **copy_arg)
13835 {
13836   /* We use the same method for breakpoint on probes.  */
13837   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13838                                        addr_start, copy_arg);
13839 }
13840
13841 static void
13842 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13843                                   struct symtabs_and_lines *sals)
13844 {
13845   /* We use the same method for breakpoint on probes.  */
13846   bkpt_probe_decode_linespec (b, s, sals);
13847 }
13848
13849 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13850
13851 /* Dprintf breakpoint_ops methods.  */
13852
13853 static void
13854 dprintf_re_set (struct breakpoint *b)
13855 {
13856   breakpoint_re_set_default (b);
13857
13858   /* This breakpoint could have been pending, and be resolved now, and
13859      if so, we should now have the extra string.  If we don't, the
13860      dprintf was malformed when created, but we couldn't tell because
13861      we can't extract the extra string until the location is
13862      resolved.  */
13863   if (b->loc != NULL && b->extra_string == NULL)
13864     error (_("Format string required"));
13865
13866   /* 1 - connect to target 1, that can run breakpoint commands.
13867      2 - create a dprintf, which resolves fine.
13868      3 - disconnect from target 1
13869      4 - connect to target 2, that can NOT run breakpoint commands.
13870
13871      After steps #3/#4, you'll want the dprintf command list to
13872      be updated, because target 1 and 2 may well return different
13873      answers for target_can_run_breakpoint_commands().
13874      Given absence of finer grained resetting, we get to do
13875      it all the time.  */
13876   if (b->extra_string != NULL)
13877     update_dprintf_command_list (b);
13878 }
13879
13880 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13881
13882 static void
13883 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13884 {
13885   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13886                       tp->extra_string);
13887   print_recreate_thread (tp, fp);
13888 }
13889
13890 /* Implement the "after_condition_true" breakpoint_ops method for
13891    dprintf.
13892
13893    dprintf's are implemented with regular commands in their command
13894    list, but we run the commands here instead of before presenting the
13895    stop to the user, as dprintf's don't actually cause a stop.  This
13896    also makes it so that the commands of multiple dprintfs at the same
13897    address are all handled.  */
13898
13899 static void
13900 dprintf_after_condition_true (struct bpstats *bs)
13901 {
13902   struct cleanup *old_chain;
13903   struct bpstats tmp_bs = { NULL };
13904   struct bpstats *tmp_bs_p = &tmp_bs;
13905
13906   /* dprintf's never cause a stop.  This wasn't set in the
13907      check_status hook instead because that would make the dprintf's
13908      condition not be evaluated.  */
13909   bs->stop = 0;
13910
13911   /* Run the command list here.  Take ownership of it instead of
13912      copying.  We never want these commands to run later in
13913      bpstat_do_actions, if a breakpoint that causes a stop happens to
13914      be set at same address as this dprintf, or even if running the
13915      commands here throws.  */
13916   tmp_bs.commands = bs->commands;
13917   bs->commands = NULL;
13918   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13919
13920   bpstat_do_actions_1 (&tmp_bs_p);
13921
13922   /* 'tmp_bs.commands' will usually be NULL by now, but
13923      bpstat_do_actions_1 may return early without processing the whole
13924      list.  */
13925   do_cleanups (old_chain);
13926 }
13927
13928 /* The breakpoint_ops structure to be used on static tracepoints with
13929    markers (`-m').  */
13930
13931 static void
13932 strace_marker_create_sals_from_address (char **arg,
13933                                         struct linespec_result *canonical,
13934                                         enum bptype type_wanted,
13935                                         char *addr_start, char **copy_arg)
13936 {
13937   struct linespec_sals lsal;
13938
13939   lsal.sals = decode_static_tracepoint_spec (arg);
13940
13941   *copy_arg = savestring (addr_start, *arg - addr_start);
13942
13943   canonical->addr_string = xstrdup (*copy_arg);
13944   lsal.canonical = xstrdup (*copy_arg);
13945   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13946 }
13947
13948 static void
13949 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13950                                       struct linespec_result *canonical,
13951                                       char *cond_string,
13952                                       char *extra_string,
13953                                       enum bptype type_wanted,
13954                                       enum bpdisp disposition,
13955                                       int thread,
13956                                       int task, int ignore_count,
13957                                       const struct breakpoint_ops *ops,
13958                                       int from_tty, int enabled,
13959                                       int internal, unsigned flags)
13960 {
13961   int i;
13962   struct linespec_sals *lsal = VEC_index (linespec_sals,
13963                                           canonical->sals, 0);
13964
13965   /* If the user is creating a static tracepoint by marker id
13966      (strace -m MARKER_ID), then store the sals index, so that
13967      breakpoint_re_set can try to match up which of the newly
13968      found markers corresponds to this one, and, don't try to
13969      expand multiple locations for each sal, given than SALS
13970      already should contain all sals for MARKER_ID.  */
13971
13972   for (i = 0; i < lsal->sals.nelts; ++i)
13973     {
13974       struct symtabs_and_lines expanded;
13975       struct tracepoint *tp;
13976       struct cleanup *old_chain;
13977       char *addr_string;
13978
13979       expanded.nelts = 1;
13980       expanded.sals = &lsal->sals.sals[i];
13981
13982       addr_string = xstrdup (canonical->addr_string);
13983       old_chain = make_cleanup (xfree, addr_string);
13984
13985       tp = XCNEW (struct tracepoint);
13986       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13987                            addr_string, NULL,
13988                            cond_string, extra_string,
13989                            type_wanted, disposition,
13990                            thread, task, ignore_count, ops,
13991                            from_tty, enabled, internal, flags,
13992                            canonical->special_display);
13993       /* Given that its possible to have multiple markers with
13994          the same string id, if the user is creating a static
13995          tracepoint by marker id ("strace -m MARKER_ID"), then
13996          store the sals index, so that breakpoint_re_set can
13997          try to match up which of the newly found markers
13998          corresponds to this one  */
13999       tp->static_trace_marker_id_idx = i;
14000
14001       install_breakpoint (internal, &tp->base, 0);
14002
14003       discard_cleanups (old_chain);
14004     }
14005 }
14006
14007 static void
14008 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14009                                struct symtabs_and_lines *sals)
14010 {
14011   struct tracepoint *tp = (struct tracepoint *) b;
14012
14013   *sals = decode_static_tracepoint_spec (s);
14014   if (sals->nelts > tp->static_trace_marker_id_idx)
14015     {
14016       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14017       sals->nelts = 1;
14018     }
14019   else
14020     error (_("marker %s not found"), tp->static_trace_marker_id);
14021 }
14022
14023 static struct breakpoint_ops strace_marker_breakpoint_ops;
14024
14025 static int
14026 strace_marker_p (struct breakpoint *b)
14027 {
14028   return b->ops == &strace_marker_breakpoint_ops;
14029 }
14030
14031 /* Delete a breakpoint and clean up all traces of it in the data
14032    structures.  */
14033
14034 void
14035 delete_breakpoint (struct breakpoint *bpt)
14036 {
14037   struct breakpoint *b;
14038
14039   gdb_assert (bpt != NULL);
14040
14041   /* Has this bp already been deleted?  This can happen because
14042      multiple lists can hold pointers to bp's.  bpstat lists are
14043      especial culprits.
14044
14045      One example of this happening is a watchpoint's scope bp.  When
14046      the scope bp triggers, we notice that the watchpoint is out of
14047      scope, and delete it.  We also delete its scope bp.  But the
14048      scope bp is marked "auto-deleting", and is already on a bpstat.
14049      That bpstat is then checked for auto-deleting bp's, which are
14050      deleted.
14051
14052      A real solution to this problem might involve reference counts in
14053      bp's, and/or giving them pointers back to their referencing
14054      bpstat's, and teaching delete_breakpoint to only free a bp's
14055      storage when no more references were extent.  A cheaper bandaid
14056      was chosen.  */
14057   if (bpt->type == bp_none)
14058     return;
14059
14060   /* At least avoid this stale reference until the reference counting
14061      of breakpoints gets resolved.  */
14062   if (bpt->related_breakpoint != bpt)
14063     {
14064       struct breakpoint *related;
14065       struct watchpoint *w;
14066
14067       if (bpt->type == bp_watchpoint_scope)
14068         w = (struct watchpoint *) bpt->related_breakpoint;
14069       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14070         w = (struct watchpoint *) bpt;
14071       else
14072         w = NULL;
14073       if (w != NULL)
14074         watchpoint_del_at_next_stop (w);
14075
14076       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14077       for (related = bpt; related->related_breakpoint != bpt;
14078            related = related->related_breakpoint);
14079       related->related_breakpoint = bpt->related_breakpoint;
14080       bpt->related_breakpoint = bpt;
14081     }
14082
14083   /* watch_command_1 creates a watchpoint but only sets its number if
14084      update_watchpoint succeeds in creating its bp_locations.  If there's
14085      a problem in that process, we'll be asked to delete the half-created
14086      watchpoint.  In that case, don't announce the deletion.  */
14087   if (bpt->number)
14088     observer_notify_breakpoint_deleted (bpt);
14089
14090   if (breakpoint_chain == bpt)
14091     breakpoint_chain = bpt->next;
14092
14093   ALL_BREAKPOINTS (b)
14094     if (b->next == bpt)
14095     {
14096       b->next = bpt->next;
14097       break;
14098     }
14099
14100   /* Be sure no bpstat's are pointing at the breakpoint after it's
14101      been freed.  */
14102   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14103      in all threads for now.  Note that we cannot just remove bpstats
14104      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14105      commands are associated with the bpstat; if we remove it here,
14106      then the later call to bpstat_do_actions (&stop_bpstat); in
14107      event-top.c won't do anything, and temporary breakpoints with
14108      commands won't work.  */
14109
14110   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14111
14112   /* Now that breakpoint is removed from breakpoint list, update the
14113      global location list.  This will remove locations that used to
14114      belong to this breakpoint.  Do this before freeing the breakpoint
14115      itself, since remove_breakpoint looks at location's owner.  It
14116      might be better design to have location completely
14117      self-contained, but it's not the case now.  */
14118   update_global_location_list (UGLL_DONT_INSERT);
14119
14120   bpt->ops->dtor (bpt);
14121   /* On the chance that someone will soon try again to delete this
14122      same bp, we mark it as deleted before freeing its storage.  */
14123   bpt->type = bp_none;
14124   xfree (bpt);
14125 }
14126
14127 static void
14128 do_delete_breakpoint_cleanup (void *b)
14129 {
14130   delete_breakpoint (b);
14131 }
14132
14133 struct cleanup *
14134 make_cleanup_delete_breakpoint (struct breakpoint *b)
14135 {
14136   return make_cleanup (do_delete_breakpoint_cleanup, b);
14137 }
14138
14139 /* Iterator function to call a user-provided callback function once
14140    for each of B and its related breakpoints.  */
14141
14142 static void
14143 iterate_over_related_breakpoints (struct breakpoint *b,
14144                                   void (*function) (struct breakpoint *,
14145                                                     void *),
14146                                   void *data)
14147 {
14148   struct breakpoint *related;
14149
14150   related = b;
14151   do
14152     {
14153       struct breakpoint *next;
14154
14155       /* FUNCTION may delete RELATED.  */
14156       next = related->related_breakpoint;
14157
14158       if (next == related)
14159         {
14160           /* RELATED is the last ring entry.  */
14161           function (related, data);
14162
14163           /* FUNCTION may have deleted it, so we'd never reach back to
14164              B.  There's nothing left to do anyway, so just break
14165              out.  */
14166           break;
14167         }
14168       else
14169         function (related, data);
14170
14171       related = next;
14172     }
14173   while (related != b);
14174 }
14175
14176 static void
14177 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14178 {
14179   delete_breakpoint (b);
14180 }
14181
14182 /* A callback for map_breakpoint_numbers that calls
14183    delete_breakpoint.  */
14184
14185 static void
14186 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14187 {
14188   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14189 }
14190
14191 void
14192 delete_command (char *arg, int from_tty)
14193 {
14194   struct breakpoint *b, *b_tmp;
14195
14196   dont_repeat ();
14197
14198   if (arg == 0)
14199     {
14200       int breaks_to_delete = 0;
14201
14202       /* Delete all breakpoints if no argument.  Do not delete
14203          internal breakpoints, these have to be deleted with an
14204          explicit breakpoint number argument.  */
14205       ALL_BREAKPOINTS (b)
14206         if (user_breakpoint_p (b))
14207           {
14208             breaks_to_delete = 1;
14209             break;
14210           }
14211
14212       /* Ask user only if there are some breakpoints to delete.  */
14213       if (!from_tty
14214           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14215         {
14216           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14217             if (user_breakpoint_p (b))
14218               delete_breakpoint (b);
14219         }
14220     }
14221   else
14222     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14223 }
14224
14225 static int
14226 all_locations_are_pending (struct bp_location *loc)
14227 {
14228   for (; loc; loc = loc->next)
14229     if (!loc->shlib_disabled
14230         && !loc->pspace->executing_startup)
14231       return 0;
14232   return 1;
14233 }
14234
14235 /* Subroutine of update_breakpoint_locations to simplify it.
14236    Return non-zero if multiple fns in list LOC have the same name.
14237    Null names are ignored.  */
14238
14239 static int
14240 ambiguous_names_p (struct bp_location *loc)
14241 {
14242   struct bp_location *l;
14243   htab_t htab = htab_create_alloc (13, htab_hash_string,
14244                                    (int (*) (const void *, 
14245                                              const void *)) streq,
14246                                    NULL, xcalloc, xfree);
14247
14248   for (l = loc; l != NULL; l = l->next)
14249     {
14250       const char **slot;
14251       const char *name = l->function_name;
14252
14253       /* Allow for some names to be NULL, ignore them.  */
14254       if (name == NULL)
14255         continue;
14256
14257       slot = (const char **) htab_find_slot (htab, (const void *) name,
14258                                              INSERT);
14259       /* NOTE: We can assume slot != NULL here because xcalloc never
14260          returns NULL.  */
14261       if (*slot != NULL)
14262         {
14263           htab_delete (htab);
14264           return 1;
14265         }
14266       *slot = name;
14267     }
14268
14269   htab_delete (htab);
14270   return 0;
14271 }
14272
14273 /* When symbols change, it probably means the sources changed as well,
14274    and it might mean the static tracepoint markers are no longer at
14275    the same address or line numbers they used to be at last we
14276    checked.  Losing your static tracepoints whenever you rebuild is
14277    undesirable.  This function tries to resync/rematch gdb static
14278    tracepoints with the markers on the target, for static tracepoints
14279    that have not been set by marker id.  Static tracepoint that have
14280    been set by marker id are reset by marker id in breakpoint_re_set.
14281    The heuristic is:
14282
14283    1) For a tracepoint set at a specific address, look for a marker at
14284    the old PC.  If one is found there, assume to be the same marker.
14285    If the name / string id of the marker found is different from the
14286    previous known name, assume that means the user renamed the marker
14287    in the sources, and output a warning.
14288
14289    2) For a tracepoint set at a given line number, look for a marker
14290    at the new address of the old line number.  If one is found there,
14291    assume to be the same marker.  If the name / string id of the
14292    marker found is different from the previous known name, assume that
14293    means the user renamed the marker in the sources, and output a
14294    warning.
14295
14296    3) If a marker is no longer found at the same address or line, it
14297    may mean the marker no longer exists.  But it may also just mean
14298    the code changed a bit.  Maybe the user added a few lines of code
14299    that made the marker move up or down (in line number terms).  Ask
14300    the target for info about the marker with the string id as we knew
14301    it.  If found, update line number and address in the matching
14302    static tracepoint.  This will get confused if there's more than one
14303    marker with the same ID (possible in UST, although unadvised
14304    precisely because it confuses tools).  */
14305
14306 static struct symtab_and_line
14307 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14308 {
14309   struct tracepoint *tp = (struct tracepoint *) b;
14310   struct static_tracepoint_marker marker;
14311   CORE_ADDR pc;
14312
14313   pc = sal.pc;
14314   if (sal.line)
14315     find_line_pc (sal.symtab, sal.line, &pc);
14316
14317   if (target_static_tracepoint_marker_at (pc, &marker))
14318     {
14319       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14320         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14321                  b->number,
14322                  tp->static_trace_marker_id, marker.str_id);
14323
14324       xfree (tp->static_trace_marker_id);
14325       tp->static_trace_marker_id = xstrdup (marker.str_id);
14326       release_static_tracepoint_marker (&marker);
14327
14328       return sal;
14329     }
14330
14331   /* Old marker wasn't found on target at lineno.  Try looking it up
14332      by string ID.  */
14333   if (!sal.explicit_pc
14334       && sal.line != 0
14335       && sal.symtab != NULL
14336       && tp->static_trace_marker_id != NULL)
14337     {
14338       VEC(static_tracepoint_marker_p) *markers;
14339
14340       markers
14341         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14342
14343       if (!VEC_empty(static_tracepoint_marker_p, markers))
14344         {
14345           struct symtab_and_line sal2;
14346           struct symbol *sym;
14347           struct static_tracepoint_marker *tpmarker;
14348           struct ui_out *uiout = current_uiout;
14349
14350           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14351
14352           xfree (tp->static_trace_marker_id);
14353           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14354
14355           warning (_("marker for static tracepoint %d (%s) not "
14356                      "found at previous line number"),
14357                    b->number, tp->static_trace_marker_id);
14358
14359           init_sal (&sal2);
14360
14361           sal2.pc = tpmarker->address;
14362
14363           sal2 = find_pc_line (tpmarker->address, 0);
14364           sym = find_pc_sect_function (tpmarker->address, NULL);
14365           ui_out_text (uiout, "Now in ");
14366           if (sym)
14367             {
14368               ui_out_field_string (uiout, "func",
14369                                    SYMBOL_PRINT_NAME (sym));
14370               ui_out_text (uiout, " at ");
14371             }
14372           ui_out_field_string (uiout, "file",
14373                                symtab_to_filename_for_display (sal2.symtab));
14374           ui_out_text (uiout, ":");
14375
14376           if (ui_out_is_mi_like_p (uiout))
14377             {
14378               const char *fullname = symtab_to_fullname (sal2.symtab);
14379
14380               ui_out_field_string (uiout, "fullname", fullname);
14381             }
14382
14383           ui_out_field_int (uiout, "line", sal2.line);
14384           ui_out_text (uiout, "\n");
14385
14386           b->loc->line_number = sal2.line;
14387           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14388
14389           xfree (b->addr_string);
14390           b->addr_string = xstrprintf ("%s:%d",
14391                                    symtab_to_filename_for_display (sal2.symtab),
14392                                        b->loc->line_number);
14393
14394           /* Might be nice to check if function changed, and warn if
14395              so.  */
14396
14397           release_static_tracepoint_marker (tpmarker);
14398         }
14399     }
14400   return sal;
14401 }
14402
14403 /* Returns 1 iff locations A and B are sufficiently same that
14404    we don't need to report breakpoint as changed.  */
14405
14406 static int
14407 locations_are_equal (struct bp_location *a, struct bp_location *b)
14408 {
14409   while (a && b)
14410     {
14411       if (a->address != b->address)
14412         return 0;
14413
14414       if (a->shlib_disabled != b->shlib_disabled)
14415         return 0;
14416
14417       if (a->enabled != b->enabled)
14418         return 0;
14419
14420       a = a->next;
14421       b = b->next;
14422     }
14423
14424   if ((a == NULL) != (b == NULL))
14425     return 0;
14426
14427   return 1;
14428 }
14429
14430 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14431    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14432    a ranged breakpoint.  */
14433
14434 void
14435 update_breakpoint_locations (struct breakpoint *b,
14436                              struct symtabs_and_lines sals,
14437                              struct symtabs_and_lines sals_end)
14438 {
14439   int i;
14440   struct bp_location *existing_locations = b->loc;
14441
14442   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14443     {
14444       /* Ranged breakpoints have only one start location and one end
14445          location.  */
14446       b->enable_state = bp_disabled;
14447       update_global_location_list (UGLL_MAY_INSERT);
14448       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14449                            "multiple locations found\n"),
14450                          b->number);
14451       return;
14452     }
14453
14454   /* If there's no new locations, and all existing locations are
14455      pending, don't do anything.  This optimizes the common case where
14456      all locations are in the same shared library, that was unloaded.
14457      We'd like to retain the location, so that when the library is
14458      loaded again, we don't loose the enabled/disabled status of the
14459      individual locations.  */
14460   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14461     return;
14462
14463   b->loc = NULL;
14464
14465   for (i = 0; i < sals.nelts; ++i)
14466     {
14467       struct bp_location *new_loc;
14468
14469       switch_to_program_space_and_thread (sals.sals[i].pspace);
14470
14471       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14472
14473       /* Reparse conditions, they might contain references to the
14474          old symtab.  */
14475       if (b->cond_string != NULL)
14476         {
14477           const char *s;
14478           volatile struct gdb_exception e;
14479
14480           s = b->cond_string;
14481           TRY_CATCH (e, RETURN_MASK_ERROR)
14482             {
14483               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14484                                            block_for_pc (sals.sals[i].pc), 
14485                                            0);
14486             }
14487           if (e.reason < 0)
14488             {
14489               warning (_("failed to reevaluate condition "
14490                          "for breakpoint %d: %s"), 
14491                        b->number, e.message);
14492               new_loc->enabled = 0;
14493             }
14494         }
14495
14496       if (sals_end.nelts)
14497         {
14498           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14499
14500           new_loc->length = end - sals.sals[0].pc + 1;
14501         }
14502     }
14503
14504   /* Update locations of permanent breakpoints.  */
14505   if (b->enable_state == bp_permanent)
14506     make_breakpoint_permanent (b);
14507
14508   /* If possible, carry over 'disable' status from existing
14509      breakpoints.  */
14510   {
14511     struct bp_location *e = existing_locations;
14512     /* If there are multiple breakpoints with the same function name,
14513        e.g. for inline functions, comparing function names won't work.
14514        Instead compare pc addresses; this is just a heuristic as things
14515        may have moved, but in practice it gives the correct answer
14516        often enough until a better solution is found.  */
14517     int have_ambiguous_names = ambiguous_names_p (b->loc);
14518
14519     for (; e; e = e->next)
14520       {
14521         if (!e->enabled && e->function_name)
14522           {
14523             struct bp_location *l = b->loc;
14524             if (have_ambiguous_names)
14525               {
14526                 for (; l; l = l->next)
14527                   if (breakpoint_locations_match (e, l))
14528                     {
14529                       l->enabled = 0;
14530                       break;
14531                     }
14532               }
14533             else
14534               {
14535                 for (; l; l = l->next)
14536                   if (l->function_name
14537                       && strcmp (e->function_name, l->function_name) == 0)
14538                     {
14539                       l->enabled = 0;
14540                       break;
14541                     }
14542               }
14543           }
14544       }
14545   }
14546
14547   if (!locations_are_equal (existing_locations, b->loc))
14548     observer_notify_breakpoint_modified (b);
14549
14550   update_global_location_list (UGLL_MAY_INSERT);
14551 }
14552
14553 /* Find the SaL locations corresponding to the given ADDR_STRING.
14554    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14555
14556 static struct symtabs_and_lines
14557 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14558 {
14559   char *s;
14560   struct symtabs_and_lines sals = {0};
14561   volatile struct gdb_exception e;
14562
14563   gdb_assert (b->ops != NULL);
14564   s = addr_string;
14565
14566   TRY_CATCH (e, RETURN_MASK_ERROR)
14567     {
14568       b->ops->decode_linespec (b, &s, &sals);
14569     }
14570   if (e.reason < 0)
14571     {
14572       int not_found_and_ok = 0;
14573       /* For pending breakpoints, it's expected that parsing will
14574          fail until the right shared library is loaded.  User has
14575          already told to create pending breakpoints and don't need
14576          extra messages.  If breakpoint is in bp_shlib_disabled
14577          state, then user already saw the message about that
14578          breakpoint being disabled, and don't want to see more
14579          errors.  */
14580       if (e.error == NOT_FOUND_ERROR
14581           && (b->condition_not_parsed 
14582               || (b->loc && b->loc->shlib_disabled)
14583               || (b->loc && b->loc->pspace->executing_startup)
14584               || b->enable_state == bp_disabled))
14585         not_found_and_ok = 1;
14586
14587       if (!not_found_and_ok)
14588         {
14589           /* We surely don't want to warn about the same breakpoint
14590              10 times.  One solution, implemented here, is disable
14591              the breakpoint on error.  Another solution would be to
14592              have separate 'warning emitted' flag.  Since this
14593              happens only when a binary has changed, I don't know
14594              which approach is better.  */
14595           b->enable_state = bp_disabled;
14596           throw_exception (e);
14597         }
14598     }
14599
14600   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14601     {
14602       int i;
14603
14604       for (i = 0; i < sals.nelts; ++i)
14605         resolve_sal_pc (&sals.sals[i]);
14606       if (b->condition_not_parsed && s && s[0])
14607         {
14608           char *cond_string, *extra_string;
14609           int thread, task;
14610
14611           find_condition_and_thread (s, sals.sals[0].pc,
14612                                      &cond_string, &thread, &task,
14613                                      &extra_string);
14614           if (cond_string)
14615             b->cond_string = cond_string;
14616           b->thread = thread;
14617           b->task = task;
14618           if (extra_string)
14619             b->extra_string = extra_string;
14620           b->condition_not_parsed = 0;
14621         }
14622
14623       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14624         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14625
14626       *found = 1;
14627     }
14628   else
14629     *found = 0;
14630
14631   return sals;
14632 }
14633
14634 /* The default re_set method, for typical hardware or software
14635    breakpoints.  Reevaluate the breakpoint and recreate its
14636    locations.  */
14637
14638 static void
14639 breakpoint_re_set_default (struct breakpoint *b)
14640 {
14641   int found;
14642   struct symtabs_and_lines sals, sals_end;
14643   struct symtabs_and_lines expanded = {0};
14644   struct symtabs_and_lines expanded_end = {0};
14645
14646   sals = addr_string_to_sals (b, b->addr_string, &found);
14647   if (found)
14648     {
14649       make_cleanup (xfree, sals.sals);
14650       expanded = sals;
14651     }
14652
14653   if (b->addr_string_range_end)
14654     {
14655       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14656       if (found)
14657         {
14658           make_cleanup (xfree, sals_end.sals);
14659           expanded_end = sals_end;
14660         }
14661     }
14662
14663   update_breakpoint_locations (b, expanded, expanded_end);
14664 }
14665
14666 /* Default method for creating SALs from an address string.  It basically
14667    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14668
14669 static void
14670 create_sals_from_address_default (char **arg,
14671                                   struct linespec_result *canonical,
14672                                   enum bptype type_wanted,
14673                                   char *addr_start, char **copy_arg)
14674 {
14675   parse_breakpoint_sals (arg, canonical);
14676 }
14677
14678 /* Call create_breakpoints_sal for the given arguments.  This is the default
14679    function for the `create_breakpoints_sal' method of
14680    breakpoint_ops.  */
14681
14682 static void
14683 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14684                                 struct linespec_result *canonical,
14685                                 char *cond_string,
14686                                 char *extra_string,
14687                                 enum bptype type_wanted,
14688                                 enum bpdisp disposition,
14689                                 int thread,
14690                                 int task, int ignore_count,
14691                                 const struct breakpoint_ops *ops,
14692                                 int from_tty, int enabled,
14693                                 int internal, unsigned flags)
14694 {
14695   create_breakpoints_sal (gdbarch, canonical, cond_string,
14696                           extra_string,
14697                           type_wanted, disposition,
14698                           thread, task, ignore_count, ops, from_tty,
14699                           enabled, internal, flags);
14700 }
14701
14702 /* Decode the line represented by S by calling decode_line_full.  This is the
14703    default function for the `decode_linespec' method of breakpoint_ops.  */
14704
14705 static void
14706 decode_linespec_default (struct breakpoint *b, char **s,
14707                          struct symtabs_and_lines *sals)
14708 {
14709   struct linespec_result canonical;
14710
14711   init_linespec_result (&canonical);
14712   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14713                     (struct symtab *) NULL, 0,
14714                     &canonical, multiple_symbols_all,
14715                     b->filter);
14716
14717   /* We should get 0 or 1 resulting SALs.  */
14718   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14719
14720   if (VEC_length (linespec_sals, canonical.sals) > 0)
14721     {
14722       struct linespec_sals *lsal;
14723
14724       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14725       *sals = lsal->sals;
14726       /* Arrange it so the destructor does not free the
14727          contents.  */
14728       lsal->sals.sals = NULL;
14729     }
14730
14731   destroy_linespec_result (&canonical);
14732 }
14733
14734 /* Prepare the global context for a re-set of breakpoint B.  */
14735
14736 static struct cleanup *
14737 prepare_re_set_context (struct breakpoint *b)
14738 {
14739   struct cleanup *cleanups;
14740
14741   input_radix = b->input_radix;
14742   cleanups = save_current_space_and_thread ();
14743   if (b->pspace != NULL)
14744     switch_to_program_space_and_thread (b->pspace);
14745   set_language (b->language);
14746
14747   return cleanups;
14748 }
14749
14750 /* Reset a breakpoint given it's struct breakpoint * BINT.
14751    The value we return ends up being the return value from catch_errors.
14752    Unused in this case.  */
14753
14754 static int
14755 breakpoint_re_set_one (void *bint)
14756 {
14757   /* Get past catch_errs.  */
14758   struct breakpoint *b = (struct breakpoint *) bint;
14759   struct cleanup *cleanups;
14760
14761   cleanups = prepare_re_set_context (b);
14762   b->ops->re_set (b);
14763   do_cleanups (cleanups);
14764   return 0;
14765 }
14766
14767 /* Re-set all breakpoints after symbols have been re-loaded.  */
14768 void
14769 breakpoint_re_set (void)
14770 {
14771   struct breakpoint *b, *b_tmp;
14772   enum language save_language;
14773   int save_input_radix;
14774   struct cleanup *old_chain;
14775
14776   save_language = current_language->la_language;
14777   save_input_radix = input_radix;
14778   old_chain = save_current_program_space ();
14779
14780   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14781   {
14782     /* Format possible error msg.  */
14783     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14784                                 b->number);
14785     struct cleanup *cleanups = make_cleanup (xfree, message);
14786     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14787     do_cleanups (cleanups);
14788   }
14789   set_language (save_language);
14790   input_radix = save_input_radix;
14791
14792   jit_breakpoint_re_set ();
14793
14794   do_cleanups (old_chain);
14795
14796   create_overlay_event_breakpoint ();
14797   create_longjmp_master_breakpoint ();
14798   create_std_terminate_master_breakpoint ();
14799   create_exception_master_breakpoint ();
14800 }
14801 \f
14802 /* Reset the thread number of this breakpoint:
14803
14804    - If the breakpoint is for all threads, leave it as-is.
14805    - Else, reset it to the current thread for inferior_ptid.  */
14806 void
14807 breakpoint_re_set_thread (struct breakpoint *b)
14808 {
14809   if (b->thread != -1)
14810     {
14811       if (in_thread_list (inferior_ptid))
14812         b->thread = pid_to_thread_id (inferior_ptid);
14813
14814       /* We're being called after following a fork.  The new fork is
14815          selected as current, and unless this was a vfork will have a
14816          different program space from the original thread.  Reset that
14817          as well.  */
14818       b->loc->pspace = current_program_space;
14819     }
14820 }
14821
14822 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14823    If from_tty is nonzero, it prints a message to that effect,
14824    which ends with a period (no newline).  */
14825
14826 void
14827 set_ignore_count (int bptnum, int count, int from_tty)
14828 {
14829   struct breakpoint *b;
14830
14831   if (count < 0)
14832     count = 0;
14833
14834   ALL_BREAKPOINTS (b)
14835     if (b->number == bptnum)
14836     {
14837       if (is_tracepoint (b))
14838         {
14839           if (from_tty && count != 0)
14840             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14841                              bptnum);
14842           return;
14843         }
14844       
14845       b->ignore_count = count;
14846       if (from_tty)
14847         {
14848           if (count == 0)
14849             printf_filtered (_("Will stop next time "
14850                                "breakpoint %d is reached."),
14851                              bptnum);
14852           else if (count == 1)
14853             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14854                              bptnum);
14855           else
14856             printf_filtered (_("Will ignore next %d "
14857                                "crossings of breakpoint %d."),
14858                              count, bptnum);
14859         }
14860       observer_notify_breakpoint_modified (b);
14861       return;
14862     }
14863
14864   error (_("No breakpoint number %d."), bptnum);
14865 }
14866
14867 /* Command to set ignore-count of breakpoint N to COUNT.  */
14868
14869 static void
14870 ignore_command (char *args, int from_tty)
14871 {
14872   char *p = args;
14873   int num;
14874
14875   if (p == 0)
14876     error_no_arg (_("a breakpoint number"));
14877
14878   num = get_number (&p);
14879   if (num == 0)
14880     error (_("bad breakpoint number: '%s'"), args);
14881   if (*p == 0)
14882     error (_("Second argument (specified ignore-count) is missing."));
14883
14884   set_ignore_count (num,
14885                     longest_to_int (value_as_long (parse_and_eval (p))),
14886                     from_tty);
14887   if (from_tty)
14888     printf_filtered ("\n");
14889 }
14890 \f
14891 /* Call FUNCTION on each of the breakpoints
14892    whose numbers are given in ARGS.  */
14893
14894 static void
14895 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14896                                                       void *),
14897                         void *data)
14898 {
14899   int num;
14900   struct breakpoint *b, *tmp;
14901   int match;
14902   struct get_number_or_range_state state;
14903
14904   if (args == 0)
14905     error_no_arg (_("one or more breakpoint numbers"));
14906
14907   init_number_or_range (&state, args);
14908
14909   while (!state.finished)
14910     {
14911       const char *p = state.string;
14912
14913       match = 0;
14914
14915       num = get_number_or_range (&state);
14916       if (num == 0)
14917         {
14918           warning (_("bad breakpoint number at or near '%s'"), p);
14919         }
14920       else
14921         {
14922           ALL_BREAKPOINTS_SAFE (b, tmp)
14923             if (b->number == num)
14924               {
14925                 match = 1;
14926                 function (b, data);
14927                 break;
14928               }
14929           if (match == 0)
14930             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14931         }
14932     }
14933 }
14934
14935 static struct bp_location *
14936 find_location_by_number (char *number)
14937 {
14938   char *dot = strchr (number, '.');
14939   char *p1;
14940   int bp_num;
14941   int loc_num;
14942   struct breakpoint *b;
14943   struct bp_location *loc;  
14944
14945   *dot = '\0';
14946
14947   p1 = number;
14948   bp_num = get_number (&p1);
14949   if (bp_num == 0)
14950     error (_("Bad breakpoint number '%s'"), number);
14951
14952   ALL_BREAKPOINTS (b)
14953     if (b->number == bp_num)
14954       {
14955         break;
14956       }
14957
14958   if (!b || b->number != bp_num)
14959     error (_("Bad breakpoint number '%s'"), number);
14960   
14961   p1 = dot+1;
14962   loc_num = get_number (&p1);
14963   if (loc_num == 0)
14964     error (_("Bad breakpoint location number '%s'"), number);
14965
14966   --loc_num;
14967   loc = b->loc;
14968   for (;loc_num && loc; --loc_num, loc = loc->next)
14969     ;
14970   if (!loc)
14971     error (_("Bad breakpoint location number '%s'"), dot+1);
14972     
14973   return loc;  
14974 }
14975
14976
14977 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14978    If from_tty is nonzero, it prints a message to that effect,
14979    which ends with a period (no newline).  */
14980
14981 void
14982 disable_breakpoint (struct breakpoint *bpt)
14983 {
14984   /* Never disable a watchpoint scope breakpoint; we want to
14985      hit them when we leave scope so we can delete both the
14986      watchpoint and its scope breakpoint at that time.  */
14987   if (bpt->type == bp_watchpoint_scope)
14988     return;
14989
14990   /* You can't disable permanent breakpoints.  */
14991   if (bpt->enable_state == bp_permanent)
14992     return;
14993
14994   bpt->enable_state = bp_disabled;
14995
14996   /* Mark breakpoint locations modified.  */
14997   mark_breakpoint_modified (bpt);
14998
14999   if (target_supports_enable_disable_tracepoint ()
15000       && current_trace_status ()->running && is_tracepoint (bpt))
15001     {
15002       struct bp_location *location;
15003      
15004       for (location = bpt->loc; location; location = location->next)
15005         target_disable_tracepoint (location);
15006     }
15007
15008   update_global_location_list (UGLL_DONT_INSERT);
15009
15010   observer_notify_breakpoint_modified (bpt);
15011 }
15012
15013 /* A callback for iterate_over_related_breakpoints.  */
15014
15015 static void
15016 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15017 {
15018   disable_breakpoint (b);
15019 }
15020
15021 /* A callback for map_breakpoint_numbers that calls
15022    disable_breakpoint.  */
15023
15024 static void
15025 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15026 {
15027   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15028 }
15029
15030 static void
15031 disable_command (char *args, int from_tty)
15032 {
15033   if (args == 0)
15034     {
15035       struct breakpoint *bpt;
15036
15037       ALL_BREAKPOINTS (bpt)
15038         if (user_breakpoint_p (bpt))
15039           disable_breakpoint (bpt);
15040     }
15041   else
15042     {
15043       char *num = extract_arg (&args);
15044
15045       while (num)
15046         {
15047           if (strchr (num, '.'))
15048             {
15049               struct bp_location *loc = find_location_by_number (num);
15050
15051               if (loc)
15052                 {
15053                   if (loc->enabled)
15054                     {
15055                       loc->enabled = 0;
15056                       mark_breakpoint_location_modified (loc);
15057                     }
15058                   if (target_supports_enable_disable_tracepoint ()
15059                       && current_trace_status ()->running && loc->owner
15060                       && is_tracepoint (loc->owner))
15061                     target_disable_tracepoint (loc);
15062                 }
15063               update_global_location_list (UGLL_DONT_INSERT);
15064             }
15065           else
15066             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15067           num = extract_arg (&args);
15068         }
15069     }
15070 }
15071
15072 static void
15073 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15074                         int count)
15075 {
15076   int target_resources_ok;
15077
15078   if (bpt->type == bp_hardware_breakpoint)
15079     {
15080       int i;
15081       i = hw_breakpoint_used_count ();
15082       target_resources_ok = 
15083         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15084                                             i + 1, 0);
15085       if (target_resources_ok == 0)
15086         error (_("No hardware breakpoint support in the target."));
15087       else if (target_resources_ok < 0)
15088         error (_("Hardware breakpoints used exceeds limit."));
15089     }
15090
15091   if (is_watchpoint (bpt))
15092     {
15093       /* Initialize it just to avoid a GCC false warning.  */
15094       enum enable_state orig_enable_state = 0;
15095       volatile struct gdb_exception e;
15096
15097       TRY_CATCH (e, RETURN_MASK_ALL)
15098         {
15099           struct watchpoint *w = (struct watchpoint *) bpt;
15100
15101           orig_enable_state = bpt->enable_state;
15102           bpt->enable_state = bp_enabled;
15103           update_watchpoint (w, 1 /* reparse */);
15104         }
15105       if (e.reason < 0)
15106         {
15107           bpt->enable_state = orig_enable_state;
15108           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15109                              bpt->number);
15110           return;
15111         }
15112     }
15113
15114   if (bpt->enable_state != bp_permanent)
15115     bpt->enable_state = bp_enabled;
15116
15117   bpt->enable_state = bp_enabled;
15118
15119   /* Mark breakpoint locations modified.  */
15120   mark_breakpoint_modified (bpt);
15121
15122   if (target_supports_enable_disable_tracepoint ()
15123       && current_trace_status ()->running && is_tracepoint (bpt))
15124     {
15125       struct bp_location *location;
15126
15127       for (location = bpt->loc; location; location = location->next)
15128         target_enable_tracepoint (location);
15129     }
15130
15131   bpt->disposition = disposition;
15132   bpt->enable_count = count;
15133   update_global_location_list (UGLL_MAY_INSERT);
15134
15135   observer_notify_breakpoint_modified (bpt);
15136 }
15137
15138
15139 void
15140 enable_breakpoint (struct breakpoint *bpt)
15141 {
15142   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15143 }
15144
15145 static void
15146 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15147 {
15148   enable_breakpoint (bpt);
15149 }
15150
15151 /* A callback for map_breakpoint_numbers that calls
15152    enable_breakpoint.  */
15153
15154 static void
15155 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15156 {
15157   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15158 }
15159
15160 /* The enable command enables the specified breakpoints (or all defined
15161    breakpoints) so they once again become (or continue to be) effective
15162    in stopping the inferior.  */
15163
15164 static void
15165 enable_command (char *args, int from_tty)
15166 {
15167   if (args == 0)
15168     {
15169       struct breakpoint *bpt;
15170
15171       ALL_BREAKPOINTS (bpt)
15172         if (user_breakpoint_p (bpt))
15173           enable_breakpoint (bpt);
15174     }
15175   else
15176     {
15177       char *num = extract_arg (&args);
15178
15179       while (num)
15180         {
15181           if (strchr (num, '.'))
15182             {
15183               struct bp_location *loc = find_location_by_number (num);
15184
15185               if (loc)
15186                 {
15187                   if (!loc->enabled)
15188                     {
15189                       loc->enabled = 1;
15190                       mark_breakpoint_location_modified (loc);
15191                     }
15192                   if (target_supports_enable_disable_tracepoint ()
15193                       && current_trace_status ()->running && loc->owner
15194                       && is_tracepoint (loc->owner))
15195                     target_enable_tracepoint (loc);
15196                 }
15197               update_global_location_list (UGLL_MAY_INSERT);
15198             }
15199           else
15200             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15201           num = extract_arg (&args);
15202         }
15203     }
15204 }
15205
15206 /* This struct packages up disposition data for application to multiple
15207    breakpoints.  */
15208
15209 struct disp_data
15210 {
15211   enum bpdisp disp;
15212   int count;
15213 };
15214
15215 static void
15216 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15217 {
15218   struct disp_data disp_data = *(struct disp_data *) arg;
15219
15220   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15221 }
15222
15223 static void
15224 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15225 {
15226   struct disp_data disp = { disp_disable, 1 };
15227
15228   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15229 }
15230
15231 static void
15232 enable_once_command (char *args, int from_tty)
15233 {
15234   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15235 }
15236
15237 static void
15238 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15239 {
15240   struct disp_data disp = { disp_disable, *(int *) countptr };
15241
15242   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15243 }
15244
15245 static void
15246 enable_count_command (char *args, int from_tty)
15247 {
15248   int count = get_number (&args);
15249
15250   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15251 }
15252
15253 static void
15254 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15255 {
15256   struct disp_data disp = { disp_del, 1 };
15257
15258   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15259 }
15260
15261 static void
15262 enable_delete_command (char *args, int from_tty)
15263 {
15264   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15265 }
15266 \f
15267 static void
15268 set_breakpoint_cmd (char *args, int from_tty)
15269 {
15270 }
15271
15272 static void
15273 show_breakpoint_cmd (char *args, int from_tty)
15274 {
15275 }
15276
15277 /* Invalidate last known value of any hardware watchpoint if
15278    the memory which that value represents has been written to by
15279    GDB itself.  */
15280
15281 static void
15282 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15283                                       CORE_ADDR addr, ssize_t len,
15284                                       const bfd_byte *data)
15285 {
15286   struct breakpoint *bp;
15287
15288   ALL_BREAKPOINTS (bp)
15289     if (bp->enable_state == bp_enabled
15290         && bp->type == bp_hardware_watchpoint)
15291       {
15292         struct watchpoint *wp = (struct watchpoint *) bp;
15293
15294         if (wp->val_valid && wp->val)
15295           {
15296             struct bp_location *loc;
15297
15298             for (loc = bp->loc; loc != NULL; loc = loc->next)
15299               if (loc->loc_type == bp_loc_hardware_watchpoint
15300                   && loc->address + loc->length > addr
15301                   && addr + len > loc->address)
15302                 {
15303                   value_free (wp->val);
15304                   wp->val = NULL;
15305                   wp->val_valid = 0;
15306                 }
15307           }
15308       }
15309 }
15310
15311 /* Create and insert a raw software breakpoint at PC.  Return an
15312    identifier, which should be used to remove the breakpoint later.
15313    In general, places which call this should be using something on the
15314    breakpoint chain instead; this function should be eliminated
15315    someday.  */
15316
15317 void *
15318 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15319                                   struct address_space *aspace, CORE_ADDR pc)
15320 {
15321   struct bp_target_info *bp_tgt;
15322   struct bp_location *bl;
15323
15324   bp_tgt = XCNEW (struct bp_target_info);
15325
15326   bp_tgt->placed_address_space = aspace;
15327   bp_tgt->placed_address = pc;
15328
15329   /* If an unconditional non-raw breakpoint is already inserted at
15330      that location, there's no need to insert another.  However, with
15331      target-side evaluation of breakpoint conditions, if the
15332      breakpoint that is currently inserted on the target is
15333      conditional, we need to make it unconditional.  Note that a
15334      breakpoint with target-side commands is not reported even if
15335      unconditional, so we need to remove the commands from the target
15336      as well.  */
15337   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15338   if (bl != NULL
15339       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15340       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15341     {
15342       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15343       return bp_tgt;
15344     }
15345
15346   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15347     {
15348       /* Could not insert the breakpoint.  */
15349       xfree (bp_tgt);
15350       return NULL;
15351     }
15352
15353   return bp_tgt;
15354 }
15355
15356 /* Remove a breakpoint BP inserted by
15357    deprecated_insert_raw_breakpoint.  */
15358
15359 int
15360 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15361 {
15362   struct bp_target_info *bp_tgt = bp;
15363   struct address_space *aspace = bp_tgt->placed_address_space;
15364   CORE_ADDR address = bp_tgt->placed_address;
15365   struct bp_location *bl;
15366   int ret;
15367
15368   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15369
15370   /* Only remove the raw breakpoint if there are no other non-raw
15371      breakpoints still inserted at this location.  Otherwise, we would
15372      be effectively disabling those breakpoints.  */
15373   if (bl == NULL)
15374     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15375   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15376            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15377     {
15378       /* The target is evaluating conditions, and when we inserted the
15379          software single-step breakpoint, we had made the breakpoint
15380          unconditional and command-less on the target side.  Reinsert
15381          to restore the conditions/commands.  */
15382       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15383     }
15384   else
15385     ret = 0;
15386
15387   xfree (bp_tgt);
15388
15389   return ret;
15390 }
15391
15392 /* Create and insert a breakpoint for software single step.  */
15393
15394 void
15395 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15396                                struct address_space *aspace, 
15397                                CORE_ADDR next_pc)
15398 {
15399   void **bpt_p;
15400
15401   if (single_step_breakpoints[0] == NULL)
15402     {
15403       bpt_p = &single_step_breakpoints[0];
15404       single_step_gdbarch[0] = gdbarch;
15405     }
15406   else
15407     {
15408       gdb_assert (single_step_breakpoints[1] == NULL);
15409       bpt_p = &single_step_breakpoints[1];
15410       single_step_gdbarch[1] = gdbarch;
15411     }
15412
15413   /* NOTE drow/2006-04-11: A future improvement to this function would
15414      be to only create the breakpoints once, and actually put them on
15415      the breakpoint chain.  That would let us use set_raw_breakpoint.
15416      We could adjust the addresses each time they were needed.  Doing
15417      this requires corresponding changes elsewhere where single step
15418      breakpoints are handled, however.  So, for now, we use this.  */
15419
15420   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15421   if (*bpt_p == NULL)
15422     error (_("Could not insert single-step breakpoint at %s"),
15423              paddress (gdbarch, next_pc));
15424 }
15425
15426 /* Check if the breakpoints used for software single stepping
15427    were inserted or not.  */
15428
15429 int
15430 single_step_breakpoints_inserted (void)
15431 {
15432   return (single_step_breakpoints[0] != NULL
15433           || single_step_breakpoints[1] != NULL);
15434 }
15435
15436 /* Remove and delete any breakpoints used for software single step.  */
15437
15438 void
15439 remove_single_step_breakpoints (void)
15440 {
15441   gdb_assert (single_step_breakpoints[0] != NULL);
15442
15443   /* See insert_single_step_breakpoint for more about this deprecated
15444      call.  */
15445   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15446                                     single_step_breakpoints[0]);
15447   single_step_gdbarch[0] = NULL;
15448   single_step_breakpoints[0] = NULL;
15449
15450   if (single_step_breakpoints[1] != NULL)
15451     {
15452       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15453                                         single_step_breakpoints[1]);
15454       single_step_gdbarch[1] = NULL;
15455       single_step_breakpoints[1] = NULL;
15456     }
15457 }
15458
15459 /* Delete software single step breakpoints without removing them from
15460    the inferior.  This is intended to be used if the inferior's address
15461    space where they were inserted is already gone, e.g. after exit or
15462    exec.  */
15463
15464 void
15465 cancel_single_step_breakpoints (void)
15466 {
15467   int i;
15468
15469   for (i = 0; i < 2; i++)
15470     if (single_step_breakpoints[i])
15471       {
15472         xfree (single_step_breakpoints[i]);
15473         single_step_breakpoints[i] = NULL;
15474         single_step_gdbarch[i] = NULL;
15475       }
15476 }
15477
15478 /* Detach software single-step breakpoints from INFERIOR_PTID without
15479    removing them.  */
15480
15481 static void
15482 detach_single_step_breakpoints (void)
15483 {
15484   int i;
15485
15486   for (i = 0; i < 2; i++)
15487     if (single_step_breakpoints[i])
15488       target_remove_breakpoint (single_step_gdbarch[i],
15489                                 single_step_breakpoints[i]);
15490 }
15491
15492 /* Find the software single-step breakpoint that inserted at PC.
15493    Returns its slot if found, and -1 if not found.  */
15494
15495 static int
15496 find_single_step_breakpoint (struct address_space *aspace,
15497                              CORE_ADDR pc)
15498 {
15499   int i;
15500
15501   for (i = 0; i < 2; i++)
15502     {
15503       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15504       if (bp_tgt
15505           && breakpoint_address_match (bp_tgt->placed_address_space,
15506                                        bp_tgt->placed_address,
15507                                        aspace, pc))
15508         return i;
15509     }
15510
15511   return -1;
15512 }
15513
15514 /* Check whether a software single-step breakpoint is inserted at
15515    PC.  */
15516
15517 int
15518 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15519                                         CORE_ADDR pc)
15520 {
15521   return find_single_step_breakpoint (aspace, pc) >= 0;
15522 }
15523
15524 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15525    non-zero otherwise.  */
15526 static int
15527 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15528 {
15529   if (syscall_catchpoint_p (bp)
15530       && bp->enable_state != bp_disabled
15531       && bp->enable_state != bp_call_disabled)
15532     return 1;
15533   else
15534     return 0;
15535 }
15536
15537 int
15538 catch_syscall_enabled (void)
15539 {
15540   struct catch_syscall_inferior_data *inf_data
15541     = get_catch_syscall_inferior_data (current_inferior ());
15542
15543   return inf_data->total_syscalls_count != 0;
15544 }
15545
15546 int
15547 catching_syscall_number (int syscall_number)
15548 {
15549   struct breakpoint *bp;
15550
15551   ALL_BREAKPOINTS (bp)
15552     if (is_syscall_catchpoint_enabled (bp))
15553       {
15554         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15555
15556         if (c->syscalls_to_be_caught)
15557           {
15558             int i, iter;
15559             for (i = 0;
15560                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15561                  i++)
15562               if (syscall_number == iter)
15563                 return 1;
15564           }
15565         else
15566           return 1;
15567       }
15568
15569   return 0;
15570 }
15571
15572 /* Complete syscall names.  Used by "catch syscall".  */
15573 static VEC (char_ptr) *
15574 catch_syscall_completer (struct cmd_list_element *cmd,
15575                          const char *text, const char *word)
15576 {
15577   const char **list = get_syscall_names ();
15578   VEC (char_ptr) *retlist
15579     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15580
15581   xfree (list);
15582   return retlist;
15583 }
15584
15585 /* Tracepoint-specific operations.  */
15586
15587 /* Set tracepoint count to NUM.  */
15588 static void
15589 set_tracepoint_count (int num)
15590 {
15591   tracepoint_count = num;
15592   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15593 }
15594
15595 static void
15596 trace_command (char *arg, int from_tty)
15597 {
15598   struct breakpoint_ops *ops;
15599   const char *arg_cp = arg;
15600
15601   if (arg && probe_linespec_to_ops (&arg_cp))
15602     ops = &tracepoint_probe_breakpoint_ops;
15603   else
15604     ops = &tracepoint_breakpoint_ops;
15605
15606   create_breakpoint (get_current_arch (),
15607                      arg,
15608                      NULL, 0, NULL, 1 /* parse arg */,
15609                      0 /* tempflag */,
15610                      bp_tracepoint /* type_wanted */,
15611                      0 /* Ignore count */,
15612                      pending_break_support,
15613                      ops,
15614                      from_tty,
15615                      1 /* enabled */,
15616                      0 /* internal */, 0);
15617 }
15618
15619 static void
15620 ftrace_command (char *arg, int from_tty)
15621 {
15622   create_breakpoint (get_current_arch (),
15623                      arg,
15624                      NULL, 0, NULL, 1 /* parse arg */,
15625                      0 /* tempflag */,
15626                      bp_fast_tracepoint /* type_wanted */,
15627                      0 /* Ignore count */,
15628                      pending_break_support,
15629                      &tracepoint_breakpoint_ops,
15630                      from_tty,
15631                      1 /* enabled */,
15632                      0 /* internal */, 0);
15633 }
15634
15635 /* strace command implementation.  Creates a static tracepoint.  */
15636
15637 static void
15638 strace_command (char *arg, int from_tty)
15639 {
15640   struct breakpoint_ops *ops;
15641
15642   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15643      or with a normal static tracepoint.  */
15644   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15645     ops = &strace_marker_breakpoint_ops;
15646   else
15647     ops = &tracepoint_breakpoint_ops;
15648
15649   create_breakpoint (get_current_arch (),
15650                      arg,
15651                      NULL, 0, NULL, 1 /* parse arg */,
15652                      0 /* tempflag */,
15653                      bp_static_tracepoint /* type_wanted */,
15654                      0 /* Ignore count */,
15655                      pending_break_support,
15656                      ops,
15657                      from_tty,
15658                      1 /* enabled */,
15659                      0 /* internal */, 0);
15660 }
15661
15662 /* Set up a fake reader function that gets command lines from a linked
15663    list that was acquired during tracepoint uploading.  */
15664
15665 static struct uploaded_tp *this_utp;
15666 static int next_cmd;
15667
15668 static char *
15669 read_uploaded_action (void)
15670 {
15671   char *rslt;
15672
15673   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15674
15675   next_cmd++;
15676
15677   return rslt;
15678 }
15679
15680 /* Given information about a tracepoint as recorded on a target (which
15681    can be either a live system or a trace file), attempt to create an
15682    equivalent GDB tracepoint.  This is not a reliable process, since
15683    the target does not necessarily have all the information used when
15684    the tracepoint was originally defined.  */
15685   
15686 struct tracepoint *
15687 create_tracepoint_from_upload (struct uploaded_tp *utp)
15688 {
15689   char *addr_str, small_buf[100];
15690   struct tracepoint *tp;
15691
15692   if (utp->at_string)
15693     addr_str = utp->at_string;
15694   else
15695     {
15696       /* In the absence of a source location, fall back to raw
15697          address.  Since there is no way to confirm that the address
15698          means the same thing as when the trace was started, warn the
15699          user.  */
15700       warning (_("Uploaded tracepoint %d has no "
15701                  "source location, using raw address"),
15702                utp->number);
15703       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15704       addr_str = small_buf;
15705     }
15706
15707   /* There's not much we can do with a sequence of bytecodes.  */
15708   if (utp->cond && !utp->cond_string)
15709     warning (_("Uploaded tracepoint %d condition "
15710                "has no source form, ignoring it"),
15711              utp->number);
15712
15713   if (!create_breakpoint (get_current_arch (),
15714                           addr_str,
15715                           utp->cond_string, -1, NULL,
15716                           0 /* parse cond/thread */,
15717                           0 /* tempflag */,
15718                           utp->type /* type_wanted */,
15719                           0 /* Ignore count */,
15720                           pending_break_support,
15721                           &tracepoint_breakpoint_ops,
15722                           0 /* from_tty */,
15723                           utp->enabled /* enabled */,
15724                           0 /* internal */,
15725                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15726     return NULL;
15727
15728   /* Get the tracepoint we just created.  */
15729   tp = get_tracepoint (tracepoint_count);
15730   gdb_assert (tp != NULL);
15731
15732   if (utp->pass > 0)
15733     {
15734       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15735                  tp->base.number);
15736
15737       trace_pass_command (small_buf, 0);
15738     }
15739
15740   /* If we have uploaded versions of the original commands, set up a
15741      special-purpose "reader" function and call the usual command line
15742      reader, then pass the result to the breakpoint command-setting
15743      function.  */
15744   if (!VEC_empty (char_ptr, utp->cmd_strings))
15745     {
15746       struct command_line *cmd_list;
15747
15748       this_utp = utp;
15749       next_cmd = 0;
15750
15751       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15752
15753       breakpoint_set_commands (&tp->base, cmd_list);
15754     }
15755   else if (!VEC_empty (char_ptr, utp->actions)
15756            || !VEC_empty (char_ptr, utp->step_actions))
15757     warning (_("Uploaded tracepoint %d actions "
15758                "have no source form, ignoring them"),
15759              utp->number);
15760
15761   /* Copy any status information that might be available.  */
15762   tp->base.hit_count = utp->hit_count;
15763   tp->traceframe_usage = utp->traceframe_usage;
15764
15765   return tp;
15766 }
15767   
15768 /* Print information on tracepoint number TPNUM_EXP, or all if
15769    omitted.  */
15770
15771 static void
15772 tracepoints_info (char *args, int from_tty)
15773 {
15774   struct ui_out *uiout = current_uiout;
15775   int num_printed;
15776
15777   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15778
15779   if (num_printed == 0)
15780     {
15781       if (args == NULL || *args == '\0')
15782         ui_out_message (uiout, 0, "No tracepoints.\n");
15783       else
15784         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15785     }
15786
15787   default_collect_info ();
15788 }
15789
15790 /* The 'enable trace' command enables tracepoints.
15791    Not supported by all targets.  */
15792 static void
15793 enable_trace_command (char *args, int from_tty)
15794 {
15795   enable_command (args, from_tty);
15796 }
15797
15798 /* The 'disable trace' command disables tracepoints.
15799    Not supported by all targets.  */
15800 static void
15801 disable_trace_command (char *args, int from_tty)
15802 {
15803   disable_command (args, from_tty);
15804 }
15805
15806 /* Remove a tracepoint (or all if no argument).  */
15807 static void
15808 delete_trace_command (char *arg, int from_tty)
15809 {
15810   struct breakpoint *b, *b_tmp;
15811
15812   dont_repeat ();
15813
15814   if (arg == 0)
15815     {
15816       int breaks_to_delete = 0;
15817
15818       /* Delete all breakpoints if no argument.
15819          Do not delete internal or call-dummy breakpoints, these
15820          have to be deleted with an explicit breakpoint number 
15821          argument.  */
15822       ALL_TRACEPOINTS (b)
15823         if (is_tracepoint (b) && user_breakpoint_p (b))
15824           {
15825             breaks_to_delete = 1;
15826             break;
15827           }
15828
15829       /* Ask user only if there are some breakpoints to delete.  */
15830       if (!from_tty
15831           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15832         {
15833           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15834             if (is_tracepoint (b) && user_breakpoint_p (b))
15835               delete_breakpoint (b);
15836         }
15837     }
15838   else
15839     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15840 }
15841
15842 /* Helper function for trace_pass_command.  */
15843
15844 static void
15845 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15846 {
15847   tp->pass_count = count;
15848   observer_notify_breakpoint_modified (&tp->base);
15849   if (from_tty)
15850     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15851                      tp->base.number, count);
15852 }
15853
15854 /* Set passcount for tracepoint.
15855
15856    First command argument is passcount, second is tracepoint number.
15857    If tracepoint number omitted, apply to most recently defined.
15858    Also accepts special argument "all".  */
15859
15860 static void
15861 trace_pass_command (char *args, int from_tty)
15862 {
15863   struct tracepoint *t1;
15864   unsigned int count;
15865
15866   if (args == 0 || *args == 0)
15867     error (_("passcount command requires an "
15868              "argument (count + optional TP num)"));
15869
15870   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15871
15872   args = skip_spaces (args);
15873   if (*args && strncasecmp (args, "all", 3) == 0)
15874     {
15875       struct breakpoint *b;
15876
15877       args += 3;                        /* Skip special argument "all".  */
15878       if (*args)
15879         error (_("Junk at end of arguments."));
15880
15881       ALL_TRACEPOINTS (b)
15882       {
15883         t1 = (struct tracepoint *) b;
15884         trace_pass_set_count (t1, count, from_tty);
15885       }
15886     }
15887   else if (*args == '\0')
15888     {
15889       t1 = get_tracepoint_by_number (&args, NULL);
15890       if (t1)
15891         trace_pass_set_count (t1, count, from_tty);
15892     }
15893   else
15894     {
15895       struct get_number_or_range_state state;
15896
15897       init_number_or_range (&state, args);
15898       while (!state.finished)
15899         {
15900           t1 = get_tracepoint_by_number (&args, &state);
15901           if (t1)
15902             trace_pass_set_count (t1, count, from_tty);
15903         }
15904     }
15905 }
15906
15907 struct tracepoint *
15908 get_tracepoint (int num)
15909 {
15910   struct breakpoint *t;
15911
15912   ALL_TRACEPOINTS (t)
15913     if (t->number == num)
15914       return (struct tracepoint *) t;
15915
15916   return NULL;
15917 }
15918
15919 /* Find the tracepoint with the given target-side number (which may be
15920    different from the tracepoint number after disconnecting and
15921    reconnecting).  */
15922
15923 struct tracepoint *
15924 get_tracepoint_by_number_on_target (int num)
15925 {
15926   struct breakpoint *b;
15927
15928   ALL_TRACEPOINTS (b)
15929     {
15930       struct tracepoint *t = (struct tracepoint *) b;
15931
15932       if (t->number_on_target == num)
15933         return t;
15934     }
15935
15936   return NULL;
15937 }
15938
15939 /* Utility: parse a tracepoint number and look it up in the list.
15940    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15941    If the argument is missing, the most recent tracepoint
15942    (tracepoint_count) is returned.  */
15943
15944 struct tracepoint *
15945 get_tracepoint_by_number (char **arg,
15946                           struct get_number_or_range_state *state)
15947 {
15948   struct breakpoint *t;
15949   int tpnum;
15950   char *instring = arg == NULL ? NULL : *arg;
15951
15952   if (state)
15953     {
15954       gdb_assert (!state->finished);
15955       tpnum = get_number_or_range (state);
15956     }
15957   else if (arg == NULL || *arg == NULL || ! **arg)
15958     tpnum = tracepoint_count;
15959   else
15960     tpnum = get_number (arg);
15961
15962   if (tpnum <= 0)
15963     {
15964       if (instring && *instring)
15965         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15966                          instring);
15967       else
15968         printf_filtered (_("No previous tracepoint\n"));
15969       return NULL;
15970     }
15971
15972   ALL_TRACEPOINTS (t)
15973     if (t->number == tpnum)
15974     {
15975       return (struct tracepoint *) t;
15976     }
15977
15978   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15979   return NULL;
15980 }
15981
15982 void
15983 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15984 {
15985   if (b->thread != -1)
15986     fprintf_unfiltered (fp, " thread %d", b->thread);
15987
15988   if (b->task != 0)
15989     fprintf_unfiltered (fp, " task %d", b->task);
15990
15991   fprintf_unfiltered (fp, "\n");
15992 }
15993
15994 /* Save information on user settable breakpoints (watchpoints, etc) to
15995    a new script file named FILENAME.  If FILTER is non-NULL, call it
15996    on each breakpoint and only include the ones for which it returns
15997    non-zero.  */
15998
15999 static void
16000 save_breakpoints (char *filename, int from_tty,
16001                   int (*filter) (const struct breakpoint *))
16002 {
16003   struct breakpoint *tp;
16004   int any = 0;
16005   struct cleanup *cleanup;
16006   struct ui_file *fp;
16007   int extra_trace_bits = 0;
16008
16009   if (filename == 0 || *filename == 0)
16010     error (_("Argument required (file name in which to save)"));
16011
16012   /* See if we have anything to save.  */
16013   ALL_BREAKPOINTS (tp)
16014   {
16015     /* Skip internal and momentary breakpoints.  */
16016     if (!user_breakpoint_p (tp))
16017       continue;
16018
16019     /* If we have a filter, only save the breakpoints it accepts.  */
16020     if (filter && !filter (tp))
16021       continue;
16022
16023     any = 1;
16024
16025     if (is_tracepoint (tp))
16026       {
16027         extra_trace_bits = 1;
16028
16029         /* We can stop searching.  */
16030         break;
16031       }
16032   }
16033
16034   if (!any)
16035     {
16036       warning (_("Nothing to save."));
16037       return;
16038     }
16039
16040   filename = tilde_expand (filename);
16041   cleanup = make_cleanup (xfree, filename);
16042   fp = gdb_fopen (filename, "w");
16043   if (!fp)
16044     error (_("Unable to open file '%s' for saving (%s)"),
16045            filename, safe_strerror (errno));
16046   make_cleanup_ui_file_delete (fp);
16047
16048   if (extra_trace_bits)
16049     save_trace_state_variables (fp);
16050
16051   ALL_BREAKPOINTS (tp)
16052   {
16053     /* Skip internal and momentary breakpoints.  */
16054     if (!user_breakpoint_p (tp))
16055       continue;
16056
16057     /* If we have a filter, only save the breakpoints it accepts.  */
16058     if (filter && !filter (tp))
16059       continue;
16060
16061     tp->ops->print_recreate (tp, fp);
16062
16063     /* Note, we can't rely on tp->number for anything, as we can't
16064        assume the recreated breakpoint numbers will match.  Use $bpnum
16065        instead.  */
16066
16067     if (tp->cond_string)
16068       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
16069
16070     if (tp->ignore_count)
16071       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
16072
16073     if (tp->type != bp_dprintf && tp->commands)
16074       {
16075         volatile struct gdb_exception ex;       
16076
16077         fprintf_unfiltered (fp, "  commands\n");
16078         
16079         ui_out_redirect (current_uiout, fp);
16080         TRY_CATCH (ex, RETURN_MASK_ALL)
16081           {
16082             print_command_lines (current_uiout, tp->commands->commands, 2);
16083           }
16084         ui_out_redirect (current_uiout, NULL);
16085
16086         if (ex.reason < 0)
16087           throw_exception (ex);
16088
16089         fprintf_unfiltered (fp, "  end\n");
16090       }
16091
16092     if (tp->enable_state == bp_disabled)
16093       fprintf_unfiltered (fp, "disable\n");
16094
16095     /* If this is a multi-location breakpoint, check if the locations
16096        should be individually disabled.  Watchpoint locations are
16097        special, and not user visible.  */
16098     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
16099       {
16100         struct bp_location *loc;
16101         int n = 1;
16102
16103         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
16104           if (!loc->enabled)
16105             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
16106       }
16107   }
16108
16109   if (extra_trace_bits && *default_collect)
16110     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
16111
16112   if (from_tty)
16113     printf_filtered (_("Saved to file '%s'.\n"), filename);
16114   do_cleanups (cleanup);
16115 }
16116
16117 /* The `save breakpoints' command.  */
16118
16119 static void
16120 save_breakpoints_command (char *args, int from_tty)
16121 {
16122   save_breakpoints (args, from_tty, NULL);
16123 }
16124
16125 /* The `save tracepoints' command.  */
16126
16127 static void
16128 save_tracepoints_command (char *args, int from_tty)
16129 {
16130   save_breakpoints (args, from_tty, is_tracepoint);
16131 }
16132
16133 /* Create a vector of all tracepoints.  */
16134
16135 VEC(breakpoint_p) *
16136 all_tracepoints (void)
16137 {
16138   VEC(breakpoint_p) *tp_vec = 0;
16139   struct breakpoint *tp;
16140
16141   ALL_TRACEPOINTS (tp)
16142   {
16143     VEC_safe_push (breakpoint_p, tp_vec, tp);
16144   }
16145
16146   return tp_vec;
16147 }
16148
16149 \f
16150 /* This help string is used for the break, hbreak, tbreak and thbreak
16151    commands.  It is defined as a macro to prevent duplication.
16152    COMMAND should be a string constant containing the name of the
16153    command.  */
16154 #define BREAK_ARGS_HELP(command) \
16155 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16156 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16157 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16158 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16159 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16160 If a line number is specified, break at start of code for that line.\n\
16161 If a function is specified, break at start of code for that function.\n\
16162 If an address is specified, break at that exact address.\n\
16163 With no LOCATION, uses current execution address of the selected\n\
16164 stack frame.  This is useful for breaking on return to a stack frame.\n\
16165 \n\
16166 THREADNUM is the number from \"info threads\".\n\
16167 CONDITION is a boolean expression.\n\
16168 \n\
16169 Multiple breakpoints at one place are permitted, and useful if their\n\
16170 conditions are different.\n\
16171 \n\
16172 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16173
16174 /* List of subcommands for "catch".  */
16175 static struct cmd_list_element *catch_cmdlist;
16176
16177 /* List of subcommands for "tcatch".  */
16178 static struct cmd_list_element *tcatch_cmdlist;
16179
16180 void
16181 add_catch_command (char *name, char *docstring,
16182                    cmd_sfunc_ftype *sfunc,
16183                    completer_ftype *completer,
16184                    void *user_data_catch,
16185                    void *user_data_tcatch)
16186 {
16187   struct cmd_list_element *command;
16188
16189   command = add_cmd (name, class_breakpoint, NULL, docstring,
16190                      &catch_cmdlist);
16191   set_cmd_sfunc (command, sfunc);
16192   set_cmd_context (command, user_data_catch);
16193   set_cmd_completer (command, completer);
16194
16195   command = add_cmd (name, class_breakpoint, NULL, docstring,
16196                      &tcatch_cmdlist);
16197   set_cmd_sfunc (command, sfunc);
16198   set_cmd_context (command, user_data_tcatch);
16199   set_cmd_completer (command, completer);
16200 }
16201
16202 static void
16203 clear_syscall_counts (struct inferior *inf)
16204 {
16205   struct catch_syscall_inferior_data *inf_data
16206     = get_catch_syscall_inferior_data (inf);
16207
16208   inf_data->total_syscalls_count = 0;
16209   inf_data->any_syscall_count = 0;
16210   VEC_free (int, inf_data->syscalls_counts);
16211 }
16212
16213 static void
16214 save_command (char *arg, int from_tty)
16215 {
16216   printf_unfiltered (_("\"save\" must be followed by "
16217                        "the name of a save subcommand.\n"));
16218   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16219 }
16220
16221 struct breakpoint *
16222 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16223                           void *data)
16224 {
16225   struct breakpoint *b, *b_tmp;
16226
16227   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16228     {
16229       if ((*callback) (b, data))
16230         return b;
16231     }
16232
16233   return NULL;
16234 }
16235
16236 /* Zero if any of the breakpoint's locations could be a location where
16237    functions have been inlined, nonzero otherwise.  */
16238
16239 static int
16240 is_non_inline_function (struct breakpoint *b)
16241 {
16242   /* The shared library event breakpoint is set on the address of a
16243      non-inline function.  */
16244   if (b->type == bp_shlib_event)
16245     return 1;
16246
16247   return 0;
16248 }
16249
16250 /* Nonzero if the specified PC cannot be a location where functions
16251    have been inlined.  */
16252
16253 int
16254 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16255                            const struct target_waitstatus *ws)
16256 {
16257   struct breakpoint *b;
16258   struct bp_location *bl;
16259
16260   ALL_BREAKPOINTS (b)
16261     {
16262       if (!is_non_inline_function (b))
16263         continue;
16264
16265       for (bl = b->loc; bl != NULL; bl = bl->next)
16266         {
16267           if (!bl->shlib_disabled
16268               && bpstat_check_location (bl, aspace, pc, ws))
16269             return 1;
16270         }
16271     }
16272
16273   return 0;
16274 }
16275
16276 /* Remove any references to OBJFILE which is going to be freed.  */
16277
16278 void
16279 breakpoint_free_objfile (struct objfile *objfile)
16280 {
16281   struct bp_location **locp, *loc;
16282
16283   ALL_BP_LOCATIONS (loc, locp)
16284     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16285       loc->symtab = NULL;
16286 }
16287
16288 void
16289 initialize_breakpoint_ops (void)
16290 {
16291   static int initialized = 0;
16292
16293   struct breakpoint_ops *ops;
16294
16295   if (initialized)
16296     return;
16297   initialized = 1;
16298
16299   /* The breakpoint_ops structure to be inherit by all kinds of
16300      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16301      internal and momentary breakpoints, etc.).  */
16302   ops = &bkpt_base_breakpoint_ops;
16303   *ops = base_breakpoint_ops;
16304   ops->re_set = bkpt_re_set;
16305   ops->insert_location = bkpt_insert_location;
16306   ops->remove_location = bkpt_remove_location;
16307   ops->breakpoint_hit = bkpt_breakpoint_hit;
16308   ops->create_sals_from_address = bkpt_create_sals_from_address;
16309   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16310   ops->decode_linespec = bkpt_decode_linespec;
16311
16312   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16313   ops = &bkpt_breakpoint_ops;
16314   *ops = bkpt_base_breakpoint_ops;
16315   ops->re_set = bkpt_re_set;
16316   ops->resources_needed = bkpt_resources_needed;
16317   ops->print_it = bkpt_print_it;
16318   ops->print_mention = bkpt_print_mention;
16319   ops->print_recreate = bkpt_print_recreate;
16320
16321   /* Ranged breakpoints.  */
16322   ops = &ranged_breakpoint_ops;
16323   *ops = bkpt_breakpoint_ops;
16324   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16325   ops->resources_needed = resources_needed_ranged_breakpoint;
16326   ops->print_it = print_it_ranged_breakpoint;
16327   ops->print_one = print_one_ranged_breakpoint;
16328   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16329   ops->print_mention = print_mention_ranged_breakpoint;
16330   ops->print_recreate = print_recreate_ranged_breakpoint;
16331
16332   /* Internal breakpoints.  */
16333   ops = &internal_breakpoint_ops;
16334   *ops = bkpt_base_breakpoint_ops;
16335   ops->re_set = internal_bkpt_re_set;
16336   ops->check_status = internal_bkpt_check_status;
16337   ops->print_it = internal_bkpt_print_it;
16338   ops->print_mention = internal_bkpt_print_mention;
16339
16340   /* Momentary breakpoints.  */
16341   ops = &momentary_breakpoint_ops;
16342   *ops = bkpt_base_breakpoint_ops;
16343   ops->re_set = momentary_bkpt_re_set;
16344   ops->check_status = momentary_bkpt_check_status;
16345   ops->print_it = momentary_bkpt_print_it;
16346   ops->print_mention = momentary_bkpt_print_mention;
16347
16348   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16349   ops = &longjmp_breakpoint_ops;
16350   *ops = momentary_breakpoint_ops;
16351   ops->dtor = longjmp_bkpt_dtor;
16352
16353   /* Probe breakpoints.  */
16354   ops = &bkpt_probe_breakpoint_ops;
16355   *ops = bkpt_breakpoint_ops;
16356   ops->insert_location = bkpt_probe_insert_location;
16357   ops->remove_location = bkpt_probe_remove_location;
16358   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16359   ops->decode_linespec = bkpt_probe_decode_linespec;
16360
16361   /* Watchpoints.  */
16362   ops = &watchpoint_breakpoint_ops;
16363   *ops = base_breakpoint_ops;
16364   ops->dtor = dtor_watchpoint;
16365   ops->re_set = re_set_watchpoint;
16366   ops->insert_location = insert_watchpoint;
16367   ops->remove_location = remove_watchpoint;
16368   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16369   ops->check_status = check_status_watchpoint;
16370   ops->resources_needed = resources_needed_watchpoint;
16371   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16372   ops->print_it = print_it_watchpoint;
16373   ops->print_mention = print_mention_watchpoint;
16374   ops->print_recreate = print_recreate_watchpoint;
16375   ops->explains_signal = explains_signal_watchpoint;
16376
16377   /* Masked watchpoints.  */
16378   ops = &masked_watchpoint_breakpoint_ops;
16379   *ops = watchpoint_breakpoint_ops;
16380   ops->insert_location = insert_masked_watchpoint;
16381   ops->remove_location = remove_masked_watchpoint;
16382   ops->resources_needed = resources_needed_masked_watchpoint;
16383   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16384   ops->print_it = print_it_masked_watchpoint;
16385   ops->print_one_detail = print_one_detail_masked_watchpoint;
16386   ops->print_mention = print_mention_masked_watchpoint;
16387   ops->print_recreate = print_recreate_masked_watchpoint;
16388
16389   /* Tracepoints.  */
16390   ops = &tracepoint_breakpoint_ops;
16391   *ops = base_breakpoint_ops;
16392   ops->re_set = tracepoint_re_set;
16393   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16394   ops->print_one_detail = tracepoint_print_one_detail;
16395   ops->print_mention = tracepoint_print_mention;
16396   ops->print_recreate = tracepoint_print_recreate;
16397   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16398   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16399   ops->decode_linespec = tracepoint_decode_linespec;
16400
16401   /* Probe tracepoints.  */
16402   ops = &tracepoint_probe_breakpoint_ops;
16403   *ops = tracepoint_breakpoint_ops;
16404   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16405   ops->decode_linespec = tracepoint_probe_decode_linespec;
16406
16407   /* Static tracepoints with marker (`-m').  */
16408   ops = &strace_marker_breakpoint_ops;
16409   *ops = tracepoint_breakpoint_ops;
16410   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16411   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16412   ops->decode_linespec = strace_marker_decode_linespec;
16413
16414   /* Fork catchpoints.  */
16415   ops = &catch_fork_breakpoint_ops;
16416   *ops = base_breakpoint_ops;
16417   ops->insert_location = insert_catch_fork;
16418   ops->remove_location = remove_catch_fork;
16419   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16420   ops->print_it = print_it_catch_fork;
16421   ops->print_one = print_one_catch_fork;
16422   ops->print_mention = print_mention_catch_fork;
16423   ops->print_recreate = print_recreate_catch_fork;
16424
16425   /* Vfork catchpoints.  */
16426   ops = &catch_vfork_breakpoint_ops;
16427   *ops = base_breakpoint_ops;
16428   ops->insert_location = insert_catch_vfork;
16429   ops->remove_location = remove_catch_vfork;
16430   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16431   ops->print_it = print_it_catch_vfork;
16432   ops->print_one = print_one_catch_vfork;
16433   ops->print_mention = print_mention_catch_vfork;
16434   ops->print_recreate = print_recreate_catch_vfork;
16435
16436   /* Exec catchpoints.  */
16437   ops = &catch_exec_breakpoint_ops;
16438   *ops = base_breakpoint_ops;
16439   ops->dtor = dtor_catch_exec;
16440   ops->insert_location = insert_catch_exec;
16441   ops->remove_location = remove_catch_exec;
16442   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16443   ops->print_it = print_it_catch_exec;
16444   ops->print_one = print_one_catch_exec;
16445   ops->print_mention = print_mention_catch_exec;
16446   ops->print_recreate = print_recreate_catch_exec;
16447
16448   /* Syscall catchpoints.  */
16449   ops = &catch_syscall_breakpoint_ops;
16450   *ops = base_breakpoint_ops;
16451   ops->dtor = dtor_catch_syscall;
16452   ops->insert_location = insert_catch_syscall;
16453   ops->remove_location = remove_catch_syscall;
16454   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16455   ops->print_it = print_it_catch_syscall;
16456   ops->print_one = print_one_catch_syscall;
16457   ops->print_mention = print_mention_catch_syscall;
16458   ops->print_recreate = print_recreate_catch_syscall;
16459
16460   /* Solib-related catchpoints.  */
16461   ops = &catch_solib_breakpoint_ops;
16462   *ops = base_breakpoint_ops;
16463   ops->dtor = dtor_catch_solib;
16464   ops->insert_location = insert_catch_solib;
16465   ops->remove_location = remove_catch_solib;
16466   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16467   ops->check_status = check_status_catch_solib;
16468   ops->print_it = print_it_catch_solib;
16469   ops->print_one = print_one_catch_solib;
16470   ops->print_mention = print_mention_catch_solib;
16471   ops->print_recreate = print_recreate_catch_solib;
16472
16473   ops = &dprintf_breakpoint_ops;
16474   *ops = bkpt_base_breakpoint_ops;
16475   ops->re_set = dprintf_re_set;
16476   ops->resources_needed = bkpt_resources_needed;
16477   ops->print_it = bkpt_print_it;
16478   ops->print_mention = bkpt_print_mention;
16479   ops->print_recreate = dprintf_print_recreate;
16480   ops->after_condition_true = dprintf_after_condition_true;
16481   ops->breakpoint_hit = dprintf_breakpoint_hit;
16482 }
16483
16484 /* Chain containing all defined "enable breakpoint" subcommands.  */
16485
16486 static struct cmd_list_element *enablebreaklist = NULL;
16487
16488 void
16489 _initialize_breakpoint (void)
16490 {
16491   struct cmd_list_element *c;
16492
16493   initialize_breakpoint_ops ();
16494
16495   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16496   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16497   observer_attach_inferior_exit (clear_syscall_counts);
16498   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16499
16500   breakpoint_objfile_key
16501     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16502
16503   catch_syscall_inferior_data
16504     = register_inferior_data_with_cleanup (NULL,
16505                                            catch_syscall_inferior_data_cleanup);
16506
16507   breakpoint_chain = 0;
16508   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16509      before a breakpoint is set.  */
16510   breakpoint_count = 0;
16511
16512   tracepoint_count = 0;
16513
16514   add_com ("ignore", class_breakpoint, ignore_command, _("\
16515 Set ignore-count of breakpoint number N to COUNT.\n\
16516 Usage is `ignore N COUNT'."));
16517   if (xdb_commands)
16518     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16519
16520   add_com ("commands", class_breakpoint, commands_command, _("\
16521 Set commands to be executed when a breakpoint is hit.\n\
16522 Give breakpoint number as argument after \"commands\".\n\
16523 With no argument, the targeted breakpoint is the last one set.\n\
16524 The commands themselves follow starting on the next line.\n\
16525 Type a line containing \"end\" to indicate the end of them.\n\
16526 Give \"silent\" as the first line to make the breakpoint silent;\n\
16527 then no output is printed when it is hit, except what the commands print."));
16528
16529   c = add_com ("condition", class_breakpoint, condition_command, _("\
16530 Specify breakpoint number N to break only if COND is true.\n\
16531 Usage is `condition N COND', where N is an integer and COND is an\n\
16532 expression to be evaluated whenever breakpoint N is reached."));
16533   set_cmd_completer (c, condition_completer);
16534
16535   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16536 Set a temporary breakpoint.\n\
16537 Like \"break\" except the breakpoint is only temporary,\n\
16538 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16539 by using \"enable delete\" on the breakpoint number.\n\
16540 \n"
16541 BREAK_ARGS_HELP ("tbreak")));
16542   set_cmd_completer (c, location_completer);
16543
16544   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16545 Set a hardware assisted breakpoint.\n\
16546 Like \"break\" except the breakpoint requires hardware support,\n\
16547 some target hardware may not have this support.\n\
16548 \n"
16549 BREAK_ARGS_HELP ("hbreak")));
16550   set_cmd_completer (c, location_completer);
16551
16552   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16553 Set a temporary hardware assisted breakpoint.\n\
16554 Like \"hbreak\" except the breakpoint is only temporary,\n\
16555 so it will be deleted when hit.\n\
16556 \n"
16557 BREAK_ARGS_HELP ("thbreak")));
16558   set_cmd_completer (c, location_completer);
16559
16560   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16561 Enable some breakpoints.\n\
16562 Give breakpoint numbers (separated by spaces) as arguments.\n\
16563 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16564 This is used to cancel the effect of the \"disable\" command.\n\
16565 With a subcommand you can enable temporarily."),
16566                   &enablelist, "enable ", 1, &cmdlist);
16567   if (xdb_commands)
16568     add_com ("ab", class_breakpoint, enable_command, _("\
16569 Enable some breakpoints.\n\
16570 Give breakpoint numbers (separated by spaces) as arguments.\n\
16571 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16572 This is used to cancel the effect of the \"disable\" command.\n\
16573 With a subcommand you can enable temporarily."));
16574
16575   add_com_alias ("en", "enable", class_breakpoint, 1);
16576
16577   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16578 Enable some breakpoints.\n\
16579 Give breakpoint numbers (separated by spaces) as arguments.\n\
16580 This is used to cancel the effect of the \"disable\" command.\n\
16581 May be abbreviated to simply \"enable\".\n"),
16582                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16583
16584   add_cmd ("once", no_class, enable_once_command, _("\
16585 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16586 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16587            &enablebreaklist);
16588
16589   add_cmd ("delete", no_class, enable_delete_command, _("\
16590 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16591 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16592            &enablebreaklist);
16593
16594   add_cmd ("count", no_class, enable_count_command, _("\
16595 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16596 If a breakpoint is hit while enabled in this fashion,\n\
16597 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16598            &enablebreaklist);
16599
16600   add_cmd ("delete", no_class, enable_delete_command, _("\
16601 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16602 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16603            &enablelist);
16604
16605   add_cmd ("once", no_class, enable_once_command, _("\
16606 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16607 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16608            &enablelist);
16609
16610   add_cmd ("count", no_class, enable_count_command, _("\
16611 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16612 If a breakpoint is hit while enabled in this fashion,\n\
16613 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16614            &enablelist);
16615
16616   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16617 Disable some breakpoints.\n\
16618 Arguments are breakpoint numbers with spaces in between.\n\
16619 To disable all breakpoints, give no argument.\n\
16620 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16621                   &disablelist, "disable ", 1, &cmdlist);
16622   add_com_alias ("dis", "disable", class_breakpoint, 1);
16623   add_com_alias ("disa", "disable", class_breakpoint, 1);
16624   if (xdb_commands)
16625     add_com ("sb", class_breakpoint, disable_command, _("\
16626 Disable some breakpoints.\n\
16627 Arguments are breakpoint numbers with spaces in between.\n\
16628 To disable all breakpoints, give no argument.\n\
16629 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16630
16631   add_cmd ("breakpoints", class_alias, disable_command, _("\
16632 Disable some breakpoints.\n\
16633 Arguments are breakpoint numbers with spaces in between.\n\
16634 To disable all breakpoints, give no argument.\n\
16635 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16636 This command may be abbreviated \"disable\"."),
16637            &disablelist);
16638
16639   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16640 Delete some breakpoints or auto-display expressions.\n\
16641 Arguments are breakpoint numbers with spaces in between.\n\
16642 To delete all breakpoints, give no argument.\n\
16643 \n\
16644 Also a prefix command for deletion of other GDB objects.\n\
16645 The \"unset\" command is also an alias for \"delete\"."),
16646                   &deletelist, "delete ", 1, &cmdlist);
16647   add_com_alias ("d", "delete", class_breakpoint, 1);
16648   add_com_alias ("del", "delete", class_breakpoint, 1);
16649   if (xdb_commands)
16650     add_com ("db", class_breakpoint, delete_command, _("\
16651 Delete some breakpoints.\n\
16652 Arguments are breakpoint numbers with spaces in between.\n\
16653 To delete all breakpoints, give no argument.\n"));
16654
16655   add_cmd ("breakpoints", class_alias, delete_command, _("\
16656 Delete some breakpoints or auto-display expressions.\n\
16657 Arguments are breakpoint numbers with spaces in between.\n\
16658 To delete all breakpoints, give no argument.\n\
16659 This command may be abbreviated \"delete\"."),
16660            &deletelist);
16661
16662   add_com ("clear", class_breakpoint, clear_command, _("\
16663 Clear breakpoint at specified line or function.\n\
16664 Argument may be line number, function name, or \"*\" and an address.\n\
16665 If line number is specified, all breakpoints in that line are cleared.\n\
16666 If function is specified, breakpoints at beginning of function are cleared.\n\
16667 If an address is specified, breakpoints at that address are cleared.\n\
16668 \n\
16669 With no argument, clears all breakpoints in the line that the selected frame\n\
16670 is executing in.\n\
16671 \n\
16672 See also the \"delete\" command which clears breakpoints by number."));
16673   add_com_alias ("cl", "clear", class_breakpoint, 1);
16674
16675   c = add_com ("break", class_breakpoint, break_command, _("\
16676 Set breakpoint at specified line or function.\n"
16677 BREAK_ARGS_HELP ("break")));
16678   set_cmd_completer (c, location_completer);
16679
16680   add_com_alias ("b", "break", class_run, 1);
16681   add_com_alias ("br", "break", class_run, 1);
16682   add_com_alias ("bre", "break", class_run, 1);
16683   add_com_alias ("brea", "break", class_run, 1);
16684
16685   if (xdb_commands)
16686    add_com_alias ("ba", "break", class_breakpoint, 1);
16687
16688   if (dbx_commands)
16689     {
16690       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16691 Break in function/address or break at a line in the current file."),
16692                              &stoplist, "stop ", 1, &cmdlist);
16693       add_cmd ("in", class_breakpoint, stopin_command,
16694                _("Break in function or address."), &stoplist);
16695       add_cmd ("at", class_breakpoint, stopat_command,
16696                _("Break at a line in the current file."), &stoplist);
16697       add_com ("status", class_info, breakpoints_info, _("\
16698 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16699 The \"Type\" column indicates one of:\n\
16700 \tbreakpoint     - normal breakpoint\n\
16701 \twatchpoint     - watchpoint\n\
16702 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16703 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16704 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16705 address and file/line number respectively.\n\
16706 \n\
16707 Convenience variable \"$_\" and default examine address for \"x\"\n\
16708 are set to the address of the last breakpoint listed unless the command\n\
16709 is prefixed with \"server \".\n\n\
16710 Convenience variable \"$bpnum\" contains the number of the last\n\
16711 breakpoint set."));
16712     }
16713
16714   add_info ("breakpoints", breakpoints_info, _("\
16715 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16716 The \"Type\" column indicates one of:\n\
16717 \tbreakpoint     - normal breakpoint\n\
16718 \twatchpoint     - watchpoint\n\
16719 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16720 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16721 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16722 address and file/line number respectively.\n\
16723 \n\
16724 Convenience variable \"$_\" and default examine address for \"x\"\n\
16725 are set to the address of the last breakpoint listed unless the command\n\
16726 is prefixed with \"server \".\n\n\
16727 Convenience variable \"$bpnum\" contains the number of the last\n\
16728 breakpoint set."));
16729
16730   add_info_alias ("b", "breakpoints", 1);
16731
16732   if (xdb_commands)
16733     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16734 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16735 The \"Type\" column indicates one of:\n\
16736 \tbreakpoint     - normal breakpoint\n\
16737 \twatchpoint     - watchpoint\n\
16738 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16739 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16740 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16741 address and file/line number respectively.\n\
16742 \n\
16743 Convenience variable \"$_\" and default examine address for \"x\"\n\
16744 are set to the address of the last breakpoint listed unless the command\n\
16745 is prefixed with \"server \".\n\n\
16746 Convenience variable \"$bpnum\" contains the number of the last\n\
16747 breakpoint set."));
16748
16749   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16750 Status of all breakpoints, or breakpoint number NUMBER.\n\
16751 The \"Type\" column indicates one of:\n\
16752 \tbreakpoint     - normal breakpoint\n\
16753 \twatchpoint     - watchpoint\n\
16754 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16755 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16756 \tuntil          - internal breakpoint used by the \"until\" command\n\
16757 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16758 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16759 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16760 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16761 address and file/line number respectively.\n\
16762 \n\
16763 Convenience variable \"$_\" and default examine address for \"x\"\n\
16764 are set to the address of the last breakpoint listed unless the command\n\
16765 is prefixed with \"server \".\n\n\
16766 Convenience variable \"$bpnum\" contains the number of the last\n\
16767 breakpoint set."),
16768            &maintenanceinfolist);
16769
16770   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16771 Set catchpoints to catch events."),
16772                   &catch_cmdlist, "catch ",
16773                   0/*allow-unknown*/, &cmdlist);
16774
16775   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16776 Set temporary catchpoints to catch events."),
16777                   &tcatch_cmdlist, "tcatch ",
16778                   0/*allow-unknown*/, &cmdlist);
16779
16780   add_catch_command ("fork", _("Catch calls to fork."),
16781                      catch_fork_command_1,
16782                      NULL,
16783                      (void *) (uintptr_t) catch_fork_permanent,
16784                      (void *) (uintptr_t) catch_fork_temporary);
16785   add_catch_command ("vfork", _("Catch calls to vfork."),
16786                      catch_fork_command_1,
16787                      NULL,
16788                      (void *) (uintptr_t) catch_vfork_permanent,
16789                      (void *) (uintptr_t) catch_vfork_temporary);
16790   add_catch_command ("exec", _("Catch calls to exec."),
16791                      catch_exec_command_1,
16792                      NULL,
16793                      CATCH_PERMANENT,
16794                      CATCH_TEMPORARY);
16795   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16796 Usage: catch load [REGEX]\n\
16797 If REGEX is given, only stop for libraries matching the regular expression."),
16798                      catch_load_command_1,
16799                      NULL,
16800                      CATCH_PERMANENT,
16801                      CATCH_TEMPORARY);
16802   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16803 Usage: catch unload [REGEX]\n\
16804 If REGEX is given, only stop for libraries matching the regular expression."),
16805                      catch_unload_command_1,
16806                      NULL,
16807                      CATCH_PERMANENT,
16808                      CATCH_TEMPORARY);
16809   add_catch_command ("syscall", _("\
16810 Catch system calls by their names and/or numbers.\n\
16811 Arguments say which system calls to catch.  If no arguments\n\
16812 are given, every system call will be caught.\n\
16813 Arguments, if given, should be one or more system call names\n\
16814 (if your system supports that), or system call numbers."),
16815                      catch_syscall_command_1,
16816                      catch_syscall_completer,
16817                      CATCH_PERMANENT,
16818                      CATCH_TEMPORARY);
16819
16820   c = add_com ("watch", class_breakpoint, watch_command, _("\
16821 Set a watchpoint for an expression.\n\
16822 Usage: watch [-l|-location] EXPRESSION\n\
16823 A watchpoint stops execution of your program whenever the value of\n\
16824 an expression changes.\n\
16825 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16826 the memory to which it refers."));
16827   set_cmd_completer (c, expression_completer);
16828
16829   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16830 Set a read watchpoint for an expression.\n\
16831 Usage: rwatch [-l|-location] EXPRESSION\n\
16832 A watchpoint stops execution of your program whenever the value of\n\
16833 an expression is read.\n\
16834 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16835 the memory to which it refers."));
16836   set_cmd_completer (c, expression_completer);
16837
16838   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16839 Set a watchpoint for an expression.\n\
16840 Usage: awatch [-l|-location] EXPRESSION\n\
16841 A watchpoint stops execution of your program whenever the value of\n\
16842 an expression is either read or written.\n\
16843 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16844 the memory to which it refers."));
16845   set_cmd_completer (c, expression_completer);
16846
16847   add_info ("watchpoints", watchpoints_info, _("\
16848 Status of specified watchpoints (all watchpoints if no argument)."));
16849
16850   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16851      respond to changes - contrary to the description.  */
16852   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16853                             &can_use_hw_watchpoints, _("\
16854 Set debugger's willingness to use watchpoint hardware."), _("\
16855 Show debugger's willingness to use watchpoint hardware."), _("\
16856 If zero, gdb will not use hardware for new watchpoints, even if\n\
16857 such is available.  (However, any hardware watchpoints that were\n\
16858 created before setting this to nonzero, will continue to use watchpoint\n\
16859 hardware.)"),
16860                             NULL,
16861                             show_can_use_hw_watchpoints,
16862                             &setlist, &showlist);
16863
16864   can_use_hw_watchpoints = 1;
16865
16866   /* Tracepoint manipulation commands.  */
16867
16868   c = add_com ("trace", class_breakpoint, trace_command, _("\
16869 Set a tracepoint at specified line or function.\n\
16870 \n"
16871 BREAK_ARGS_HELP ("trace") "\n\
16872 Do \"help tracepoints\" for info on other tracepoint commands."));
16873   set_cmd_completer (c, location_completer);
16874
16875   add_com_alias ("tp", "trace", class_alias, 0);
16876   add_com_alias ("tr", "trace", class_alias, 1);
16877   add_com_alias ("tra", "trace", class_alias, 1);
16878   add_com_alias ("trac", "trace", class_alias, 1);
16879
16880   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16881 Set a fast tracepoint at specified line or function.\n\
16882 \n"
16883 BREAK_ARGS_HELP ("ftrace") "\n\
16884 Do \"help tracepoints\" for info on other tracepoint commands."));
16885   set_cmd_completer (c, location_completer);
16886
16887   c = add_com ("strace", class_breakpoint, strace_command, _("\
16888 Set a static tracepoint at specified line, function or marker.\n\
16889 \n\
16890 strace [LOCATION] [if CONDITION]\n\
16891 LOCATION may be a line number, function name, \"*\" and an address,\n\
16892 or -m MARKER_ID.\n\
16893 If a line number is specified, probe the marker at start of code\n\
16894 for that line.  If a function is specified, probe the marker at start\n\
16895 of code for that function.  If an address is specified, probe the marker\n\
16896 at that exact address.  If a marker id is specified, probe the marker\n\
16897 with that name.  With no LOCATION, uses current execution address of\n\
16898 the selected stack frame.\n\
16899 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16900 This collects arbitrary user data passed in the probe point call to the\n\
16901 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16902 by printing the $_sdata variable like any other convenience variable.\n\
16903 \n\
16904 CONDITION is a boolean expression.\n\
16905 \n\
16906 Multiple tracepoints at one place are permitted, and useful if their\n\
16907 conditions are different.\n\
16908 \n\
16909 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16910 Do \"help tracepoints\" for info on other tracepoint commands."));
16911   set_cmd_completer (c, location_completer);
16912
16913   add_info ("tracepoints", tracepoints_info, _("\
16914 Status of specified tracepoints (all tracepoints if no argument).\n\
16915 Convenience variable \"$tpnum\" contains the number of the\n\
16916 last tracepoint set."));
16917
16918   add_info_alias ("tp", "tracepoints", 1);
16919
16920   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16921 Delete specified tracepoints.\n\
16922 Arguments are tracepoint numbers, separated by spaces.\n\
16923 No argument means delete all tracepoints."),
16924            &deletelist);
16925   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16926
16927   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16928 Disable specified tracepoints.\n\
16929 Arguments are tracepoint numbers, separated by spaces.\n\
16930 No argument means disable all tracepoints."),
16931            &disablelist);
16932   deprecate_cmd (c, "disable");
16933
16934   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16935 Enable specified tracepoints.\n\
16936 Arguments are tracepoint numbers, separated by spaces.\n\
16937 No argument means enable all tracepoints."),
16938            &enablelist);
16939   deprecate_cmd (c, "enable");
16940
16941   add_com ("passcount", class_trace, trace_pass_command, _("\
16942 Set the passcount for a tracepoint.\n\
16943 The trace will end when the tracepoint has been passed 'count' times.\n\
16944 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16945 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16946
16947   add_prefix_cmd ("save", class_breakpoint, save_command,
16948                   _("Save breakpoint definitions as a script."),
16949                   &save_cmdlist, "save ",
16950                   0/*allow-unknown*/, &cmdlist);
16951
16952   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16953 Save current breakpoint definitions as a script.\n\
16954 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16955 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16956 session to restore them."),
16957                &save_cmdlist);
16958   set_cmd_completer (c, filename_completer);
16959
16960   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16961 Save current tracepoint definitions as a script.\n\
16962 Use the 'source' command in another debug session to restore them."),
16963                &save_cmdlist);
16964   set_cmd_completer (c, filename_completer);
16965
16966   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16967   deprecate_cmd (c, "save tracepoints");
16968
16969   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16970 Breakpoint specific settings\n\
16971 Configure various breakpoint-specific variables such as\n\
16972 pending breakpoint behavior"),
16973                   &breakpoint_set_cmdlist, "set breakpoint ",
16974                   0/*allow-unknown*/, &setlist);
16975   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16976 Breakpoint specific settings\n\
16977 Configure various breakpoint-specific variables such as\n\
16978 pending breakpoint behavior"),
16979                   &breakpoint_show_cmdlist, "show breakpoint ",
16980                   0/*allow-unknown*/, &showlist);
16981
16982   add_setshow_auto_boolean_cmd ("pending", no_class,
16983                                 &pending_break_support, _("\
16984 Set debugger's behavior regarding pending breakpoints."), _("\
16985 Show debugger's behavior regarding pending breakpoints."), _("\
16986 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16987 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16988 an error.  If auto, an unrecognized breakpoint location results in a\n\
16989 user-query to see if a pending breakpoint should be created."),
16990                                 NULL,
16991                                 show_pending_break_support,
16992                                 &breakpoint_set_cmdlist,
16993                                 &breakpoint_show_cmdlist);
16994
16995   pending_break_support = AUTO_BOOLEAN_AUTO;
16996
16997   add_setshow_boolean_cmd ("auto-hw", no_class,
16998                            &automatic_hardware_breakpoints, _("\
16999 Set automatic usage of hardware breakpoints."), _("\
17000 Show automatic usage of hardware breakpoints."), _("\
17001 If set, the debugger will automatically use hardware breakpoints for\n\
17002 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
17003 a warning will be emitted for such breakpoints."),
17004                            NULL,
17005                            show_automatic_hardware_breakpoints,
17006                            &breakpoint_set_cmdlist,
17007                            &breakpoint_show_cmdlist);
17008
17009   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
17010                                 &always_inserted_mode, _("\
17011 Set mode for inserting breakpoints."), _("\
17012 Show mode for inserting breakpoints."), _("\
17013 When this mode is off, breakpoints are inserted in inferior when it is\n\
17014 resumed, and removed when execution stops.  When this mode is on,\n\
17015 breakpoints are inserted immediately and removed only when the user\n\
17016 deletes the breakpoint.  When this mode is auto (which is the default),\n\
17017 the behaviour depends on the non-stop setting (see help set non-stop).\n\
17018 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
17019 behaves as if always-inserted mode is on; if gdb is controlling the\n\
17020 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
17021                                 NULL,
17022                                 &show_always_inserted_mode,
17023                                 &breakpoint_set_cmdlist,
17024                                 &breakpoint_show_cmdlist);
17025
17026   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
17027                         condition_evaluation_enums,
17028                         &condition_evaluation_mode_1, _("\
17029 Set mode of breakpoint condition evaluation."), _("\
17030 Show mode of breakpoint condition evaluation."), _("\
17031 When this is set to \"host\", breakpoint conditions will be\n\
17032 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
17033 breakpoint conditions will be downloaded to the target (if the target\n\
17034 supports such feature) and conditions will be evaluated on the target's side.\n\
17035 If this is set to \"auto\" (default), this will be automatically set to\n\
17036 \"target\" if it supports condition evaluation, otherwise it will\n\
17037 be set to \"gdb\""),
17038                            &set_condition_evaluation_mode,
17039                            &show_condition_evaluation_mode,
17040                            &breakpoint_set_cmdlist,
17041                            &breakpoint_show_cmdlist);
17042
17043   add_com ("break-range", class_breakpoint, break_range_command, _("\
17044 Set a breakpoint for an address range.\n\
17045 break-range START-LOCATION, END-LOCATION\n\
17046 where START-LOCATION and END-LOCATION can be one of the following:\n\
17047   LINENUM, for that line in the current file,\n\
17048   FILE:LINENUM, for that line in that file,\n\
17049   +OFFSET, for that number of lines after the current line\n\
17050            or the start of the range\n\
17051   FUNCTION, for the first line in that function,\n\
17052   FILE:FUNCTION, to distinguish among like-named static functions.\n\
17053   *ADDRESS, for the instruction at that address.\n\
17054 \n\
17055 The breakpoint will stop execution of the inferior whenever it executes\n\
17056 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
17057 range (including START-LOCATION and END-LOCATION)."));
17058
17059   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
17060 Set a dynamic printf at specified line or function.\n\
17061 dprintf location,format string,arg1,arg2,...\n\
17062 location may be a line number, function name, or \"*\" and an address.\n\
17063 If a line number is specified, break at start of code for that line.\n\
17064 If a function is specified, break at start of code for that function."));
17065   set_cmd_completer (c, location_completer);
17066
17067   add_setshow_enum_cmd ("dprintf-style", class_support,
17068                         dprintf_style_enums, &dprintf_style, _("\
17069 Set the style of usage for dynamic printf."), _("\
17070 Show the style of usage for dynamic printf."), _("\
17071 This setting chooses how GDB will do a dynamic printf.\n\
17072 If the value is \"gdb\", then the printing is done by GDB to its own\n\
17073 console, as with the \"printf\" command.\n\
17074 If the value is \"call\", the print is done by calling a function in your\n\
17075 program; by default printf(), but you can choose a different function or\n\
17076 output stream by setting dprintf-function and dprintf-channel."),
17077                         update_dprintf_commands, NULL,
17078                         &setlist, &showlist);
17079
17080   dprintf_function = xstrdup ("printf");
17081   add_setshow_string_cmd ("dprintf-function", class_support,
17082                           &dprintf_function, _("\
17083 Set the function to use for dynamic printf"), _("\
17084 Show the function to use for dynamic printf"), NULL,
17085                           update_dprintf_commands, NULL,
17086                           &setlist, &showlist);
17087
17088   dprintf_channel = xstrdup ("");
17089   add_setshow_string_cmd ("dprintf-channel", class_support,
17090                           &dprintf_channel, _("\
17091 Set the channel to use for dynamic printf"), _("\
17092 Show the channel to use for dynamic printf"), NULL,
17093                           update_dprintf_commands, NULL,
17094                           &setlist, &showlist);
17095
17096   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
17097                            &disconnected_dprintf, _("\
17098 Set whether dprintf continues after GDB disconnects."), _("\
17099 Show whether dprintf continues after GDB disconnects."), _("\
17100 Use this to let dprintf commands continue to hit and produce output\n\
17101 even if GDB disconnects or detaches from the target."),
17102                            NULL,
17103                            NULL,
17104                            &setlist, &showlist);
17105
17106   add_com ("agent-printf", class_vars, agent_printf_command, _("\
17107 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
17108 (target agent only) This is useful for formatted output in user-defined commands."));
17109
17110   automatic_hardware_breakpoints = 1;
17111
17112   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
17113   observer_attach_thread_exit (remove_threaded_breakpoints);
17114 }
This page took 0.975427 seconds and 4 git commands to generate.