Tell update_global_location_list to insert breakpoints
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "exceptions.h"
55 #include "memattr.h"
56 #include "ada-lang.h"
57 #include "top.h"
58 #include "valprint.h"
59 #include "jit.h"
60 #include "xml-syscall.h"
61 #include "parser-defs.h"
62 #include "gdb_regex.h"
63 #include "probe.h"
64 #include "cli/cli-utils.h"
65 #include "continuations.h"
66 #include "stack.h"
67 #include "skip.h"
68 #include "ax-gdb.h"
69 #include "dummy-frame.h"
70
71 #include "format.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82
83 /* Enums for exception-handling support.  */
84 enum exception_event_kind
85 {
86   EX_EVENT_THROW,
87   EX_EVENT_RETHROW,
88   EX_EVENT_CATCH
89 };
90
91 /* Prototypes for local functions.  */
92
93 static void enable_delete_command (char *, int);
94
95 static void enable_once_command (char *, int);
96
97 static void enable_count_command (char *, int);
98
99 static void disable_command (char *, int);
100
101 static void enable_command (char *, int);
102
103 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
104                                                       void *),
105                                     void *);
106
107 static void ignore_command (char *, int);
108
109 static int breakpoint_re_set_one (void *);
110
111 static void breakpoint_re_set_default (struct breakpoint *);
112
113 static void create_sals_from_address_default (char **,
114                                               struct linespec_result *,
115                                               enum bptype, char *,
116                                               char **);
117
118 static void create_breakpoints_sal_default (struct gdbarch *,
119                                             struct linespec_result *,
120                                             char *, char *, enum bptype,
121                                             enum bpdisp, int, int,
122                                             int,
123                                             const struct breakpoint_ops *,
124                                             int, int, int, unsigned);
125
126 static void decode_linespec_default (struct breakpoint *, char **,
127                                      struct symtabs_and_lines *);
128
129 static void clear_command (char *, int);
130
131 static void catch_command (char *, int);
132
133 static int can_use_hardware_watchpoint (struct value *);
134
135 static void break_command_1 (char *, int, int);
136
137 static void mention (struct breakpoint *);
138
139 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
140                                                                enum bptype,
141                                                                const struct breakpoint_ops *);
142 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
143                                                        const struct symtab_and_line *);
144
145 /* This function is used in gdbtk sources and thus can not be made
146    static.  */
147 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
148                                        struct symtab_and_line,
149                                        enum bptype,
150                                        const struct breakpoint_ops *);
151
152 static struct breakpoint *
153   momentary_breakpoint_from_master (struct breakpoint *orig,
154                                     enum bptype type,
155                                     const struct breakpoint_ops *ops,
156                                     int loc_enabled);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int watchpoint_locations_match (struct bp_location *loc1,
169                                        struct bp_location *loc2);
170
171 static int breakpoint_location_address_match (struct bp_location *bl,
172                                               struct address_space *aspace,
173                                               CORE_ADDR addr);
174
175 static void breakpoints_info (char *, int);
176
177 static void watchpoints_info (char *, int);
178
179 static int breakpoint_1 (char *, int, 
180                          int (*) (const struct breakpoint *));
181
182 static int breakpoint_cond_eval (void *);
183
184 static void cleanup_executing_breakpoints (void *);
185
186 static void commands_command (char *, int);
187
188 static void condition_command (char *, int);
189
190 typedef enum
191   {
192     mark_inserted,
193     mark_uninserted
194   }
195 insertion_state_t;
196
197 static int remove_breakpoint (struct bp_location *, insertion_state_t);
198 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
199
200 static enum print_stop_action print_bp_stop_message (bpstat bs);
201
202 static int watchpoint_check (void *);
203
204 static void maintenance_info_breakpoints (char *, int);
205
206 static int hw_breakpoint_used_count (void);
207
208 static int hw_watchpoint_use_count (struct breakpoint *);
209
210 static int hw_watchpoint_used_count_others (struct breakpoint *except,
211                                             enum bptype type,
212                                             int *other_type_used);
213
214 static void hbreak_command (char *, int);
215
216 static void thbreak_command (char *, int);
217
218 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
219                                     int count);
220
221 static void stop_command (char *arg, int from_tty);
222
223 static void stopin_command (char *arg, int from_tty);
224
225 static void stopat_command (char *arg, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int find_single_step_breakpoint (struct address_space *aspace,
232                                         CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 /* 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   /* Insert locations now, even if breakpoints_always_inserted_mode is
266      false.  */
267   UGLL_INSERT
268 };
269
270 static void update_global_location_list (enum ugll_insert_mode);
271
272 static void update_global_location_list_nothrow (enum ugll_insert_mode);
273
274 static int is_hardware_watchpoint (const struct breakpoint *bpt);
275
276 static void insert_breakpoint_locations (void);
277
278 static int syscall_catchpoint_p (struct breakpoint *b);
279
280 static void tracepoints_info (char *, int);
281
282 static void delete_trace_command (char *, int);
283
284 static void enable_trace_command (char *, int);
285
286 static void disable_trace_command (char *, int);
287
288 static void trace_pass_command (char *, int);
289
290 static void set_tracepoint_count (int num);
291
292 static int is_masked_watchpoint (const struct breakpoint *b);
293
294 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
295
296 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
297    otherwise.  */
298
299 static int strace_marker_p (struct breakpoint *b);
300
301 /* The abstract base class all breakpoint_ops structures inherit
302    from.  */
303 struct breakpoint_ops base_breakpoint_ops;
304
305 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
306    that are implemented on top of software or hardware breakpoints
307    (user breakpoints, internal and momentary breakpoints, etc.).  */
308 static struct breakpoint_ops bkpt_base_breakpoint_ops;
309
310 /* Internal breakpoints class type.  */
311 static struct breakpoint_ops internal_breakpoint_ops;
312
313 /* Momentary breakpoints class type.  */
314 static struct breakpoint_ops momentary_breakpoint_ops;
315
316 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
317 static struct breakpoint_ops longjmp_breakpoint_ops;
318
319 /* The breakpoint_ops structure to be used in regular user created
320    breakpoints.  */
321 struct breakpoint_ops bkpt_breakpoint_ops;
322
323 /* Breakpoints set on probes.  */
324 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
325
326 /* Dynamic printf class type.  */
327 struct breakpoint_ops dprintf_breakpoint_ops;
328
329 /* One (or perhaps two) breakpoints used for software single
330    stepping.  */
331
332 static void *single_step_breakpoints[2];
333 static struct gdbarch *single_step_gdbarch[2];
334
335 /* The style in which to perform a dynamic printf.  This is a user
336    option because different output options have different tradeoffs;
337    if GDB does the printing, there is better error handling if there
338    is a problem with any of the arguments, but using an inferior
339    function lets you have special-purpose printers and sending of
340    output to the same place as compiled-in print functions.  */
341
342 static const char dprintf_style_gdb[] = "gdb";
343 static const char dprintf_style_call[] = "call";
344 static const char dprintf_style_agent[] = "agent";
345 static const char *const dprintf_style_enums[] = {
346   dprintf_style_gdb,
347   dprintf_style_call,
348   dprintf_style_agent,
349   NULL
350 };
351 static const char *dprintf_style = dprintf_style_gdb;
352
353 /* The function to use for dynamic printf if the preferred style is to
354    call into the inferior.  The value is simply a string that is
355    copied into the command, so it can be anything that GDB can
356    evaluate to a callable address, not necessarily a function name.  */
357
358 static char *dprintf_function = "";
359
360 /* The channel to use for dynamic printf if the preferred style is to
361    call into the inferior; if a nonempty string, it will be passed to
362    the call as the first argument, with the format string as the
363    second.  As with the dprintf function, this can be anything that
364    GDB knows how to evaluate, so in addition to common choices like
365    "stderr", this could be an app-specific expression like
366    "mystreams[curlogger]".  */
367
368 static char *dprintf_channel = "";
369
370 /* True if dprintf commands should continue to operate even if GDB
371    has disconnected.  */
372 static int disconnected_dprintf = 1;
373
374 /* A reference-counted struct command_line.  This lets multiple
375    breakpoints share a single command list.  */
376 struct counted_command_line
377 {
378   /* The reference count.  */
379   int refc;
380
381   /* The command list.  */
382   struct command_line *commands;
383 };
384
385 struct command_line *
386 breakpoint_commands (struct breakpoint *b)
387 {
388   return b->commands ? b->commands->commands : NULL;
389 }
390
391 /* Flag indicating that a command has proceeded the inferior past the
392    current breakpoint.  */
393
394 static int breakpoint_proceeded;
395
396 const char *
397 bpdisp_text (enum bpdisp disp)
398 {
399   /* NOTE: the following values are a part of MI protocol and
400      represent values of 'disp' field returned when inferior stops at
401      a breakpoint.  */
402   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
403
404   return bpdisps[(int) disp];
405 }
406
407 /* Prototypes for exported functions.  */
408 /* If FALSE, gdb will not use hardware support for watchpoints, even
409    if such is available.  */
410 static int can_use_hw_watchpoints;
411
412 static void
413 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
414                              struct cmd_list_element *c,
415                              const char *value)
416 {
417   fprintf_filtered (file,
418                     _("Debugger's willingness to use "
419                       "watchpoint hardware is %s.\n"),
420                     value);
421 }
422
423 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
424    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
425    for unrecognized breakpoint locations.
426    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
427 static enum auto_boolean pending_break_support;
428 static void
429 show_pending_break_support (struct ui_file *file, int from_tty,
430                             struct cmd_list_element *c,
431                             const char *value)
432 {
433   fprintf_filtered (file,
434                     _("Debugger's behavior regarding "
435                       "pending breakpoints is %s.\n"),
436                     value);
437 }
438
439 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
440    set with "break" but falling in read-only memory.
441    If 0, gdb will warn about such breakpoints, but won't automatically
442    use hardware breakpoints.  */
443 static int automatic_hardware_breakpoints;
444 static void
445 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
446                                      struct cmd_list_element *c,
447                                      const char *value)
448 {
449   fprintf_filtered (file,
450                     _("Automatic usage of hardware breakpoints is %s.\n"),
451                     value);
452 }
453
454 /* If on, gdb will keep breakpoints inserted even as inferior is
455    stopped, and immediately insert any new breakpoints.  If off, gdb
456    will insert breakpoints into inferior only when resuming it, and
457    will remove breakpoints upon stop.  If auto, GDB will behave as ON
458    if in non-stop mode, and as OFF if all-stop mode.*/
459
460 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
461
462 static void
463 show_always_inserted_mode (struct ui_file *file, int from_tty,
464                      struct cmd_list_element *c, const char *value)
465 {
466   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
467     fprintf_filtered (file,
468                       _("Always inserted breakpoint "
469                         "mode is %s (currently %s).\n"),
470                       value,
471                       breakpoints_always_inserted_mode () ? "on" : "off");
472   else
473     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
474                       value);
475 }
476
477 int
478 breakpoints_always_inserted_mode (void)
479 {
480   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
481           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
482 }
483
484 static const char condition_evaluation_both[] = "host or target";
485
486 /* Modes for breakpoint condition evaluation.  */
487 static const char condition_evaluation_auto[] = "auto";
488 static const char condition_evaluation_host[] = "host";
489 static const char condition_evaluation_target[] = "target";
490 static const char *const condition_evaluation_enums[] = {
491   condition_evaluation_auto,
492   condition_evaluation_host,
493   condition_evaluation_target,
494   NULL
495 };
496
497 /* Global that holds the current mode for breakpoint condition evaluation.  */
498 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
499
500 /* Global that we use to display information to the user (gets its value from
501    condition_evaluation_mode_1.  */
502 static const char *condition_evaluation_mode = condition_evaluation_auto;
503
504 /* Translate a condition evaluation mode MODE into either "host"
505    or "target".  This is used mostly to translate from "auto" to the
506    real setting that is being used.  It returns the translated
507    evaluation mode.  */
508
509 static const char *
510 translate_condition_evaluation_mode (const char *mode)
511 {
512   if (mode == condition_evaluation_auto)
513     {
514       if (target_supports_evaluation_of_breakpoint_conditions ())
515         return condition_evaluation_target;
516       else
517         return condition_evaluation_host;
518     }
519   else
520     return mode;
521 }
522
523 /* Discovers what condition_evaluation_auto translates to.  */
524
525 static const char *
526 breakpoint_condition_evaluation_mode (void)
527 {
528   return translate_condition_evaluation_mode (condition_evaluation_mode);
529 }
530
531 /* Return true if GDB should evaluate breakpoint conditions or false
532    otherwise.  */
533
534 static int
535 gdb_evaluates_breakpoint_condition_p (void)
536 {
537   const char *mode = breakpoint_condition_evaluation_mode ();
538
539   return (mode == condition_evaluation_host);
540 }
541
542 void _initialize_breakpoint (void);
543
544 /* Are we executing breakpoint commands?  */
545 static int executing_breakpoint_commands;
546
547 /* Are overlay event breakpoints enabled? */
548 static int overlay_events_enabled;
549
550 /* See description in breakpoint.h. */
551 int target_exact_watchpoints = 0;
552
553 /* Walk the following statement or block through all breakpoints.
554    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
555    current breakpoint.  */
556
557 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
558
559 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
560         for (B = breakpoint_chain;      \
561              B ? (TMP=B->next, 1): 0;   \
562              B = TMP)
563
564 /* Similar iterator for the low-level breakpoints.  SAFE variant is
565    not provided so update_global_location_list must not be called
566    while executing the block of ALL_BP_LOCATIONS.  */
567
568 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
569         for (BP_TMP = bp_location;                                      \
570              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
571              BP_TMP++)
572
573 /* Iterates through locations with address ADDRESS for the currently selected
574    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
575    to where the loop should start from.
576    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
577    appropriate location to start with.  */
578
579 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
580         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
581              BP_LOCP_TMP = BP_LOCP_START;                               \
582              BP_LOCP_START                                              \
583              && (BP_LOCP_TMP < bp_location + bp_location_count          \
584              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
585              BP_LOCP_TMP++)
586
587 /* Iterator for tracepoints only.  */
588
589 #define ALL_TRACEPOINTS(B)  \
590   for (B = breakpoint_chain; B; B = B->next)  \
591     if (is_tracepoint (B))
592
593 /* Chains of all breakpoints defined.  */
594
595 struct breakpoint *breakpoint_chain;
596
597 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
598
599 static struct bp_location **bp_location;
600
601 /* Number of elements of BP_LOCATION.  */
602
603 static unsigned bp_location_count;
604
605 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
606    ADDRESS for the current elements of BP_LOCATION which get a valid
607    result from bp_location_has_shadow.  You can use it for roughly
608    limiting the subrange of BP_LOCATION to scan for shadow bytes for
609    an address you need to read.  */
610
611 static CORE_ADDR bp_location_placed_address_before_address_max;
612
613 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
614    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
615    BP_LOCATION which get a valid result from bp_location_has_shadow.
616    You can use it for roughly limiting the subrange of BP_LOCATION to
617    scan for shadow bytes for an address you need to read.  */
618
619 static CORE_ADDR bp_location_shadow_len_after_address_max;
620
621 /* The locations that no longer correspond to any breakpoint, unlinked
622    from bp_location array, but for which a hit may still be reported
623    by a target.  */
624 VEC(bp_location_p) *moribund_locations = NULL;
625
626 /* Number of last breakpoint made.  */
627
628 static int breakpoint_count;
629
630 /* The value of `breakpoint_count' before the last command that
631    created breakpoints.  If the last (break-like) command created more
632    than one breakpoint, then the difference between BREAKPOINT_COUNT
633    and PREV_BREAKPOINT_COUNT is more than one.  */
634 static int prev_breakpoint_count;
635
636 /* Number of last tracepoint made.  */
637
638 static int tracepoint_count;
639
640 static struct cmd_list_element *breakpoint_set_cmdlist;
641 static struct cmd_list_element *breakpoint_show_cmdlist;
642 struct cmd_list_element *save_cmdlist;
643
644 /* Return whether a breakpoint is an active enabled breakpoint.  */
645 static int
646 breakpoint_enabled (struct breakpoint *b)
647 {
648   return (b->enable_state == bp_enabled);
649 }
650
651 /* Set breakpoint count to NUM.  */
652
653 static void
654 set_breakpoint_count (int num)
655 {
656   prev_breakpoint_count = breakpoint_count;
657   breakpoint_count = num;
658   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
659 }
660
661 /* Used by `start_rbreak_breakpoints' below, to record the current
662    breakpoint count before "rbreak" creates any breakpoint.  */
663 static int rbreak_start_breakpoint_count;
664
665 /* Called at the start an "rbreak" command to record the first
666    breakpoint made.  */
667
668 void
669 start_rbreak_breakpoints (void)
670 {
671   rbreak_start_breakpoint_count = breakpoint_count;
672 }
673
674 /* Called at the end of an "rbreak" command to record the last
675    breakpoint made.  */
676
677 void
678 end_rbreak_breakpoints (void)
679 {
680   prev_breakpoint_count = rbreak_start_breakpoint_count;
681 }
682
683 /* Used in run_command to zero the hit count when a new run starts.  */
684
685 void
686 clear_breakpoint_hit_counts (void)
687 {
688   struct breakpoint *b;
689
690   ALL_BREAKPOINTS (b)
691     b->hit_count = 0;
692 }
693
694 /* Allocate a new counted_command_line with reference count of 1.
695    The new structure owns COMMANDS.  */
696
697 static struct counted_command_line *
698 alloc_counted_command_line (struct command_line *commands)
699 {
700   struct counted_command_line *result
701     = xmalloc (sizeof (struct counted_command_line));
702
703   result->refc = 1;
704   result->commands = commands;
705   return result;
706 }
707
708 /* Increment reference count.  This does nothing if CMD is NULL.  */
709
710 static void
711 incref_counted_command_line (struct counted_command_line *cmd)
712 {
713   if (cmd)
714     ++cmd->refc;
715 }
716
717 /* Decrement reference count.  If the reference count reaches 0,
718    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
719    nothing if *CMDP is NULL.  */
720
721 static void
722 decref_counted_command_line (struct counted_command_line **cmdp)
723 {
724   if (*cmdp)
725     {
726       if (--(*cmdp)->refc == 0)
727         {
728           free_command_lines (&(*cmdp)->commands);
729           xfree (*cmdp);
730         }
731       *cmdp = NULL;
732     }
733 }
734
735 /* A cleanup function that calls decref_counted_command_line.  */
736
737 static void
738 do_cleanup_counted_command_line (void *arg)
739 {
740   decref_counted_command_line (arg);
741 }
742
743 /* Create a cleanup that calls decref_counted_command_line on the
744    argument.  */
745
746 static struct cleanup *
747 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
748 {
749   return make_cleanup (do_cleanup_counted_command_line, cmdp);
750 }
751
752 \f
753 /* Return the breakpoint with the specified number, or NULL
754    if the number does not refer to an existing breakpoint.  */
755
756 struct breakpoint *
757 get_breakpoint (int num)
758 {
759   struct breakpoint *b;
760
761   ALL_BREAKPOINTS (b)
762     if (b->number == num)
763       return b;
764   
765   return NULL;
766 }
767
768 \f
769
770 /* Mark locations as "conditions have changed" in case the target supports
771    evaluating conditions on its side.  */
772
773 static void
774 mark_breakpoint_modified (struct breakpoint *b)
775 {
776   struct bp_location *loc;
777
778   /* This is only meaningful if the target is
779      evaluating conditions and if the user has
780      opted for condition evaluation on the target's
781      side.  */
782   if (gdb_evaluates_breakpoint_condition_p ()
783       || !target_supports_evaluation_of_breakpoint_conditions ())
784     return;
785
786   if (!is_breakpoint (b))
787     return;
788
789   for (loc = b->loc; loc; loc = loc->next)
790     loc->condition_changed = condition_modified;
791 }
792
793 /* Mark location as "conditions have changed" in case the target supports
794    evaluating conditions on its side.  */
795
796 static void
797 mark_breakpoint_location_modified (struct bp_location *loc)
798 {
799   /* This is only meaningful if the target is
800      evaluating conditions and if the user has
801      opted for condition evaluation on the target's
802      side.  */
803   if (gdb_evaluates_breakpoint_condition_p ()
804       || !target_supports_evaluation_of_breakpoint_conditions ())
805
806     return;
807
808   if (!is_breakpoint (loc->owner))
809     return;
810
811   loc->condition_changed = condition_modified;
812 }
813
814 /* Sets the condition-evaluation mode using the static global
815    condition_evaluation_mode.  */
816
817 static void
818 set_condition_evaluation_mode (char *args, int from_tty,
819                                struct cmd_list_element *c)
820 {
821   const char *old_mode, *new_mode;
822
823   if ((condition_evaluation_mode_1 == condition_evaluation_target)
824       && !target_supports_evaluation_of_breakpoint_conditions ())
825     {
826       condition_evaluation_mode_1 = condition_evaluation_mode;
827       warning (_("Target does not support breakpoint condition evaluation.\n"
828                  "Using host evaluation mode instead."));
829       return;
830     }
831
832   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
833   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
834
835   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
836      settings was "auto".  */
837   condition_evaluation_mode = condition_evaluation_mode_1;
838
839   /* Only update the mode if the user picked a different one.  */
840   if (new_mode != old_mode)
841     {
842       struct bp_location *loc, **loc_tmp;
843       /* If the user switched to a different evaluation mode, we
844          need to synch the changes with the target as follows:
845
846          "host" -> "target": Send all (valid) conditions to the target.
847          "target" -> "host": Remove all the conditions from the target.
848       */
849
850       if (new_mode == condition_evaluation_target)
851         {
852           /* Mark everything modified and synch conditions with the
853              target.  */
854           ALL_BP_LOCATIONS (loc, loc_tmp)
855             mark_breakpoint_location_modified (loc);
856         }
857       else
858         {
859           /* Manually mark non-duplicate locations to synch conditions
860              with the target.  We do this to remove all the conditions the
861              target knows about.  */
862           ALL_BP_LOCATIONS (loc, loc_tmp)
863             if (is_breakpoint (loc->owner) && loc->inserted)
864               loc->needs_update = 1;
865         }
866
867       /* Do the update.  */
868       update_global_location_list (UGLL_MAY_INSERT);
869     }
870
871   return;
872 }
873
874 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
875    what "auto" is translating to.  */
876
877 static void
878 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
879                                 struct cmd_list_element *c, const char *value)
880 {
881   if (condition_evaluation_mode == condition_evaluation_auto)
882     fprintf_filtered (file,
883                       _("Breakpoint condition evaluation "
884                         "mode is %s (currently %s).\n"),
885                       value,
886                       breakpoint_condition_evaluation_mode ());
887   else
888     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
889                       value);
890 }
891
892 /* A comparison function for bp_location AP and BP that is used by
893    bsearch.  This comparison function only cares about addresses, unlike
894    the more general bp_location_compare function.  */
895
896 static int
897 bp_location_compare_addrs (const void *ap, const void *bp)
898 {
899   struct bp_location *a = *(void **) ap;
900   struct bp_location *b = *(void **) bp;
901
902   if (a->address == b->address)
903     return 0;
904   else
905     return ((a->address > b->address) - (a->address < b->address));
906 }
907
908 /* Helper function to skip all bp_locations with addresses
909    less than ADDRESS.  It returns the first bp_location that
910    is greater than or equal to ADDRESS.  If none is found, just
911    return NULL.  */
912
913 static struct bp_location **
914 get_first_locp_gte_addr (CORE_ADDR address)
915 {
916   struct bp_location dummy_loc;
917   struct bp_location *dummy_locp = &dummy_loc;
918   struct bp_location **locp_found = NULL;
919
920   /* Initialize the dummy location's address field.  */
921   memset (&dummy_loc, 0, sizeof (struct bp_location));
922   dummy_loc.address = address;
923
924   /* Find a close match to the first location at ADDRESS.  */
925   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
926                         sizeof (struct bp_location **),
927                         bp_location_compare_addrs);
928
929   /* Nothing was found, nothing left to do.  */
930   if (locp_found == NULL)
931     return NULL;
932
933   /* We may have found a location that is at ADDRESS but is not the first in the
934      location's list.  Go backwards (if possible) and locate the first one.  */
935   while ((locp_found - 1) >= bp_location
936          && (*(locp_found - 1))->address == address)
937     locp_found--;
938
939   return locp_found;
940 }
941
942 void
943 set_breakpoint_condition (struct breakpoint *b, char *exp,
944                           int from_tty)
945 {
946   xfree (b->cond_string);
947   b->cond_string = NULL;
948
949   if (is_watchpoint (b))
950     {
951       struct watchpoint *w = (struct watchpoint *) b;
952
953       xfree (w->cond_exp);
954       w->cond_exp = NULL;
955     }
956   else
957     {
958       struct bp_location *loc;
959
960       for (loc = b->loc; loc; loc = loc->next)
961         {
962           xfree (loc->cond);
963           loc->cond = NULL;
964
965           /* No need to free the condition agent expression
966              bytecode (if we have one).  We will handle this
967              when we go through update_global_location_list.  */
968         }
969     }
970
971   if (*exp == 0)
972     {
973       if (from_tty)
974         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
975     }
976   else
977     {
978       const char *arg = exp;
979
980       /* I don't know if it matters whether this is the string the user
981          typed in or the decompiled expression.  */
982       b->cond_string = xstrdup (arg);
983       b->condition_not_parsed = 0;
984
985       if (is_watchpoint (b))
986         {
987           struct watchpoint *w = (struct watchpoint *) b;
988
989           innermost_block = NULL;
990           arg = exp;
991           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
992           if (*arg)
993             error (_("Junk at end of expression"));
994           w->cond_exp_valid_block = innermost_block;
995         }
996       else
997         {
998           struct bp_location *loc;
999
1000           for (loc = b->loc; loc; loc = loc->next)
1001             {
1002               arg = exp;
1003               loc->cond =
1004                 parse_exp_1 (&arg, loc->address,
1005                              block_for_pc (loc->address), 0);
1006               if (*arg)
1007                 error (_("Junk at end of expression"));
1008             }
1009         }
1010     }
1011   mark_breakpoint_modified (b);
1012
1013   observer_notify_breakpoint_modified (b);
1014 }
1015
1016 /* Completion for the "condition" command.  */
1017
1018 static VEC (char_ptr) *
1019 condition_completer (struct cmd_list_element *cmd,
1020                      const char *text, const char *word)
1021 {
1022   const char *space;
1023
1024   text = skip_spaces_const (text);
1025   space = skip_to_space_const (text);
1026   if (*space == '\0')
1027     {
1028       int len;
1029       struct breakpoint *b;
1030       VEC (char_ptr) *result = NULL;
1031
1032       if (text[0] == '$')
1033         {
1034           /* We don't support completion of history indices.  */
1035           if (isdigit (text[1]))
1036             return NULL;
1037           return complete_internalvar (&text[1]);
1038         }
1039
1040       /* We're completing the breakpoint number.  */
1041       len = strlen (text);
1042
1043       ALL_BREAKPOINTS (b)
1044         {
1045           char number[50];
1046
1047           xsnprintf (number, sizeof (number), "%d", b->number);
1048
1049           if (strncmp (number, text, len) == 0)
1050             VEC_safe_push (char_ptr, result, xstrdup (number));
1051         }
1052
1053       return result;
1054     }
1055
1056   /* We're completing the expression part.  */
1057   text = skip_spaces_const (space);
1058   return expression_completer (cmd, text, word);
1059 }
1060
1061 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1062
1063 static void
1064 condition_command (char *arg, int from_tty)
1065 {
1066   struct breakpoint *b;
1067   char *p;
1068   int bnum;
1069
1070   if (arg == 0)
1071     error_no_arg (_("breakpoint number"));
1072
1073   p = arg;
1074   bnum = get_number (&p);
1075   if (bnum == 0)
1076     error (_("Bad breakpoint argument: '%s'"), arg);
1077
1078   ALL_BREAKPOINTS (b)
1079     if (b->number == bnum)
1080       {
1081         /* Check if this breakpoint has a "stop" method implemented in an
1082            extension language.  This method and conditions entered into GDB
1083            from the CLI are mutually exclusive.  */
1084         const struct extension_language_defn *extlang
1085           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1086
1087         if (extlang != NULL)
1088           {
1089             error (_("Only one stop condition allowed.  There is currently"
1090                      " a %s stop condition defined for this breakpoint."),
1091                    ext_lang_capitalized_name (extlang));
1092           }
1093         set_breakpoint_condition (b, p, from_tty);
1094
1095         if (is_breakpoint (b))
1096           update_global_location_list (UGLL_MAY_INSERT);
1097
1098         return;
1099       }
1100
1101   error (_("No breakpoint number %d."), bnum);
1102 }
1103
1104 /* Check that COMMAND do not contain commands that are suitable
1105    only for tracepoints and not suitable for ordinary breakpoints.
1106    Throw if any such commands is found.  */
1107
1108 static void
1109 check_no_tracepoint_commands (struct command_line *commands)
1110 {
1111   struct command_line *c;
1112
1113   for (c = commands; c; c = c->next)
1114     {
1115       int i;
1116
1117       if (c->control_type == while_stepping_control)
1118         error (_("The 'while-stepping' command can "
1119                  "only be used for tracepoints"));
1120
1121       for (i = 0; i < c->body_count; ++i)
1122         check_no_tracepoint_commands ((c->body_list)[i]);
1123
1124       /* Not that command parsing removes leading whitespace and comment
1125          lines and also empty lines.  So, we only need to check for
1126          command directly.  */
1127       if (strstr (c->line, "collect ") == c->line)
1128         error (_("The 'collect' command can only be used for tracepoints"));
1129
1130       if (strstr (c->line, "teval ") == c->line)
1131         error (_("The 'teval' command can only be used for tracepoints"));
1132     }
1133 }
1134
1135 /* Encapsulate tests for different types of tracepoints.  */
1136
1137 static int
1138 is_tracepoint_type (enum bptype type)
1139 {
1140   return (type == bp_tracepoint
1141           || type == bp_fast_tracepoint
1142           || type == bp_static_tracepoint);
1143 }
1144
1145 int
1146 is_tracepoint (const struct breakpoint *b)
1147 {
1148   return is_tracepoint_type (b->type);
1149 }
1150
1151 /* A helper function that validates that COMMANDS are valid for a
1152    breakpoint.  This function will throw an exception if a problem is
1153    found.  */
1154
1155 static void
1156 validate_commands_for_breakpoint (struct breakpoint *b,
1157                                   struct command_line *commands)
1158 {
1159   if (is_tracepoint (b))
1160     {
1161       struct tracepoint *t = (struct tracepoint *) b;
1162       struct command_line *c;
1163       struct command_line *while_stepping = 0;
1164
1165       /* Reset the while-stepping step count.  The previous commands
1166          might have included a while-stepping action, while the new
1167          ones might not.  */
1168       t->step_count = 0;
1169
1170       /* We need to verify that each top-level element of commands is
1171          valid for tracepoints, that there's at most one
1172          while-stepping element, and that the while-stepping's body
1173          has valid tracing commands excluding nested while-stepping.
1174          We also need to validate the tracepoint action line in the
1175          context of the tracepoint --- validate_actionline actually
1176          has side effects, like setting the tracepoint's
1177          while-stepping STEP_COUNT, in addition to checking if the
1178          collect/teval actions parse and make sense in the
1179          tracepoint's context.  */
1180       for (c = commands; c; c = c->next)
1181         {
1182           if (c->control_type == while_stepping_control)
1183             {
1184               if (b->type == bp_fast_tracepoint)
1185                 error (_("The 'while-stepping' command "
1186                          "cannot be used for fast tracepoint"));
1187               else if (b->type == bp_static_tracepoint)
1188                 error (_("The 'while-stepping' command "
1189                          "cannot be used for static tracepoint"));
1190
1191               if (while_stepping)
1192                 error (_("The 'while-stepping' command "
1193                          "can be used only once"));
1194               else
1195                 while_stepping = c;
1196             }
1197
1198           validate_actionline (c->line, b);
1199         }
1200       if (while_stepping)
1201         {
1202           struct command_line *c2;
1203
1204           gdb_assert (while_stepping->body_count == 1);
1205           c2 = while_stepping->body_list[0];
1206           for (; c2; c2 = c2->next)
1207             {
1208               if (c2->control_type == while_stepping_control)
1209                 error (_("The 'while-stepping' command cannot be nested"));
1210             }
1211         }
1212     }
1213   else
1214     {
1215       check_no_tracepoint_commands (commands);
1216     }
1217 }
1218
1219 /* Return a vector of all the static tracepoints set at ADDR.  The
1220    caller is responsible for releasing the vector.  */
1221
1222 VEC(breakpoint_p) *
1223 static_tracepoints_here (CORE_ADDR addr)
1224 {
1225   struct breakpoint *b;
1226   VEC(breakpoint_p) *found = 0;
1227   struct bp_location *loc;
1228
1229   ALL_BREAKPOINTS (b)
1230     if (b->type == bp_static_tracepoint)
1231       {
1232         for (loc = b->loc; loc; loc = loc->next)
1233           if (loc->address == addr)
1234             VEC_safe_push(breakpoint_p, found, b);
1235       }
1236
1237   return found;
1238 }
1239
1240 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1241    validate that only allowed commands are included.  */
1242
1243 void
1244 breakpoint_set_commands (struct breakpoint *b, 
1245                          struct command_line *commands)
1246 {
1247   validate_commands_for_breakpoint (b, commands);
1248
1249   decref_counted_command_line (&b->commands);
1250   b->commands = alloc_counted_command_line (commands);
1251   observer_notify_breakpoint_modified (b);
1252 }
1253
1254 /* Set the internal `silent' flag on the breakpoint.  Note that this
1255    is not the same as the "silent" that may appear in the breakpoint's
1256    commands.  */
1257
1258 void
1259 breakpoint_set_silent (struct breakpoint *b, int silent)
1260 {
1261   int old_silent = b->silent;
1262
1263   b->silent = silent;
1264   if (old_silent != silent)
1265     observer_notify_breakpoint_modified (b);
1266 }
1267
1268 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1269    breakpoint work for any thread.  */
1270
1271 void
1272 breakpoint_set_thread (struct breakpoint *b, int thread)
1273 {
1274   int old_thread = b->thread;
1275
1276   b->thread = thread;
1277   if (old_thread != thread)
1278     observer_notify_breakpoint_modified (b);
1279 }
1280
1281 /* Set the task for this breakpoint.  If TASK is 0, make the
1282    breakpoint work for any task.  */
1283
1284 void
1285 breakpoint_set_task (struct breakpoint *b, int task)
1286 {
1287   int old_task = b->task;
1288
1289   b->task = task;
1290   if (old_task != task)
1291     observer_notify_breakpoint_modified (b);
1292 }
1293
1294 void
1295 check_tracepoint_command (char *line, void *closure)
1296 {
1297   struct breakpoint *b = closure;
1298
1299   validate_actionline (line, b);
1300 }
1301
1302 /* A structure used to pass information through
1303    map_breakpoint_numbers.  */
1304
1305 struct commands_info
1306 {
1307   /* True if the command was typed at a tty.  */
1308   int from_tty;
1309
1310   /* The breakpoint range spec.  */
1311   char *arg;
1312
1313   /* Non-NULL if the body of the commands are being read from this
1314      already-parsed command.  */
1315   struct command_line *control;
1316
1317   /* The command lines read from the user, or NULL if they have not
1318      yet been read.  */
1319   struct counted_command_line *cmd;
1320 };
1321
1322 /* A callback for map_breakpoint_numbers that sets the commands for
1323    commands_command.  */
1324
1325 static void
1326 do_map_commands_command (struct breakpoint *b, void *data)
1327 {
1328   struct commands_info *info = data;
1329
1330   if (info->cmd == NULL)
1331     {
1332       struct command_line *l;
1333
1334       if (info->control != NULL)
1335         l = copy_command_lines (info->control->body_list[0]);
1336       else
1337         {
1338           struct cleanup *old_chain;
1339           char *str;
1340
1341           str = xstrprintf (_("Type commands for breakpoint(s) "
1342                               "%s, one per line."),
1343                             info->arg);
1344
1345           old_chain = make_cleanup (xfree, str);
1346
1347           l = read_command_lines (str,
1348                                   info->from_tty, 1,
1349                                   (is_tracepoint (b)
1350                                    ? check_tracepoint_command : 0),
1351                                   b);
1352
1353           do_cleanups (old_chain);
1354         }
1355
1356       info->cmd = alloc_counted_command_line (l);
1357     }
1358
1359   /* If a breakpoint was on the list more than once, we don't need to
1360      do anything.  */
1361   if (b->commands != info->cmd)
1362     {
1363       validate_commands_for_breakpoint (b, info->cmd->commands);
1364       incref_counted_command_line (info->cmd);
1365       decref_counted_command_line (&b->commands);
1366       b->commands = info->cmd;
1367       observer_notify_breakpoint_modified (b);
1368     }
1369 }
1370
1371 static void
1372 commands_command_1 (char *arg, int from_tty, 
1373                     struct command_line *control)
1374 {
1375   struct cleanup *cleanups;
1376   struct commands_info info;
1377
1378   info.from_tty = from_tty;
1379   info.control = control;
1380   info.cmd = NULL;
1381   /* If we read command lines from the user, then `info' will hold an
1382      extra reference to the commands that we must clean up.  */
1383   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1384
1385   if (arg == NULL || !*arg)
1386     {
1387       if (breakpoint_count - prev_breakpoint_count > 1)
1388         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1389                           breakpoint_count);
1390       else if (breakpoint_count > 0)
1391         arg = xstrprintf ("%d", breakpoint_count);
1392       else
1393         {
1394           /* So that we don't try to free the incoming non-NULL
1395              argument in the cleanup below.  Mapping breakpoint
1396              numbers will fail in this case.  */
1397           arg = NULL;
1398         }
1399     }
1400   else
1401     /* The command loop has some static state, so we need to preserve
1402        our argument.  */
1403     arg = xstrdup (arg);
1404
1405   if (arg != NULL)
1406     make_cleanup (xfree, arg);
1407
1408   info.arg = arg;
1409
1410   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1411
1412   if (info.cmd == NULL)
1413     error (_("No breakpoints specified."));
1414
1415   do_cleanups (cleanups);
1416 }
1417
1418 static void
1419 commands_command (char *arg, int from_tty)
1420 {
1421   commands_command_1 (arg, from_tty, NULL);
1422 }
1423
1424 /* Like commands_command, but instead of reading the commands from
1425    input stream, takes them from an already parsed command structure.
1426
1427    This is used by cli-script.c to DTRT with breakpoint commands
1428    that are part of if and while bodies.  */
1429 enum command_control_type
1430 commands_from_control_command (char *arg, struct command_line *cmd)
1431 {
1432   commands_command_1 (arg, 0, cmd);
1433   return simple_control;
1434 }
1435
1436 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1437
1438 static int
1439 bp_location_has_shadow (struct bp_location *bl)
1440 {
1441   if (bl->loc_type != bp_loc_software_breakpoint)
1442     return 0;
1443   if (!bl->inserted)
1444     return 0;
1445   if (bl->target_info.shadow_len == 0)
1446     /* BL isn't valid, or doesn't shadow memory.  */
1447     return 0;
1448   return 1;
1449 }
1450
1451 /* Update BUF, which is LEN bytes read from the target address
1452    MEMADDR, by replacing a memory breakpoint with its shadowed
1453    contents.
1454
1455    If READBUF is not NULL, this buffer must not overlap with the of
1456    the breakpoint location's shadow_contents buffer.  Otherwise, a
1457    failed assertion internal error will be raised.  */
1458
1459 static void
1460 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1461                             const gdb_byte *writebuf_org,
1462                             ULONGEST memaddr, LONGEST len,
1463                             struct bp_target_info *target_info,
1464                             struct gdbarch *gdbarch)
1465 {
1466   /* Now do full processing of the found relevant range of elements.  */
1467   CORE_ADDR bp_addr = 0;
1468   int bp_size = 0;
1469   int bptoffset = 0;
1470
1471   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1472                                  current_program_space->aspace, 0))
1473     {
1474       /* The breakpoint is inserted in a different address space.  */
1475       return;
1476     }
1477
1478   /* Addresses and length of the part of the breakpoint that
1479      we need to copy.  */
1480   bp_addr = target_info->placed_address;
1481   bp_size = target_info->shadow_len;
1482
1483   if (bp_addr + bp_size <= memaddr)
1484     {
1485       /* The breakpoint is entirely before the chunk of memory we are
1486          reading.  */
1487       return;
1488     }
1489
1490   if (bp_addr >= memaddr + len)
1491     {
1492       /* The breakpoint is entirely after the chunk of memory we are
1493          reading.  */
1494       return;
1495     }
1496
1497   /* Offset within shadow_contents.  */
1498   if (bp_addr < memaddr)
1499     {
1500       /* Only copy the second part of the breakpoint.  */
1501       bp_size -= memaddr - bp_addr;
1502       bptoffset = memaddr - bp_addr;
1503       bp_addr = memaddr;
1504     }
1505
1506   if (bp_addr + bp_size > memaddr + len)
1507     {
1508       /* Only copy the first part of the breakpoint.  */
1509       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1510     }
1511
1512   if (readbuf != NULL)
1513     {
1514       /* Verify that the readbuf buffer does not overlap with the
1515          shadow_contents buffer.  */
1516       gdb_assert (target_info->shadow_contents >= readbuf + len
1517                   || readbuf >= (target_info->shadow_contents
1518                                  + target_info->shadow_len));
1519
1520       /* Update the read buffer with this inserted breakpoint's
1521          shadow.  */
1522       memcpy (readbuf + bp_addr - memaddr,
1523               target_info->shadow_contents + bptoffset, bp_size);
1524     }
1525   else
1526     {
1527       const unsigned char *bp;
1528       CORE_ADDR placed_address = target_info->placed_address;
1529       int placed_size = target_info->placed_size;
1530
1531       /* Update the shadow with what we want to write to memory.  */
1532       memcpy (target_info->shadow_contents + bptoffset,
1533               writebuf_org + bp_addr - memaddr, bp_size);
1534
1535       /* Determine appropriate breakpoint contents and size for this
1536          address.  */
1537       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1538
1539       /* Update the final write buffer with this inserted
1540          breakpoint's INSN.  */
1541       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1542     }
1543 }
1544
1545 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1546    by replacing any memory breakpoints with their shadowed contents.
1547
1548    If READBUF is not NULL, this buffer must not overlap with any of
1549    the breakpoint location's shadow_contents buffers.  Otherwise,
1550    a failed assertion internal error will be raised.
1551
1552    The range of shadowed area by each bp_location is:
1553      bl->address - bp_location_placed_address_before_address_max
1554      up to bl->address + bp_location_shadow_len_after_address_max
1555    The range we were requested to resolve shadows for is:
1556      memaddr ... memaddr + len
1557    Thus the safe cutoff boundaries for performance optimization are
1558      memaddr + len <= (bl->address
1559                        - bp_location_placed_address_before_address_max)
1560    and:
1561      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1562
1563 void
1564 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1565                         const gdb_byte *writebuf_org,
1566                         ULONGEST memaddr, LONGEST len)
1567 {
1568   /* Left boundary, right boundary and median element of our binary
1569      search.  */
1570   unsigned bc_l, bc_r, bc;
1571   size_t i;
1572
1573   /* Find BC_L which is a leftmost element which may affect BUF
1574      content.  It is safe to report lower value but a failure to
1575      report higher one.  */
1576
1577   bc_l = 0;
1578   bc_r = bp_location_count;
1579   while (bc_l + 1 < bc_r)
1580     {
1581       struct bp_location *bl;
1582
1583       bc = (bc_l + bc_r) / 2;
1584       bl = bp_location[bc];
1585
1586       /* Check first BL->ADDRESS will not overflow due to the added
1587          constant.  Then advance the left boundary only if we are sure
1588          the BC element can in no way affect the BUF content (MEMADDR
1589          to MEMADDR + LEN range).
1590
1591          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1592          offset so that we cannot miss a breakpoint with its shadow
1593          range tail still reaching MEMADDR.  */
1594
1595       if ((bl->address + bp_location_shadow_len_after_address_max
1596            >= bl->address)
1597           && (bl->address + bp_location_shadow_len_after_address_max
1598               <= memaddr))
1599         bc_l = bc;
1600       else
1601         bc_r = bc;
1602     }
1603
1604   /* Due to the binary search above, we need to make sure we pick the
1605      first location that's at BC_L's address.  E.g., if there are
1606      multiple locations at the same address, BC_L may end up pointing
1607      at a duplicate location, and miss the "master"/"inserted"
1608      location.  Say, given locations L1, L2 and L3 at addresses A and
1609      B:
1610
1611       L1@A, L2@A, L3@B, ...
1612
1613      BC_L could end up pointing at location L2, while the "master"
1614      location could be L1.  Since the `loc->inserted' flag is only set
1615      on "master" locations, we'd forget to restore the shadow of L1
1616      and L2.  */
1617   while (bc_l > 0
1618          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1619     bc_l--;
1620
1621   /* Now do full processing of the found relevant range of elements.  */
1622
1623   for (bc = bc_l; bc < bp_location_count; bc++)
1624   {
1625     struct bp_location *bl = bp_location[bc];
1626     CORE_ADDR bp_addr = 0;
1627     int bp_size = 0;
1628     int bptoffset = 0;
1629
1630     /* bp_location array has BL->OWNER always non-NULL.  */
1631     if (bl->owner->type == bp_none)
1632       warning (_("reading through apparently deleted breakpoint #%d?"),
1633                bl->owner->number);
1634
1635     /* Performance optimization: any further element can no longer affect BUF
1636        content.  */
1637
1638     if (bl->address >= bp_location_placed_address_before_address_max
1639         && memaddr + len <= (bl->address
1640                              - bp_location_placed_address_before_address_max))
1641       break;
1642
1643     if (!bp_location_has_shadow (bl))
1644       continue;
1645
1646     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1647                                 memaddr, len, &bl->target_info, bl->gdbarch);
1648   }
1649
1650   /* Now process single-step breakpoints.  These are not found in the
1651      bp_location array.  */
1652   for (i = 0; i < 2; i++)
1653     {
1654       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1655
1656       if (bp_tgt != NULL)
1657         {
1658           struct gdbarch *gdbarch = single_step_gdbarch[i];
1659
1660           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1661                                       memaddr, len, bp_tgt, gdbarch);
1662         }
1663     }
1664 }
1665
1666 \f
1667
1668 /* Return true if BPT is either a software breakpoint or a hardware
1669    breakpoint.  */
1670
1671 int
1672 is_breakpoint (const struct breakpoint *bpt)
1673 {
1674   return (bpt->type == bp_breakpoint
1675           || bpt->type == bp_hardware_breakpoint
1676           || bpt->type == bp_dprintf);
1677 }
1678
1679 /* Return true if BPT is of any hardware watchpoint kind.  */
1680
1681 static int
1682 is_hardware_watchpoint (const struct breakpoint *bpt)
1683 {
1684   return (bpt->type == bp_hardware_watchpoint
1685           || bpt->type == bp_read_watchpoint
1686           || bpt->type == bp_access_watchpoint);
1687 }
1688
1689 /* Return true if BPT is of any watchpoint kind, hardware or
1690    software.  */
1691
1692 int
1693 is_watchpoint (const struct breakpoint *bpt)
1694 {
1695   return (is_hardware_watchpoint (bpt)
1696           || bpt->type == bp_watchpoint);
1697 }
1698
1699 /* Returns true if the current thread and its running state are safe
1700    to evaluate or update watchpoint B.  Watchpoints on local
1701    expressions need to be evaluated in the context of the thread that
1702    was current when the watchpoint was created, and, that thread needs
1703    to be stopped to be able to select the correct frame context.
1704    Watchpoints on global expressions can be evaluated on any thread,
1705    and in any state.  It is presently left to the target allowing
1706    memory accesses when threads are running.  */
1707
1708 static int
1709 watchpoint_in_thread_scope (struct watchpoint *b)
1710 {
1711   return (b->base.pspace == current_program_space
1712           && (ptid_equal (b->watchpoint_thread, null_ptid)
1713               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1714                   && !is_executing (inferior_ptid))));
1715 }
1716
1717 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1718    associated bp_watchpoint_scope breakpoint.  */
1719
1720 static void
1721 watchpoint_del_at_next_stop (struct watchpoint *w)
1722 {
1723   struct breakpoint *b = &w->base;
1724
1725   if (b->related_breakpoint != b)
1726     {
1727       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1728       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1729       b->related_breakpoint->disposition = disp_del_at_next_stop;
1730       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1731       b->related_breakpoint = b;
1732     }
1733   b->disposition = disp_del_at_next_stop;
1734 }
1735
1736 /* Extract a bitfield value from value VAL using the bit parameters contained in
1737    watchpoint W.  */
1738
1739 static struct value *
1740 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1741 {
1742   struct value *bit_val;
1743
1744   if (val == NULL)
1745     return NULL;
1746
1747   bit_val = allocate_value (value_type (val));
1748
1749   unpack_value_bitfield (bit_val,
1750                          w->val_bitpos,
1751                          w->val_bitsize,
1752                          value_contents_for_printing (val),
1753                          value_offset (val),
1754                          val);
1755
1756   return bit_val;
1757 }
1758
1759 /* Assuming that B is a watchpoint:
1760    - Reparse watchpoint expression, if REPARSE is non-zero
1761    - Evaluate expression and store the result in B->val
1762    - Evaluate the condition if there is one, and store the result
1763      in b->loc->cond.
1764    - Update the list of values that must be watched in B->loc.
1765
1766    If the watchpoint disposition is disp_del_at_next_stop, then do
1767    nothing.  If this is local watchpoint that is out of scope, delete
1768    it.
1769
1770    Even with `set breakpoint always-inserted on' the watchpoints are
1771    removed + inserted on each stop here.  Normal breakpoints must
1772    never be removed because they might be missed by a running thread
1773    when debugging in non-stop mode.  On the other hand, hardware
1774    watchpoints (is_hardware_watchpoint; processed here) are specific
1775    to each LWP since they are stored in each LWP's hardware debug
1776    registers.  Therefore, such LWP must be stopped first in order to
1777    be able to modify its hardware watchpoints.
1778
1779    Hardware watchpoints must be reset exactly once after being
1780    presented to the user.  It cannot be done sooner, because it would
1781    reset the data used to present the watchpoint hit to the user.  And
1782    it must not be done later because it could display the same single
1783    watchpoint hit during multiple GDB stops.  Note that the latter is
1784    relevant only to the hardware watchpoint types bp_read_watchpoint
1785    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1786    not user-visible - its hit is suppressed if the memory content has
1787    not changed.
1788
1789    The following constraints influence the location where we can reset
1790    hardware watchpoints:
1791
1792    * target_stopped_by_watchpoint and target_stopped_data_address are
1793      called several times when GDB stops.
1794
1795    [linux] 
1796    * Multiple hardware watchpoints can be hit at the same time,
1797      causing GDB to stop.  GDB only presents one hardware watchpoint
1798      hit at a time as the reason for stopping, and all the other hits
1799      are presented later, one after the other, each time the user
1800      requests the execution to be resumed.  Execution is not resumed
1801      for the threads still having pending hit event stored in
1802      LWP_INFO->STATUS.  While the watchpoint is already removed from
1803      the inferior on the first stop the thread hit event is kept being
1804      reported from its cached value by linux_nat_stopped_data_address
1805      until the real thread resume happens after the watchpoint gets
1806      presented and thus its LWP_INFO->STATUS gets reset.
1807
1808    Therefore the hardware watchpoint hit can get safely reset on the
1809    watchpoint removal from inferior.  */
1810
1811 static void
1812 update_watchpoint (struct watchpoint *b, int reparse)
1813 {
1814   int within_current_scope;
1815   struct frame_id saved_frame_id;
1816   int frame_saved;
1817
1818   /* If this is a local watchpoint, we only want to check if the
1819      watchpoint frame is in scope if the current thread is the thread
1820      that was used to create the watchpoint.  */
1821   if (!watchpoint_in_thread_scope (b))
1822     return;
1823
1824   if (b->base.disposition == disp_del_at_next_stop)
1825     return;
1826  
1827   frame_saved = 0;
1828
1829   /* Determine if the watchpoint is within scope.  */
1830   if (b->exp_valid_block == NULL)
1831     within_current_scope = 1;
1832   else
1833     {
1834       struct frame_info *fi = get_current_frame ();
1835       struct gdbarch *frame_arch = get_frame_arch (fi);
1836       CORE_ADDR frame_pc = get_frame_pc (fi);
1837
1838       /* If we're in a function epilogue, unwinding may not work
1839          properly, so do not attempt to recreate locations at this
1840          point.  See similar comments in watchpoint_check.  */
1841       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1842         return;
1843
1844       /* Save the current frame's ID so we can restore it after
1845          evaluating the watchpoint expression on its own frame.  */
1846       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1847          took a frame parameter, so that we didn't have to change the
1848          selected frame.  */
1849       frame_saved = 1;
1850       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1851
1852       fi = frame_find_by_id (b->watchpoint_frame);
1853       within_current_scope = (fi != NULL);
1854       if (within_current_scope)
1855         select_frame (fi);
1856     }
1857
1858   /* We don't free locations.  They are stored in the bp_location array
1859      and update_global_location_list will eventually delete them and
1860      remove breakpoints if needed.  */
1861   b->base.loc = NULL;
1862
1863   if (within_current_scope && reparse)
1864     {
1865       const char *s;
1866
1867       if (b->exp)
1868         {
1869           xfree (b->exp);
1870           b->exp = NULL;
1871         }
1872       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1873       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1874       /* If the meaning of expression itself changed, the old value is
1875          no longer relevant.  We don't want to report a watchpoint hit
1876          to the user when the old value and the new value may actually
1877          be completely different objects.  */
1878       value_free (b->val);
1879       b->val = NULL;
1880       b->val_valid = 0;
1881
1882       /* Note that unlike with breakpoints, the watchpoint's condition
1883          expression is stored in the breakpoint object, not in the
1884          locations (re)created below.  */
1885       if (b->base.cond_string != NULL)
1886         {
1887           if (b->cond_exp != NULL)
1888             {
1889               xfree (b->cond_exp);
1890               b->cond_exp = NULL;
1891             }
1892
1893           s = b->base.cond_string;
1894           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1895         }
1896     }
1897
1898   /* If we failed to parse the expression, for example because
1899      it refers to a global variable in a not-yet-loaded shared library,
1900      don't try to insert watchpoint.  We don't automatically delete
1901      such watchpoint, though, since failure to parse expression
1902      is different from out-of-scope watchpoint.  */
1903   if (!target_has_execution)
1904     {
1905       /* Without execution, memory can't change.  No use to try and
1906          set watchpoint locations.  The watchpoint will be reset when
1907          the target gains execution, through breakpoint_re_set.  */
1908       if (!can_use_hw_watchpoints)
1909         {
1910           if (b->base.ops->works_in_software_mode (&b->base))
1911             b->base.type = bp_watchpoint;
1912           else
1913             error (_("Can't set read/access watchpoint when "
1914                      "hardware watchpoints are disabled."));
1915         }
1916     }
1917   else if (within_current_scope && b->exp)
1918     {
1919       int pc = 0;
1920       struct value *val_chain, *v, *result, *next;
1921       struct program_space *frame_pspace;
1922
1923       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1924
1925       /* Avoid setting b->val if it's already set.  The meaning of
1926          b->val is 'the last value' user saw, and we should update
1927          it only if we reported that last value to user.  As it
1928          happens, the code that reports it updates b->val directly.
1929          We don't keep track of the memory value for masked
1930          watchpoints.  */
1931       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1932         {
1933           if (b->val_bitsize != 0)
1934             {
1935               v = extract_bitfield_from_watchpoint_value (b, v);
1936               if (v != NULL)
1937                 release_value (v);
1938             }
1939           b->val = v;
1940           b->val_valid = 1;
1941         }
1942
1943       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1944
1945       /* Look at each value on the value chain.  */
1946       for (v = val_chain; v; v = value_next (v))
1947         {
1948           /* If it's a memory location, and GDB actually needed
1949              its contents to evaluate the expression, then we
1950              must watch it.  If the first value returned is
1951              still lazy, that means an error occurred reading it;
1952              watch it anyway in case it becomes readable.  */
1953           if (VALUE_LVAL (v) == lval_memory
1954               && (v == val_chain || ! value_lazy (v)))
1955             {
1956               struct type *vtype = check_typedef (value_type (v));
1957
1958               /* We only watch structs and arrays if user asked
1959                  for it explicitly, never if they just happen to
1960                  appear in the middle of some value chain.  */
1961               if (v == result
1962                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1963                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1964                 {
1965                   CORE_ADDR addr;
1966                   int type;
1967                   struct bp_location *loc, **tmp;
1968                   int bitpos = 0, bitsize = 0;
1969
1970                   if (value_bitsize (v) != 0)
1971                     {
1972                       /* Extract the bit parameters out from the bitfield
1973                          sub-expression.  */
1974                       bitpos = value_bitpos (v);
1975                       bitsize = value_bitsize (v);
1976                     }
1977                   else if (v == result && b->val_bitsize != 0)
1978                     {
1979                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1980                         lvalue whose bit parameters are saved in the fields
1981                         VAL_BITPOS and VAL_BITSIZE.  */
1982                       bitpos = b->val_bitpos;
1983                       bitsize = b->val_bitsize;
1984                     }
1985
1986                   addr = value_address (v);
1987                   if (bitsize != 0)
1988                     {
1989                       /* Skip the bytes that don't contain the bitfield.  */
1990                       addr += bitpos / 8;
1991                     }
1992
1993                   type = hw_write;
1994                   if (b->base.type == bp_read_watchpoint)
1995                     type = hw_read;
1996                   else if (b->base.type == bp_access_watchpoint)
1997                     type = hw_access;
1998
1999                   loc = allocate_bp_location (&b->base);
2000                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2001                     ;
2002                   *tmp = loc;
2003                   loc->gdbarch = get_type_arch (value_type (v));
2004
2005                   loc->pspace = frame_pspace;
2006                   loc->address = addr;
2007
2008                   if (bitsize != 0)
2009                     {
2010                       /* Just cover the bytes that make up the bitfield.  */
2011                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2012                     }
2013                   else
2014                     loc->length = TYPE_LENGTH (value_type (v));
2015
2016                   loc->watchpoint_type = type;
2017                 }
2018             }
2019         }
2020
2021       /* Change the type of breakpoint between hardware assisted or
2022          an ordinary watchpoint depending on the hardware support
2023          and free hardware slots.  REPARSE is set when the inferior
2024          is started.  */
2025       if (reparse)
2026         {
2027           int reg_cnt;
2028           enum bp_loc_type loc_type;
2029           struct bp_location *bl;
2030
2031           reg_cnt = can_use_hardware_watchpoint (val_chain);
2032
2033           if (reg_cnt)
2034             {
2035               int i, target_resources_ok, other_type_used;
2036               enum bptype type;
2037
2038               /* Use an exact watchpoint when there's only one memory region to be
2039                  watched, and only one debug register is needed to watch it.  */
2040               b->exact = target_exact_watchpoints && reg_cnt == 1;
2041
2042               /* We need to determine how many resources are already
2043                  used for all other hardware watchpoints plus this one
2044                  to see if we still have enough resources to also fit
2045                  this watchpoint in as well.  */
2046
2047               /* If this is a software watchpoint, we try to turn it
2048                  to a hardware one -- count resources as if B was of
2049                  hardware watchpoint type.  */
2050               type = b->base.type;
2051               if (type == bp_watchpoint)
2052                 type = bp_hardware_watchpoint;
2053
2054               /* This watchpoint may or may not have been placed on
2055                  the list yet at this point (it won't be in the list
2056                  if we're trying to create it for the first time,
2057                  through watch_command), so always account for it
2058                  manually.  */
2059
2060               /* Count resources used by all watchpoints except B.  */
2061               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2062
2063               /* Add in the resources needed for B.  */
2064               i += hw_watchpoint_use_count (&b->base);
2065
2066               target_resources_ok
2067                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2068               if (target_resources_ok <= 0)
2069                 {
2070                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2071
2072                   if (target_resources_ok == 0 && !sw_mode)
2073                     error (_("Target does not support this type of "
2074                              "hardware watchpoint."));
2075                   else if (target_resources_ok < 0 && !sw_mode)
2076                     error (_("There are not enough available hardware "
2077                              "resources for this watchpoint."));
2078
2079                   /* Downgrade to software watchpoint.  */
2080                   b->base.type = bp_watchpoint;
2081                 }
2082               else
2083                 {
2084                   /* If this was a software watchpoint, we've just
2085                      found we have enough resources to turn it to a
2086                      hardware watchpoint.  Otherwise, this is a
2087                      nop.  */
2088                   b->base.type = type;
2089                 }
2090             }
2091           else if (!b->base.ops->works_in_software_mode (&b->base))
2092             {
2093               if (!can_use_hw_watchpoints)
2094                 error (_("Can't set read/access watchpoint when "
2095                          "hardware watchpoints are disabled."));
2096               else
2097                 error (_("Expression cannot be implemented with "
2098                          "read/access watchpoint."));
2099             }
2100           else
2101             b->base.type = bp_watchpoint;
2102
2103           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2104                       : bp_loc_hardware_watchpoint);
2105           for (bl = b->base.loc; bl; bl = bl->next)
2106             bl->loc_type = loc_type;
2107         }
2108
2109       for (v = val_chain; v; v = next)
2110         {
2111           next = value_next (v);
2112           if (v != b->val)
2113             value_free (v);
2114         }
2115
2116       /* If a software watchpoint is not watching any memory, then the
2117          above left it without any location set up.  But,
2118          bpstat_stop_status requires a location to be able to report
2119          stops, so make sure there's at least a dummy one.  */
2120       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2121         {
2122           struct breakpoint *base = &b->base;
2123           base->loc = allocate_bp_location (base);
2124           base->loc->pspace = frame_pspace;
2125           base->loc->address = -1;
2126           base->loc->length = -1;
2127           base->loc->watchpoint_type = -1;
2128         }
2129     }
2130   else if (!within_current_scope)
2131     {
2132       printf_filtered (_("\
2133 Watchpoint %d deleted because the program has left the block\n\
2134 in which its expression is valid.\n"),
2135                        b->base.number);
2136       watchpoint_del_at_next_stop (b);
2137     }
2138
2139   /* Restore the selected frame.  */
2140   if (frame_saved)
2141     select_frame (frame_find_by_id (saved_frame_id));
2142 }
2143
2144
2145 /* Returns 1 iff breakpoint location should be
2146    inserted in the inferior.  We don't differentiate the type of BL's owner
2147    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2148    breakpoint_ops is not defined, because in insert_bp_location,
2149    tracepoint's insert_location will not be called.  */
2150 static int
2151 should_be_inserted (struct bp_location *bl)
2152 {
2153   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2154     return 0;
2155
2156   if (bl->owner->disposition == disp_del_at_next_stop)
2157     return 0;
2158
2159   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2160     return 0;
2161
2162   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2163     return 0;
2164
2165   /* This is set for example, when we're attached to the parent of a
2166      vfork, and have detached from the child.  The child is running
2167      free, and we expect it to do an exec or exit, at which point the
2168      OS makes the parent schedulable again (and the target reports
2169      that the vfork is done).  Until the child is done with the shared
2170      memory region, do not insert breakpoints in the parent, otherwise
2171      the child could still trip on the parent's breakpoints.  Since
2172      the parent is blocked anyway, it won't miss any breakpoint.  */
2173   if (bl->pspace->breakpoints_not_allowed)
2174     return 0;
2175
2176   /* Don't insert a breakpoint if we're trying to step past its
2177      location.  */
2178   if ((bl->loc_type == bp_loc_software_breakpoint
2179        || bl->loc_type == bp_loc_hardware_breakpoint)
2180       && stepping_past_instruction_at (bl->pspace->aspace,
2181                                        bl->address))
2182     return 0;
2183
2184   return 1;
2185 }
2186
2187 /* Same as should_be_inserted but does the check assuming
2188    that the location is not duplicated.  */
2189
2190 static int
2191 unduplicated_should_be_inserted (struct bp_location *bl)
2192 {
2193   int result;
2194   const int save_duplicate = bl->duplicate;
2195
2196   bl->duplicate = 0;
2197   result = should_be_inserted (bl);
2198   bl->duplicate = save_duplicate;
2199   return result;
2200 }
2201
2202 /* Parses a conditional described by an expression COND into an
2203    agent expression bytecode suitable for evaluation
2204    by the bytecode interpreter.  Return NULL if there was
2205    any error during parsing.  */
2206
2207 static struct agent_expr *
2208 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2209 {
2210   struct agent_expr *aexpr = NULL;
2211   volatile struct gdb_exception ex;
2212
2213   if (!cond)
2214     return NULL;
2215
2216   /* We don't want to stop processing, so catch any errors
2217      that may show up.  */
2218   TRY_CATCH (ex, RETURN_MASK_ERROR)
2219     {
2220       aexpr = gen_eval_for_expr (scope, cond);
2221     }
2222
2223   if (ex.reason < 0)
2224     {
2225       /* If we got here, it means the condition could not be parsed to a valid
2226          bytecode expression and thus can't be evaluated on the target's side.
2227          It's no use iterating through the conditions.  */
2228       return NULL;
2229     }
2230
2231   /* We have a valid agent expression.  */
2232   return aexpr;
2233 }
2234
2235 /* Based on location BL, create a list of breakpoint conditions to be
2236    passed on to the target.  If we have duplicated locations with different
2237    conditions, we will add such conditions to the list.  The idea is that the
2238    target will evaluate the list of conditions and will only notify GDB when
2239    one of them is true.  */
2240
2241 static void
2242 build_target_condition_list (struct bp_location *bl)
2243 {
2244   struct bp_location **locp = NULL, **loc2p;
2245   int null_condition_or_parse_error = 0;
2246   int modified = bl->needs_update;
2247   struct bp_location *loc;
2248
2249   /* Release conditions left over from a previous insert.  */
2250   VEC_free (agent_expr_p, bl->target_info.conditions);
2251
2252   /* This is only meaningful if the target is
2253      evaluating conditions and if the user has
2254      opted for condition evaluation on the target's
2255      side.  */
2256   if (gdb_evaluates_breakpoint_condition_p ()
2257       || !target_supports_evaluation_of_breakpoint_conditions ())
2258     return;
2259
2260   /* Do a first pass to check for locations with no assigned
2261      conditions or conditions that fail to parse to a valid agent expression
2262      bytecode.  If any of these happen, then it's no use to send conditions
2263      to the target since this location will always trigger and generate a
2264      response back to GDB.  */
2265   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2266     {
2267       loc = (*loc2p);
2268       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2269         {
2270           if (modified)
2271             {
2272               struct agent_expr *aexpr;
2273
2274               /* Re-parse the conditions since something changed.  In that
2275                  case we already freed the condition bytecodes (see
2276                  force_breakpoint_reinsertion).  We just
2277                  need to parse the condition to bytecodes again.  */
2278               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2279               loc->cond_bytecode = aexpr;
2280
2281               /* Check if we managed to parse the conditional expression
2282                  correctly.  If not, we will not send this condition
2283                  to the target.  */
2284               if (aexpr)
2285                 continue;
2286             }
2287
2288           /* If we have a NULL bytecode expression, it means something
2289              went wrong or we have a null condition expression.  */
2290           if (!loc->cond_bytecode)
2291             {
2292               null_condition_or_parse_error = 1;
2293               break;
2294             }
2295         }
2296     }
2297
2298   /* If any of these happened, it means we will have to evaluate the conditions
2299      for the location's address on gdb's side.  It is no use keeping bytecodes
2300      for all the other duplicate locations, thus we free all of them here.
2301
2302      This is so we have a finer control over which locations' conditions are
2303      being evaluated by GDB or the remote stub.  */
2304   if (null_condition_or_parse_error)
2305     {
2306       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2307         {
2308           loc = (*loc2p);
2309           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2310             {
2311               /* Only go as far as the first NULL bytecode is
2312                  located.  */
2313               if (!loc->cond_bytecode)
2314                 return;
2315
2316               free_agent_expr (loc->cond_bytecode);
2317               loc->cond_bytecode = NULL;
2318             }
2319         }
2320     }
2321
2322   /* No NULL conditions or failed bytecode generation.  Build a condition list
2323      for this location's address.  */
2324   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2325     {
2326       loc = (*loc2p);
2327       if (loc->cond
2328           && is_breakpoint (loc->owner)
2329           && loc->pspace->num == bl->pspace->num
2330           && loc->owner->enable_state == bp_enabled
2331           && loc->enabled)
2332         /* Add the condition to the vector.  This will be used later to send the
2333            conditions to the target.  */
2334         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2335                        loc->cond_bytecode);
2336     }
2337
2338   return;
2339 }
2340
2341 /* Parses a command described by string CMD into an agent expression
2342    bytecode suitable for evaluation by the bytecode interpreter.
2343    Return NULL if there was any error during parsing.  */
2344
2345 static struct agent_expr *
2346 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2347 {
2348   struct cleanup *old_cleanups = 0;
2349   struct expression *expr, **argvec;
2350   struct agent_expr *aexpr = NULL;
2351   volatile struct gdb_exception ex;
2352   const char *cmdrest;
2353   const char *format_start, *format_end;
2354   struct format_piece *fpieces;
2355   int nargs;
2356   struct gdbarch *gdbarch = get_current_arch ();
2357
2358   if (!cmd)
2359     return NULL;
2360
2361   cmdrest = cmd;
2362
2363   if (*cmdrest == ',')
2364     ++cmdrest;
2365   cmdrest = skip_spaces_const (cmdrest);
2366
2367   if (*cmdrest++ != '"')
2368     error (_("No format string following the location"));
2369
2370   format_start = cmdrest;
2371
2372   fpieces = parse_format_string (&cmdrest);
2373
2374   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2375
2376   format_end = cmdrest;
2377
2378   if (*cmdrest++ != '"')
2379     error (_("Bad format string, non-terminated '\"'."));
2380   
2381   cmdrest = skip_spaces_const (cmdrest);
2382
2383   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2384     error (_("Invalid argument syntax"));
2385
2386   if (*cmdrest == ',')
2387     cmdrest++;
2388   cmdrest = skip_spaces_const (cmdrest);
2389
2390   /* For each argument, make an expression.  */
2391
2392   argvec = (struct expression **) alloca (strlen (cmd)
2393                                          * sizeof (struct expression *));
2394
2395   nargs = 0;
2396   while (*cmdrest != '\0')
2397     {
2398       const char *cmd1;
2399
2400       cmd1 = cmdrest;
2401       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2402       argvec[nargs++] = expr;
2403       cmdrest = cmd1;
2404       if (*cmdrest == ',')
2405         ++cmdrest;
2406     }
2407
2408   /* We don't want to stop processing, so catch any errors
2409      that may show up.  */
2410   TRY_CATCH (ex, RETURN_MASK_ERROR)
2411     {
2412       aexpr = gen_printf (scope, gdbarch, 0, 0,
2413                           format_start, format_end - format_start,
2414                           fpieces, nargs, argvec);
2415     }
2416
2417   do_cleanups (old_cleanups);
2418
2419   if (ex.reason < 0)
2420     {
2421       /* If we got here, it means the command could not be parsed to a valid
2422          bytecode expression and thus can't be evaluated on the target's side.
2423          It's no use iterating through the other commands.  */
2424       return NULL;
2425     }
2426
2427   /* We have a valid agent expression, return it.  */
2428   return aexpr;
2429 }
2430
2431 /* Based on location BL, create a list of breakpoint commands to be
2432    passed on to the target.  If we have duplicated locations with
2433    different commands, we will add any such to the list.  */
2434
2435 static void
2436 build_target_command_list (struct bp_location *bl)
2437 {
2438   struct bp_location **locp = NULL, **loc2p;
2439   int null_command_or_parse_error = 0;
2440   int modified = bl->needs_update;
2441   struct bp_location *loc;
2442
2443   /* Release commands left over from a previous insert.  */
2444   VEC_free (agent_expr_p, bl->target_info.tcommands);
2445
2446   if (!target_can_run_breakpoint_commands ())
2447     return;
2448
2449   /* For now, limit to agent-style dprintf breakpoints.  */
2450   if (dprintf_style != dprintf_style_agent)
2451     return;
2452
2453   /* For now, if we have any duplicate location that isn't a dprintf,
2454      don't install the target-side commands, as that would make the
2455      breakpoint not be reported to the core, and we'd lose
2456      control.  */
2457   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2458     {
2459       loc = (*loc2p);
2460       if (is_breakpoint (loc->owner)
2461           && loc->pspace->num == bl->pspace->num
2462           && loc->owner->type != bp_dprintf)
2463         return;
2464     }
2465
2466   /* Do a first pass to check for locations with no assigned
2467      conditions or conditions that fail to parse to a valid agent expression
2468      bytecode.  If any of these happen, then it's no use to send conditions
2469      to the target since this location will always trigger and generate a
2470      response back to GDB.  */
2471   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2472     {
2473       loc = (*loc2p);
2474       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2475         {
2476           if (modified)
2477             {
2478               struct agent_expr *aexpr;
2479
2480               /* Re-parse the commands since something changed.  In that
2481                  case we already freed the command bytecodes (see
2482                  force_breakpoint_reinsertion).  We just
2483                  need to parse the command to bytecodes again.  */
2484               aexpr = parse_cmd_to_aexpr (bl->address,
2485                                           loc->owner->extra_string);
2486               loc->cmd_bytecode = aexpr;
2487
2488               if (!aexpr)
2489                 continue;
2490             }
2491
2492           /* If we have a NULL bytecode expression, it means something
2493              went wrong or we have a null command expression.  */
2494           if (!loc->cmd_bytecode)
2495             {
2496               null_command_or_parse_error = 1;
2497               break;
2498             }
2499         }
2500     }
2501
2502   /* If anything failed, then we're not doing target-side commands,
2503      and so clean up.  */
2504   if (null_command_or_parse_error)
2505     {
2506       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2507         {
2508           loc = (*loc2p);
2509           if (is_breakpoint (loc->owner)
2510               && loc->pspace->num == bl->pspace->num)
2511             {
2512               /* Only go as far as the first NULL bytecode is
2513                  located.  */
2514               if (loc->cmd_bytecode == NULL)
2515                 return;
2516
2517               free_agent_expr (loc->cmd_bytecode);
2518               loc->cmd_bytecode = NULL;
2519             }
2520         }
2521     }
2522
2523   /* No NULL commands or failed bytecode generation.  Build a command list
2524      for this location's address.  */
2525   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2526     {
2527       loc = (*loc2p);
2528       if (loc->owner->extra_string
2529           && is_breakpoint (loc->owner)
2530           && loc->pspace->num == bl->pspace->num
2531           && loc->owner->enable_state == bp_enabled
2532           && loc->enabled)
2533         /* Add the command to the vector.  This will be used later
2534            to send the commands to the target.  */
2535         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2536                        loc->cmd_bytecode);
2537     }
2538
2539   bl->target_info.persist = 0;
2540   /* Maybe flag this location as persistent.  */
2541   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2542     bl->target_info.persist = 1;
2543 }
2544
2545 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2546    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2547    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2548    Returns 0 for success, 1 if the bp_location type is not supported or
2549    -1 for failure.
2550
2551    NOTE drow/2003-09-09: This routine could be broken down to an
2552    object-style method for each breakpoint or catchpoint type.  */
2553 static int
2554 insert_bp_location (struct bp_location *bl,
2555                     struct ui_file *tmp_error_stream,
2556                     int *disabled_breaks,
2557                     int *hw_breakpoint_error,
2558                     int *hw_bp_error_explained_already)
2559 {
2560   enum errors bp_err = GDB_NO_ERROR;
2561   const char *bp_err_message = NULL;
2562   volatile struct gdb_exception e;
2563
2564   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2565     return 0;
2566
2567   /* Note we don't initialize bl->target_info, as that wipes out
2568      the breakpoint location's shadow_contents if the breakpoint
2569      is still inserted at that location.  This in turn breaks
2570      target_read_memory which depends on these buffers when
2571      a memory read is requested at the breakpoint location:
2572      Once the target_info has been wiped, we fail to see that
2573      we have a breakpoint inserted at that address and thus
2574      read the breakpoint instead of returning the data saved in
2575      the breakpoint location's shadow contents.  */
2576   bl->target_info.placed_address = bl->address;
2577   bl->target_info.placed_address_space = bl->pspace->aspace;
2578   bl->target_info.length = bl->length;
2579
2580   /* When working with target-side conditions, we must pass all the conditions
2581      for the same breakpoint address down to the target since GDB will not
2582      insert those locations.  With a list of breakpoint conditions, the target
2583      can decide when to stop and notify GDB.  */
2584
2585   if (is_breakpoint (bl->owner))
2586     {
2587       build_target_condition_list (bl);
2588       build_target_command_list (bl);
2589       /* Reset the modification marker.  */
2590       bl->needs_update = 0;
2591     }
2592
2593   if (bl->loc_type == bp_loc_software_breakpoint
2594       || bl->loc_type == bp_loc_hardware_breakpoint)
2595     {
2596       if (bl->owner->type != bp_hardware_breakpoint)
2597         {
2598           /* If the explicitly specified breakpoint type
2599              is not hardware breakpoint, check the memory map to see
2600              if the breakpoint address is in read only memory or not.
2601
2602              Two important cases are:
2603              - location type is not hardware breakpoint, memory
2604              is readonly.  We change the type of the location to
2605              hardware breakpoint.
2606              - location type is hardware breakpoint, memory is
2607              read-write.  This means we've previously made the
2608              location hardware one, but then the memory map changed,
2609              so we undo.
2610              
2611              When breakpoints are removed, remove_breakpoints will use
2612              location types we've just set here, the only possible
2613              problem is that memory map has changed during running
2614              program, but it's not going to work anyway with current
2615              gdb.  */
2616           struct mem_region *mr 
2617             = lookup_mem_region (bl->target_info.placed_address);
2618           
2619           if (mr)
2620             {
2621               if (automatic_hardware_breakpoints)
2622                 {
2623                   enum bp_loc_type new_type;
2624                   
2625                   if (mr->attrib.mode != MEM_RW)
2626                     new_type = bp_loc_hardware_breakpoint;
2627                   else 
2628                     new_type = bp_loc_software_breakpoint;
2629                   
2630                   if (new_type != bl->loc_type)
2631                     {
2632                       static int said = 0;
2633
2634                       bl->loc_type = new_type;
2635                       if (!said)
2636                         {
2637                           fprintf_filtered (gdb_stdout,
2638                                             _("Note: automatically using "
2639                                               "hardware breakpoints for "
2640                                               "read-only addresses.\n"));
2641                           said = 1;
2642                         }
2643                     }
2644                 }
2645               else if (bl->loc_type == bp_loc_software_breakpoint
2646                        && mr->attrib.mode != MEM_RW)        
2647                 warning (_("cannot set software breakpoint "
2648                            "at readonly address %s"),
2649                          paddress (bl->gdbarch, bl->address));
2650             }
2651         }
2652         
2653       /* First check to see if we have to handle an overlay.  */
2654       if (overlay_debugging == ovly_off
2655           || bl->section == NULL
2656           || !(section_is_overlay (bl->section)))
2657         {
2658           /* No overlay handling: just set the breakpoint.  */
2659           TRY_CATCH (e, RETURN_MASK_ALL)
2660             {
2661               int val;
2662
2663               val = bl->owner->ops->insert_location (bl);
2664               if (val)
2665                 bp_err = GENERIC_ERROR;
2666             }
2667           if (e.reason < 0)
2668             {
2669               bp_err = e.error;
2670               bp_err_message = e.message;
2671             }
2672         }
2673       else
2674         {
2675           /* This breakpoint is in an overlay section.
2676              Shall we set a breakpoint at the LMA?  */
2677           if (!overlay_events_enabled)
2678             {
2679               /* Yes -- overlay event support is not active, 
2680                  so we must try to set a breakpoint at the LMA.
2681                  This will not work for a hardware breakpoint.  */
2682               if (bl->loc_type == bp_loc_hardware_breakpoint)
2683                 warning (_("hardware breakpoint %d not supported in overlay!"),
2684                          bl->owner->number);
2685               else
2686                 {
2687                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2688                                                              bl->section);
2689                   /* Set a software (trap) breakpoint at the LMA.  */
2690                   bl->overlay_target_info = bl->target_info;
2691                   bl->overlay_target_info.placed_address = addr;
2692
2693                   /* No overlay handling: just set the breakpoint.  */
2694                   TRY_CATCH (e, RETURN_MASK_ALL)
2695                     {
2696                       int val;
2697
2698                       val = target_insert_breakpoint (bl->gdbarch,
2699                                                       &bl->overlay_target_info);
2700                       if (val)
2701                         bp_err = GENERIC_ERROR;
2702                     }
2703                   if (e.reason < 0)
2704                     {
2705                       bp_err = e.error;
2706                       bp_err_message = e.message;
2707                     }
2708
2709                   if (bp_err != GDB_NO_ERROR)
2710                     fprintf_unfiltered (tmp_error_stream,
2711                                         "Overlay breakpoint %d "
2712                                         "failed: in ROM?\n",
2713                                         bl->owner->number);
2714                 }
2715             }
2716           /* Shall we set a breakpoint at the VMA? */
2717           if (section_is_mapped (bl->section))
2718             {
2719               /* Yes.  This overlay section is mapped into memory.  */
2720               TRY_CATCH (e, RETURN_MASK_ALL)
2721                 {
2722                   int val;
2723
2724                   val = bl->owner->ops->insert_location (bl);
2725                   if (val)
2726                     bp_err = GENERIC_ERROR;
2727                 }
2728               if (e.reason < 0)
2729                 {
2730                   bp_err = e.error;
2731                   bp_err_message = e.message;
2732                 }
2733             }
2734           else
2735             {
2736               /* No.  This breakpoint will not be inserted.  
2737                  No error, but do not mark the bp as 'inserted'.  */
2738               return 0;
2739             }
2740         }
2741
2742       if (bp_err != GDB_NO_ERROR)
2743         {
2744           /* Can't set the breakpoint.  */
2745
2746           /* In some cases, we might not be able to insert a
2747              breakpoint in a shared library that has already been
2748              removed, but we have not yet processed the shlib unload
2749              event.  Unfortunately, some targets that implement
2750              breakpoint insertion themselves can't tell why the
2751              breakpoint insertion failed (e.g., the remote target
2752              doesn't define error codes), so we must treat generic
2753              errors as memory errors.  */
2754           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2755               && bl->loc_type == bp_loc_software_breakpoint
2756               && (solib_name_from_address (bl->pspace, bl->address)
2757                   || shared_objfile_contains_address_p (bl->pspace,
2758                                                         bl->address)))
2759             {
2760               /* See also: disable_breakpoints_in_shlibs.  */
2761               bl->shlib_disabled = 1;
2762               observer_notify_breakpoint_modified (bl->owner);
2763               if (!*disabled_breaks)
2764                 {
2765                   fprintf_unfiltered (tmp_error_stream, 
2766                                       "Cannot insert breakpoint %d.\n", 
2767                                       bl->owner->number);
2768                   fprintf_unfiltered (tmp_error_stream, 
2769                                       "Temporarily disabling shared "
2770                                       "library breakpoints:\n");
2771                 }
2772               *disabled_breaks = 1;
2773               fprintf_unfiltered (tmp_error_stream,
2774                                   "breakpoint #%d\n", bl->owner->number);
2775               return 0;
2776             }
2777           else
2778             {
2779               if (bl->loc_type == bp_loc_hardware_breakpoint)
2780                 {
2781                   *hw_breakpoint_error = 1;
2782                   *hw_bp_error_explained_already = bp_err_message != NULL;
2783                   fprintf_unfiltered (tmp_error_stream,
2784                                       "Cannot insert hardware breakpoint %d%s",
2785                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2786                   if (bp_err_message != NULL)
2787                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2788                 }
2789               else
2790                 {
2791                   if (bp_err_message == NULL)
2792                     {
2793                       char *message
2794                         = memory_error_message (TARGET_XFER_E_IO,
2795                                                 bl->gdbarch, bl->address);
2796                       struct cleanup *old_chain = make_cleanup (xfree, message);
2797
2798                       fprintf_unfiltered (tmp_error_stream,
2799                                           "Cannot insert breakpoint %d.\n"
2800                                           "%s\n",
2801                                           bl->owner->number, message);
2802                       do_cleanups (old_chain);
2803                     }
2804                   else
2805                     {
2806                       fprintf_unfiltered (tmp_error_stream,
2807                                           "Cannot insert breakpoint %d: %s\n",
2808                                           bl->owner->number,
2809                                           bp_err_message);
2810                     }
2811                 }
2812               return 1;
2813
2814             }
2815         }
2816       else
2817         bl->inserted = 1;
2818
2819       return 0;
2820     }
2821
2822   else if (bl->loc_type == bp_loc_hardware_watchpoint
2823            /* NOTE drow/2003-09-08: This state only exists for removing
2824               watchpoints.  It's not clear that it's necessary...  */
2825            && bl->owner->disposition != disp_del_at_next_stop)
2826     {
2827       int val;
2828
2829       gdb_assert (bl->owner->ops != NULL
2830                   && bl->owner->ops->insert_location != NULL);
2831
2832       val = bl->owner->ops->insert_location (bl);
2833
2834       /* If trying to set a read-watchpoint, and it turns out it's not
2835          supported, try emulating one with an access watchpoint.  */
2836       if (val == 1 && bl->watchpoint_type == hw_read)
2837         {
2838           struct bp_location *loc, **loc_temp;
2839
2840           /* But don't try to insert it, if there's already another
2841              hw_access location that would be considered a duplicate
2842              of this one.  */
2843           ALL_BP_LOCATIONS (loc, loc_temp)
2844             if (loc != bl
2845                 && loc->watchpoint_type == hw_access
2846                 && watchpoint_locations_match (bl, loc))
2847               {
2848                 bl->duplicate = 1;
2849                 bl->inserted = 1;
2850                 bl->target_info = loc->target_info;
2851                 bl->watchpoint_type = hw_access;
2852                 val = 0;
2853                 break;
2854               }
2855
2856           if (val == 1)
2857             {
2858               bl->watchpoint_type = hw_access;
2859               val = bl->owner->ops->insert_location (bl);
2860
2861               if (val)
2862                 /* Back to the original value.  */
2863                 bl->watchpoint_type = hw_read;
2864             }
2865         }
2866
2867       bl->inserted = (val == 0);
2868     }
2869
2870   else if (bl->owner->type == bp_catchpoint)
2871     {
2872       int val;
2873
2874       gdb_assert (bl->owner->ops != NULL
2875                   && bl->owner->ops->insert_location != NULL);
2876
2877       val = bl->owner->ops->insert_location (bl);
2878       if (val)
2879         {
2880           bl->owner->enable_state = bp_disabled;
2881
2882           if (val == 1)
2883             warning (_("\
2884 Error inserting catchpoint %d: Your system does not support this type\n\
2885 of catchpoint."), bl->owner->number);
2886           else
2887             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2888         }
2889
2890       bl->inserted = (val == 0);
2891
2892       /* We've already printed an error message if there was a problem
2893          inserting this catchpoint, and we've disabled the catchpoint,
2894          so just return success.  */
2895       return 0;
2896     }
2897
2898   return 0;
2899 }
2900
2901 /* This function is called when program space PSPACE is about to be
2902    deleted.  It takes care of updating breakpoints to not reference
2903    PSPACE anymore.  */
2904
2905 void
2906 breakpoint_program_space_exit (struct program_space *pspace)
2907 {
2908   struct breakpoint *b, *b_temp;
2909   struct bp_location *loc, **loc_temp;
2910
2911   /* Remove any breakpoint that was set through this program space.  */
2912   ALL_BREAKPOINTS_SAFE (b, b_temp)
2913     {
2914       if (b->pspace == pspace)
2915         delete_breakpoint (b);
2916     }
2917
2918   /* Breakpoints set through other program spaces could have locations
2919      bound to PSPACE as well.  Remove those.  */
2920   ALL_BP_LOCATIONS (loc, loc_temp)
2921     {
2922       struct bp_location *tmp;
2923
2924       if (loc->pspace == pspace)
2925         {
2926           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2927           if (loc->owner->loc == loc)
2928             loc->owner->loc = loc->next;
2929           else
2930             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2931               if (tmp->next == loc)
2932                 {
2933                   tmp->next = loc->next;
2934                   break;
2935                 }
2936         }
2937     }
2938
2939   /* Now update the global location list to permanently delete the
2940      removed locations above.  */
2941   update_global_location_list (UGLL_DONT_INSERT);
2942 }
2943
2944 /* Make sure all breakpoints are inserted in inferior.
2945    Throws exception on any error.
2946    A breakpoint that is already inserted won't be inserted
2947    again, so calling this function twice is safe.  */
2948 void
2949 insert_breakpoints (void)
2950 {
2951   struct breakpoint *bpt;
2952
2953   ALL_BREAKPOINTS (bpt)
2954     if (is_hardware_watchpoint (bpt))
2955       {
2956         struct watchpoint *w = (struct watchpoint *) bpt;
2957
2958         update_watchpoint (w, 0 /* don't reparse.  */);
2959       }
2960
2961   /* Updating watchpoints creates new locations, so update the global
2962      location list.  Explicitly tell ugll to insert locations and
2963      ignore breakpoints_always_inserted_mode.  */
2964   update_global_location_list (UGLL_INSERT);
2965 }
2966
2967 /* Invoke CALLBACK for each of bp_location.  */
2968
2969 void
2970 iterate_over_bp_locations (walk_bp_location_callback callback)
2971 {
2972   struct bp_location *loc, **loc_tmp;
2973
2974   ALL_BP_LOCATIONS (loc, loc_tmp)
2975     {
2976       callback (loc, NULL);
2977     }
2978 }
2979
2980 /* This is used when we need to synch breakpoint conditions between GDB and the
2981    target.  It is the case with deleting and disabling of breakpoints when using
2982    always-inserted mode.  */
2983
2984 static void
2985 update_inserted_breakpoint_locations (void)
2986 {
2987   struct bp_location *bl, **blp_tmp;
2988   int error_flag = 0;
2989   int val = 0;
2990   int disabled_breaks = 0;
2991   int hw_breakpoint_error = 0;
2992   int hw_bp_details_reported = 0;
2993
2994   struct ui_file *tmp_error_stream = mem_fileopen ();
2995   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2996
2997   /* Explicitly mark the warning -- this will only be printed if
2998      there was an error.  */
2999   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3000
3001   save_current_space_and_thread ();
3002
3003   ALL_BP_LOCATIONS (bl, blp_tmp)
3004     {
3005       /* We only want to update software breakpoints and hardware
3006          breakpoints.  */
3007       if (!is_breakpoint (bl->owner))
3008         continue;
3009
3010       /* We only want to update locations that are already inserted
3011          and need updating.  This is to avoid unwanted insertion during
3012          deletion of breakpoints.  */
3013       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3014         continue;
3015
3016       switch_to_program_space_and_thread (bl->pspace);
3017
3018       /* For targets that support global breakpoints, there's no need
3019          to select an inferior to insert breakpoint to.  In fact, even
3020          if we aren't attached to any process yet, we should still
3021          insert breakpoints.  */
3022       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3023           && ptid_equal (inferior_ptid, null_ptid))
3024         continue;
3025
3026       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3027                                     &hw_breakpoint_error, &hw_bp_details_reported);
3028       if (val)
3029         error_flag = val;
3030     }
3031
3032   if (error_flag)
3033     {
3034       target_terminal_ours_for_output ();
3035       error_stream (tmp_error_stream);
3036     }
3037
3038   do_cleanups (cleanups);
3039 }
3040
3041 /* Used when starting or continuing the program.  */
3042
3043 static void
3044 insert_breakpoint_locations (void)
3045 {
3046   struct breakpoint *bpt;
3047   struct bp_location *bl, **blp_tmp;
3048   int error_flag = 0;
3049   int val = 0;
3050   int disabled_breaks = 0;
3051   int hw_breakpoint_error = 0;
3052   int hw_bp_error_explained_already = 0;
3053
3054   struct ui_file *tmp_error_stream = mem_fileopen ();
3055   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3056   
3057   /* Explicitly mark the warning -- this will only be printed if
3058      there was an error.  */
3059   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3060
3061   save_current_space_and_thread ();
3062
3063   ALL_BP_LOCATIONS (bl, blp_tmp)
3064     {
3065       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3066         continue;
3067
3068       /* There is no point inserting thread-specific breakpoints if
3069          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3070          has BL->OWNER always non-NULL.  */
3071       if (bl->owner->thread != -1
3072           && !valid_thread_id (bl->owner->thread))
3073         continue;
3074
3075       switch_to_program_space_and_thread (bl->pspace);
3076
3077       /* For targets that support global breakpoints, there's no need
3078          to select an inferior to insert breakpoint to.  In fact, even
3079          if we aren't attached to any process yet, we should still
3080          insert breakpoints.  */
3081       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3082           && ptid_equal (inferior_ptid, null_ptid))
3083         continue;
3084
3085       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3086                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3087       if (val)
3088         error_flag = val;
3089     }
3090
3091   /* If we failed to insert all locations of a watchpoint, remove
3092      them, as half-inserted watchpoint is of limited use.  */
3093   ALL_BREAKPOINTS (bpt)  
3094     {
3095       int some_failed = 0;
3096       struct bp_location *loc;
3097
3098       if (!is_hardware_watchpoint (bpt))
3099         continue;
3100
3101       if (!breakpoint_enabled (bpt))
3102         continue;
3103
3104       if (bpt->disposition == disp_del_at_next_stop)
3105         continue;
3106       
3107       for (loc = bpt->loc; loc; loc = loc->next)
3108         if (!loc->inserted && should_be_inserted (loc))
3109           {
3110             some_failed = 1;
3111             break;
3112           }
3113       if (some_failed)
3114         {
3115           for (loc = bpt->loc; loc; loc = loc->next)
3116             if (loc->inserted)
3117               remove_breakpoint (loc, mark_uninserted);
3118
3119           hw_breakpoint_error = 1;
3120           fprintf_unfiltered (tmp_error_stream,
3121                               "Could not insert hardware watchpoint %d.\n", 
3122                               bpt->number);
3123           error_flag = -1;
3124         }
3125     }
3126
3127   if (error_flag)
3128     {
3129       /* If a hardware breakpoint or watchpoint was inserted, add a
3130          message about possibly exhausted resources.  */
3131       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3132         {
3133           fprintf_unfiltered (tmp_error_stream, 
3134                               "Could not insert hardware breakpoints:\n\
3135 You may have requested too many hardware breakpoints/watchpoints.\n");
3136         }
3137       target_terminal_ours_for_output ();
3138       error_stream (tmp_error_stream);
3139     }
3140
3141   do_cleanups (cleanups);
3142 }
3143
3144 /* Used when the program stops.
3145    Returns zero if successful, or non-zero if there was a problem
3146    removing a breakpoint location.  */
3147
3148 int
3149 remove_breakpoints (void)
3150 {
3151   struct bp_location *bl, **blp_tmp;
3152   int val = 0;
3153
3154   ALL_BP_LOCATIONS (bl, blp_tmp)
3155   {
3156     if (bl->inserted && !is_tracepoint (bl->owner))
3157       val |= remove_breakpoint (bl, mark_uninserted);
3158   }
3159   return val;
3160 }
3161
3162 /* When a thread exits, remove breakpoints that are related to
3163    that thread.  */
3164
3165 static void
3166 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3167 {
3168   struct breakpoint *b, *b_tmp;
3169
3170   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3171     {
3172       if (b->thread == tp->num && user_breakpoint_p (b))
3173         {
3174           b->disposition = disp_del_at_next_stop;
3175
3176           printf_filtered (_("\
3177 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3178                           b->number, tp->num);
3179
3180           /* Hide it from the user.  */
3181           b->number = 0;
3182        }
3183     }
3184 }
3185
3186 /* Remove breakpoints of process PID.  */
3187
3188 int
3189 remove_breakpoints_pid (int pid)
3190 {
3191   struct bp_location *bl, **blp_tmp;
3192   int val;
3193   struct inferior *inf = find_inferior_pid (pid);
3194
3195   ALL_BP_LOCATIONS (bl, blp_tmp)
3196   {
3197     if (bl->pspace != inf->pspace)
3198       continue;
3199
3200     if (bl->owner->type == bp_dprintf)
3201       continue;
3202
3203     if (bl->inserted)
3204       {
3205         val = remove_breakpoint (bl, mark_uninserted);
3206         if (val != 0)
3207           return val;
3208       }
3209   }
3210   return 0;
3211 }
3212
3213 int
3214 reattach_breakpoints (int pid)
3215 {
3216   struct cleanup *old_chain;
3217   struct bp_location *bl, **blp_tmp;
3218   int val;
3219   struct ui_file *tmp_error_stream;
3220   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3221   struct inferior *inf;
3222   struct thread_info *tp;
3223
3224   tp = any_live_thread_of_process (pid);
3225   if (tp == NULL)
3226     return 1;
3227
3228   inf = find_inferior_pid (pid);
3229   old_chain = save_inferior_ptid ();
3230
3231   inferior_ptid = tp->ptid;
3232
3233   tmp_error_stream = mem_fileopen ();
3234   make_cleanup_ui_file_delete (tmp_error_stream);
3235
3236   ALL_BP_LOCATIONS (bl, blp_tmp)
3237   {
3238     if (bl->pspace != inf->pspace)
3239       continue;
3240
3241     if (bl->inserted)
3242       {
3243         bl->inserted = 0;
3244         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3245         if (val != 0)
3246           {
3247             do_cleanups (old_chain);
3248             return val;
3249           }
3250       }
3251   }
3252   do_cleanups (old_chain);
3253   return 0;
3254 }
3255
3256 static int internal_breakpoint_number = -1;
3257
3258 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3259    If INTERNAL is non-zero, the breakpoint number will be populated
3260    from internal_breakpoint_number and that variable decremented.
3261    Otherwise the breakpoint number will be populated from
3262    breakpoint_count and that value incremented.  Internal breakpoints
3263    do not set the internal var bpnum.  */
3264 static void
3265 set_breakpoint_number (int internal, struct breakpoint *b)
3266 {
3267   if (internal)
3268     b->number = internal_breakpoint_number--;
3269   else
3270     {
3271       set_breakpoint_count (breakpoint_count + 1);
3272       b->number = breakpoint_count;
3273     }
3274 }
3275
3276 static struct breakpoint *
3277 create_internal_breakpoint (struct gdbarch *gdbarch,
3278                             CORE_ADDR address, enum bptype type,
3279                             const struct breakpoint_ops *ops)
3280 {
3281   struct symtab_and_line sal;
3282   struct breakpoint *b;
3283
3284   init_sal (&sal);              /* Initialize to zeroes.  */
3285
3286   sal.pc = address;
3287   sal.section = find_pc_overlay (sal.pc);
3288   sal.pspace = current_program_space;
3289
3290   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3291   b->number = internal_breakpoint_number--;
3292   b->disposition = disp_donttouch;
3293
3294   return b;
3295 }
3296
3297 static const char *const longjmp_names[] =
3298   {
3299     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3300   };
3301 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3302
3303 /* Per-objfile data private to breakpoint.c.  */
3304 struct breakpoint_objfile_data
3305 {
3306   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3307   struct bound_minimal_symbol overlay_msym;
3308
3309   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3310   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3311
3312   /* True if we have looked for longjmp probes.  */
3313   int longjmp_searched;
3314
3315   /* SystemTap probe points for longjmp (if any).  */
3316   VEC (probe_p) *longjmp_probes;
3317
3318   /* Minimal symbol for "std::terminate()" (if any).  */
3319   struct bound_minimal_symbol terminate_msym;
3320
3321   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3322   struct bound_minimal_symbol exception_msym;
3323
3324   /* True if we have looked for exception probes.  */
3325   int exception_searched;
3326
3327   /* SystemTap probe points for unwinding (if any).  */
3328   VEC (probe_p) *exception_probes;
3329 };
3330
3331 static const struct objfile_data *breakpoint_objfile_key;
3332
3333 /* Minimal symbol not found sentinel.  */
3334 static struct minimal_symbol msym_not_found;
3335
3336 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3337
3338 static int
3339 msym_not_found_p (const struct minimal_symbol *msym)
3340 {
3341   return msym == &msym_not_found;
3342 }
3343
3344 /* Return per-objfile data needed by breakpoint.c.
3345    Allocate the data if necessary.  */
3346
3347 static struct breakpoint_objfile_data *
3348 get_breakpoint_objfile_data (struct objfile *objfile)
3349 {
3350   struct breakpoint_objfile_data *bp_objfile_data;
3351
3352   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3353   if (bp_objfile_data == NULL)
3354     {
3355       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3356                                        sizeof (*bp_objfile_data));
3357
3358       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3359       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3360     }
3361   return bp_objfile_data;
3362 }
3363
3364 static void
3365 free_breakpoint_probes (struct objfile *obj, void *data)
3366 {
3367   struct breakpoint_objfile_data *bp_objfile_data = data;
3368
3369   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3370   VEC_free (probe_p, bp_objfile_data->exception_probes);
3371 }
3372
3373 static void
3374 create_overlay_event_breakpoint (void)
3375 {
3376   struct objfile *objfile;
3377   const char *const func_name = "_ovly_debug_event";
3378
3379   ALL_OBJFILES (objfile)
3380     {
3381       struct breakpoint *b;
3382       struct breakpoint_objfile_data *bp_objfile_data;
3383       CORE_ADDR addr;
3384
3385       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3386
3387       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3388         continue;
3389
3390       if (bp_objfile_data->overlay_msym.minsym == NULL)
3391         {
3392           struct bound_minimal_symbol m;
3393
3394           m = lookup_minimal_symbol_text (func_name, objfile);
3395           if (m.minsym == NULL)
3396             {
3397               /* Avoid future lookups in this objfile.  */
3398               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3399               continue;
3400             }
3401           bp_objfile_data->overlay_msym = m;
3402         }
3403
3404       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3405       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3406                                       bp_overlay_event,
3407                                       &internal_breakpoint_ops);
3408       b->addr_string = xstrdup (func_name);
3409
3410       if (overlay_debugging == ovly_auto)
3411         {
3412           b->enable_state = bp_enabled;
3413           overlay_events_enabled = 1;
3414         }
3415       else
3416        {
3417          b->enable_state = bp_disabled;
3418          overlay_events_enabled = 0;
3419        }
3420     }
3421   update_global_location_list (UGLL_MAY_INSERT);
3422 }
3423
3424 static void
3425 create_longjmp_master_breakpoint (void)
3426 {
3427   struct program_space *pspace;
3428   struct cleanup *old_chain;
3429
3430   old_chain = save_current_program_space ();
3431
3432   ALL_PSPACES (pspace)
3433   {
3434     struct objfile *objfile;
3435
3436     set_current_program_space (pspace);
3437
3438     ALL_OBJFILES (objfile)
3439     {
3440       int i;
3441       struct gdbarch *gdbarch;
3442       struct breakpoint_objfile_data *bp_objfile_data;
3443
3444       gdbarch = get_objfile_arch (objfile);
3445
3446       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3447
3448       if (!bp_objfile_data->longjmp_searched)
3449         {
3450           VEC (probe_p) *ret;
3451
3452           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3453           if (ret != NULL)
3454             {
3455               /* We are only interested in checking one element.  */
3456               struct probe *p = VEC_index (probe_p, ret, 0);
3457
3458               if (!can_evaluate_probe_arguments (p))
3459                 {
3460                   /* We cannot use the probe interface here, because it does
3461                      not know how to evaluate arguments.  */
3462                   VEC_free (probe_p, ret);
3463                   ret = NULL;
3464                 }
3465             }
3466           bp_objfile_data->longjmp_probes = ret;
3467           bp_objfile_data->longjmp_searched = 1;
3468         }
3469
3470       if (bp_objfile_data->longjmp_probes != NULL)
3471         {
3472           int i;
3473           struct probe *probe;
3474           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3475
3476           for (i = 0;
3477                VEC_iterate (probe_p,
3478                             bp_objfile_data->longjmp_probes,
3479                             i, probe);
3480                ++i)
3481             {
3482               struct breakpoint *b;
3483
3484               b = create_internal_breakpoint (gdbarch,
3485                                               get_probe_address (probe,
3486                                                                  objfile),
3487                                               bp_longjmp_master,
3488                                               &internal_breakpoint_ops);
3489               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3490               b->enable_state = bp_disabled;
3491             }
3492
3493           continue;
3494         }
3495
3496       if (!gdbarch_get_longjmp_target_p (gdbarch))
3497         continue;
3498
3499       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3500         {
3501           struct breakpoint *b;
3502           const char *func_name;
3503           CORE_ADDR addr;
3504
3505           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3506             continue;
3507
3508           func_name = longjmp_names[i];
3509           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3510             {
3511               struct bound_minimal_symbol m;
3512
3513               m = lookup_minimal_symbol_text (func_name, objfile);
3514               if (m.minsym == NULL)
3515                 {
3516                   /* Prevent future lookups in this objfile.  */
3517                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3518                   continue;
3519                 }
3520               bp_objfile_data->longjmp_msym[i] = m;
3521             }
3522
3523           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3524           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3525                                           &internal_breakpoint_ops);
3526           b->addr_string = xstrdup (func_name);
3527           b->enable_state = bp_disabled;
3528         }
3529     }
3530   }
3531   update_global_location_list (UGLL_MAY_INSERT);
3532
3533   do_cleanups (old_chain);
3534 }
3535
3536 /* Create a master std::terminate breakpoint.  */
3537 static void
3538 create_std_terminate_master_breakpoint (void)
3539 {
3540   struct program_space *pspace;
3541   struct cleanup *old_chain;
3542   const char *const func_name = "std::terminate()";
3543
3544   old_chain = save_current_program_space ();
3545
3546   ALL_PSPACES (pspace)
3547   {
3548     struct objfile *objfile;
3549     CORE_ADDR addr;
3550
3551     set_current_program_space (pspace);
3552
3553     ALL_OBJFILES (objfile)
3554     {
3555       struct breakpoint *b;
3556       struct breakpoint_objfile_data *bp_objfile_data;
3557
3558       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3559
3560       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3561         continue;
3562
3563       if (bp_objfile_data->terminate_msym.minsym == NULL)
3564         {
3565           struct bound_minimal_symbol m;
3566
3567           m = lookup_minimal_symbol (func_name, NULL, objfile);
3568           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3569                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3570             {
3571               /* Prevent future lookups in this objfile.  */
3572               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3573               continue;
3574             }
3575           bp_objfile_data->terminate_msym = m;
3576         }
3577
3578       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3579       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3580                                       bp_std_terminate_master,
3581                                       &internal_breakpoint_ops);
3582       b->addr_string = xstrdup (func_name);
3583       b->enable_state = bp_disabled;
3584     }
3585   }
3586
3587   update_global_location_list (UGLL_MAY_INSERT);
3588
3589   do_cleanups (old_chain);
3590 }
3591
3592 /* Install a master breakpoint on the unwinder's debug hook.  */
3593
3594 static void
3595 create_exception_master_breakpoint (void)
3596 {
3597   struct objfile *objfile;
3598   const char *const func_name = "_Unwind_DebugHook";
3599
3600   ALL_OBJFILES (objfile)
3601     {
3602       struct breakpoint *b;
3603       struct gdbarch *gdbarch;
3604       struct breakpoint_objfile_data *bp_objfile_data;
3605       CORE_ADDR addr;
3606
3607       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3608
3609       /* We prefer the SystemTap probe point if it exists.  */
3610       if (!bp_objfile_data->exception_searched)
3611         {
3612           VEC (probe_p) *ret;
3613
3614           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3615
3616           if (ret != NULL)
3617             {
3618               /* We are only interested in checking one element.  */
3619               struct probe *p = VEC_index (probe_p, ret, 0);
3620
3621               if (!can_evaluate_probe_arguments (p))
3622                 {
3623                   /* We cannot use the probe interface here, because it does
3624                      not know how to evaluate arguments.  */
3625                   VEC_free (probe_p, ret);
3626                   ret = NULL;
3627                 }
3628             }
3629           bp_objfile_data->exception_probes = ret;
3630           bp_objfile_data->exception_searched = 1;
3631         }
3632
3633       if (bp_objfile_data->exception_probes != NULL)
3634         {
3635           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3636           int i;
3637           struct probe *probe;
3638
3639           for (i = 0;
3640                VEC_iterate (probe_p,
3641                             bp_objfile_data->exception_probes,
3642                             i, probe);
3643                ++i)
3644             {
3645               struct breakpoint *b;
3646
3647               b = create_internal_breakpoint (gdbarch,
3648                                               get_probe_address (probe,
3649                                                                  objfile),
3650                                               bp_exception_master,
3651                                               &internal_breakpoint_ops);
3652               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3653               b->enable_state = bp_disabled;
3654             }
3655
3656           continue;
3657         }
3658
3659       /* Otherwise, try the hook function.  */
3660
3661       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3662         continue;
3663
3664       gdbarch = get_objfile_arch (objfile);
3665
3666       if (bp_objfile_data->exception_msym.minsym == NULL)
3667         {
3668           struct bound_minimal_symbol debug_hook;
3669
3670           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3671           if (debug_hook.minsym == NULL)
3672             {
3673               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3674               continue;
3675             }
3676
3677           bp_objfile_data->exception_msym = debug_hook;
3678         }
3679
3680       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3681       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3682                                                  &current_target);
3683       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3684                                       &internal_breakpoint_ops);
3685       b->addr_string = xstrdup (func_name);
3686       b->enable_state = bp_disabled;
3687     }
3688
3689   update_global_location_list (UGLL_MAY_INSERT);
3690 }
3691
3692 void
3693 update_breakpoints_after_exec (void)
3694 {
3695   struct breakpoint *b, *b_tmp;
3696   struct bp_location *bploc, **bplocp_tmp;
3697
3698   /* We're about to delete breakpoints from GDB's lists.  If the
3699      INSERTED flag is true, GDB will try to lift the breakpoints by
3700      writing the breakpoints' "shadow contents" back into memory.  The
3701      "shadow contents" are NOT valid after an exec, so GDB should not
3702      do that.  Instead, the target is responsible from marking
3703      breakpoints out as soon as it detects an exec.  We don't do that
3704      here instead, because there may be other attempts to delete
3705      breakpoints after detecting an exec and before reaching here.  */
3706   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3707     if (bploc->pspace == current_program_space)
3708       gdb_assert (!bploc->inserted);
3709
3710   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3711   {
3712     if (b->pspace != current_program_space)
3713       continue;
3714
3715     /* Solib breakpoints must be explicitly reset after an exec().  */
3716     if (b->type == bp_shlib_event)
3717       {
3718         delete_breakpoint (b);
3719         continue;
3720       }
3721
3722     /* JIT breakpoints must be explicitly reset after an exec().  */
3723     if (b->type == bp_jit_event)
3724       {
3725         delete_breakpoint (b);
3726         continue;
3727       }
3728
3729     /* Thread event breakpoints must be set anew after an exec(),
3730        as must overlay event and longjmp master breakpoints.  */
3731     if (b->type == bp_thread_event || b->type == bp_overlay_event
3732         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3733         || b->type == bp_exception_master)
3734       {
3735         delete_breakpoint (b);
3736         continue;
3737       }
3738
3739     /* Step-resume breakpoints are meaningless after an exec().  */
3740     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3741       {
3742         delete_breakpoint (b);
3743         continue;
3744       }
3745
3746     /* Longjmp and longjmp-resume breakpoints are also meaningless
3747        after an exec.  */
3748     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3749         || b->type == bp_longjmp_call_dummy
3750         || b->type == bp_exception || b->type == bp_exception_resume)
3751       {
3752         delete_breakpoint (b);
3753         continue;
3754       }
3755
3756     if (b->type == bp_catchpoint)
3757       {
3758         /* For now, none of the bp_catchpoint breakpoints need to
3759            do anything at this point.  In the future, if some of
3760            the catchpoints need to something, we will need to add
3761            a new method, and call this method from here.  */
3762         continue;
3763       }
3764
3765     /* bp_finish is a special case.  The only way we ought to be able
3766        to see one of these when an exec() has happened, is if the user
3767        caught a vfork, and then said "finish".  Ordinarily a finish just
3768        carries them to the call-site of the current callee, by setting
3769        a temporary bp there and resuming.  But in this case, the finish
3770        will carry them entirely through the vfork & exec.
3771
3772        We don't want to allow a bp_finish to remain inserted now.  But
3773        we can't safely delete it, 'cause finish_command has a handle to
3774        the bp on a bpstat, and will later want to delete it.  There's a
3775        chance (and I've seen it happen) that if we delete the bp_finish
3776        here, that its storage will get reused by the time finish_command
3777        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3778        We really must allow finish_command to delete a bp_finish.
3779
3780        In the absence of a general solution for the "how do we know
3781        it's safe to delete something others may have handles to?"
3782        problem, what we'll do here is just uninsert the bp_finish, and
3783        let finish_command delete it.
3784
3785        (We know the bp_finish is "doomed" in the sense that it's
3786        momentary, and will be deleted as soon as finish_command sees
3787        the inferior stopped.  So it doesn't matter that the bp's
3788        address is probably bogus in the new a.out, unlike e.g., the
3789        solib breakpoints.)  */
3790
3791     if (b->type == bp_finish)
3792       {
3793         continue;
3794       }
3795
3796     /* Without a symbolic address, we have little hope of the
3797        pre-exec() address meaning the same thing in the post-exec()
3798        a.out.  */
3799     if (b->addr_string == NULL)
3800       {
3801         delete_breakpoint (b);
3802         continue;
3803       }
3804   }
3805   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3806   create_overlay_event_breakpoint ();
3807   create_longjmp_master_breakpoint ();
3808   create_std_terminate_master_breakpoint ();
3809   create_exception_master_breakpoint ();
3810 }
3811
3812 int
3813 detach_breakpoints (ptid_t ptid)
3814 {
3815   struct bp_location *bl, **blp_tmp;
3816   int val = 0;
3817   struct cleanup *old_chain = save_inferior_ptid ();
3818   struct inferior *inf = current_inferior ();
3819
3820   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3821     error (_("Cannot detach breakpoints of inferior_ptid"));
3822
3823   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3824   inferior_ptid = ptid;
3825   ALL_BP_LOCATIONS (bl, blp_tmp)
3826   {
3827     if (bl->pspace != inf->pspace)
3828       continue;
3829
3830     /* This function must physically remove breakpoints locations
3831        from the specified ptid, without modifying the breakpoint
3832        package's state.  Locations of type bp_loc_other are only
3833        maintained at GDB side.  So, there is no need to remove
3834        these bp_loc_other locations.  Moreover, removing these
3835        would modify the breakpoint package's state.  */
3836     if (bl->loc_type == bp_loc_other)
3837       continue;
3838
3839     if (bl->inserted)
3840       val |= remove_breakpoint_1 (bl, mark_inserted);
3841   }
3842
3843   /* Detach single-step breakpoints as well.  */
3844   detach_single_step_breakpoints ();
3845
3846   do_cleanups (old_chain);
3847   return val;
3848 }
3849
3850 /* Remove the breakpoint location BL from the current address space.
3851    Note that this is used to detach breakpoints from a child fork.
3852    When we get here, the child isn't in the inferior list, and neither
3853    do we have objects to represent its address space --- we should
3854    *not* look at bl->pspace->aspace here.  */
3855
3856 static int
3857 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3858 {
3859   int val;
3860
3861   /* BL is never in moribund_locations by our callers.  */
3862   gdb_assert (bl->owner != NULL);
3863
3864   if (bl->owner->enable_state == bp_permanent)
3865     /* Permanent breakpoints cannot be inserted or removed.  */
3866     return 0;
3867
3868   /* The type of none suggests that owner is actually deleted.
3869      This should not ever happen.  */
3870   gdb_assert (bl->owner->type != bp_none);
3871
3872   if (bl->loc_type == bp_loc_software_breakpoint
3873       || bl->loc_type == bp_loc_hardware_breakpoint)
3874     {
3875       /* "Normal" instruction breakpoint: either the standard
3876          trap-instruction bp (bp_breakpoint), or a
3877          bp_hardware_breakpoint.  */
3878
3879       /* First check to see if we have to handle an overlay.  */
3880       if (overlay_debugging == ovly_off
3881           || bl->section == NULL
3882           || !(section_is_overlay (bl->section)))
3883         {
3884           /* No overlay handling: just remove the breakpoint.  */
3885
3886           /* If we're trying to uninsert a memory breakpoint that we
3887              know is set in a dynamic object that is marked
3888              shlib_disabled, then either the dynamic object was
3889              removed with "remove-symbol-file" or with
3890              "nosharedlibrary".  In the former case, we don't know
3891              whether another dynamic object might have loaded over the
3892              breakpoint's address -- the user might well let us know
3893              about it next with add-symbol-file (the whole point of
3894              add-symbol-file is letting the user manually maintain a
3895              list of dynamically loaded objects).  If we have the
3896              breakpoint's shadow memory, that is, this is a software
3897              breakpoint managed by GDB, check whether the breakpoint
3898              is still inserted in memory, to avoid overwriting wrong
3899              code with stale saved shadow contents.  Note that HW
3900              breakpoints don't have shadow memory, as they're
3901              implemented using a mechanism that is not dependent on
3902              being able to modify the target's memory, and as such
3903              they should always be removed.  */
3904           if (bl->shlib_disabled
3905               && bl->target_info.shadow_len != 0
3906               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3907             val = 0;
3908           else
3909             val = bl->owner->ops->remove_location (bl);
3910         }
3911       else
3912         {
3913           /* This breakpoint is in an overlay section.
3914              Did we set a breakpoint at the LMA?  */
3915           if (!overlay_events_enabled)
3916               {
3917                 /* Yes -- overlay event support is not active, so we
3918                    should have set a breakpoint at the LMA.  Remove it.  
3919                 */
3920                 /* Ignore any failures: if the LMA is in ROM, we will
3921                    have already warned when we failed to insert it.  */
3922                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3923                   target_remove_hw_breakpoint (bl->gdbarch,
3924                                                &bl->overlay_target_info);
3925                 else
3926                   target_remove_breakpoint (bl->gdbarch,
3927                                             &bl->overlay_target_info);
3928               }
3929           /* Did we set a breakpoint at the VMA? 
3930              If so, we will have marked the breakpoint 'inserted'.  */
3931           if (bl->inserted)
3932             {
3933               /* Yes -- remove it.  Previously we did not bother to
3934                  remove the breakpoint if the section had been
3935                  unmapped, but let's not rely on that being safe.  We
3936                  don't know what the overlay manager might do.  */
3937
3938               /* However, we should remove *software* breakpoints only
3939                  if the section is still mapped, or else we overwrite
3940                  wrong code with the saved shadow contents.  */
3941               if (bl->loc_type == bp_loc_hardware_breakpoint
3942                   || section_is_mapped (bl->section))
3943                 val = bl->owner->ops->remove_location (bl);
3944               else
3945                 val = 0;
3946             }
3947           else
3948             {
3949               /* No -- not inserted, so no need to remove.  No error.  */
3950               val = 0;
3951             }
3952         }
3953
3954       /* In some cases, we might not be able to remove a breakpoint in
3955          a shared library that has already been removed, but we have
3956          not yet processed the shlib unload event.  Similarly for an
3957          unloaded add-symbol-file object - the user might not yet have
3958          had the chance to remove-symbol-file it.  shlib_disabled will
3959          be set if the library/object has already been removed, but
3960          the breakpoint hasn't been uninserted yet, e.g., after
3961          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3962          always-inserted mode.  */
3963       if (val
3964           && (bl->loc_type == bp_loc_software_breakpoint
3965               && (bl->shlib_disabled
3966                   || solib_name_from_address (bl->pspace, bl->address)
3967                   || shared_objfile_contains_address_p (bl->pspace,
3968                                                         bl->address))))
3969         val = 0;
3970
3971       if (val)
3972         return val;
3973       bl->inserted = (is == mark_inserted);
3974     }
3975   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3976     {
3977       gdb_assert (bl->owner->ops != NULL
3978                   && bl->owner->ops->remove_location != NULL);
3979
3980       bl->inserted = (is == mark_inserted);
3981       bl->owner->ops->remove_location (bl);
3982
3983       /* Failure to remove any of the hardware watchpoints comes here.  */
3984       if ((is == mark_uninserted) && (bl->inserted))
3985         warning (_("Could not remove hardware watchpoint %d."),
3986                  bl->owner->number);
3987     }
3988   else if (bl->owner->type == bp_catchpoint
3989            && breakpoint_enabled (bl->owner)
3990            && !bl->duplicate)
3991     {
3992       gdb_assert (bl->owner->ops != NULL
3993                   && bl->owner->ops->remove_location != NULL);
3994
3995       val = bl->owner->ops->remove_location (bl);
3996       if (val)
3997         return val;
3998
3999       bl->inserted = (is == mark_inserted);
4000     }
4001
4002   return 0;
4003 }
4004
4005 static int
4006 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4007 {
4008   int ret;
4009   struct cleanup *old_chain;
4010
4011   /* BL is never in moribund_locations by our callers.  */
4012   gdb_assert (bl->owner != NULL);
4013
4014   if (bl->owner->enable_state == bp_permanent)
4015     /* Permanent breakpoints cannot be inserted or removed.  */
4016     return 0;
4017
4018   /* The type of none suggests that owner is actually deleted.
4019      This should not ever happen.  */
4020   gdb_assert (bl->owner->type != bp_none);
4021
4022   old_chain = save_current_space_and_thread ();
4023
4024   switch_to_program_space_and_thread (bl->pspace);
4025
4026   ret = remove_breakpoint_1 (bl, is);
4027
4028   do_cleanups (old_chain);
4029   return ret;
4030 }
4031
4032 /* Clear the "inserted" flag in all breakpoints.  */
4033
4034 void
4035 mark_breakpoints_out (void)
4036 {
4037   struct bp_location *bl, **blp_tmp;
4038
4039   ALL_BP_LOCATIONS (bl, blp_tmp)
4040     if (bl->pspace == current_program_space)
4041       bl->inserted = 0;
4042 }
4043
4044 /* Clear the "inserted" flag in all breakpoints and delete any
4045    breakpoints which should go away between runs of the program.
4046
4047    Plus other such housekeeping that has to be done for breakpoints
4048    between runs.
4049
4050    Note: this function gets called at the end of a run (by
4051    generic_mourn_inferior) and when a run begins (by
4052    init_wait_for_inferior).  */
4053
4054
4055
4056 void
4057 breakpoint_init_inferior (enum inf_context context)
4058 {
4059   struct breakpoint *b, *b_tmp;
4060   struct bp_location *bl, **blp_tmp;
4061   int ix;
4062   struct program_space *pspace = current_program_space;
4063
4064   /* If breakpoint locations are shared across processes, then there's
4065      nothing to do.  */
4066   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4067     return;
4068
4069   ALL_BP_LOCATIONS (bl, blp_tmp)
4070   {
4071     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4072     if (bl->pspace == pspace
4073         && bl->owner->enable_state != bp_permanent)
4074       bl->inserted = 0;
4075   }
4076
4077   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4078   {
4079     if (b->loc && b->loc->pspace != pspace)
4080       continue;
4081
4082     switch (b->type)
4083       {
4084       case bp_call_dummy:
4085       case bp_longjmp_call_dummy:
4086
4087         /* If the call dummy breakpoint is at the entry point it will
4088            cause problems when the inferior is rerun, so we better get
4089            rid of it.  */
4090
4091       case bp_watchpoint_scope:
4092
4093         /* Also get rid of scope breakpoints.  */
4094
4095       case bp_shlib_event:
4096
4097         /* Also remove solib event breakpoints.  Their addresses may
4098            have changed since the last time we ran the program.
4099            Actually we may now be debugging against different target;
4100            and so the solib backend that installed this breakpoint may
4101            not be used in by the target.  E.g.,
4102
4103            (gdb) file prog-linux
4104            (gdb) run               # native linux target
4105            ...
4106            (gdb) kill
4107            (gdb) file prog-win.exe
4108            (gdb) tar rem :9999     # remote Windows gdbserver.
4109         */
4110
4111       case bp_step_resume:
4112
4113         /* Also remove step-resume breakpoints.  */
4114
4115         delete_breakpoint (b);
4116         break;
4117
4118       case bp_watchpoint:
4119       case bp_hardware_watchpoint:
4120       case bp_read_watchpoint:
4121       case bp_access_watchpoint:
4122         {
4123           struct watchpoint *w = (struct watchpoint *) b;
4124
4125           /* Likewise for watchpoints on local expressions.  */
4126           if (w->exp_valid_block != NULL)
4127             delete_breakpoint (b);
4128           else if (context == inf_starting)
4129             {
4130               /* Reset val field to force reread of starting value in
4131                  insert_breakpoints.  */
4132               if (w->val)
4133                 value_free (w->val);
4134               w->val = NULL;
4135               w->val_valid = 0;
4136           }
4137         }
4138         break;
4139       default:
4140         break;
4141       }
4142   }
4143
4144   /* Get rid of the moribund locations.  */
4145   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4146     decref_bp_location (&bl);
4147   VEC_free (bp_location_p, moribund_locations);
4148 }
4149
4150 /* These functions concern about actual breakpoints inserted in the
4151    target --- to e.g. check if we need to do decr_pc adjustment or if
4152    we need to hop over the bkpt --- so we check for address space
4153    match, not program space.  */
4154
4155 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4156    exists at PC.  It returns ordinary_breakpoint_here if it's an
4157    ordinary breakpoint, or permanent_breakpoint_here if it's a
4158    permanent breakpoint.
4159    - When continuing from a location with an ordinary breakpoint, we
4160      actually single step once before calling insert_breakpoints.
4161    - When continuing from a location with a permanent breakpoint, we
4162      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4163      the target, to advance the PC past the breakpoint.  */
4164
4165 enum breakpoint_here
4166 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4167 {
4168   struct bp_location *bl, **blp_tmp;
4169   int any_breakpoint_here = 0;
4170
4171   ALL_BP_LOCATIONS (bl, blp_tmp)
4172     {
4173       if (bl->loc_type != bp_loc_software_breakpoint
4174           && bl->loc_type != bp_loc_hardware_breakpoint)
4175         continue;
4176
4177       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4178       if ((breakpoint_enabled (bl->owner)
4179            || bl->owner->enable_state == bp_permanent)
4180           && breakpoint_location_address_match (bl, aspace, pc))
4181         {
4182           if (overlay_debugging 
4183               && section_is_overlay (bl->section)
4184               && !section_is_mapped (bl->section))
4185             continue;           /* unmapped overlay -- can't be a match */
4186           else if (bl->owner->enable_state == bp_permanent)
4187             return permanent_breakpoint_here;
4188           else
4189             any_breakpoint_here = 1;
4190         }
4191     }
4192
4193   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4194 }
4195
4196 /* Return true if there's a moribund breakpoint at PC.  */
4197
4198 int
4199 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4200 {
4201   struct bp_location *loc;
4202   int ix;
4203
4204   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4205     if (breakpoint_location_address_match (loc, aspace, pc))
4206       return 1;
4207
4208   return 0;
4209 }
4210
4211 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4212    inserted using regular breakpoint_chain / bp_location array
4213    mechanism.  This does not check for single-step breakpoints, which
4214    are inserted and removed using direct target manipulation.  */
4215
4216 int
4217 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4218                                     CORE_ADDR pc)
4219 {
4220   struct bp_location *bl, **blp_tmp;
4221
4222   ALL_BP_LOCATIONS (bl, blp_tmp)
4223     {
4224       if (bl->loc_type != bp_loc_software_breakpoint
4225           && bl->loc_type != bp_loc_hardware_breakpoint)
4226         continue;
4227
4228       if (bl->inserted
4229           && breakpoint_location_address_match (bl, aspace, pc))
4230         {
4231           if (overlay_debugging 
4232               && section_is_overlay (bl->section)
4233               && !section_is_mapped (bl->section))
4234             continue;           /* unmapped overlay -- can't be a match */
4235           else
4236             return 1;
4237         }
4238     }
4239   return 0;
4240 }
4241
4242 /* Returns non-zero iff there's either regular breakpoint
4243    or a single step breakpoint inserted at PC.  */
4244
4245 int
4246 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4247 {
4248   if (regular_breakpoint_inserted_here_p (aspace, pc))
4249     return 1;
4250
4251   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4252     return 1;
4253
4254   return 0;
4255 }
4256
4257 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4258    software breakpoint inserted at PC.  */
4259
4260 static struct bp_location *
4261 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4262                                                 CORE_ADDR pc)
4263 {
4264   struct bp_location *bl, **blp_tmp;
4265
4266   ALL_BP_LOCATIONS (bl, blp_tmp)
4267     {
4268       if (bl->loc_type != bp_loc_software_breakpoint)
4269         continue;
4270
4271       if (bl->inserted
4272           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4273                                        aspace, pc))
4274         {
4275           if (overlay_debugging 
4276               && section_is_overlay (bl->section)
4277               && !section_is_mapped (bl->section))
4278             continue;           /* unmapped overlay -- can't be a match */
4279           else
4280             return bl;
4281         }
4282     }
4283
4284   return NULL;
4285 }
4286
4287 /* This function returns non-zero iff there is a software breakpoint
4288    inserted at PC.  */
4289
4290 int
4291 software_breakpoint_inserted_here_p (struct address_space *aspace,
4292                                      CORE_ADDR pc)
4293 {
4294   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4295     return 1;
4296
4297   /* Also check for software single-step breakpoints.  */
4298   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4299     return 1;
4300
4301   return 0;
4302 }
4303
4304 int
4305 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4306                                        CORE_ADDR addr, ULONGEST len)
4307 {
4308   struct breakpoint *bpt;
4309
4310   ALL_BREAKPOINTS (bpt)
4311     {
4312       struct bp_location *loc;
4313
4314       if (bpt->type != bp_hardware_watchpoint
4315           && bpt->type != bp_access_watchpoint)
4316         continue;
4317
4318       if (!breakpoint_enabled (bpt))
4319         continue;
4320
4321       for (loc = bpt->loc; loc; loc = loc->next)
4322         if (loc->pspace->aspace == aspace && loc->inserted)
4323           {
4324             CORE_ADDR l, h;
4325
4326             /* Check for intersection.  */
4327             l = max (loc->address, addr);
4328             h = min (loc->address + loc->length, addr + len);
4329             if (l < h)
4330               return 1;
4331           }
4332     }
4333   return 0;
4334 }
4335
4336 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4337    PC is valid for process/thread PTID.  */
4338
4339 int
4340 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4341                          ptid_t ptid)
4342 {
4343   struct bp_location *bl, **blp_tmp;
4344   /* The thread and task IDs associated to PTID, computed lazily.  */
4345   int thread = -1;
4346   int task = 0;
4347   
4348   ALL_BP_LOCATIONS (bl, blp_tmp)
4349     {
4350       if (bl->loc_type != bp_loc_software_breakpoint
4351           && bl->loc_type != bp_loc_hardware_breakpoint)
4352         continue;
4353
4354       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4355       if (!breakpoint_enabled (bl->owner)
4356           && bl->owner->enable_state != bp_permanent)
4357         continue;
4358
4359       if (!breakpoint_location_address_match (bl, aspace, pc))
4360         continue;
4361
4362       if (bl->owner->thread != -1)
4363         {
4364           /* This is a thread-specific breakpoint.  Check that ptid
4365              matches that thread.  If thread hasn't been computed yet,
4366              it is now time to do so.  */
4367           if (thread == -1)
4368             thread = pid_to_thread_id (ptid);
4369           if (bl->owner->thread != thread)
4370             continue;
4371         }
4372
4373       if (bl->owner->task != 0)
4374         {
4375           /* This is a task-specific breakpoint.  Check that ptid
4376              matches that task.  If task hasn't been computed yet,
4377              it is now time to do so.  */
4378           if (task == 0)
4379             task = ada_get_task_number (ptid);
4380           if (bl->owner->task != task)
4381             continue;
4382         }
4383
4384       if (overlay_debugging 
4385           && section_is_overlay (bl->section)
4386           && !section_is_mapped (bl->section))
4387         continue;           /* unmapped overlay -- can't be a match */
4388
4389       return 1;
4390     }
4391
4392   return 0;
4393 }
4394 \f
4395
4396 /* bpstat stuff.  External routines' interfaces are documented
4397    in breakpoint.h.  */
4398
4399 int
4400 is_catchpoint (struct breakpoint *ep)
4401 {
4402   return (ep->type == bp_catchpoint);
4403 }
4404
4405 /* Frees any storage that is part of a bpstat.  Does not walk the
4406    'next' chain.  */
4407
4408 static void
4409 bpstat_free (bpstat bs)
4410 {
4411   if (bs->old_val != NULL)
4412     value_free (bs->old_val);
4413   decref_counted_command_line (&bs->commands);
4414   decref_bp_location (&bs->bp_location_at);
4415   xfree (bs);
4416 }
4417
4418 /* Clear a bpstat so that it says we are not at any breakpoint.
4419    Also free any storage that is part of a bpstat.  */
4420
4421 void
4422 bpstat_clear (bpstat *bsp)
4423 {
4424   bpstat p;
4425   bpstat q;
4426
4427   if (bsp == 0)
4428     return;
4429   p = *bsp;
4430   while (p != NULL)
4431     {
4432       q = p->next;
4433       bpstat_free (p);
4434       p = q;
4435     }
4436   *bsp = NULL;
4437 }
4438
4439 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4440    is part of the bpstat is copied as well.  */
4441
4442 bpstat
4443 bpstat_copy (bpstat bs)
4444 {
4445   bpstat p = NULL;
4446   bpstat tmp;
4447   bpstat retval = NULL;
4448
4449   if (bs == NULL)
4450     return bs;
4451
4452   for (; bs != NULL; bs = bs->next)
4453     {
4454       tmp = (bpstat) xmalloc (sizeof (*tmp));
4455       memcpy (tmp, bs, sizeof (*tmp));
4456       incref_counted_command_line (tmp->commands);
4457       incref_bp_location (tmp->bp_location_at);
4458       if (bs->old_val != NULL)
4459         {
4460           tmp->old_val = value_copy (bs->old_val);
4461           release_value (tmp->old_val);
4462         }
4463
4464       if (p == NULL)
4465         /* This is the first thing in the chain.  */
4466         retval = tmp;
4467       else
4468         p->next = tmp;
4469       p = tmp;
4470     }
4471   p->next = NULL;
4472   return retval;
4473 }
4474
4475 /* Find the bpstat associated with this breakpoint.  */
4476
4477 bpstat
4478 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4479 {
4480   if (bsp == NULL)
4481     return NULL;
4482
4483   for (; bsp != NULL; bsp = bsp->next)
4484     {
4485       if (bsp->breakpoint_at == breakpoint)
4486         return bsp;
4487     }
4488   return NULL;
4489 }
4490
4491 /* See breakpoint.h.  */
4492
4493 int
4494 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4495 {
4496   for (; bsp != NULL; bsp = bsp->next)
4497     {
4498       if (bsp->breakpoint_at == NULL)
4499         {
4500           /* A moribund location can never explain a signal other than
4501              GDB_SIGNAL_TRAP.  */
4502           if (sig == GDB_SIGNAL_TRAP)
4503             return 1;
4504         }
4505       else
4506         {
4507           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4508                                                         sig))
4509             return 1;
4510         }
4511     }
4512
4513   return 0;
4514 }
4515
4516 /* Put in *NUM the breakpoint number of the first breakpoint we are
4517    stopped at.  *BSP upon return is a bpstat which points to the
4518    remaining breakpoints stopped at (but which is not guaranteed to be
4519    good for anything but further calls to bpstat_num).
4520
4521    Return 0 if passed a bpstat which does not indicate any breakpoints.
4522    Return -1 if stopped at a breakpoint that has been deleted since
4523    we set it.
4524    Return 1 otherwise.  */
4525
4526 int
4527 bpstat_num (bpstat *bsp, int *num)
4528 {
4529   struct breakpoint *b;
4530
4531   if ((*bsp) == NULL)
4532     return 0;                   /* No more breakpoint values */
4533
4534   /* We assume we'll never have several bpstats that correspond to a
4535      single breakpoint -- otherwise, this function might return the
4536      same number more than once and this will look ugly.  */
4537   b = (*bsp)->breakpoint_at;
4538   *bsp = (*bsp)->next;
4539   if (b == NULL)
4540     return -1;                  /* breakpoint that's been deleted since */
4541
4542   *num = b->number;             /* We have its number */
4543   return 1;
4544 }
4545
4546 /* See breakpoint.h.  */
4547
4548 void
4549 bpstat_clear_actions (void)
4550 {
4551   struct thread_info *tp;
4552   bpstat bs;
4553
4554   if (ptid_equal (inferior_ptid, null_ptid))
4555     return;
4556
4557   tp = find_thread_ptid (inferior_ptid);
4558   if (tp == NULL)
4559     return;
4560
4561   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4562     {
4563       decref_counted_command_line (&bs->commands);
4564
4565       if (bs->old_val != NULL)
4566         {
4567           value_free (bs->old_val);
4568           bs->old_val = NULL;
4569         }
4570     }
4571 }
4572
4573 /* Called when a command is about to proceed the inferior.  */
4574
4575 static void
4576 breakpoint_about_to_proceed (void)
4577 {
4578   if (!ptid_equal (inferior_ptid, null_ptid))
4579     {
4580       struct thread_info *tp = inferior_thread ();
4581
4582       /* Allow inferior function calls in breakpoint commands to not
4583          interrupt the command list.  When the call finishes
4584          successfully, the inferior will be standing at the same
4585          breakpoint as if nothing happened.  */
4586       if (tp->control.in_infcall)
4587         return;
4588     }
4589
4590   breakpoint_proceeded = 1;
4591 }
4592
4593 /* Stub for cleaning up our state if we error-out of a breakpoint
4594    command.  */
4595 static void
4596 cleanup_executing_breakpoints (void *ignore)
4597 {
4598   executing_breakpoint_commands = 0;
4599 }
4600
4601 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4602    or its equivalent.  */
4603
4604 static int
4605 command_line_is_silent (struct command_line *cmd)
4606 {
4607   return cmd && (strcmp ("silent", cmd->line) == 0
4608                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4609 }
4610
4611 /* Execute all the commands associated with all the breakpoints at
4612    this location.  Any of these commands could cause the process to
4613    proceed beyond this point, etc.  We look out for such changes by
4614    checking the global "breakpoint_proceeded" after each command.
4615
4616    Returns true if a breakpoint command resumed the inferior.  In that
4617    case, it is the caller's responsibility to recall it again with the
4618    bpstat of the current thread.  */
4619
4620 static int
4621 bpstat_do_actions_1 (bpstat *bsp)
4622 {
4623   bpstat bs;
4624   struct cleanup *old_chain;
4625   int again = 0;
4626
4627   /* Avoid endless recursion if a `source' command is contained
4628      in bs->commands.  */
4629   if (executing_breakpoint_commands)
4630     return 0;
4631
4632   executing_breakpoint_commands = 1;
4633   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4634
4635   prevent_dont_repeat ();
4636
4637   /* This pointer will iterate over the list of bpstat's.  */
4638   bs = *bsp;
4639
4640   breakpoint_proceeded = 0;
4641   for (; bs != NULL; bs = bs->next)
4642     {
4643       struct counted_command_line *ccmd;
4644       struct command_line *cmd;
4645       struct cleanup *this_cmd_tree_chain;
4646
4647       /* Take ownership of the BSP's command tree, if it has one.
4648
4649          The command tree could legitimately contain commands like
4650          'step' and 'next', which call clear_proceed_status, which
4651          frees stop_bpstat's command tree.  To make sure this doesn't
4652          free the tree we're executing out from under us, we need to
4653          take ownership of the tree ourselves.  Since a given bpstat's
4654          commands are only executed once, we don't need to copy it; we
4655          can clear the pointer in the bpstat, and make sure we free
4656          the tree when we're done.  */
4657       ccmd = bs->commands;
4658       bs->commands = NULL;
4659       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4660       cmd = ccmd ? ccmd->commands : NULL;
4661       if (command_line_is_silent (cmd))
4662         {
4663           /* The action has been already done by bpstat_stop_status.  */
4664           cmd = cmd->next;
4665         }
4666
4667       while (cmd != NULL)
4668         {
4669           execute_control_command (cmd);
4670
4671           if (breakpoint_proceeded)
4672             break;
4673           else
4674             cmd = cmd->next;
4675         }
4676
4677       /* We can free this command tree now.  */
4678       do_cleanups (this_cmd_tree_chain);
4679
4680       if (breakpoint_proceeded)
4681         {
4682           if (target_can_async_p ())
4683             /* If we are in async mode, then the target might be still
4684                running, not stopped at any breakpoint, so nothing for
4685                us to do here -- just return to the event loop.  */
4686             ;
4687           else
4688             /* In sync mode, when execute_control_command returns
4689                we're already standing on the next breakpoint.
4690                Breakpoint commands for that stop were not run, since
4691                execute_command does not run breakpoint commands --
4692                only command_line_handler does, but that one is not
4693                involved in execution of breakpoint commands.  So, we
4694                can now execute breakpoint commands.  It should be
4695                noted that making execute_command do bpstat actions is
4696                not an option -- in this case we'll have recursive
4697                invocation of bpstat for each breakpoint with a
4698                command, and can easily blow up GDB stack.  Instead, we
4699                return true, which will trigger the caller to recall us
4700                with the new stop_bpstat.  */
4701             again = 1;
4702           break;
4703         }
4704     }
4705   do_cleanups (old_chain);
4706   return again;
4707 }
4708
4709 void
4710 bpstat_do_actions (void)
4711 {
4712   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4713
4714   /* Do any commands attached to breakpoint we are stopped at.  */
4715   while (!ptid_equal (inferior_ptid, null_ptid)
4716          && target_has_execution
4717          && !is_exited (inferior_ptid)
4718          && !is_executing (inferior_ptid))
4719     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4720        and only return when it is stopped at the next breakpoint, we
4721        keep doing breakpoint actions until it returns false to
4722        indicate the inferior was not resumed.  */
4723     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4724       break;
4725
4726   discard_cleanups (cleanup_if_error);
4727 }
4728
4729 /* Print out the (old or new) value associated with a watchpoint.  */
4730
4731 static void
4732 watchpoint_value_print (struct value *val, struct ui_file *stream)
4733 {
4734   if (val == NULL)
4735     fprintf_unfiltered (stream, _("<unreadable>"));
4736   else
4737     {
4738       struct value_print_options opts;
4739       get_user_print_options (&opts);
4740       value_print (val, stream, &opts);
4741     }
4742 }
4743
4744 /* Generic routine for printing messages indicating why we
4745    stopped.  The behavior of this function depends on the value
4746    'print_it' in the bpstat structure.  Under some circumstances we
4747    may decide not to print anything here and delegate the task to
4748    normal_stop().  */
4749
4750 static enum print_stop_action
4751 print_bp_stop_message (bpstat bs)
4752 {
4753   switch (bs->print_it)
4754     {
4755     case print_it_noop:
4756       /* Nothing should be printed for this bpstat entry.  */
4757       return PRINT_UNKNOWN;
4758       break;
4759
4760     case print_it_done:
4761       /* We still want to print the frame, but we already printed the
4762          relevant messages.  */
4763       return PRINT_SRC_AND_LOC;
4764       break;
4765
4766     case print_it_normal:
4767       {
4768         struct breakpoint *b = bs->breakpoint_at;
4769
4770         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4771            which has since been deleted.  */
4772         if (b == NULL)
4773           return PRINT_UNKNOWN;
4774
4775         /* Normal case.  Call the breakpoint's print_it method.  */
4776         return b->ops->print_it (bs);
4777       }
4778       break;
4779
4780     default:
4781       internal_error (__FILE__, __LINE__,
4782                       _("print_bp_stop_message: unrecognized enum value"));
4783       break;
4784     }
4785 }
4786
4787 /* A helper function that prints a shared library stopped event.  */
4788
4789 static void
4790 print_solib_event (int is_catchpoint)
4791 {
4792   int any_deleted
4793     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4794   int any_added
4795     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4796
4797   if (!is_catchpoint)
4798     {
4799       if (any_added || any_deleted)
4800         ui_out_text (current_uiout,
4801                      _("Stopped due to shared library event:\n"));
4802       else
4803         ui_out_text (current_uiout,
4804                      _("Stopped due to shared library event (no "
4805                        "libraries added or removed)\n"));
4806     }
4807
4808   if (ui_out_is_mi_like_p (current_uiout))
4809     ui_out_field_string (current_uiout, "reason",
4810                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4811
4812   if (any_deleted)
4813     {
4814       struct cleanup *cleanup;
4815       char *name;
4816       int ix;
4817
4818       ui_out_text (current_uiout, _("  Inferior unloaded "));
4819       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4820                                                     "removed");
4821       for (ix = 0;
4822            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4823                         ix, name);
4824            ++ix)
4825         {
4826           if (ix > 0)
4827             ui_out_text (current_uiout, "    ");
4828           ui_out_field_string (current_uiout, "library", name);
4829           ui_out_text (current_uiout, "\n");
4830         }
4831
4832       do_cleanups (cleanup);
4833     }
4834
4835   if (any_added)
4836     {
4837       struct so_list *iter;
4838       int ix;
4839       struct cleanup *cleanup;
4840
4841       ui_out_text (current_uiout, _("  Inferior loaded "));
4842       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4843                                                     "added");
4844       for (ix = 0;
4845            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4846                         ix, iter);
4847            ++ix)
4848         {
4849           if (ix > 0)
4850             ui_out_text (current_uiout, "    ");
4851           ui_out_field_string (current_uiout, "library", iter->so_name);
4852           ui_out_text (current_uiout, "\n");
4853         }
4854
4855       do_cleanups (cleanup);
4856     }
4857 }
4858
4859 /* Print a message indicating what happened.  This is called from
4860    normal_stop().  The input to this routine is the head of the bpstat
4861    list - a list of the eventpoints that caused this stop.  KIND is
4862    the target_waitkind for the stopping event.  This
4863    routine calls the generic print routine for printing a message
4864    about reasons for stopping.  This will print (for example) the
4865    "Breakpoint n," part of the output.  The return value of this
4866    routine is one of:
4867
4868    PRINT_UNKNOWN: Means we printed nothing.
4869    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4870    code to print the location.  An example is 
4871    "Breakpoint 1, " which should be followed by
4872    the location.
4873    PRINT_SRC_ONLY: Means we printed something, but there is no need
4874    to also print the location part of the message.
4875    An example is the catch/throw messages, which
4876    don't require a location appended to the end.
4877    PRINT_NOTHING: We have done some printing and we don't need any 
4878    further info to be printed.  */
4879
4880 enum print_stop_action
4881 bpstat_print (bpstat bs, int kind)
4882 {
4883   int val;
4884
4885   /* Maybe another breakpoint in the chain caused us to stop.
4886      (Currently all watchpoints go on the bpstat whether hit or not.
4887      That probably could (should) be changed, provided care is taken
4888      with respect to bpstat_explains_signal).  */
4889   for (; bs; bs = bs->next)
4890     {
4891       val = print_bp_stop_message (bs);
4892       if (val == PRINT_SRC_ONLY 
4893           || val == PRINT_SRC_AND_LOC 
4894           || val == PRINT_NOTHING)
4895         return val;
4896     }
4897
4898   /* If we had hit a shared library event breakpoint,
4899      print_bp_stop_message would print out this message.  If we hit an
4900      OS-level shared library event, do the same thing.  */
4901   if (kind == TARGET_WAITKIND_LOADED)
4902     {
4903       print_solib_event (0);
4904       return PRINT_NOTHING;
4905     }
4906
4907   /* We reached the end of the chain, or we got a null BS to start
4908      with and nothing was printed.  */
4909   return PRINT_UNKNOWN;
4910 }
4911
4912 /* Evaluate the expression EXP and return 1 if value is zero.
4913    This returns the inverse of the condition because it is called
4914    from catch_errors which returns 0 if an exception happened, and if an
4915    exception happens we want execution to stop.
4916    The argument is a "struct expression *" that has been cast to a
4917    "void *" to make it pass through catch_errors.  */
4918
4919 static int
4920 breakpoint_cond_eval (void *exp)
4921 {
4922   struct value *mark = value_mark ();
4923   int i = !value_true (evaluate_expression ((struct expression *) exp));
4924
4925   value_free_to_mark (mark);
4926   return i;
4927 }
4928
4929 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4930
4931 static bpstat
4932 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4933 {
4934   bpstat bs;
4935
4936   bs = (bpstat) xmalloc (sizeof (*bs));
4937   bs->next = NULL;
4938   **bs_link_pointer = bs;
4939   *bs_link_pointer = &bs->next;
4940   bs->breakpoint_at = bl->owner;
4941   bs->bp_location_at = bl;
4942   incref_bp_location (bl);
4943   /* If the condition is false, etc., don't do the commands.  */
4944   bs->commands = NULL;
4945   bs->old_val = NULL;
4946   bs->print_it = print_it_normal;
4947   return bs;
4948 }
4949 \f
4950 /* The target has stopped with waitstatus WS.  Check if any hardware
4951    watchpoints have triggered, according to the target.  */
4952
4953 int
4954 watchpoints_triggered (struct target_waitstatus *ws)
4955 {
4956   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4957   CORE_ADDR addr;
4958   struct breakpoint *b;
4959
4960   if (!stopped_by_watchpoint)
4961     {
4962       /* We were not stopped by a watchpoint.  Mark all watchpoints
4963          as not triggered.  */
4964       ALL_BREAKPOINTS (b)
4965         if (is_hardware_watchpoint (b))
4966           {
4967             struct watchpoint *w = (struct watchpoint *) b;
4968
4969             w->watchpoint_triggered = watch_triggered_no;
4970           }
4971
4972       return 0;
4973     }
4974
4975   if (!target_stopped_data_address (&current_target, &addr))
4976     {
4977       /* We were stopped by a watchpoint, but we don't know where.
4978          Mark all watchpoints as unknown.  */
4979       ALL_BREAKPOINTS (b)
4980         if (is_hardware_watchpoint (b))
4981           {
4982             struct watchpoint *w = (struct watchpoint *) b;
4983
4984             w->watchpoint_triggered = watch_triggered_unknown;
4985           }
4986
4987       return 1;
4988     }
4989
4990   /* The target could report the data address.  Mark watchpoints
4991      affected by this data address as triggered, and all others as not
4992      triggered.  */
4993
4994   ALL_BREAKPOINTS (b)
4995     if (is_hardware_watchpoint (b))
4996       {
4997         struct watchpoint *w = (struct watchpoint *) b;
4998         struct bp_location *loc;
4999
5000         w->watchpoint_triggered = watch_triggered_no;
5001         for (loc = b->loc; loc; loc = loc->next)
5002           {
5003             if (is_masked_watchpoint (b))
5004               {
5005                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5006                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5007
5008                 if (newaddr == start)
5009                   {
5010                     w->watchpoint_triggered = watch_triggered_yes;
5011                     break;
5012                   }
5013               }
5014             /* Exact match not required.  Within range is sufficient.  */
5015             else if (target_watchpoint_addr_within_range (&current_target,
5016                                                          addr, loc->address,
5017                                                          loc->length))
5018               {
5019                 w->watchpoint_triggered = watch_triggered_yes;
5020                 break;
5021               }
5022           }
5023       }
5024
5025   return 1;
5026 }
5027
5028 /* Possible return values for watchpoint_check (this can't be an enum
5029    because of check_errors).  */
5030 /* The watchpoint has been deleted.  */
5031 #define WP_DELETED 1
5032 /* The value has changed.  */
5033 #define WP_VALUE_CHANGED 2
5034 /* The value has not changed.  */
5035 #define WP_VALUE_NOT_CHANGED 3
5036 /* Ignore this watchpoint, no matter if the value changed or not.  */
5037 #define WP_IGNORE 4
5038
5039 #define BP_TEMPFLAG 1
5040 #define BP_HARDWAREFLAG 2
5041
5042 /* Evaluate watchpoint condition expression and check if its value
5043    changed.
5044
5045    P should be a pointer to struct bpstat, but is defined as a void *
5046    in order for this function to be usable with catch_errors.  */
5047
5048 static int
5049 watchpoint_check (void *p)
5050 {
5051   bpstat bs = (bpstat) p;
5052   struct watchpoint *b;
5053   struct frame_info *fr;
5054   int within_current_scope;
5055
5056   /* BS is built from an existing struct breakpoint.  */
5057   gdb_assert (bs->breakpoint_at != NULL);
5058   b = (struct watchpoint *) bs->breakpoint_at;
5059
5060   /* If this is a local watchpoint, we only want to check if the
5061      watchpoint frame is in scope if the current thread is the thread
5062      that was used to create the watchpoint.  */
5063   if (!watchpoint_in_thread_scope (b))
5064     return WP_IGNORE;
5065
5066   if (b->exp_valid_block == NULL)
5067     within_current_scope = 1;
5068   else
5069     {
5070       struct frame_info *frame = get_current_frame ();
5071       struct gdbarch *frame_arch = get_frame_arch (frame);
5072       CORE_ADDR frame_pc = get_frame_pc (frame);
5073
5074       /* in_function_epilogue_p() returns a non-zero value if we're
5075          still in the function but the stack frame has already been
5076          invalidated.  Since we can't rely on the values of local
5077          variables after the stack has been destroyed, we are treating
5078          the watchpoint in that state as `not changed' without further
5079          checking.  Don't mark watchpoints as changed if the current
5080          frame is in an epilogue - even if they are in some other
5081          frame, our view of the stack is likely to be wrong and
5082          frame_find_by_id could error out.  */
5083       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5084         return WP_IGNORE;
5085
5086       fr = frame_find_by_id (b->watchpoint_frame);
5087       within_current_scope = (fr != NULL);
5088
5089       /* If we've gotten confused in the unwinder, we might have
5090          returned a frame that can't describe this variable.  */
5091       if (within_current_scope)
5092         {
5093           struct symbol *function;
5094
5095           function = get_frame_function (fr);
5096           if (function == NULL
5097               || !contained_in (b->exp_valid_block,
5098                                 SYMBOL_BLOCK_VALUE (function)))
5099             within_current_scope = 0;
5100         }
5101
5102       if (within_current_scope)
5103         /* If we end up stopping, the current frame will get selected
5104            in normal_stop.  So this call to select_frame won't affect
5105            the user.  */
5106         select_frame (fr);
5107     }
5108
5109   if (within_current_scope)
5110     {
5111       /* We use value_{,free_to_}mark because it could be a *long*
5112          time before we return to the command level and call
5113          free_all_values.  We can't call free_all_values because we
5114          might be in the middle of evaluating a function call.  */
5115
5116       int pc = 0;
5117       struct value *mark;
5118       struct value *new_val;
5119
5120       if (is_masked_watchpoint (&b->base))
5121         /* Since we don't know the exact trigger address (from
5122            stopped_data_address), just tell the user we've triggered
5123            a mask watchpoint.  */
5124         return WP_VALUE_CHANGED;
5125
5126       mark = value_mark ();
5127       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5128
5129       if (b->val_bitsize != 0)
5130         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5131
5132       /* We use value_equal_contents instead of value_equal because
5133          the latter coerces an array to a pointer, thus comparing just
5134          the address of the array instead of its contents.  This is
5135          not what we want.  */
5136       if ((b->val != NULL) != (new_val != NULL)
5137           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5138         {
5139           if (new_val != NULL)
5140             {
5141               release_value (new_val);
5142               value_free_to_mark (mark);
5143             }
5144           bs->old_val = b->val;
5145           b->val = new_val;
5146           b->val_valid = 1;
5147           return WP_VALUE_CHANGED;
5148         }
5149       else
5150         {
5151           /* Nothing changed.  */
5152           value_free_to_mark (mark);
5153           return WP_VALUE_NOT_CHANGED;
5154         }
5155     }
5156   else
5157     {
5158       struct ui_out *uiout = current_uiout;
5159
5160       /* This seems like the only logical thing to do because
5161          if we temporarily ignored the watchpoint, then when
5162          we reenter the block in which it is valid it contains
5163          garbage (in the case of a function, it may have two
5164          garbage values, one before and one after the prologue).
5165          So we can't even detect the first assignment to it and
5166          watch after that (since the garbage may or may not equal
5167          the first value assigned).  */
5168       /* We print all the stop information in
5169          breakpoint_ops->print_it, but in this case, by the time we
5170          call breakpoint_ops->print_it this bp will be deleted
5171          already.  So we have no choice but print the information
5172          here.  */
5173       if (ui_out_is_mi_like_p (uiout))
5174         ui_out_field_string
5175           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5176       ui_out_text (uiout, "\nWatchpoint ");
5177       ui_out_field_int (uiout, "wpnum", b->base.number);
5178       ui_out_text (uiout,
5179                    " deleted because the program has left the block in\n\
5180 which its expression is valid.\n");     
5181
5182       /* Make sure the watchpoint's commands aren't executed.  */
5183       decref_counted_command_line (&b->base.commands);
5184       watchpoint_del_at_next_stop (b);
5185
5186       return WP_DELETED;
5187     }
5188 }
5189
5190 /* Return true if it looks like target has stopped due to hitting
5191    breakpoint location BL.  This function does not check if we should
5192    stop, only if BL explains the stop.  */
5193
5194 static int
5195 bpstat_check_location (const struct bp_location *bl,
5196                        struct address_space *aspace, CORE_ADDR bp_addr,
5197                        const struct target_waitstatus *ws)
5198 {
5199   struct breakpoint *b = bl->owner;
5200
5201   /* BL is from an existing breakpoint.  */
5202   gdb_assert (b != NULL);
5203
5204   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5205 }
5206
5207 /* Determine if the watched values have actually changed, and we
5208    should stop.  If not, set BS->stop to 0.  */
5209
5210 static void
5211 bpstat_check_watchpoint (bpstat bs)
5212 {
5213   const struct bp_location *bl;
5214   struct watchpoint *b;
5215
5216   /* BS is built for existing struct breakpoint.  */
5217   bl = bs->bp_location_at;
5218   gdb_assert (bl != NULL);
5219   b = (struct watchpoint *) bs->breakpoint_at;
5220   gdb_assert (b != NULL);
5221
5222     {
5223       int must_check_value = 0;
5224       
5225       if (b->base.type == bp_watchpoint)
5226         /* For a software watchpoint, we must always check the
5227            watched value.  */
5228         must_check_value = 1;
5229       else if (b->watchpoint_triggered == watch_triggered_yes)
5230         /* We have a hardware watchpoint (read, write, or access)
5231            and the target earlier reported an address watched by
5232            this watchpoint.  */
5233         must_check_value = 1;
5234       else if (b->watchpoint_triggered == watch_triggered_unknown
5235                && b->base.type == bp_hardware_watchpoint)
5236         /* We were stopped by a hardware watchpoint, but the target could
5237            not report the data address.  We must check the watchpoint's
5238            value.  Access and read watchpoints are out of luck; without
5239            a data address, we can't figure it out.  */
5240         must_check_value = 1;
5241
5242       if (must_check_value)
5243         {
5244           char *message
5245             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5246                           b->base.number);
5247           struct cleanup *cleanups = make_cleanup (xfree, message);
5248           int e = catch_errors (watchpoint_check, bs, message,
5249                                 RETURN_MASK_ALL);
5250           do_cleanups (cleanups);
5251           switch (e)
5252             {
5253             case WP_DELETED:
5254               /* We've already printed what needs to be printed.  */
5255               bs->print_it = print_it_done;
5256               /* Stop.  */
5257               break;
5258             case WP_IGNORE:
5259               bs->print_it = print_it_noop;
5260               bs->stop = 0;
5261               break;
5262             case WP_VALUE_CHANGED:
5263               if (b->base.type == bp_read_watchpoint)
5264                 {
5265                   /* There are two cases to consider here:
5266
5267                      1. We're watching the triggered memory for reads.
5268                      In that case, trust the target, and always report
5269                      the watchpoint hit to the user.  Even though
5270                      reads don't cause value changes, the value may
5271                      have changed since the last time it was read, and
5272                      since we're not trapping writes, we will not see
5273                      those, and as such we should ignore our notion of
5274                      old value.
5275
5276                      2. We're watching the triggered memory for both
5277                      reads and writes.  There are two ways this may
5278                      happen:
5279
5280                      2.1. This is a target that can't break on data
5281                      reads only, but can break on accesses (reads or
5282                      writes), such as e.g., x86.  We detect this case
5283                      at the time we try to insert read watchpoints.
5284
5285                      2.2. Otherwise, the target supports read
5286                      watchpoints, but, the user set an access or write
5287                      watchpoint watching the same memory as this read
5288                      watchpoint.
5289
5290                      If we're watching memory writes as well as reads,
5291                      ignore watchpoint hits when we find that the
5292                      value hasn't changed, as reads don't cause
5293                      changes.  This still gives false positives when
5294                      the program writes the same value to memory as
5295                      what there was already in memory (we will confuse
5296                      it for a read), but it's much better than
5297                      nothing.  */
5298
5299                   int other_write_watchpoint = 0;
5300
5301                   if (bl->watchpoint_type == hw_read)
5302                     {
5303                       struct breakpoint *other_b;
5304
5305                       ALL_BREAKPOINTS (other_b)
5306                         if (other_b->type == bp_hardware_watchpoint
5307                             || other_b->type == bp_access_watchpoint)
5308                           {
5309                             struct watchpoint *other_w =
5310                               (struct watchpoint *) other_b;
5311
5312                             if (other_w->watchpoint_triggered
5313                                 == watch_triggered_yes)
5314                               {
5315                                 other_write_watchpoint = 1;
5316                                 break;
5317                               }
5318                           }
5319                     }
5320
5321                   if (other_write_watchpoint
5322                       || bl->watchpoint_type == hw_access)
5323                     {
5324                       /* We're watching the same memory for writes,
5325                          and the value changed since the last time we
5326                          updated it, so this trap must be for a write.
5327                          Ignore it.  */
5328                       bs->print_it = print_it_noop;
5329                       bs->stop = 0;
5330                     }
5331                 }
5332               break;
5333             case WP_VALUE_NOT_CHANGED:
5334               if (b->base.type == bp_hardware_watchpoint
5335                   || b->base.type == bp_watchpoint)
5336                 {
5337                   /* Don't stop: write watchpoints shouldn't fire if
5338                      the value hasn't changed.  */
5339                   bs->print_it = print_it_noop;
5340                   bs->stop = 0;
5341                 }
5342               /* Stop.  */
5343               break;
5344             default:
5345               /* Can't happen.  */
5346             case 0:
5347               /* Error from catch_errors.  */
5348               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5349               watchpoint_del_at_next_stop (b);
5350               /* We've already printed what needs to be printed.  */
5351               bs->print_it = print_it_done;
5352               break;
5353             }
5354         }
5355       else      /* must_check_value == 0 */
5356         {
5357           /* This is a case where some watchpoint(s) triggered, but
5358              not at the address of this watchpoint, or else no
5359              watchpoint triggered after all.  So don't print
5360              anything for this watchpoint.  */
5361           bs->print_it = print_it_noop;
5362           bs->stop = 0;
5363         }
5364     }
5365 }
5366
5367 /* For breakpoints that are currently marked as telling gdb to stop,
5368    check conditions (condition proper, frame, thread and ignore count)
5369    of breakpoint referred to by BS.  If we should not stop for this
5370    breakpoint, set BS->stop to 0.  */
5371
5372 static void
5373 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5374 {
5375   const struct bp_location *bl;
5376   struct breakpoint *b;
5377   int value_is_zero = 0;
5378   struct expression *cond;
5379
5380   gdb_assert (bs->stop);
5381
5382   /* BS is built for existing struct breakpoint.  */
5383   bl = bs->bp_location_at;
5384   gdb_assert (bl != NULL);
5385   b = bs->breakpoint_at;
5386   gdb_assert (b != NULL);
5387
5388   /* Even if the target evaluated the condition on its end and notified GDB, we
5389      need to do so again since GDB does not know if we stopped due to a
5390      breakpoint or a single step breakpoint.  */
5391
5392   if (frame_id_p (b->frame_id)
5393       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5394     {
5395       bs->stop = 0;
5396       return;
5397     }
5398
5399   /* If this is a thread/task-specific breakpoint, don't waste cpu
5400      evaluating the condition if this isn't the specified
5401      thread/task.  */
5402   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5403       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5404
5405     {
5406       bs->stop = 0;
5407       return;
5408     }
5409
5410   /* Evaluate extension language breakpoints that have a "stop" method
5411      implemented.  */
5412   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5413
5414   if (is_watchpoint (b))
5415     {
5416       struct watchpoint *w = (struct watchpoint *) b;
5417
5418       cond = w->cond_exp;
5419     }
5420   else
5421     cond = bl->cond;
5422
5423   if (cond && b->disposition != disp_del_at_next_stop)
5424     {
5425       int within_current_scope = 1;
5426       struct watchpoint * w;
5427
5428       /* We use value_mark and value_free_to_mark because it could
5429          be a long time before we return to the command level and
5430          call free_all_values.  We can't call free_all_values
5431          because we might be in the middle of evaluating a
5432          function call.  */
5433       struct value *mark = value_mark ();
5434
5435       if (is_watchpoint (b))
5436         w = (struct watchpoint *) b;
5437       else
5438         w = NULL;
5439
5440       /* Need to select the frame, with all that implies so that
5441          the conditions will have the right context.  Because we
5442          use the frame, we will not see an inlined function's
5443          variables when we arrive at a breakpoint at the start
5444          of the inlined function; the current frame will be the
5445          call site.  */
5446       if (w == NULL || w->cond_exp_valid_block == NULL)
5447         select_frame (get_current_frame ());
5448       else
5449         {
5450           struct frame_info *frame;
5451
5452           /* For local watchpoint expressions, which particular
5453              instance of a local is being watched matters, so we
5454              keep track of the frame to evaluate the expression
5455              in.  To evaluate the condition however, it doesn't
5456              really matter which instantiation of the function
5457              where the condition makes sense triggers the
5458              watchpoint.  This allows an expression like "watch
5459              global if q > 10" set in `func', catch writes to
5460              global on all threads that call `func', or catch
5461              writes on all recursive calls of `func' by a single
5462              thread.  We simply always evaluate the condition in
5463              the innermost frame that's executing where it makes
5464              sense to evaluate the condition.  It seems
5465              intuitive.  */
5466           frame = block_innermost_frame (w->cond_exp_valid_block);
5467           if (frame != NULL)
5468             select_frame (frame);
5469           else
5470             within_current_scope = 0;
5471         }
5472       if (within_current_scope)
5473         value_is_zero
5474           = catch_errors (breakpoint_cond_eval, cond,
5475                           "Error in testing breakpoint condition:\n",
5476                           RETURN_MASK_ALL);
5477       else
5478         {
5479           warning (_("Watchpoint condition cannot be tested "
5480                      "in the current scope"));
5481           /* If we failed to set the right context for this
5482              watchpoint, unconditionally report it.  */
5483           value_is_zero = 0;
5484         }
5485       /* FIXME-someday, should give breakpoint #.  */
5486       value_free_to_mark (mark);
5487     }
5488
5489   if (cond && value_is_zero)
5490     {
5491       bs->stop = 0;
5492     }
5493   else if (b->ignore_count > 0)
5494     {
5495       b->ignore_count--;
5496       bs->stop = 0;
5497       /* Increase the hit count even though we don't stop.  */
5498       ++(b->hit_count);
5499       observer_notify_breakpoint_modified (b);
5500     }   
5501 }
5502
5503
5504 /* Get a bpstat associated with having just stopped at address
5505    BP_ADDR in thread PTID.
5506
5507    Determine whether we stopped at a breakpoint, etc, or whether we
5508    don't understand this stop.  Result is a chain of bpstat's such
5509    that:
5510
5511    if we don't understand the stop, the result is a null pointer.
5512
5513    if we understand why we stopped, the result is not null.
5514
5515    Each element of the chain refers to a particular breakpoint or
5516    watchpoint at which we have stopped.  (We may have stopped for
5517    several reasons concurrently.)
5518
5519    Each element of the chain has valid next, breakpoint_at,
5520    commands, FIXME??? fields.  */
5521
5522 bpstat
5523 bpstat_stop_status (struct address_space *aspace,
5524                     CORE_ADDR bp_addr, ptid_t ptid,
5525                     const struct target_waitstatus *ws)
5526 {
5527   struct breakpoint *b = NULL;
5528   struct bp_location *bl;
5529   struct bp_location *loc;
5530   /* First item of allocated bpstat's.  */
5531   bpstat bs_head = NULL, *bs_link = &bs_head;
5532   /* Pointer to the last thing in the chain currently.  */
5533   bpstat bs;
5534   int ix;
5535   int need_remove_insert;
5536   int removed_any;
5537
5538   /* First, build the bpstat chain with locations that explain a
5539      target stop, while being careful to not set the target running,
5540      as that may invalidate locations (in particular watchpoint
5541      locations are recreated).  Resuming will happen here with
5542      breakpoint conditions or watchpoint expressions that include
5543      inferior function calls.  */
5544
5545   ALL_BREAKPOINTS (b)
5546     {
5547       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5548         continue;
5549
5550       for (bl = b->loc; bl != NULL; bl = bl->next)
5551         {
5552           /* For hardware watchpoints, we look only at the first
5553              location.  The watchpoint_check function will work on the
5554              entire expression, not the individual locations.  For
5555              read watchpoints, the watchpoints_triggered function has
5556              checked all locations already.  */
5557           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5558             break;
5559
5560           if (!bl->enabled || bl->shlib_disabled)
5561             continue;
5562
5563           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5564             continue;
5565
5566           /* Come here if it's a watchpoint, or if the break address
5567              matches.  */
5568
5569           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5570                                                    explain stop.  */
5571
5572           /* Assume we stop.  Should we find a watchpoint that is not
5573              actually triggered, or if the condition of the breakpoint
5574              evaluates as false, we'll reset 'stop' to 0.  */
5575           bs->stop = 1;
5576           bs->print = 1;
5577
5578           /* If this is a scope breakpoint, mark the associated
5579              watchpoint as triggered so that we will handle the
5580              out-of-scope event.  We'll get to the watchpoint next
5581              iteration.  */
5582           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5583             {
5584               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5585
5586               w->watchpoint_triggered = watch_triggered_yes;
5587             }
5588         }
5589     }
5590
5591   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5592     {
5593       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5594         {
5595           bs = bpstat_alloc (loc, &bs_link);
5596           /* For hits of moribund locations, we should just proceed.  */
5597           bs->stop = 0;
5598           bs->print = 0;
5599           bs->print_it = print_it_noop;
5600         }
5601     }
5602
5603   /* A bit of special processing for shlib breakpoints.  We need to
5604      process solib loading here, so that the lists of loaded and
5605      unloaded libraries are correct before we handle "catch load" and
5606      "catch unload".  */
5607   for (bs = bs_head; bs != NULL; bs = bs->next)
5608     {
5609       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5610         {
5611           handle_solib_event ();
5612           break;
5613         }
5614     }
5615
5616   /* Now go through the locations that caused the target to stop, and
5617      check whether we're interested in reporting this stop to higher
5618      layers, or whether we should resume the target transparently.  */
5619
5620   removed_any = 0;
5621
5622   for (bs = bs_head; bs != NULL; bs = bs->next)
5623     {
5624       if (!bs->stop)
5625         continue;
5626
5627       b = bs->breakpoint_at;
5628       b->ops->check_status (bs);
5629       if (bs->stop)
5630         {
5631           bpstat_check_breakpoint_conditions (bs, ptid);
5632
5633           if (bs->stop)
5634             {
5635               ++(b->hit_count);
5636               observer_notify_breakpoint_modified (b);
5637
5638               /* We will stop here.  */
5639               if (b->disposition == disp_disable)
5640                 {
5641                   --(b->enable_count);
5642                   if (b->enable_count <= 0
5643                       && b->enable_state != bp_permanent)
5644                     b->enable_state = bp_disabled;
5645                   removed_any = 1;
5646                 }
5647               if (b->silent)
5648                 bs->print = 0;
5649               bs->commands = b->commands;
5650               incref_counted_command_line (bs->commands);
5651               if (command_line_is_silent (bs->commands
5652                                           ? bs->commands->commands : NULL))
5653                 bs->print = 0;
5654
5655               b->ops->after_condition_true (bs);
5656             }
5657
5658         }
5659
5660       /* Print nothing for this entry if we don't stop or don't
5661          print.  */
5662       if (!bs->stop || !bs->print)
5663         bs->print_it = print_it_noop;
5664     }
5665
5666   /* If we aren't stopping, the value of some hardware watchpoint may
5667      not have changed, but the intermediate memory locations we are
5668      watching may have.  Don't bother if we're stopping; this will get
5669      done later.  */
5670   need_remove_insert = 0;
5671   if (! bpstat_causes_stop (bs_head))
5672     for (bs = bs_head; bs != NULL; bs = bs->next)
5673       if (!bs->stop
5674           && bs->breakpoint_at
5675           && is_hardware_watchpoint (bs->breakpoint_at))
5676         {
5677           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5678
5679           update_watchpoint (w, 0 /* don't reparse.  */);
5680           need_remove_insert = 1;
5681         }
5682
5683   if (need_remove_insert)
5684     update_global_location_list (UGLL_MAY_INSERT);
5685   else if (removed_any)
5686     update_global_location_list (UGLL_DONT_INSERT);
5687
5688   return bs_head;
5689 }
5690
5691 static void
5692 handle_jit_event (void)
5693 {
5694   struct frame_info *frame;
5695   struct gdbarch *gdbarch;
5696
5697   /* Switch terminal for any messages produced by
5698      breakpoint_re_set.  */
5699   target_terminal_ours_for_output ();
5700
5701   frame = get_current_frame ();
5702   gdbarch = get_frame_arch (frame);
5703
5704   jit_event_handler (gdbarch);
5705
5706   target_terminal_inferior ();
5707 }
5708
5709 /* Prepare WHAT final decision for infrun.  */
5710
5711 /* Decide what infrun needs to do with this bpstat.  */
5712
5713 struct bpstat_what
5714 bpstat_what (bpstat bs_head)
5715 {
5716   struct bpstat_what retval;
5717   int jit_event = 0;
5718   bpstat bs;
5719
5720   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5721   retval.call_dummy = STOP_NONE;
5722   retval.is_longjmp = 0;
5723
5724   for (bs = bs_head; bs != NULL; bs = bs->next)
5725     {
5726       /* Extract this BS's action.  After processing each BS, we check
5727          if its action overrides all we've seem so far.  */
5728       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5729       enum bptype bptype;
5730
5731       if (bs->breakpoint_at == NULL)
5732         {
5733           /* I suspect this can happen if it was a momentary
5734              breakpoint which has since been deleted.  */
5735           bptype = bp_none;
5736         }
5737       else
5738         bptype = bs->breakpoint_at->type;
5739
5740       switch (bptype)
5741         {
5742         case bp_none:
5743           break;
5744         case bp_breakpoint:
5745         case bp_hardware_breakpoint:
5746         case bp_until:
5747         case bp_finish:
5748         case bp_shlib_event:
5749           if (bs->stop)
5750             {
5751               if (bs->print)
5752                 this_action = BPSTAT_WHAT_STOP_NOISY;
5753               else
5754                 this_action = BPSTAT_WHAT_STOP_SILENT;
5755             }
5756           else
5757             this_action = BPSTAT_WHAT_SINGLE;
5758           break;
5759         case bp_watchpoint:
5760         case bp_hardware_watchpoint:
5761         case bp_read_watchpoint:
5762         case bp_access_watchpoint:
5763           if (bs->stop)
5764             {
5765               if (bs->print)
5766                 this_action = BPSTAT_WHAT_STOP_NOISY;
5767               else
5768                 this_action = BPSTAT_WHAT_STOP_SILENT;
5769             }
5770           else
5771             {
5772               /* There was a watchpoint, but we're not stopping.
5773                  This requires no further action.  */
5774             }
5775           break;
5776         case bp_longjmp:
5777         case bp_longjmp_call_dummy:
5778         case bp_exception:
5779           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5780           retval.is_longjmp = bptype != bp_exception;
5781           break;
5782         case bp_longjmp_resume:
5783         case bp_exception_resume:
5784           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5785           retval.is_longjmp = bptype == bp_longjmp_resume;
5786           break;
5787         case bp_step_resume:
5788           if (bs->stop)
5789             this_action = BPSTAT_WHAT_STEP_RESUME;
5790           else
5791             {
5792               /* It is for the wrong frame.  */
5793               this_action = BPSTAT_WHAT_SINGLE;
5794             }
5795           break;
5796         case bp_hp_step_resume:
5797           if (bs->stop)
5798             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5799           else
5800             {
5801               /* It is for the wrong frame.  */
5802               this_action = BPSTAT_WHAT_SINGLE;
5803             }
5804           break;
5805         case bp_watchpoint_scope:
5806         case bp_thread_event:
5807         case bp_overlay_event:
5808         case bp_longjmp_master:
5809         case bp_std_terminate_master:
5810         case bp_exception_master:
5811           this_action = BPSTAT_WHAT_SINGLE;
5812           break;
5813         case bp_catchpoint:
5814           if (bs->stop)
5815             {
5816               if (bs->print)
5817                 this_action = BPSTAT_WHAT_STOP_NOISY;
5818               else
5819                 this_action = BPSTAT_WHAT_STOP_SILENT;
5820             }
5821           else
5822             {
5823               /* There was a catchpoint, but we're not stopping.
5824                  This requires no further action.  */
5825             }
5826           break;
5827         case bp_jit_event:
5828           jit_event = 1;
5829           this_action = BPSTAT_WHAT_SINGLE;
5830           break;
5831         case bp_call_dummy:
5832           /* Make sure the action is stop (silent or noisy),
5833              so infrun.c pops the dummy frame.  */
5834           retval.call_dummy = STOP_STACK_DUMMY;
5835           this_action = BPSTAT_WHAT_STOP_SILENT;
5836           break;
5837         case bp_std_terminate:
5838           /* Make sure the action is stop (silent or noisy),
5839              so infrun.c pops the dummy frame.  */
5840           retval.call_dummy = STOP_STD_TERMINATE;
5841           this_action = BPSTAT_WHAT_STOP_SILENT;
5842           break;
5843         case bp_tracepoint:
5844         case bp_fast_tracepoint:
5845         case bp_static_tracepoint:
5846           /* Tracepoint hits should not be reported back to GDB, and
5847              if one got through somehow, it should have been filtered
5848              out already.  */
5849           internal_error (__FILE__, __LINE__,
5850                           _("bpstat_what: tracepoint encountered"));
5851           break;
5852         case bp_gnu_ifunc_resolver:
5853           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5854           this_action = BPSTAT_WHAT_SINGLE;
5855           break;
5856         case bp_gnu_ifunc_resolver_return:
5857           /* The breakpoint will be removed, execution will restart from the
5858              PC of the former breakpoint.  */
5859           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5860           break;
5861
5862         case bp_dprintf:
5863           if (bs->stop)
5864             this_action = BPSTAT_WHAT_STOP_SILENT;
5865           else
5866             this_action = BPSTAT_WHAT_SINGLE;
5867           break;
5868
5869         default:
5870           internal_error (__FILE__, __LINE__,
5871                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5872         }
5873
5874       retval.main_action = max (retval.main_action, this_action);
5875     }
5876
5877   /* These operations may affect the bs->breakpoint_at state so they are
5878      delayed after MAIN_ACTION is decided above.  */
5879
5880   if (jit_event)
5881     {
5882       if (debug_infrun)
5883         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5884
5885       handle_jit_event ();
5886     }
5887
5888   for (bs = bs_head; bs != NULL; bs = bs->next)
5889     {
5890       struct breakpoint *b = bs->breakpoint_at;
5891
5892       if (b == NULL)
5893         continue;
5894       switch (b->type)
5895         {
5896         case bp_gnu_ifunc_resolver:
5897           gnu_ifunc_resolver_stop (b);
5898           break;
5899         case bp_gnu_ifunc_resolver_return:
5900           gnu_ifunc_resolver_return_stop (b);
5901           break;
5902         }
5903     }
5904
5905   return retval;
5906 }
5907
5908 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5909    without hardware support).  This isn't related to a specific bpstat,
5910    just to things like whether watchpoints are set.  */
5911
5912 int
5913 bpstat_should_step (void)
5914 {
5915   struct breakpoint *b;
5916
5917   ALL_BREAKPOINTS (b)
5918     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5919       return 1;
5920   return 0;
5921 }
5922
5923 int
5924 bpstat_causes_stop (bpstat bs)
5925 {
5926   for (; bs != NULL; bs = bs->next)
5927     if (bs->stop)
5928       return 1;
5929
5930   return 0;
5931 }
5932
5933 \f
5934
5935 /* Compute a string of spaces suitable to indent the next line
5936    so it starts at the position corresponding to the table column
5937    named COL_NAME in the currently active table of UIOUT.  */
5938
5939 static char *
5940 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5941 {
5942   static char wrap_indent[80];
5943   int i, total_width, width, align;
5944   char *text;
5945
5946   total_width = 0;
5947   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5948     {
5949       if (strcmp (text, col_name) == 0)
5950         {
5951           gdb_assert (total_width < sizeof wrap_indent);
5952           memset (wrap_indent, ' ', total_width);
5953           wrap_indent[total_width] = 0;
5954
5955           return wrap_indent;
5956         }
5957
5958       total_width += width + 1;
5959     }
5960
5961   return NULL;
5962 }
5963
5964 /* Determine if the locations of this breakpoint will have their conditions
5965    evaluated by the target, host or a mix of both.  Returns the following:
5966
5967     "host": Host evals condition.
5968     "host or target": Host or Target evals condition.
5969     "target": Target evals condition.
5970 */
5971
5972 static const char *
5973 bp_condition_evaluator (struct breakpoint *b)
5974 {
5975   struct bp_location *bl;
5976   char host_evals = 0;
5977   char target_evals = 0;
5978
5979   if (!b)
5980     return NULL;
5981
5982   if (!is_breakpoint (b))
5983     return NULL;
5984
5985   if (gdb_evaluates_breakpoint_condition_p ()
5986       || !target_supports_evaluation_of_breakpoint_conditions ())
5987     return condition_evaluation_host;
5988
5989   for (bl = b->loc; bl; bl = bl->next)
5990     {
5991       if (bl->cond_bytecode)
5992         target_evals++;
5993       else
5994         host_evals++;
5995     }
5996
5997   if (host_evals && target_evals)
5998     return condition_evaluation_both;
5999   else if (target_evals)
6000     return condition_evaluation_target;
6001   else
6002     return condition_evaluation_host;
6003 }
6004
6005 /* Determine the breakpoint location's condition evaluator.  This is
6006    similar to bp_condition_evaluator, but for locations.  */
6007
6008 static const char *
6009 bp_location_condition_evaluator (struct bp_location *bl)
6010 {
6011   if (bl && !is_breakpoint (bl->owner))
6012     return NULL;
6013
6014   if (gdb_evaluates_breakpoint_condition_p ()
6015       || !target_supports_evaluation_of_breakpoint_conditions ())
6016     return condition_evaluation_host;
6017
6018   if (bl && bl->cond_bytecode)
6019     return condition_evaluation_target;
6020   else
6021     return condition_evaluation_host;
6022 }
6023
6024 /* Print the LOC location out of the list of B->LOC locations.  */
6025
6026 static void
6027 print_breakpoint_location (struct breakpoint *b,
6028                            struct bp_location *loc)
6029 {
6030   struct ui_out *uiout = current_uiout;
6031   struct cleanup *old_chain = save_current_program_space ();
6032
6033   if (loc != NULL && loc->shlib_disabled)
6034     loc = NULL;
6035
6036   if (loc != NULL)
6037     set_current_program_space (loc->pspace);
6038
6039   if (b->display_canonical)
6040     ui_out_field_string (uiout, "what", b->addr_string);
6041   else if (loc && loc->symtab)
6042     {
6043       struct symbol *sym 
6044         = find_pc_sect_function (loc->address, loc->section);
6045       if (sym)
6046         {
6047           ui_out_text (uiout, "in ");
6048           ui_out_field_string (uiout, "func",
6049                                SYMBOL_PRINT_NAME (sym));
6050           ui_out_text (uiout, " ");
6051           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6052           ui_out_text (uiout, "at ");
6053         }
6054       ui_out_field_string (uiout, "file",
6055                            symtab_to_filename_for_display (loc->symtab));
6056       ui_out_text (uiout, ":");
6057
6058       if (ui_out_is_mi_like_p (uiout))
6059         ui_out_field_string (uiout, "fullname",
6060                              symtab_to_fullname (loc->symtab));
6061       
6062       ui_out_field_int (uiout, "line", loc->line_number);
6063     }
6064   else if (loc)
6065     {
6066       struct ui_file *stb = mem_fileopen ();
6067       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6068
6069       print_address_symbolic (loc->gdbarch, loc->address, stb,
6070                               demangle, "");
6071       ui_out_field_stream (uiout, "at", stb);
6072
6073       do_cleanups (stb_chain);
6074     }
6075   else
6076     ui_out_field_string (uiout, "pending", b->addr_string);
6077
6078   if (loc && is_breakpoint (b)
6079       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6080       && bp_condition_evaluator (b) == condition_evaluation_both)
6081     {
6082       ui_out_text (uiout, " (");
6083       ui_out_field_string (uiout, "evaluated-by",
6084                            bp_location_condition_evaluator (loc));
6085       ui_out_text (uiout, ")");
6086     }
6087
6088   do_cleanups (old_chain);
6089 }
6090
6091 static const char *
6092 bptype_string (enum bptype type)
6093 {
6094   struct ep_type_description
6095     {
6096       enum bptype type;
6097       char *description;
6098     };
6099   static struct ep_type_description bptypes[] =
6100   {
6101     {bp_none, "?deleted?"},
6102     {bp_breakpoint, "breakpoint"},
6103     {bp_hardware_breakpoint, "hw breakpoint"},
6104     {bp_until, "until"},
6105     {bp_finish, "finish"},
6106     {bp_watchpoint, "watchpoint"},
6107     {bp_hardware_watchpoint, "hw watchpoint"},
6108     {bp_read_watchpoint, "read watchpoint"},
6109     {bp_access_watchpoint, "acc watchpoint"},
6110     {bp_longjmp, "longjmp"},
6111     {bp_longjmp_resume, "longjmp resume"},
6112     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6113     {bp_exception, "exception"},
6114     {bp_exception_resume, "exception resume"},
6115     {bp_step_resume, "step resume"},
6116     {bp_hp_step_resume, "high-priority step resume"},
6117     {bp_watchpoint_scope, "watchpoint scope"},
6118     {bp_call_dummy, "call dummy"},
6119     {bp_std_terminate, "std::terminate"},
6120     {bp_shlib_event, "shlib events"},
6121     {bp_thread_event, "thread events"},
6122     {bp_overlay_event, "overlay events"},
6123     {bp_longjmp_master, "longjmp master"},
6124     {bp_std_terminate_master, "std::terminate master"},
6125     {bp_exception_master, "exception master"},
6126     {bp_catchpoint, "catchpoint"},
6127     {bp_tracepoint, "tracepoint"},
6128     {bp_fast_tracepoint, "fast tracepoint"},
6129     {bp_static_tracepoint, "static tracepoint"},
6130     {bp_dprintf, "dprintf"},
6131     {bp_jit_event, "jit events"},
6132     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6133     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6134   };
6135
6136   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6137       || ((int) type != bptypes[(int) type].type))
6138     internal_error (__FILE__, __LINE__,
6139                     _("bptypes table does not describe type #%d."),
6140                     (int) type);
6141
6142   return bptypes[(int) type].description;
6143 }
6144
6145 /* For MI, output a field named 'thread-groups' with a list as the value.
6146    For CLI, prefix the list with the string 'inf'. */
6147
6148 static void
6149 output_thread_groups (struct ui_out *uiout,
6150                       const char *field_name,
6151                       VEC(int) *inf_num,
6152                       int mi_only)
6153 {
6154   struct cleanup *back_to;
6155   int is_mi = ui_out_is_mi_like_p (uiout);
6156   int inf;
6157   int i;
6158
6159   /* For backward compatibility, don't display inferiors in CLI unless
6160      there are several.  Always display them for MI. */
6161   if (!is_mi && mi_only)
6162     return;
6163
6164   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6165
6166   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6167     {
6168       if (is_mi)
6169         {
6170           char mi_group[10];
6171
6172           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6173           ui_out_field_string (uiout, NULL, mi_group);
6174         }
6175       else
6176         {
6177           if (i == 0)
6178             ui_out_text (uiout, " inf ");
6179           else
6180             ui_out_text (uiout, ", ");
6181         
6182           ui_out_text (uiout, plongest (inf));
6183         }
6184     }
6185
6186   do_cleanups (back_to);
6187 }
6188
6189 /* Print B to gdb_stdout.  */
6190
6191 static void
6192 print_one_breakpoint_location (struct breakpoint *b,
6193                                struct bp_location *loc,
6194                                int loc_number,
6195                                struct bp_location **last_loc,
6196                                int allflag)
6197 {
6198   struct command_line *l;
6199   static char bpenables[] = "nynny";
6200
6201   struct ui_out *uiout = current_uiout;
6202   int header_of_multiple = 0;
6203   int part_of_multiple = (loc != NULL);
6204   struct value_print_options opts;
6205
6206   get_user_print_options (&opts);
6207
6208   gdb_assert (!loc || loc_number != 0);
6209   /* See comment in print_one_breakpoint concerning treatment of
6210      breakpoints with single disabled location.  */
6211   if (loc == NULL 
6212       && (b->loc != NULL 
6213           && (b->loc->next != NULL || !b->loc->enabled)))
6214     header_of_multiple = 1;
6215   if (loc == NULL)
6216     loc = b->loc;
6217
6218   annotate_record ();
6219
6220   /* 1 */
6221   annotate_field (0);
6222   if (part_of_multiple)
6223     {
6224       char *formatted;
6225       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6226       ui_out_field_string (uiout, "number", formatted);
6227       xfree (formatted);
6228     }
6229   else
6230     {
6231       ui_out_field_int (uiout, "number", b->number);
6232     }
6233
6234   /* 2 */
6235   annotate_field (1);
6236   if (part_of_multiple)
6237     ui_out_field_skip (uiout, "type");
6238   else
6239     ui_out_field_string (uiout, "type", bptype_string (b->type));
6240
6241   /* 3 */
6242   annotate_field (2);
6243   if (part_of_multiple)
6244     ui_out_field_skip (uiout, "disp");
6245   else
6246     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6247
6248
6249   /* 4 */
6250   annotate_field (3);
6251   if (part_of_multiple)
6252     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6253   else
6254     ui_out_field_fmt (uiout, "enabled", "%c", 
6255                       bpenables[(int) b->enable_state]);
6256   ui_out_spaces (uiout, 2);
6257
6258   
6259   /* 5 and 6 */
6260   if (b->ops != NULL && b->ops->print_one != NULL)
6261     {
6262       /* Although the print_one can possibly print all locations,
6263          calling it here is not likely to get any nice result.  So,
6264          make sure there's just one location.  */
6265       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6266       b->ops->print_one (b, last_loc);
6267     }
6268   else
6269     switch (b->type)
6270       {
6271       case bp_none:
6272         internal_error (__FILE__, __LINE__,
6273                         _("print_one_breakpoint: bp_none encountered\n"));
6274         break;
6275
6276       case bp_watchpoint:
6277       case bp_hardware_watchpoint:
6278       case bp_read_watchpoint:
6279       case bp_access_watchpoint:
6280         {
6281           struct watchpoint *w = (struct watchpoint *) b;
6282
6283           /* Field 4, the address, is omitted (which makes the columns
6284              not line up too nicely with the headers, but the effect
6285              is relatively readable).  */
6286           if (opts.addressprint)
6287             ui_out_field_skip (uiout, "addr");
6288           annotate_field (5);
6289           ui_out_field_string (uiout, "what", w->exp_string);
6290         }
6291         break;
6292
6293       case bp_breakpoint:
6294       case bp_hardware_breakpoint:
6295       case bp_until:
6296       case bp_finish:
6297       case bp_longjmp:
6298       case bp_longjmp_resume:
6299       case bp_longjmp_call_dummy:
6300       case bp_exception:
6301       case bp_exception_resume:
6302       case bp_step_resume:
6303       case bp_hp_step_resume:
6304       case bp_watchpoint_scope:
6305       case bp_call_dummy:
6306       case bp_std_terminate:
6307       case bp_shlib_event:
6308       case bp_thread_event:
6309       case bp_overlay_event:
6310       case bp_longjmp_master:
6311       case bp_std_terminate_master:
6312       case bp_exception_master:
6313       case bp_tracepoint:
6314       case bp_fast_tracepoint:
6315       case bp_static_tracepoint:
6316       case bp_dprintf:
6317       case bp_jit_event:
6318       case bp_gnu_ifunc_resolver:
6319       case bp_gnu_ifunc_resolver_return:
6320         if (opts.addressprint)
6321           {
6322             annotate_field (4);
6323             if (header_of_multiple)
6324               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6325             else if (b->loc == NULL || loc->shlib_disabled)
6326               ui_out_field_string (uiout, "addr", "<PENDING>");
6327             else
6328               ui_out_field_core_addr (uiout, "addr",
6329                                       loc->gdbarch, loc->address);
6330           }
6331         annotate_field (5);
6332         if (!header_of_multiple)
6333           print_breakpoint_location (b, loc);
6334         if (b->loc)
6335           *last_loc = b->loc;
6336         break;
6337       }
6338
6339
6340   if (loc != NULL && !header_of_multiple)
6341     {
6342       struct inferior *inf;
6343       VEC(int) *inf_num = NULL;
6344       int mi_only = 1;
6345
6346       ALL_INFERIORS (inf)
6347         {
6348           if (inf->pspace == loc->pspace)
6349             VEC_safe_push (int, inf_num, inf->num);
6350         }
6351
6352         /* For backward compatibility, don't display inferiors in CLI unless
6353            there are several.  Always display for MI. */
6354         if (allflag
6355             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6356                 && (number_of_program_spaces () > 1
6357                     || number_of_inferiors () > 1)
6358                 /* LOC is for existing B, it cannot be in
6359                    moribund_locations and thus having NULL OWNER.  */
6360                 && loc->owner->type != bp_catchpoint))
6361         mi_only = 0;
6362       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6363       VEC_free (int, inf_num);
6364     }
6365
6366   if (!part_of_multiple)
6367     {
6368       if (b->thread != -1)
6369         {
6370           /* FIXME: This seems to be redundant and lost here; see the
6371              "stop only in" line a little further down.  */
6372           ui_out_text (uiout, " thread ");
6373           ui_out_field_int (uiout, "thread", b->thread);
6374         }
6375       else if (b->task != 0)
6376         {
6377           ui_out_text (uiout, " task ");
6378           ui_out_field_int (uiout, "task", b->task);
6379         }
6380     }
6381
6382   ui_out_text (uiout, "\n");
6383
6384   if (!part_of_multiple)
6385     b->ops->print_one_detail (b, uiout);
6386
6387   if (part_of_multiple && frame_id_p (b->frame_id))
6388     {
6389       annotate_field (6);
6390       ui_out_text (uiout, "\tstop only in stack frame at ");
6391       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6392          the frame ID.  */
6393       ui_out_field_core_addr (uiout, "frame",
6394                               b->gdbarch, b->frame_id.stack_addr);
6395       ui_out_text (uiout, "\n");
6396     }
6397   
6398   if (!part_of_multiple && b->cond_string)
6399     {
6400       annotate_field (7);
6401       if (is_tracepoint (b))
6402         ui_out_text (uiout, "\ttrace only if ");
6403       else
6404         ui_out_text (uiout, "\tstop only if ");
6405       ui_out_field_string (uiout, "cond", b->cond_string);
6406
6407       /* Print whether the target is doing the breakpoint's condition
6408          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6409       if (is_breakpoint (b)
6410           && breakpoint_condition_evaluation_mode ()
6411           == condition_evaluation_target)
6412         {
6413           ui_out_text (uiout, " (");
6414           ui_out_field_string (uiout, "evaluated-by",
6415                                bp_condition_evaluator (b));
6416           ui_out_text (uiout, " evals)");
6417         }
6418       ui_out_text (uiout, "\n");
6419     }
6420
6421   if (!part_of_multiple && b->thread != -1)
6422     {
6423       /* FIXME should make an annotation for this.  */
6424       ui_out_text (uiout, "\tstop only in thread ");
6425       ui_out_field_int (uiout, "thread", b->thread);
6426       ui_out_text (uiout, "\n");
6427     }
6428   
6429   if (!part_of_multiple)
6430     {
6431       if (b->hit_count)
6432         {
6433           /* FIXME should make an annotation for this.  */
6434           if (is_catchpoint (b))
6435             ui_out_text (uiout, "\tcatchpoint");
6436           else if (is_tracepoint (b))
6437             ui_out_text (uiout, "\ttracepoint");
6438           else
6439             ui_out_text (uiout, "\tbreakpoint");
6440           ui_out_text (uiout, " already hit ");
6441           ui_out_field_int (uiout, "times", b->hit_count);
6442           if (b->hit_count == 1)
6443             ui_out_text (uiout, " time\n");
6444           else
6445             ui_out_text (uiout, " times\n");
6446         }
6447       else
6448         {
6449           /* Output the count also if it is zero, but only if this is mi.  */
6450           if (ui_out_is_mi_like_p (uiout))
6451             ui_out_field_int (uiout, "times", b->hit_count);
6452         }
6453     }
6454
6455   if (!part_of_multiple && b->ignore_count)
6456     {
6457       annotate_field (8);
6458       ui_out_text (uiout, "\tignore next ");
6459       ui_out_field_int (uiout, "ignore", b->ignore_count);
6460       ui_out_text (uiout, " hits\n");
6461     }
6462
6463   /* Note that an enable count of 1 corresponds to "enable once"
6464      behavior, which is reported by the combination of enablement and
6465      disposition, so we don't need to mention it here.  */
6466   if (!part_of_multiple && b->enable_count > 1)
6467     {
6468       annotate_field (8);
6469       ui_out_text (uiout, "\tdisable after ");
6470       /* Tweak the wording to clarify that ignore and enable counts
6471          are distinct, and have additive effect.  */
6472       if (b->ignore_count)
6473         ui_out_text (uiout, "additional ");
6474       else
6475         ui_out_text (uiout, "next ");
6476       ui_out_field_int (uiout, "enable", b->enable_count);
6477       ui_out_text (uiout, " hits\n");
6478     }
6479
6480   if (!part_of_multiple && is_tracepoint (b))
6481     {
6482       struct tracepoint *tp = (struct tracepoint *) b;
6483
6484       if (tp->traceframe_usage)
6485         {
6486           ui_out_text (uiout, "\ttrace buffer usage ");
6487           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6488           ui_out_text (uiout, " bytes\n");
6489         }
6490     }
6491
6492   l = b->commands ? b->commands->commands : NULL;
6493   if (!part_of_multiple && l)
6494     {
6495       struct cleanup *script_chain;
6496
6497       annotate_field (9);
6498       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6499       print_command_lines (uiout, l, 4);
6500       do_cleanups (script_chain);
6501     }
6502
6503   if (is_tracepoint (b))
6504     {
6505       struct tracepoint *t = (struct tracepoint *) b;
6506
6507       if (!part_of_multiple && t->pass_count)
6508         {
6509           annotate_field (10);
6510           ui_out_text (uiout, "\tpass count ");
6511           ui_out_field_int (uiout, "pass", t->pass_count);
6512           ui_out_text (uiout, " \n");
6513         }
6514
6515       /* Don't display it when tracepoint or tracepoint location is
6516          pending.   */
6517       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6518         {
6519           annotate_field (11);
6520
6521           if (ui_out_is_mi_like_p (uiout))
6522             ui_out_field_string (uiout, "installed",
6523                                  loc->inserted ? "y" : "n");
6524           else
6525             {
6526               if (loc->inserted)
6527                 ui_out_text (uiout, "\t");
6528               else
6529                 ui_out_text (uiout, "\tnot ");
6530               ui_out_text (uiout, "installed on target\n");
6531             }
6532         }
6533     }
6534
6535   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6536     {
6537       if (is_watchpoint (b))
6538         {
6539           struct watchpoint *w = (struct watchpoint *) b;
6540
6541           ui_out_field_string (uiout, "original-location", w->exp_string);
6542         }
6543       else if (b->addr_string)
6544         ui_out_field_string (uiout, "original-location", b->addr_string);
6545     }
6546 }
6547
6548 static void
6549 print_one_breakpoint (struct breakpoint *b,
6550                       struct bp_location **last_loc, 
6551                       int allflag)
6552 {
6553   struct cleanup *bkpt_chain;
6554   struct ui_out *uiout = current_uiout;
6555
6556   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6557
6558   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6559   do_cleanups (bkpt_chain);
6560
6561   /* If this breakpoint has custom print function,
6562      it's already printed.  Otherwise, print individual
6563      locations, if any.  */
6564   if (b->ops == NULL || b->ops->print_one == NULL)
6565     {
6566       /* If breakpoint has a single location that is disabled, we
6567          print it as if it had several locations, since otherwise it's
6568          hard to represent "breakpoint enabled, location disabled"
6569          situation.
6570
6571          Note that while hardware watchpoints have several locations
6572          internally, that's not a property exposed to user.  */
6573       if (b->loc 
6574           && !is_hardware_watchpoint (b)
6575           && (b->loc->next || !b->loc->enabled))
6576         {
6577           struct bp_location *loc;
6578           int n = 1;
6579
6580           for (loc = b->loc; loc; loc = loc->next, ++n)
6581             {
6582               struct cleanup *inner2 =
6583                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6584               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6585               do_cleanups (inner2);
6586             }
6587         }
6588     }
6589 }
6590
6591 static int
6592 breakpoint_address_bits (struct breakpoint *b)
6593 {
6594   int print_address_bits = 0;
6595   struct bp_location *loc;
6596
6597   for (loc = b->loc; loc; loc = loc->next)
6598     {
6599       int addr_bit;
6600
6601       /* Software watchpoints that aren't watching memory don't have
6602          an address to print.  */
6603       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6604         continue;
6605
6606       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6607       if (addr_bit > print_address_bits)
6608         print_address_bits = addr_bit;
6609     }
6610
6611   return print_address_bits;
6612 }
6613
6614 struct captured_breakpoint_query_args
6615   {
6616     int bnum;
6617   };
6618
6619 static int
6620 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6621 {
6622   struct captured_breakpoint_query_args *args = data;
6623   struct breakpoint *b;
6624   struct bp_location *dummy_loc = NULL;
6625
6626   ALL_BREAKPOINTS (b)
6627     {
6628       if (args->bnum == b->number)
6629         {
6630           print_one_breakpoint (b, &dummy_loc, 0);
6631           return GDB_RC_OK;
6632         }
6633     }
6634   return GDB_RC_NONE;
6635 }
6636
6637 enum gdb_rc
6638 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6639                       char **error_message)
6640 {
6641   struct captured_breakpoint_query_args args;
6642
6643   args.bnum = bnum;
6644   /* For the moment we don't trust print_one_breakpoint() to not throw
6645      an error.  */
6646   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6647                                  error_message, RETURN_MASK_ALL) < 0)
6648     return GDB_RC_FAIL;
6649   else
6650     return GDB_RC_OK;
6651 }
6652
6653 /* Return true if this breakpoint was set by the user, false if it is
6654    internal or momentary.  */
6655
6656 int
6657 user_breakpoint_p (struct breakpoint *b)
6658 {
6659   return b->number > 0;
6660 }
6661
6662 /* Print information on user settable breakpoint (watchpoint, etc)
6663    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6664    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6665    FILTER is non-NULL, call it on each breakpoint and only include the
6666    ones for which it returns non-zero.  Return the total number of
6667    breakpoints listed.  */
6668
6669 static int
6670 breakpoint_1 (char *args, int allflag, 
6671               int (*filter) (const struct breakpoint *))
6672 {
6673   struct breakpoint *b;
6674   struct bp_location *last_loc = NULL;
6675   int nr_printable_breakpoints;
6676   struct cleanup *bkpttbl_chain;
6677   struct value_print_options opts;
6678   int print_address_bits = 0;
6679   int print_type_col_width = 14;
6680   struct ui_out *uiout = current_uiout;
6681
6682   get_user_print_options (&opts);
6683
6684   /* Compute the number of rows in the table, as well as the size
6685      required for address fields.  */
6686   nr_printable_breakpoints = 0;
6687   ALL_BREAKPOINTS (b)
6688     {
6689       /* If we have a filter, only list the breakpoints it accepts.  */
6690       if (filter && !filter (b))
6691         continue;
6692
6693       /* If we have an "args" string, it is a list of breakpoints to 
6694          accept.  Skip the others.  */
6695       if (args != NULL && *args != '\0')
6696         {
6697           if (allflag && parse_and_eval_long (args) != b->number)
6698             continue;
6699           if (!allflag && !number_is_in_list (args, b->number))
6700             continue;
6701         }
6702
6703       if (allflag || user_breakpoint_p (b))
6704         {
6705           int addr_bit, type_len;
6706
6707           addr_bit = breakpoint_address_bits (b);
6708           if (addr_bit > print_address_bits)
6709             print_address_bits = addr_bit;
6710
6711           type_len = strlen (bptype_string (b->type));
6712           if (type_len > print_type_col_width)
6713             print_type_col_width = type_len;
6714
6715           nr_printable_breakpoints++;
6716         }
6717     }
6718
6719   if (opts.addressprint)
6720     bkpttbl_chain 
6721       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6722                                              nr_printable_breakpoints,
6723                                              "BreakpointTable");
6724   else
6725     bkpttbl_chain 
6726       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6727                                              nr_printable_breakpoints,
6728                                              "BreakpointTable");
6729
6730   if (nr_printable_breakpoints > 0)
6731     annotate_breakpoints_headers ();
6732   if (nr_printable_breakpoints > 0)
6733     annotate_field (0);
6734   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6735   if (nr_printable_breakpoints > 0)
6736     annotate_field (1);
6737   ui_out_table_header (uiout, print_type_col_width, ui_left,
6738                        "type", "Type");                         /* 2 */
6739   if (nr_printable_breakpoints > 0)
6740     annotate_field (2);
6741   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6742   if (nr_printable_breakpoints > 0)
6743     annotate_field (3);
6744   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6745   if (opts.addressprint)
6746     {
6747       if (nr_printable_breakpoints > 0)
6748         annotate_field (4);
6749       if (print_address_bits <= 32)
6750         ui_out_table_header (uiout, 10, ui_left, 
6751                              "addr", "Address");                /* 5 */
6752       else
6753         ui_out_table_header (uiout, 18, ui_left, 
6754                              "addr", "Address");                /* 5 */
6755     }
6756   if (nr_printable_breakpoints > 0)
6757     annotate_field (5);
6758   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6759   ui_out_table_body (uiout);
6760   if (nr_printable_breakpoints > 0)
6761     annotate_breakpoints_table ();
6762
6763   ALL_BREAKPOINTS (b)
6764     {
6765       QUIT;
6766       /* If we have a filter, only list the breakpoints it accepts.  */
6767       if (filter && !filter (b))
6768         continue;
6769
6770       /* If we have an "args" string, it is a list of breakpoints to 
6771          accept.  Skip the others.  */
6772
6773       if (args != NULL && *args != '\0')
6774         {
6775           if (allflag)  /* maintenance info breakpoint */
6776             {
6777               if (parse_and_eval_long (args) != b->number)
6778                 continue;
6779             }
6780           else          /* all others */
6781             {
6782               if (!number_is_in_list (args, b->number))
6783                 continue;
6784             }
6785         }
6786       /* We only print out user settable breakpoints unless the
6787          allflag is set.  */
6788       if (allflag || user_breakpoint_p (b))
6789         print_one_breakpoint (b, &last_loc, allflag);
6790     }
6791
6792   do_cleanups (bkpttbl_chain);
6793
6794   if (nr_printable_breakpoints == 0)
6795     {
6796       /* If there's a filter, let the caller decide how to report
6797          empty list.  */
6798       if (!filter)
6799         {
6800           if (args == NULL || *args == '\0')
6801             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6802           else
6803             ui_out_message (uiout, 0, 
6804                             "No breakpoint or watchpoint matching '%s'.\n",
6805                             args);
6806         }
6807     }
6808   else
6809     {
6810       if (last_loc && !server_command)
6811         set_next_address (last_loc->gdbarch, last_loc->address);
6812     }
6813
6814   /* FIXME?  Should this be moved up so that it is only called when
6815      there have been breakpoints? */
6816   annotate_breakpoints_table_end ();
6817
6818   return nr_printable_breakpoints;
6819 }
6820
6821 /* Display the value of default-collect in a way that is generally
6822    compatible with the breakpoint list.  */
6823
6824 static void
6825 default_collect_info (void)
6826 {
6827   struct ui_out *uiout = current_uiout;
6828
6829   /* If it has no value (which is frequently the case), say nothing; a
6830      message like "No default-collect." gets in user's face when it's
6831      not wanted.  */
6832   if (!*default_collect)
6833     return;
6834
6835   /* The following phrase lines up nicely with per-tracepoint collect
6836      actions.  */
6837   ui_out_text (uiout, "default collect ");
6838   ui_out_field_string (uiout, "default-collect", default_collect);
6839   ui_out_text (uiout, " \n");
6840 }
6841   
6842 static void
6843 breakpoints_info (char *args, int from_tty)
6844 {
6845   breakpoint_1 (args, 0, NULL);
6846
6847   default_collect_info ();
6848 }
6849
6850 static void
6851 watchpoints_info (char *args, int from_tty)
6852 {
6853   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6854   struct ui_out *uiout = current_uiout;
6855
6856   if (num_printed == 0)
6857     {
6858       if (args == NULL || *args == '\0')
6859         ui_out_message (uiout, 0, "No watchpoints.\n");
6860       else
6861         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6862     }
6863 }
6864
6865 static void
6866 maintenance_info_breakpoints (char *args, int from_tty)
6867 {
6868   breakpoint_1 (args, 1, NULL);
6869
6870   default_collect_info ();
6871 }
6872
6873 static int
6874 breakpoint_has_pc (struct breakpoint *b,
6875                    struct program_space *pspace,
6876                    CORE_ADDR pc, struct obj_section *section)
6877 {
6878   struct bp_location *bl = b->loc;
6879
6880   for (; bl; bl = bl->next)
6881     {
6882       if (bl->pspace == pspace
6883           && bl->address == pc
6884           && (!overlay_debugging || bl->section == section))
6885         return 1;         
6886     }
6887   return 0;
6888 }
6889
6890 /* Print a message describing any user-breakpoints set at PC.  This
6891    concerns with logical breakpoints, so we match program spaces, not
6892    address spaces.  */
6893
6894 static void
6895 describe_other_breakpoints (struct gdbarch *gdbarch,
6896                             struct program_space *pspace, CORE_ADDR pc,
6897                             struct obj_section *section, int thread)
6898 {
6899   int others = 0;
6900   struct breakpoint *b;
6901
6902   ALL_BREAKPOINTS (b)
6903     others += (user_breakpoint_p (b)
6904                && breakpoint_has_pc (b, pspace, pc, section));
6905   if (others > 0)
6906     {
6907       if (others == 1)
6908         printf_filtered (_("Note: breakpoint "));
6909       else /* if (others == ???) */
6910         printf_filtered (_("Note: breakpoints "));
6911       ALL_BREAKPOINTS (b)
6912         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6913           {
6914             others--;
6915             printf_filtered ("%d", b->number);
6916             if (b->thread == -1 && thread != -1)
6917               printf_filtered (" (all threads)");
6918             else if (b->thread != -1)
6919               printf_filtered (" (thread %d)", b->thread);
6920             printf_filtered ("%s%s ",
6921                              ((b->enable_state == bp_disabled
6922                                || b->enable_state == bp_call_disabled)
6923                               ? " (disabled)"
6924                               : b->enable_state == bp_permanent 
6925                               ? " (permanent)"
6926                               : ""),
6927                              (others > 1) ? "," 
6928                              : ((others == 1) ? " and" : ""));
6929           }
6930       printf_filtered (_("also set at pc "));
6931       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6932       printf_filtered (".\n");
6933     }
6934 }
6935 \f
6936
6937 /* Return true iff it is meaningful to use the address member of
6938    BPT.  For some breakpoint types, the address member is irrelevant
6939    and it makes no sense to attempt to compare it to other addresses
6940    (or use it for any other purpose either).
6941
6942    More specifically, each of the following breakpoint types will
6943    always have a zero valued address and we don't want to mark
6944    breakpoints of any of these types to be a duplicate of an actual
6945    breakpoint at address zero:
6946
6947       bp_watchpoint
6948       bp_catchpoint
6949
6950 */
6951
6952 static int
6953 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6954 {
6955   enum bptype type = bpt->type;
6956
6957   return (type != bp_watchpoint && type != bp_catchpoint);
6958 }
6959
6960 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6961    true if LOC1 and LOC2 represent the same watchpoint location.  */
6962
6963 static int
6964 watchpoint_locations_match (struct bp_location *loc1, 
6965                             struct bp_location *loc2)
6966 {
6967   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6968   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6969
6970   /* Both of them must exist.  */
6971   gdb_assert (w1 != NULL);
6972   gdb_assert (w2 != NULL);
6973
6974   /* If the target can evaluate the condition expression in hardware,
6975      then we we need to insert both watchpoints even if they are at
6976      the same place.  Otherwise the watchpoint will only trigger when
6977      the condition of whichever watchpoint was inserted evaluates to
6978      true, not giving a chance for GDB to check the condition of the
6979      other watchpoint.  */
6980   if ((w1->cond_exp
6981        && target_can_accel_watchpoint_condition (loc1->address, 
6982                                                  loc1->length,
6983                                                  loc1->watchpoint_type,
6984                                                  w1->cond_exp))
6985       || (w2->cond_exp
6986           && target_can_accel_watchpoint_condition (loc2->address, 
6987                                                     loc2->length,
6988                                                     loc2->watchpoint_type,
6989                                                     w2->cond_exp)))
6990     return 0;
6991
6992   /* Note that this checks the owner's type, not the location's.  In
6993      case the target does not support read watchpoints, but does
6994      support access watchpoints, we'll have bp_read_watchpoint
6995      watchpoints with hw_access locations.  Those should be considered
6996      duplicates of hw_read locations.  The hw_read locations will
6997      become hw_access locations later.  */
6998   return (loc1->owner->type == loc2->owner->type
6999           && loc1->pspace->aspace == loc2->pspace->aspace
7000           && loc1->address == loc2->address
7001           && loc1->length == loc2->length);
7002 }
7003
7004 /* See breakpoint.h.  */
7005
7006 int
7007 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7008                           struct address_space *aspace2, CORE_ADDR addr2)
7009 {
7010   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7011            || aspace1 == aspace2)
7012           && addr1 == addr2);
7013 }
7014
7015 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7016    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7017    matches ASPACE2.  On targets that have global breakpoints, the address
7018    space doesn't really matter.  */
7019
7020 static int
7021 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7022                                 int len1, struct address_space *aspace2,
7023                                 CORE_ADDR addr2)
7024 {
7025   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7026            || aspace1 == aspace2)
7027           && addr2 >= addr1 && addr2 < addr1 + len1);
7028 }
7029
7030 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7031    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7032    matches the breakpoint's address space.  On targets that have global
7033    breakpoints, the address space doesn't really matter.  */
7034
7035 static int
7036 breakpoint_location_address_match (struct bp_location *bl,
7037                                    struct address_space *aspace,
7038                                    CORE_ADDR addr)
7039 {
7040   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7041                                     aspace, addr)
7042           || (bl->length
7043               && breakpoint_address_match_range (bl->pspace->aspace,
7044                                                  bl->address, bl->length,
7045                                                  aspace, addr)));
7046 }
7047
7048 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7049    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7050    true, otherwise returns false.  */
7051
7052 static int
7053 tracepoint_locations_match (struct bp_location *loc1,
7054                             struct bp_location *loc2)
7055 {
7056   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7057     /* Since tracepoint locations are never duplicated with others', tracepoint
7058        locations at the same address of different tracepoints are regarded as
7059        different locations.  */
7060     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7061   else
7062     return 0;
7063 }
7064
7065 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7066    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7067    represent the same location.  */
7068
7069 static int
7070 breakpoint_locations_match (struct bp_location *loc1, 
7071                             struct bp_location *loc2)
7072 {
7073   int hw_point1, hw_point2;
7074
7075   /* Both of them must not be in moribund_locations.  */
7076   gdb_assert (loc1->owner != NULL);
7077   gdb_assert (loc2->owner != NULL);
7078
7079   hw_point1 = is_hardware_watchpoint (loc1->owner);
7080   hw_point2 = is_hardware_watchpoint (loc2->owner);
7081
7082   if (hw_point1 != hw_point2)
7083     return 0;
7084   else if (hw_point1)
7085     return watchpoint_locations_match (loc1, loc2);
7086   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7087     return tracepoint_locations_match (loc1, loc2);
7088   else
7089     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7090     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7091                                      loc2->pspace->aspace, loc2->address)
7092             && loc1->length == loc2->length);
7093 }
7094
7095 static void
7096 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7097                                int bnum, int have_bnum)
7098 {
7099   /* The longest string possibly returned by hex_string_custom
7100      is 50 chars.  These must be at least that big for safety.  */
7101   char astr1[64];
7102   char astr2[64];
7103
7104   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7105   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7106   if (have_bnum)
7107     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7108              bnum, astr1, astr2);
7109   else
7110     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7111 }
7112
7113 /* Adjust a breakpoint's address to account for architectural
7114    constraints on breakpoint placement.  Return the adjusted address.
7115    Note: Very few targets require this kind of adjustment.  For most
7116    targets, this function is simply the identity function.  */
7117
7118 static CORE_ADDR
7119 adjust_breakpoint_address (struct gdbarch *gdbarch,
7120                            CORE_ADDR bpaddr, enum bptype bptype)
7121 {
7122   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7123     {
7124       /* Very few targets need any kind of breakpoint adjustment.  */
7125       return bpaddr;
7126     }
7127   else if (bptype == bp_watchpoint
7128            || bptype == bp_hardware_watchpoint
7129            || bptype == bp_read_watchpoint
7130            || bptype == bp_access_watchpoint
7131            || bptype == bp_catchpoint)
7132     {
7133       /* Watchpoints and the various bp_catch_* eventpoints should not
7134          have their addresses modified.  */
7135       return bpaddr;
7136     }
7137   else
7138     {
7139       CORE_ADDR adjusted_bpaddr;
7140
7141       /* Some targets have architectural constraints on the placement
7142          of breakpoint instructions.  Obtain the adjusted address.  */
7143       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7144
7145       /* An adjusted breakpoint address can significantly alter
7146          a user's expectations.  Print a warning if an adjustment
7147          is required.  */
7148       if (adjusted_bpaddr != bpaddr)
7149         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7150
7151       return adjusted_bpaddr;
7152     }
7153 }
7154
7155 void
7156 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7157                   struct breakpoint *owner)
7158 {
7159   memset (loc, 0, sizeof (*loc));
7160
7161   gdb_assert (ops != NULL);
7162
7163   loc->ops = ops;
7164   loc->owner = owner;
7165   loc->cond = NULL;
7166   loc->cond_bytecode = NULL;
7167   loc->shlib_disabled = 0;
7168   loc->enabled = 1;
7169
7170   switch (owner->type)
7171     {
7172     case bp_breakpoint:
7173     case bp_until:
7174     case bp_finish:
7175     case bp_longjmp:
7176     case bp_longjmp_resume:
7177     case bp_longjmp_call_dummy:
7178     case bp_exception:
7179     case bp_exception_resume:
7180     case bp_step_resume:
7181     case bp_hp_step_resume:
7182     case bp_watchpoint_scope:
7183     case bp_call_dummy:
7184     case bp_std_terminate:
7185     case bp_shlib_event:
7186     case bp_thread_event:
7187     case bp_overlay_event:
7188     case bp_jit_event:
7189     case bp_longjmp_master:
7190     case bp_std_terminate_master:
7191     case bp_exception_master:
7192     case bp_gnu_ifunc_resolver:
7193     case bp_gnu_ifunc_resolver_return:
7194     case bp_dprintf:
7195       loc->loc_type = bp_loc_software_breakpoint;
7196       mark_breakpoint_location_modified (loc);
7197       break;
7198     case bp_hardware_breakpoint:
7199       loc->loc_type = bp_loc_hardware_breakpoint;
7200       mark_breakpoint_location_modified (loc);
7201       break;
7202     case bp_hardware_watchpoint:
7203     case bp_read_watchpoint:
7204     case bp_access_watchpoint:
7205       loc->loc_type = bp_loc_hardware_watchpoint;
7206       break;
7207     case bp_watchpoint:
7208     case bp_catchpoint:
7209     case bp_tracepoint:
7210     case bp_fast_tracepoint:
7211     case bp_static_tracepoint:
7212       loc->loc_type = bp_loc_other;
7213       break;
7214     default:
7215       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7216     }
7217
7218   loc->refc = 1;
7219 }
7220
7221 /* Allocate a struct bp_location.  */
7222
7223 static struct bp_location *
7224 allocate_bp_location (struct breakpoint *bpt)
7225 {
7226   return bpt->ops->allocate_location (bpt);
7227 }
7228
7229 static void
7230 free_bp_location (struct bp_location *loc)
7231 {
7232   loc->ops->dtor (loc);
7233   xfree (loc);
7234 }
7235
7236 /* Increment reference count.  */
7237
7238 static void
7239 incref_bp_location (struct bp_location *bl)
7240 {
7241   ++bl->refc;
7242 }
7243
7244 /* Decrement reference count.  If the reference count reaches 0,
7245    destroy the bp_location.  Sets *BLP to NULL.  */
7246
7247 static void
7248 decref_bp_location (struct bp_location **blp)
7249 {
7250   gdb_assert ((*blp)->refc > 0);
7251
7252   if (--(*blp)->refc == 0)
7253     free_bp_location (*blp);
7254   *blp = NULL;
7255 }
7256
7257 /* Add breakpoint B at the end of the global breakpoint chain.  */
7258
7259 static void
7260 add_to_breakpoint_chain (struct breakpoint *b)
7261 {
7262   struct breakpoint *b1;
7263
7264   /* Add this breakpoint to the end of the chain so that a list of
7265      breakpoints will come out in order of increasing numbers.  */
7266
7267   b1 = breakpoint_chain;
7268   if (b1 == 0)
7269     breakpoint_chain = b;
7270   else
7271     {
7272       while (b1->next)
7273         b1 = b1->next;
7274       b1->next = b;
7275     }
7276 }
7277
7278 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7279
7280 static void
7281 init_raw_breakpoint_without_location (struct breakpoint *b,
7282                                       struct gdbarch *gdbarch,
7283                                       enum bptype bptype,
7284                                       const struct breakpoint_ops *ops)
7285 {
7286   memset (b, 0, sizeof (*b));
7287
7288   gdb_assert (ops != NULL);
7289
7290   b->ops = ops;
7291   b->type = bptype;
7292   b->gdbarch = gdbarch;
7293   b->language = current_language->la_language;
7294   b->input_radix = input_radix;
7295   b->thread = -1;
7296   b->enable_state = bp_enabled;
7297   b->next = 0;
7298   b->silent = 0;
7299   b->ignore_count = 0;
7300   b->commands = NULL;
7301   b->frame_id = null_frame_id;
7302   b->condition_not_parsed = 0;
7303   b->py_bp_object = NULL;
7304   b->related_breakpoint = b;
7305 }
7306
7307 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7308    that has type BPTYPE and has no locations as yet.  */
7309
7310 static struct breakpoint *
7311 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7312                                      enum bptype bptype,
7313                                      const struct breakpoint_ops *ops)
7314 {
7315   struct breakpoint *b = XNEW (struct breakpoint);
7316
7317   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7318   add_to_breakpoint_chain (b);
7319   return b;
7320 }
7321
7322 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7323    resolutions should be made as the user specified the location explicitly
7324    enough.  */
7325
7326 static void
7327 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7328 {
7329   gdb_assert (loc->owner != NULL);
7330
7331   if (loc->owner->type == bp_breakpoint
7332       || loc->owner->type == bp_hardware_breakpoint
7333       || is_tracepoint (loc->owner))
7334     {
7335       int is_gnu_ifunc;
7336       const char *function_name;
7337       CORE_ADDR func_addr;
7338
7339       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7340                                           &func_addr, NULL, &is_gnu_ifunc);
7341
7342       if (is_gnu_ifunc && !explicit_loc)
7343         {
7344           struct breakpoint *b = loc->owner;
7345
7346           gdb_assert (loc->pspace == current_program_space);
7347           if (gnu_ifunc_resolve_name (function_name,
7348                                       &loc->requested_address))
7349             {
7350               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7351               loc->address = adjust_breakpoint_address (loc->gdbarch,
7352                                                         loc->requested_address,
7353                                                         b->type);
7354             }
7355           else if (b->type == bp_breakpoint && b->loc == loc
7356                    && loc->next == NULL && b->related_breakpoint == b)
7357             {
7358               /* Create only the whole new breakpoint of this type but do not
7359                  mess more complicated breakpoints with multiple locations.  */
7360               b->type = bp_gnu_ifunc_resolver;
7361               /* Remember the resolver's address for use by the return
7362                  breakpoint.  */
7363               loc->related_address = func_addr;
7364             }
7365         }
7366
7367       if (function_name)
7368         loc->function_name = xstrdup (function_name);
7369     }
7370 }
7371
7372 /* Attempt to determine architecture of location identified by SAL.  */
7373 struct gdbarch *
7374 get_sal_arch (struct symtab_and_line sal)
7375 {
7376   if (sal.section)
7377     return get_objfile_arch (sal.section->objfile);
7378   if (sal.symtab)
7379     return get_objfile_arch (sal.symtab->objfile);
7380
7381   return NULL;
7382 }
7383
7384 /* Low level routine for partially initializing a breakpoint of type
7385    BPTYPE.  The newly created breakpoint's address, section, source
7386    file name, and line number are provided by SAL.
7387
7388    It is expected that the caller will complete the initialization of
7389    the newly created breakpoint struct as well as output any status
7390    information regarding the creation of a new breakpoint.  */
7391
7392 static void
7393 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7394                      struct symtab_and_line sal, enum bptype bptype,
7395                      const struct breakpoint_ops *ops)
7396 {
7397   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7398
7399   add_location_to_breakpoint (b, &sal);
7400
7401   if (bptype != bp_catchpoint)
7402     gdb_assert (sal.pspace != NULL);
7403
7404   /* Store the program space that was used to set the breakpoint,
7405      except for ordinary breakpoints, which are independent of the
7406      program space.  */
7407   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7408     b->pspace = sal.pspace;
7409 }
7410
7411 /* set_raw_breakpoint is a low level routine for allocating and
7412    partially initializing a breakpoint of type BPTYPE.  The newly
7413    created breakpoint's address, section, source file name, and line
7414    number are provided by SAL.  The newly created and partially
7415    initialized breakpoint is added to the breakpoint chain and
7416    is also returned as the value of this function.
7417
7418    It is expected that the caller will complete the initialization of
7419    the newly created breakpoint struct as well as output any status
7420    information regarding the creation of a new breakpoint.  In
7421    particular, set_raw_breakpoint does NOT set the breakpoint
7422    number!  Care should be taken to not allow an error to occur
7423    prior to completing the initialization of the breakpoint.  If this
7424    should happen, a bogus breakpoint will be left on the chain.  */
7425
7426 struct breakpoint *
7427 set_raw_breakpoint (struct gdbarch *gdbarch,
7428                     struct symtab_and_line sal, enum bptype bptype,
7429                     const struct breakpoint_ops *ops)
7430 {
7431   struct breakpoint *b = XNEW (struct breakpoint);
7432
7433   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7434   add_to_breakpoint_chain (b);
7435   return b;
7436 }
7437
7438
7439 /* Note that the breakpoint object B describes a permanent breakpoint
7440    instruction, hard-wired into the inferior's code.  */
7441 void
7442 make_breakpoint_permanent (struct breakpoint *b)
7443 {
7444   struct bp_location *bl;
7445
7446   b->enable_state = bp_permanent;
7447
7448   /* By definition, permanent breakpoints are already present in the
7449      code.  Mark all locations as inserted.  For now,
7450      make_breakpoint_permanent is called in just one place, so it's
7451      hard to say if it's reasonable to have permanent breakpoint with
7452      multiple locations or not, but it's easy to implement.  */
7453   for (bl = b->loc; bl; bl = bl->next)
7454     bl->inserted = 1;
7455 }
7456
7457 /* Call this routine when stepping and nexting to enable a breakpoint
7458    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7459    initiated the operation.  */
7460
7461 void
7462 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7463 {
7464   struct breakpoint *b, *b_tmp;
7465   int thread = tp->num;
7466
7467   /* To avoid having to rescan all objfile symbols at every step,
7468      we maintain a list of continually-inserted but always disabled
7469      longjmp "master" breakpoints.  Here, we simply create momentary
7470      clones of those and enable them for the requested thread.  */
7471   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7472     if (b->pspace == current_program_space
7473         && (b->type == bp_longjmp_master
7474             || b->type == bp_exception_master))
7475       {
7476         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7477         struct breakpoint *clone;
7478
7479         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7480            after their removal.  */
7481         clone = momentary_breakpoint_from_master (b, type,
7482                                                   &longjmp_breakpoint_ops, 1);
7483         clone->thread = thread;
7484       }
7485
7486   tp->initiating_frame = frame;
7487 }
7488
7489 /* Delete all longjmp breakpoints from THREAD.  */
7490 void
7491 delete_longjmp_breakpoint (int thread)
7492 {
7493   struct breakpoint *b, *b_tmp;
7494
7495   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7496     if (b->type == bp_longjmp || b->type == bp_exception)
7497       {
7498         if (b->thread == thread)
7499           delete_breakpoint (b);
7500       }
7501 }
7502
7503 void
7504 delete_longjmp_breakpoint_at_next_stop (int thread)
7505 {
7506   struct breakpoint *b, *b_tmp;
7507
7508   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7509     if (b->type == bp_longjmp || b->type == bp_exception)
7510       {
7511         if (b->thread == thread)
7512           b->disposition = disp_del_at_next_stop;
7513       }
7514 }
7515
7516 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7517    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7518    pointer to any of them.  Return NULL if this system cannot place longjmp
7519    breakpoints.  */
7520
7521 struct breakpoint *
7522 set_longjmp_breakpoint_for_call_dummy (void)
7523 {
7524   struct breakpoint *b, *retval = NULL;
7525
7526   ALL_BREAKPOINTS (b)
7527     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7528       {
7529         struct breakpoint *new_b;
7530
7531         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7532                                                   &momentary_breakpoint_ops,
7533                                                   1);
7534         new_b->thread = pid_to_thread_id (inferior_ptid);
7535
7536         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7537
7538         gdb_assert (new_b->related_breakpoint == new_b);
7539         if (retval == NULL)
7540           retval = new_b;
7541         new_b->related_breakpoint = retval;
7542         while (retval->related_breakpoint != new_b->related_breakpoint)
7543           retval = retval->related_breakpoint;
7544         retval->related_breakpoint = new_b;
7545       }
7546
7547   return retval;
7548 }
7549
7550 /* Verify all existing dummy frames and their associated breakpoints for
7551    TP.  Remove those which can no longer be found in the current frame
7552    stack.
7553
7554    You should call this function only at places where it is safe to currently
7555    unwind the whole stack.  Failed stack unwind would discard live dummy
7556    frames.  */
7557
7558 void
7559 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7560 {
7561   struct breakpoint *b, *b_tmp;
7562
7563   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7564     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7565       {
7566         struct breakpoint *dummy_b = b->related_breakpoint;
7567
7568         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7569           dummy_b = dummy_b->related_breakpoint;
7570         if (dummy_b->type != bp_call_dummy
7571             || frame_find_by_id (dummy_b->frame_id) != NULL)
7572           continue;
7573         
7574         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7575
7576         while (b->related_breakpoint != b)
7577           {
7578             if (b_tmp == b->related_breakpoint)
7579               b_tmp = b->related_breakpoint->next;
7580             delete_breakpoint (b->related_breakpoint);
7581           }
7582         delete_breakpoint (b);
7583       }
7584 }
7585
7586 void
7587 enable_overlay_breakpoints (void)
7588 {
7589   struct breakpoint *b;
7590
7591   ALL_BREAKPOINTS (b)
7592     if (b->type == bp_overlay_event)
7593     {
7594       b->enable_state = bp_enabled;
7595       update_global_location_list (UGLL_MAY_INSERT);
7596       overlay_events_enabled = 1;
7597     }
7598 }
7599
7600 void
7601 disable_overlay_breakpoints (void)
7602 {
7603   struct breakpoint *b;
7604
7605   ALL_BREAKPOINTS (b)
7606     if (b->type == bp_overlay_event)
7607     {
7608       b->enable_state = bp_disabled;
7609       update_global_location_list (UGLL_DONT_INSERT);
7610       overlay_events_enabled = 0;
7611     }
7612 }
7613
7614 /* Set an active std::terminate breakpoint for each std::terminate
7615    master breakpoint.  */
7616 void
7617 set_std_terminate_breakpoint (void)
7618 {
7619   struct breakpoint *b, *b_tmp;
7620
7621   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7622     if (b->pspace == current_program_space
7623         && b->type == bp_std_terminate_master)
7624       {
7625         momentary_breakpoint_from_master (b, bp_std_terminate,
7626                                           &momentary_breakpoint_ops, 1);
7627       }
7628 }
7629
7630 /* Delete all the std::terminate breakpoints.  */
7631 void
7632 delete_std_terminate_breakpoint (void)
7633 {
7634   struct breakpoint *b, *b_tmp;
7635
7636   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7637     if (b->type == bp_std_terminate)
7638       delete_breakpoint (b);
7639 }
7640
7641 struct breakpoint *
7642 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7643 {
7644   struct breakpoint *b;
7645
7646   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7647                                   &internal_breakpoint_ops);
7648
7649   b->enable_state = bp_enabled;
7650   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7651   b->addr_string
7652     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7653
7654   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7655
7656   return b;
7657 }
7658
7659 void
7660 remove_thread_event_breakpoints (void)
7661 {
7662   struct breakpoint *b, *b_tmp;
7663
7664   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7665     if (b->type == bp_thread_event
7666         && b->loc->pspace == current_program_space)
7667       delete_breakpoint (b);
7668 }
7669
7670 struct lang_and_radix
7671   {
7672     enum language lang;
7673     int radix;
7674   };
7675
7676 /* Create a breakpoint for JIT code registration and unregistration.  */
7677
7678 struct breakpoint *
7679 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7680 {
7681   struct breakpoint *b;
7682
7683   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7684                                   &internal_breakpoint_ops);
7685   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7686   return b;
7687 }
7688
7689 /* Remove JIT code registration and unregistration breakpoint(s).  */
7690
7691 void
7692 remove_jit_event_breakpoints (void)
7693 {
7694   struct breakpoint *b, *b_tmp;
7695
7696   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7697     if (b->type == bp_jit_event
7698         && b->loc->pspace == current_program_space)
7699       delete_breakpoint (b);
7700 }
7701
7702 void
7703 remove_solib_event_breakpoints (void)
7704 {
7705   struct breakpoint *b, *b_tmp;
7706
7707   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7708     if (b->type == bp_shlib_event
7709         && b->loc->pspace == current_program_space)
7710       delete_breakpoint (b);
7711 }
7712
7713 /* See breakpoint.h.  */
7714
7715 void
7716 remove_solib_event_breakpoints_at_next_stop (void)
7717 {
7718   struct breakpoint *b, *b_tmp;
7719
7720   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7721     if (b->type == bp_shlib_event
7722         && b->loc->pspace == current_program_space)
7723       b->disposition = disp_del_at_next_stop;
7724 }
7725
7726 /* Helper for create_solib_event_breakpoint /
7727    create_and_insert_solib_event_breakpoint.  Allows specifying which
7728    INSERT_MODE to pass through to update_global_location_list.  */
7729
7730 static struct breakpoint *
7731 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7732                                  enum ugll_insert_mode insert_mode)
7733 {
7734   struct breakpoint *b;
7735
7736   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7737                                   &internal_breakpoint_ops);
7738   update_global_location_list_nothrow (insert_mode);
7739   return b;
7740 }
7741
7742 struct breakpoint *
7743 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7744 {
7745   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7746 }
7747
7748 /* See breakpoint.h.  */
7749
7750 struct breakpoint *
7751 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7752 {
7753   struct breakpoint *b;
7754
7755   /* Explicitly tell update_global_location_list to insert
7756      locations.  */
7757   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7758   if (!b->loc->inserted)
7759     {
7760       delete_breakpoint (b);
7761       return NULL;
7762     }
7763   return b;
7764 }
7765
7766 /* Disable any breakpoints that are on code in shared libraries.  Only
7767    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7768
7769 void
7770 disable_breakpoints_in_shlibs (void)
7771 {
7772   struct bp_location *loc, **locp_tmp;
7773
7774   ALL_BP_LOCATIONS (loc, locp_tmp)
7775   {
7776     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7777     struct breakpoint *b = loc->owner;
7778
7779     /* We apply the check to all breakpoints, including disabled for
7780        those with loc->duplicate set.  This is so that when breakpoint
7781        becomes enabled, or the duplicate is removed, gdb will try to
7782        insert all breakpoints.  If we don't set shlib_disabled here,
7783        we'll try to insert those breakpoints and fail.  */
7784     if (((b->type == bp_breakpoint)
7785          || (b->type == bp_jit_event)
7786          || (b->type == bp_hardware_breakpoint)
7787          || (is_tracepoint (b)))
7788         && loc->pspace == current_program_space
7789         && !loc->shlib_disabled
7790         && solib_name_from_address (loc->pspace, loc->address)
7791         )
7792       {
7793         loc->shlib_disabled = 1;
7794       }
7795   }
7796 }
7797
7798 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7799    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7800    disabled ones can just stay disabled.  */
7801
7802 static void
7803 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7804 {
7805   struct bp_location *loc, **locp_tmp;
7806   int disabled_shlib_breaks = 0;
7807
7808   /* SunOS a.out shared libraries are always mapped, so do not
7809      disable breakpoints; they will only be reported as unloaded
7810      through clear_solib when GDB discards its shared library
7811      list.  See clear_solib for more information.  */
7812   if (exec_bfd != NULL
7813       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7814     return;
7815
7816   ALL_BP_LOCATIONS (loc, locp_tmp)
7817   {
7818     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7819     struct breakpoint *b = loc->owner;
7820
7821     if (solib->pspace == loc->pspace
7822         && !loc->shlib_disabled
7823         && (((b->type == bp_breakpoint
7824               || b->type == bp_jit_event
7825               || b->type == bp_hardware_breakpoint)
7826              && (loc->loc_type == bp_loc_hardware_breakpoint
7827                  || loc->loc_type == bp_loc_software_breakpoint))
7828             || is_tracepoint (b))
7829         && solib_contains_address_p (solib, loc->address))
7830       {
7831         loc->shlib_disabled = 1;
7832         /* At this point, we cannot rely on remove_breakpoint
7833            succeeding so we must mark the breakpoint as not inserted
7834            to prevent future errors occurring in remove_breakpoints.  */
7835         loc->inserted = 0;
7836
7837         /* This may cause duplicate notifications for the same breakpoint.  */
7838         observer_notify_breakpoint_modified (b);
7839
7840         if (!disabled_shlib_breaks)
7841           {
7842             target_terminal_ours_for_output ();
7843             warning (_("Temporarily disabling breakpoints "
7844                        "for unloaded shared library \"%s\""),
7845                      solib->so_name);
7846           }
7847         disabled_shlib_breaks = 1;
7848       }
7849   }
7850 }
7851
7852 /* Disable any breakpoints and tracepoints in OBJFILE upon
7853    notification of free_objfile.  Only apply to enabled breakpoints,
7854    disabled ones can just stay disabled.  */
7855
7856 static void
7857 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7858 {
7859   struct breakpoint *b;
7860
7861   if (objfile == NULL)
7862     return;
7863
7864   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7865      managed by the user with add-symbol-file/remove-symbol-file.
7866      Similarly to how breakpoints in shared libraries are handled in
7867      response to "nosharedlibrary", mark breakpoints in such modules
7868      shlib_disabled so they end up uninserted on the next global
7869      location list update.  Shared libraries not loaded by the user
7870      aren't handled here -- they're already handled in
7871      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7872      solib_unloaded observer.  We skip objfiles that are not
7873      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7874      main objfile).  */
7875   if ((objfile->flags & OBJF_SHARED) == 0
7876       || (objfile->flags & OBJF_USERLOADED) == 0)
7877     return;
7878
7879   ALL_BREAKPOINTS (b)
7880     {
7881       struct bp_location *loc;
7882       int bp_modified = 0;
7883
7884       if (!is_breakpoint (b) && !is_tracepoint (b))
7885         continue;
7886
7887       for (loc = b->loc; loc != NULL; loc = loc->next)
7888         {
7889           CORE_ADDR loc_addr = loc->address;
7890
7891           if (loc->loc_type != bp_loc_hardware_breakpoint
7892               && loc->loc_type != bp_loc_software_breakpoint)
7893             continue;
7894
7895           if (loc->shlib_disabled != 0)
7896             continue;
7897
7898           if (objfile->pspace != loc->pspace)
7899             continue;
7900
7901           if (loc->loc_type != bp_loc_hardware_breakpoint
7902               && loc->loc_type != bp_loc_software_breakpoint)
7903             continue;
7904
7905           if (is_addr_in_objfile (loc_addr, objfile))
7906             {
7907               loc->shlib_disabled = 1;
7908               /* At this point, we don't know whether the object was
7909                  unmapped from the inferior or not, so leave the
7910                  inserted flag alone.  We'll handle failure to
7911                  uninsert quietly, in case the object was indeed
7912                  unmapped.  */
7913
7914               mark_breakpoint_location_modified (loc);
7915
7916               bp_modified = 1;
7917             }
7918         }
7919
7920       if (bp_modified)
7921         observer_notify_breakpoint_modified (b);
7922     }
7923 }
7924
7925 /* FORK & VFORK catchpoints.  */
7926
7927 /* An instance of this type is used to represent a fork or vfork
7928    catchpoint.  It includes a "struct breakpoint" as a kind of base
7929    class; users downcast to "struct breakpoint *" when needed.  A
7930    breakpoint is really of this type iff its ops pointer points to
7931    CATCH_FORK_BREAKPOINT_OPS.  */
7932
7933 struct fork_catchpoint
7934 {
7935   /* The base class.  */
7936   struct breakpoint base;
7937
7938   /* Process id of a child process whose forking triggered this
7939      catchpoint.  This field is only valid immediately after this
7940      catchpoint has triggered.  */
7941   ptid_t forked_inferior_pid;
7942 };
7943
7944 /* Implement the "insert" breakpoint_ops method for fork
7945    catchpoints.  */
7946
7947 static int
7948 insert_catch_fork (struct bp_location *bl)
7949 {
7950   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7951 }
7952
7953 /* Implement the "remove" breakpoint_ops method for fork
7954    catchpoints.  */
7955
7956 static int
7957 remove_catch_fork (struct bp_location *bl)
7958 {
7959   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7960 }
7961
7962 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7963    catchpoints.  */
7964
7965 static int
7966 breakpoint_hit_catch_fork (const struct bp_location *bl,
7967                            struct address_space *aspace, CORE_ADDR bp_addr,
7968                            const struct target_waitstatus *ws)
7969 {
7970   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7971
7972   if (ws->kind != TARGET_WAITKIND_FORKED)
7973     return 0;
7974
7975   c->forked_inferior_pid = ws->value.related_pid;
7976   return 1;
7977 }
7978
7979 /* Implement the "print_it" breakpoint_ops method for fork
7980    catchpoints.  */
7981
7982 static enum print_stop_action
7983 print_it_catch_fork (bpstat bs)
7984 {
7985   struct ui_out *uiout = current_uiout;
7986   struct breakpoint *b = bs->breakpoint_at;
7987   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7988
7989   annotate_catchpoint (b->number);
7990   if (b->disposition == disp_del)
7991     ui_out_text (uiout, "\nTemporary catchpoint ");
7992   else
7993     ui_out_text (uiout, "\nCatchpoint ");
7994   if (ui_out_is_mi_like_p (uiout))
7995     {
7996       ui_out_field_string (uiout, "reason",
7997                            async_reason_lookup (EXEC_ASYNC_FORK));
7998       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7999     }
8000   ui_out_field_int (uiout, "bkptno", b->number);
8001   ui_out_text (uiout, " (forked process ");
8002   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8003   ui_out_text (uiout, "), ");
8004   return PRINT_SRC_AND_LOC;
8005 }
8006
8007 /* Implement the "print_one" breakpoint_ops method for fork
8008    catchpoints.  */
8009
8010 static void
8011 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8012 {
8013   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8014   struct value_print_options opts;
8015   struct ui_out *uiout = current_uiout;
8016
8017   get_user_print_options (&opts);
8018
8019   /* Field 4, the address, is omitted (which makes the columns not
8020      line up too nicely with the headers, but the effect is relatively
8021      readable).  */
8022   if (opts.addressprint)
8023     ui_out_field_skip (uiout, "addr");
8024   annotate_field (5);
8025   ui_out_text (uiout, "fork");
8026   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8027     {
8028       ui_out_text (uiout, ", process ");
8029       ui_out_field_int (uiout, "what",
8030                         ptid_get_pid (c->forked_inferior_pid));
8031       ui_out_spaces (uiout, 1);
8032     }
8033
8034   if (ui_out_is_mi_like_p (uiout))
8035     ui_out_field_string (uiout, "catch-type", "fork");
8036 }
8037
8038 /* Implement the "print_mention" breakpoint_ops method for fork
8039    catchpoints.  */
8040
8041 static void
8042 print_mention_catch_fork (struct breakpoint *b)
8043 {
8044   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8045 }
8046
8047 /* Implement the "print_recreate" breakpoint_ops method for fork
8048    catchpoints.  */
8049
8050 static void
8051 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8052 {
8053   fprintf_unfiltered (fp, "catch fork");
8054   print_recreate_thread (b, fp);
8055 }
8056
8057 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8058
8059 static struct breakpoint_ops catch_fork_breakpoint_ops;
8060
8061 /* Implement the "insert" breakpoint_ops method for vfork
8062    catchpoints.  */
8063
8064 static int
8065 insert_catch_vfork (struct bp_location *bl)
8066 {
8067   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8068 }
8069
8070 /* Implement the "remove" breakpoint_ops method for vfork
8071    catchpoints.  */
8072
8073 static int
8074 remove_catch_vfork (struct bp_location *bl)
8075 {
8076   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8077 }
8078
8079 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8080    catchpoints.  */
8081
8082 static int
8083 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8084                             struct address_space *aspace, CORE_ADDR bp_addr,
8085                             const struct target_waitstatus *ws)
8086 {
8087   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8088
8089   if (ws->kind != TARGET_WAITKIND_VFORKED)
8090     return 0;
8091
8092   c->forked_inferior_pid = ws->value.related_pid;
8093   return 1;
8094 }
8095
8096 /* Implement the "print_it" breakpoint_ops method for vfork
8097    catchpoints.  */
8098
8099 static enum print_stop_action
8100 print_it_catch_vfork (bpstat bs)
8101 {
8102   struct ui_out *uiout = current_uiout;
8103   struct breakpoint *b = bs->breakpoint_at;
8104   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8105
8106   annotate_catchpoint (b->number);
8107   if (b->disposition == disp_del)
8108     ui_out_text (uiout, "\nTemporary catchpoint ");
8109   else
8110     ui_out_text (uiout, "\nCatchpoint ");
8111   if (ui_out_is_mi_like_p (uiout))
8112     {
8113       ui_out_field_string (uiout, "reason",
8114                            async_reason_lookup (EXEC_ASYNC_VFORK));
8115       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8116     }
8117   ui_out_field_int (uiout, "bkptno", b->number);
8118   ui_out_text (uiout, " (vforked process ");
8119   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8120   ui_out_text (uiout, "), ");
8121   return PRINT_SRC_AND_LOC;
8122 }
8123
8124 /* Implement the "print_one" breakpoint_ops method for vfork
8125    catchpoints.  */
8126
8127 static void
8128 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8129 {
8130   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8131   struct value_print_options opts;
8132   struct ui_out *uiout = current_uiout;
8133
8134   get_user_print_options (&opts);
8135   /* Field 4, the address, is omitted (which makes the columns not
8136      line up too nicely with the headers, but the effect is relatively
8137      readable).  */
8138   if (opts.addressprint)
8139     ui_out_field_skip (uiout, "addr");
8140   annotate_field (5);
8141   ui_out_text (uiout, "vfork");
8142   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8143     {
8144       ui_out_text (uiout, ", process ");
8145       ui_out_field_int (uiout, "what",
8146                         ptid_get_pid (c->forked_inferior_pid));
8147       ui_out_spaces (uiout, 1);
8148     }
8149
8150   if (ui_out_is_mi_like_p (uiout))
8151     ui_out_field_string (uiout, "catch-type", "vfork");
8152 }
8153
8154 /* Implement the "print_mention" breakpoint_ops method for vfork
8155    catchpoints.  */
8156
8157 static void
8158 print_mention_catch_vfork (struct breakpoint *b)
8159 {
8160   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8161 }
8162
8163 /* Implement the "print_recreate" breakpoint_ops method for vfork
8164    catchpoints.  */
8165
8166 static void
8167 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8168 {
8169   fprintf_unfiltered (fp, "catch vfork");
8170   print_recreate_thread (b, fp);
8171 }
8172
8173 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8174
8175 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8176
8177 /* An instance of this type is used to represent an solib catchpoint.
8178    It includes a "struct breakpoint" as a kind of base class; users
8179    downcast to "struct breakpoint *" when needed.  A breakpoint is
8180    really of this type iff its ops pointer points to
8181    CATCH_SOLIB_BREAKPOINT_OPS.  */
8182
8183 struct solib_catchpoint
8184 {
8185   /* The base class.  */
8186   struct breakpoint base;
8187
8188   /* True for "catch load", false for "catch unload".  */
8189   unsigned char is_load;
8190
8191   /* Regular expression to match, if any.  COMPILED is only valid when
8192      REGEX is non-NULL.  */
8193   char *regex;
8194   regex_t compiled;
8195 };
8196
8197 static void
8198 dtor_catch_solib (struct breakpoint *b)
8199 {
8200   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8201
8202   if (self->regex)
8203     regfree (&self->compiled);
8204   xfree (self->regex);
8205
8206   base_breakpoint_ops.dtor (b);
8207 }
8208
8209 static int
8210 insert_catch_solib (struct bp_location *ignore)
8211 {
8212   return 0;
8213 }
8214
8215 static int
8216 remove_catch_solib (struct bp_location *ignore)
8217 {
8218   return 0;
8219 }
8220
8221 static int
8222 breakpoint_hit_catch_solib (const struct bp_location *bl,
8223                             struct address_space *aspace,
8224                             CORE_ADDR bp_addr,
8225                             const struct target_waitstatus *ws)
8226 {
8227   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8228   struct breakpoint *other;
8229
8230   if (ws->kind == TARGET_WAITKIND_LOADED)
8231     return 1;
8232
8233   ALL_BREAKPOINTS (other)
8234   {
8235     struct bp_location *other_bl;
8236
8237     if (other == bl->owner)
8238       continue;
8239
8240     if (other->type != bp_shlib_event)
8241       continue;
8242
8243     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8244       continue;
8245
8246     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8247       {
8248         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8249           return 1;
8250       }
8251   }
8252
8253   return 0;
8254 }
8255
8256 static void
8257 check_status_catch_solib (struct bpstats *bs)
8258 {
8259   struct solib_catchpoint *self
8260     = (struct solib_catchpoint *) bs->breakpoint_at;
8261   int ix;
8262
8263   if (self->is_load)
8264     {
8265       struct so_list *iter;
8266
8267       for (ix = 0;
8268            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8269                         ix, iter);
8270            ++ix)
8271         {
8272           if (!self->regex
8273               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8274             return;
8275         }
8276     }
8277   else
8278     {
8279       char *iter;
8280
8281       for (ix = 0;
8282            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8283                         ix, iter);
8284            ++ix)
8285         {
8286           if (!self->regex
8287               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8288             return;
8289         }
8290     }
8291
8292   bs->stop = 0;
8293   bs->print_it = print_it_noop;
8294 }
8295
8296 static enum print_stop_action
8297 print_it_catch_solib (bpstat bs)
8298 {
8299   struct breakpoint *b = bs->breakpoint_at;
8300   struct ui_out *uiout = current_uiout;
8301
8302   annotate_catchpoint (b->number);
8303   if (b->disposition == disp_del)
8304     ui_out_text (uiout, "\nTemporary catchpoint ");
8305   else
8306     ui_out_text (uiout, "\nCatchpoint ");
8307   ui_out_field_int (uiout, "bkptno", b->number);
8308   ui_out_text (uiout, "\n");
8309   if (ui_out_is_mi_like_p (uiout))
8310     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8311   print_solib_event (1);
8312   return PRINT_SRC_AND_LOC;
8313 }
8314
8315 static void
8316 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8317 {
8318   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8319   struct value_print_options opts;
8320   struct ui_out *uiout = current_uiout;
8321   char *msg;
8322
8323   get_user_print_options (&opts);
8324   /* Field 4, the address, is omitted (which makes the columns not
8325      line up too nicely with the headers, but the effect is relatively
8326      readable).  */
8327   if (opts.addressprint)
8328     {
8329       annotate_field (4);
8330       ui_out_field_skip (uiout, "addr");
8331     }
8332
8333   annotate_field (5);
8334   if (self->is_load)
8335     {
8336       if (self->regex)
8337         msg = xstrprintf (_("load of library matching %s"), self->regex);
8338       else
8339         msg = xstrdup (_("load of library"));
8340     }
8341   else
8342     {
8343       if (self->regex)
8344         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8345       else
8346         msg = xstrdup (_("unload of library"));
8347     }
8348   ui_out_field_string (uiout, "what", msg);
8349   xfree (msg);
8350
8351   if (ui_out_is_mi_like_p (uiout))
8352     ui_out_field_string (uiout, "catch-type",
8353                          self->is_load ? "load" : "unload");
8354 }
8355
8356 static void
8357 print_mention_catch_solib (struct breakpoint *b)
8358 {
8359   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8360
8361   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8362                    self->is_load ? "load" : "unload");
8363 }
8364
8365 static void
8366 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8367 {
8368   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8369
8370   fprintf_unfiltered (fp, "%s %s",
8371                       b->disposition == disp_del ? "tcatch" : "catch",
8372                       self->is_load ? "load" : "unload");
8373   if (self->regex)
8374     fprintf_unfiltered (fp, " %s", self->regex);
8375   fprintf_unfiltered (fp, "\n");
8376 }
8377
8378 static struct breakpoint_ops catch_solib_breakpoint_ops;
8379
8380 /* Shared helper function (MI and CLI) for creating and installing
8381    a shared object event catchpoint.  If IS_LOAD is non-zero then
8382    the events to be caught are load events, otherwise they are
8383    unload events.  If IS_TEMP is non-zero the catchpoint is a
8384    temporary one.  If ENABLED is non-zero the catchpoint is
8385    created in an enabled state.  */
8386
8387 void
8388 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8389 {
8390   struct solib_catchpoint *c;
8391   struct gdbarch *gdbarch = get_current_arch ();
8392   struct cleanup *cleanup;
8393
8394   if (!arg)
8395     arg = "";
8396   arg = skip_spaces (arg);
8397
8398   c = XCNEW (struct solib_catchpoint);
8399   cleanup = make_cleanup (xfree, c);
8400
8401   if (*arg != '\0')
8402     {
8403       int errcode;
8404
8405       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8406       if (errcode != 0)
8407         {
8408           char *err = get_regcomp_error (errcode, &c->compiled);
8409
8410           make_cleanup (xfree, err);
8411           error (_("Invalid regexp (%s): %s"), err, arg);
8412         }
8413       c->regex = xstrdup (arg);
8414     }
8415
8416   c->is_load = is_load;
8417   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8418                    &catch_solib_breakpoint_ops);
8419
8420   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8421
8422   discard_cleanups (cleanup);
8423   install_breakpoint (0, &c->base, 1);
8424 }
8425
8426 /* A helper function that does all the work for "catch load" and
8427    "catch unload".  */
8428
8429 static void
8430 catch_load_or_unload (char *arg, int from_tty, int is_load,
8431                       struct cmd_list_element *command)
8432 {
8433   int tempflag;
8434   const int enabled = 1;
8435
8436   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8437
8438   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8439 }
8440
8441 static void
8442 catch_load_command_1 (char *arg, int from_tty,
8443                       struct cmd_list_element *command)
8444 {
8445   catch_load_or_unload (arg, from_tty, 1, command);
8446 }
8447
8448 static void
8449 catch_unload_command_1 (char *arg, int from_tty,
8450                         struct cmd_list_element *command)
8451 {
8452   catch_load_or_unload (arg, from_tty, 0, command);
8453 }
8454
8455 /* An instance of this type is used to represent a syscall catchpoint.
8456    It includes a "struct breakpoint" as a kind of base class; users
8457    downcast to "struct breakpoint *" when needed.  A breakpoint is
8458    really of this type iff its ops pointer points to
8459    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8460
8461 struct syscall_catchpoint
8462 {
8463   /* The base class.  */
8464   struct breakpoint base;
8465
8466   /* Syscall numbers used for the 'catch syscall' feature.  If no
8467      syscall has been specified for filtering, its value is NULL.
8468      Otherwise, it holds a list of all syscalls to be caught.  The
8469      list elements are allocated with xmalloc.  */
8470   VEC(int) *syscalls_to_be_caught;
8471 };
8472
8473 /* Implement the "dtor" breakpoint_ops method for syscall
8474    catchpoints.  */
8475
8476 static void
8477 dtor_catch_syscall (struct breakpoint *b)
8478 {
8479   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8480
8481   VEC_free (int, c->syscalls_to_be_caught);
8482
8483   base_breakpoint_ops.dtor (b);
8484 }
8485
8486 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8487
8488 struct catch_syscall_inferior_data
8489 {
8490   /* We keep a count of the number of times the user has requested a
8491      particular syscall to be tracked, and pass this information to the
8492      target.  This lets capable targets implement filtering directly.  */
8493
8494   /* Number of times that "any" syscall is requested.  */
8495   int any_syscall_count;
8496
8497   /* Count of each system call.  */
8498   VEC(int) *syscalls_counts;
8499
8500   /* This counts all syscall catch requests, so we can readily determine
8501      if any catching is necessary.  */
8502   int total_syscalls_count;
8503 };
8504
8505 static struct catch_syscall_inferior_data*
8506 get_catch_syscall_inferior_data (struct inferior *inf)
8507 {
8508   struct catch_syscall_inferior_data *inf_data;
8509
8510   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8511   if (inf_data == NULL)
8512     {
8513       inf_data = XCNEW (struct catch_syscall_inferior_data);
8514       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8515     }
8516
8517   return inf_data;
8518 }
8519
8520 static void
8521 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8522 {
8523   xfree (arg);
8524 }
8525
8526
8527 /* Implement the "insert" breakpoint_ops method for syscall
8528    catchpoints.  */
8529
8530 static int
8531 insert_catch_syscall (struct bp_location *bl)
8532 {
8533   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8534   struct inferior *inf = current_inferior ();
8535   struct catch_syscall_inferior_data *inf_data
8536     = get_catch_syscall_inferior_data (inf);
8537
8538   ++inf_data->total_syscalls_count;
8539   if (!c->syscalls_to_be_caught)
8540     ++inf_data->any_syscall_count;
8541   else
8542     {
8543       int i, iter;
8544
8545       for (i = 0;
8546            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8547            i++)
8548         {
8549           int elem;
8550
8551           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8552             {
8553               int old_size = VEC_length (int, inf_data->syscalls_counts);
8554               uintptr_t vec_addr_offset
8555                 = old_size * ((uintptr_t) sizeof (int));
8556               uintptr_t vec_addr;
8557               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8558               vec_addr = ((uintptr_t) VEC_address (int,
8559                                                   inf_data->syscalls_counts)
8560                           + vec_addr_offset);
8561               memset ((void *) vec_addr, 0,
8562                       (iter + 1 - old_size) * sizeof (int));
8563             }
8564           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8565           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8566         }
8567     }
8568
8569   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8570                                         inf_data->total_syscalls_count != 0,
8571                                         inf_data->any_syscall_count,
8572                                         VEC_length (int,
8573                                                     inf_data->syscalls_counts),
8574                                         VEC_address (int,
8575                                                      inf_data->syscalls_counts));
8576 }
8577
8578 /* Implement the "remove" breakpoint_ops method for syscall
8579    catchpoints.  */
8580
8581 static int
8582 remove_catch_syscall (struct bp_location *bl)
8583 {
8584   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8585   struct inferior *inf = current_inferior ();
8586   struct catch_syscall_inferior_data *inf_data
8587     = get_catch_syscall_inferior_data (inf);
8588
8589   --inf_data->total_syscalls_count;
8590   if (!c->syscalls_to_be_caught)
8591     --inf_data->any_syscall_count;
8592   else
8593     {
8594       int i, iter;
8595
8596       for (i = 0;
8597            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8598            i++)
8599         {
8600           int elem;
8601           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8602             /* Shouldn't happen.  */
8603             continue;
8604           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8605           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8606         }
8607     }
8608
8609   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8610                                         inf_data->total_syscalls_count != 0,
8611                                         inf_data->any_syscall_count,
8612                                         VEC_length (int,
8613                                                     inf_data->syscalls_counts),
8614                                         VEC_address (int,
8615                                                      inf_data->syscalls_counts));
8616 }
8617
8618 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8619    catchpoints.  */
8620
8621 static int
8622 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8623                               struct address_space *aspace, CORE_ADDR bp_addr,
8624                               const struct target_waitstatus *ws)
8625 {
8626   /* We must check if we are catching specific syscalls in this
8627      breakpoint.  If we are, then we must guarantee that the called
8628      syscall is the same syscall we are catching.  */
8629   int syscall_number = 0;
8630   const struct syscall_catchpoint *c
8631     = (const struct syscall_catchpoint *) bl->owner;
8632
8633   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8634       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8635     return 0;
8636
8637   syscall_number = ws->value.syscall_number;
8638
8639   /* Now, checking if the syscall is the same.  */
8640   if (c->syscalls_to_be_caught)
8641     {
8642       int i, iter;
8643
8644       for (i = 0;
8645            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8646            i++)
8647         if (syscall_number == iter)
8648           return 1;
8649
8650       return 0;
8651     }
8652
8653   return 1;
8654 }
8655
8656 /* Implement the "print_it" breakpoint_ops method for syscall
8657    catchpoints.  */
8658
8659 static enum print_stop_action
8660 print_it_catch_syscall (bpstat bs)
8661 {
8662   struct ui_out *uiout = current_uiout;
8663   struct breakpoint *b = bs->breakpoint_at;
8664   /* These are needed because we want to know in which state a
8665      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8666      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8667      must print "called syscall" or "returned from syscall".  */
8668   ptid_t ptid;
8669   struct target_waitstatus last;
8670   struct syscall s;
8671
8672   get_last_target_status (&ptid, &last);
8673
8674   get_syscall_by_number (last.value.syscall_number, &s);
8675
8676   annotate_catchpoint (b->number);
8677
8678   if (b->disposition == disp_del)
8679     ui_out_text (uiout, "\nTemporary catchpoint ");
8680   else
8681     ui_out_text (uiout, "\nCatchpoint ");
8682   if (ui_out_is_mi_like_p (uiout))
8683     {
8684       ui_out_field_string (uiout, "reason",
8685                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8686                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8687                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8688       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8689     }
8690   ui_out_field_int (uiout, "bkptno", b->number);
8691
8692   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8693     ui_out_text (uiout, " (call to syscall ");
8694   else
8695     ui_out_text (uiout, " (returned from syscall ");
8696
8697   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8698     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8699   if (s.name != NULL)
8700     ui_out_field_string (uiout, "syscall-name", s.name);
8701
8702   ui_out_text (uiout, "), ");
8703
8704   return PRINT_SRC_AND_LOC;
8705 }
8706
8707 /* Implement the "print_one" breakpoint_ops method for syscall
8708    catchpoints.  */
8709
8710 static void
8711 print_one_catch_syscall (struct breakpoint *b,
8712                          struct bp_location **last_loc)
8713 {
8714   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8715   struct value_print_options opts;
8716   struct ui_out *uiout = current_uiout;
8717
8718   get_user_print_options (&opts);
8719   /* Field 4, the address, is omitted (which makes the columns not
8720      line up too nicely with the headers, but the effect is relatively
8721      readable).  */
8722   if (opts.addressprint)
8723     ui_out_field_skip (uiout, "addr");
8724   annotate_field (5);
8725
8726   if (c->syscalls_to_be_caught
8727       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8728     ui_out_text (uiout, "syscalls \"");
8729   else
8730     ui_out_text (uiout, "syscall \"");
8731
8732   if (c->syscalls_to_be_caught)
8733     {
8734       int i, iter;
8735       char *text = xstrprintf ("%s", "");
8736
8737       for (i = 0;
8738            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8739            i++)
8740         {
8741           char *x = text;
8742           struct syscall s;
8743           get_syscall_by_number (iter, &s);
8744
8745           if (s.name != NULL)
8746             text = xstrprintf ("%s%s, ", text, s.name);
8747           else
8748             text = xstrprintf ("%s%d, ", text, iter);
8749
8750           /* We have to xfree the last 'text' (now stored at 'x')
8751              because xstrprintf dynamically allocates new space for it
8752              on every call.  */
8753           xfree (x);
8754         }
8755       /* Remove the last comma.  */
8756       text[strlen (text) - 2] = '\0';
8757       ui_out_field_string (uiout, "what", text);
8758     }
8759   else
8760     ui_out_field_string (uiout, "what", "<any syscall>");
8761   ui_out_text (uiout, "\" ");
8762
8763   if (ui_out_is_mi_like_p (uiout))
8764     ui_out_field_string (uiout, "catch-type", "syscall");
8765 }
8766
8767 /* Implement the "print_mention" breakpoint_ops method for syscall
8768    catchpoints.  */
8769
8770 static void
8771 print_mention_catch_syscall (struct breakpoint *b)
8772 {
8773   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8774
8775   if (c->syscalls_to_be_caught)
8776     {
8777       int i, iter;
8778
8779       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8780         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8781       else
8782         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8783
8784       for (i = 0;
8785            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8786            i++)
8787         {
8788           struct syscall s;
8789           get_syscall_by_number (iter, &s);
8790
8791           if (s.name)
8792             printf_filtered (" '%s' [%d]", s.name, s.number);
8793           else
8794             printf_filtered (" %d", s.number);
8795         }
8796       printf_filtered (")");
8797     }
8798   else
8799     printf_filtered (_("Catchpoint %d (any syscall)"),
8800                      b->number);
8801 }
8802
8803 /* Implement the "print_recreate" breakpoint_ops method for syscall
8804    catchpoints.  */
8805
8806 static void
8807 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8808 {
8809   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8810
8811   fprintf_unfiltered (fp, "catch syscall");
8812
8813   if (c->syscalls_to_be_caught)
8814     {
8815       int i, iter;
8816
8817       for (i = 0;
8818            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8819            i++)
8820         {
8821           struct syscall s;
8822
8823           get_syscall_by_number (iter, &s);
8824           if (s.name)
8825             fprintf_unfiltered (fp, " %s", s.name);
8826           else
8827             fprintf_unfiltered (fp, " %d", s.number);
8828         }
8829     }
8830   print_recreate_thread (b, fp);
8831 }
8832
8833 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8834
8835 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8836
8837 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8838
8839 static int
8840 syscall_catchpoint_p (struct breakpoint *b)
8841 {
8842   return (b->ops == &catch_syscall_breakpoint_ops);
8843 }
8844
8845 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8846    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8847    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8848    the breakpoint_ops structure associated to the catchpoint.  */
8849
8850 void
8851 init_catchpoint (struct breakpoint *b,
8852                  struct gdbarch *gdbarch, int tempflag,
8853                  char *cond_string,
8854                  const struct breakpoint_ops *ops)
8855 {
8856   struct symtab_and_line sal;
8857
8858   init_sal (&sal);
8859   sal.pspace = current_program_space;
8860
8861   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8862
8863   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8864   b->disposition = tempflag ? disp_del : disp_donttouch;
8865 }
8866
8867 void
8868 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8869 {
8870   add_to_breakpoint_chain (b);
8871   set_breakpoint_number (internal, b);
8872   if (is_tracepoint (b))
8873     set_tracepoint_count (breakpoint_count);
8874   if (!internal)
8875     mention (b);
8876   observer_notify_breakpoint_created (b);
8877
8878   if (update_gll)
8879     update_global_location_list (UGLL_MAY_INSERT);
8880 }
8881
8882 static void
8883 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8884                                     int tempflag, char *cond_string,
8885                                     const struct breakpoint_ops *ops)
8886 {
8887   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8888
8889   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8890
8891   c->forked_inferior_pid = null_ptid;
8892
8893   install_breakpoint (0, &c->base, 1);
8894 }
8895
8896 /* Exec catchpoints.  */
8897
8898 /* An instance of this type is used to represent an exec catchpoint.
8899    It includes a "struct breakpoint" as a kind of base class; users
8900    downcast to "struct breakpoint *" when needed.  A breakpoint is
8901    really of this type iff its ops pointer points to
8902    CATCH_EXEC_BREAKPOINT_OPS.  */
8903
8904 struct exec_catchpoint
8905 {
8906   /* The base class.  */
8907   struct breakpoint base;
8908
8909   /* Filename of a program whose exec triggered this catchpoint.
8910      This field is only valid immediately after this catchpoint has
8911      triggered.  */
8912   char *exec_pathname;
8913 };
8914
8915 /* Implement the "dtor" breakpoint_ops method for exec
8916    catchpoints.  */
8917
8918 static void
8919 dtor_catch_exec (struct breakpoint *b)
8920 {
8921   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8922
8923   xfree (c->exec_pathname);
8924
8925   base_breakpoint_ops.dtor (b);
8926 }
8927
8928 static int
8929 insert_catch_exec (struct bp_location *bl)
8930 {
8931   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8932 }
8933
8934 static int
8935 remove_catch_exec (struct bp_location *bl)
8936 {
8937   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8938 }
8939
8940 static int
8941 breakpoint_hit_catch_exec (const struct bp_location *bl,
8942                            struct address_space *aspace, CORE_ADDR bp_addr,
8943                            const struct target_waitstatus *ws)
8944 {
8945   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8946
8947   if (ws->kind != TARGET_WAITKIND_EXECD)
8948     return 0;
8949
8950   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8951   return 1;
8952 }
8953
8954 static enum print_stop_action
8955 print_it_catch_exec (bpstat bs)
8956 {
8957   struct ui_out *uiout = current_uiout;
8958   struct breakpoint *b = bs->breakpoint_at;
8959   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8960
8961   annotate_catchpoint (b->number);
8962   if (b->disposition == disp_del)
8963     ui_out_text (uiout, "\nTemporary catchpoint ");
8964   else
8965     ui_out_text (uiout, "\nCatchpoint ");
8966   if (ui_out_is_mi_like_p (uiout))
8967     {
8968       ui_out_field_string (uiout, "reason",
8969                            async_reason_lookup (EXEC_ASYNC_EXEC));
8970       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8971     }
8972   ui_out_field_int (uiout, "bkptno", b->number);
8973   ui_out_text (uiout, " (exec'd ");
8974   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8975   ui_out_text (uiout, "), ");
8976
8977   return PRINT_SRC_AND_LOC;
8978 }
8979
8980 static void
8981 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8982 {
8983   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8984   struct value_print_options opts;
8985   struct ui_out *uiout = current_uiout;
8986
8987   get_user_print_options (&opts);
8988
8989   /* Field 4, the address, is omitted (which makes the columns
8990      not line up too nicely with the headers, but the effect
8991      is relatively readable).  */
8992   if (opts.addressprint)
8993     ui_out_field_skip (uiout, "addr");
8994   annotate_field (5);
8995   ui_out_text (uiout, "exec");
8996   if (c->exec_pathname != NULL)
8997     {
8998       ui_out_text (uiout, ", program \"");
8999       ui_out_field_string (uiout, "what", c->exec_pathname);
9000       ui_out_text (uiout, "\" ");
9001     }
9002
9003   if (ui_out_is_mi_like_p (uiout))
9004     ui_out_field_string (uiout, "catch-type", "exec");
9005 }
9006
9007 static void
9008 print_mention_catch_exec (struct breakpoint *b)
9009 {
9010   printf_filtered (_("Catchpoint %d (exec)"), b->number);
9011 }
9012
9013 /* Implement the "print_recreate" breakpoint_ops method for exec
9014    catchpoints.  */
9015
9016 static void
9017 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9018 {
9019   fprintf_unfiltered (fp, "catch exec");
9020   print_recreate_thread (b, fp);
9021 }
9022
9023 static struct breakpoint_ops catch_exec_breakpoint_ops;
9024
9025 static void
9026 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9027                                  const struct breakpoint_ops *ops)
9028 {
9029   struct syscall_catchpoint *c;
9030   struct gdbarch *gdbarch = get_current_arch ();
9031
9032   c = XNEW (struct syscall_catchpoint);
9033   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9034   c->syscalls_to_be_caught = filter;
9035
9036   install_breakpoint (0, &c->base, 1);
9037 }
9038
9039 static int
9040 hw_breakpoint_used_count (void)
9041 {
9042   int i = 0;
9043   struct breakpoint *b;
9044   struct bp_location *bl;
9045
9046   ALL_BREAKPOINTS (b)
9047   {
9048     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9049       for (bl = b->loc; bl; bl = bl->next)
9050         {
9051           /* Special types of hardware breakpoints may use more than
9052              one register.  */
9053           i += b->ops->resources_needed (bl);
9054         }
9055   }
9056
9057   return i;
9058 }
9059
9060 /* Returns the resources B would use if it were a hardware
9061    watchpoint.  */
9062
9063 static int
9064 hw_watchpoint_use_count (struct breakpoint *b)
9065 {
9066   int i = 0;
9067   struct bp_location *bl;
9068
9069   if (!breakpoint_enabled (b))
9070     return 0;
9071
9072   for (bl = b->loc; bl; bl = bl->next)
9073     {
9074       /* Special types of hardware watchpoints may use more than
9075          one register.  */
9076       i += b->ops->resources_needed (bl);
9077     }
9078
9079   return i;
9080 }
9081
9082 /* Returns the sum the used resources of all hardware watchpoints of
9083    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9084    the sum of the used resources of all hardware watchpoints of other
9085    types _not_ TYPE.  */
9086
9087 static int
9088 hw_watchpoint_used_count_others (struct breakpoint *except,
9089                                  enum bptype type, int *other_type_used)
9090 {
9091   int i = 0;
9092   struct breakpoint *b;
9093
9094   *other_type_used = 0;
9095   ALL_BREAKPOINTS (b)
9096     {
9097       if (b == except)
9098         continue;
9099       if (!breakpoint_enabled (b))
9100         continue;
9101
9102       if (b->type == type)
9103         i += hw_watchpoint_use_count (b);
9104       else if (is_hardware_watchpoint (b))
9105         *other_type_used = 1;
9106     }
9107
9108   return i;
9109 }
9110
9111 void
9112 disable_watchpoints_before_interactive_call_start (void)
9113 {
9114   struct breakpoint *b;
9115
9116   ALL_BREAKPOINTS (b)
9117   {
9118     if (is_watchpoint (b) && breakpoint_enabled (b))
9119       {
9120         b->enable_state = bp_call_disabled;
9121         update_global_location_list (UGLL_DONT_INSERT);
9122       }
9123   }
9124 }
9125
9126 void
9127 enable_watchpoints_after_interactive_call_stop (void)
9128 {
9129   struct breakpoint *b;
9130
9131   ALL_BREAKPOINTS (b)
9132   {
9133     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9134       {
9135         b->enable_state = bp_enabled;
9136         update_global_location_list (UGLL_MAY_INSERT);
9137       }
9138   }
9139 }
9140
9141 void
9142 disable_breakpoints_before_startup (void)
9143 {
9144   current_program_space->executing_startup = 1;
9145   update_global_location_list (UGLL_DONT_INSERT);
9146 }
9147
9148 void
9149 enable_breakpoints_after_startup (void)
9150 {
9151   current_program_space->executing_startup = 0;
9152   breakpoint_re_set ();
9153 }
9154
9155
9156 /* Set a breakpoint that will evaporate an end of command
9157    at address specified by SAL.
9158    Restrict it to frame FRAME if FRAME is nonzero.  */
9159
9160 struct breakpoint *
9161 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9162                           struct frame_id frame_id, enum bptype type)
9163 {
9164   struct breakpoint *b;
9165
9166   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9167      tail-called one.  */
9168   gdb_assert (!frame_id_artificial_p (frame_id));
9169
9170   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9171   b->enable_state = bp_enabled;
9172   b->disposition = disp_donttouch;
9173   b->frame_id = frame_id;
9174
9175   /* If we're debugging a multi-threaded program, then we want
9176      momentary breakpoints to be active in only a single thread of
9177      control.  */
9178   if (in_thread_list (inferior_ptid))
9179     b->thread = pid_to_thread_id (inferior_ptid);
9180
9181   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9182
9183   return b;
9184 }
9185
9186 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9187    The new breakpoint will have type TYPE, use OPS as its
9188    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9189
9190 static struct breakpoint *
9191 momentary_breakpoint_from_master (struct breakpoint *orig,
9192                                   enum bptype type,
9193                                   const struct breakpoint_ops *ops,
9194                                   int loc_enabled)
9195 {
9196   struct breakpoint *copy;
9197
9198   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9199   copy->loc = allocate_bp_location (copy);
9200   set_breakpoint_location_function (copy->loc, 1);
9201
9202   copy->loc->gdbarch = orig->loc->gdbarch;
9203   copy->loc->requested_address = orig->loc->requested_address;
9204   copy->loc->address = orig->loc->address;
9205   copy->loc->section = orig->loc->section;
9206   copy->loc->pspace = orig->loc->pspace;
9207   copy->loc->probe = orig->loc->probe;
9208   copy->loc->line_number = orig->loc->line_number;
9209   copy->loc->symtab = orig->loc->symtab;
9210   copy->loc->enabled = loc_enabled;
9211   copy->frame_id = orig->frame_id;
9212   copy->thread = orig->thread;
9213   copy->pspace = orig->pspace;
9214
9215   copy->enable_state = bp_enabled;
9216   copy->disposition = disp_donttouch;
9217   copy->number = internal_breakpoint_number--;
9218
9219   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9220   return copy;
9221 }
9222
9223 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9224    ORIG is NULL.  */
9225
9226 struct breakpoint *
9227 clone_momentary_breakpoint (struct breakpoint *orig)
9228 {
9229   /* If there's nothing to clone, then return nothing.  */
9230   if (orig == NULL)
9231     return NULL;
9232
9233   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9234 }
9235
9236 struct breakpoint *
9237 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9238                                 enum bptype type)
9239 {
9240   struct symtab_and_line sal;
9241
9242   sal = find_pc_line (pc, 0);
9243   sal.pc = pc;
9244   sal.section = find_pc_overlay (pc);
9245   sal.explicit_pc = 1;
9246
9247   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9248 }
9249 \f
9250
9251 /* Tell the user we have just set a breakpoint B.  */
9252
9253 static void
9254 mention (struct breakpoint *b)
9255 {
9256   b->ops->print_mention (b);
9257   if (ui_out_is_mi_like_p (current_uiout))
9258     return;
9259   printf_filtered ("\n");
9260 }
9261 \f
9262
9263 static struct bp_location *
9264 add_location_to_breakpoint (struct breakpoint *b,
9265                             const struct symtab_and_line *sal)
9266 {
9267   struct bp_location *loc, **tmp;
9268   CORE_ADDR adjusted_address;
9269   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9270
9271   if (loc_gdbarch == NULL)
9272     loc_gdbarch = b->gdbarch;
9273
9274   /* Adjust the breakpoint's address prior to allocating a location.
9275      Once we call allocate_bp_location(), that mostly uninitialized
9276      location will be placed on the location chain.  Adjustment of the
9277      breakpoint may cause target_read_memory() to be called and we do
9278      not want its scan of the location chain to find a breakpoint and
9279      location that's only been partially initialized.  */
9280   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9281                                                 sal->pc, b->type);
9282
9283   /* Sort the locations by their ADDRESS.  */
9284   loc = allocate_bp_location (b);
9285   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9286        tmp = &((*tmp)->next))
9287     ;
9288   loc->next = *tmp;
9289   *tmp = loc;
9290
9291   loc->requested_address = sal->pc;
9292   loc->address = adjusted_address;
9293   loc->pspace = sal->pspace;
9294   loc->probe.probe = sal->probe;
9295   loc->probe.objfile = sal->objfile;
9296   gdb_assert (loc->pspace != NULL);
9297   loc->section = sal->section;
9298   loc->gdbarch = loc_gdbarch;
9299   loc->line_number = sal->line;
9300   loc->symtab = sal->symtab;
9301
9302   set_breakpoint_location_function (loc,
9303                                     sal->explicit_pc || sal->explicit_line);
9304   return loc;
9305 }
9306 \f
9307
9308 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9309    return 0 otherwise.  */
9310
9311 static int
9312 bp_loc_is_permanent (struct bp_location *loc)
9313 {
9314   int len;
9315   CORE_ADDR addr;
9316   const gdb_byte *bpoint;
9317   gdb_byte *target_mem;
9318   struct cleanup *cleanup;
9319   int retval = 0;
9320
9321   gdb_assert (loc != NULL);
9322
9323   addr = loc->address;
9324   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9325
9326   /* Software breakpoints unsupported?  */
9327   if (bpoint == NULL)
9328     return 0;
9329
9330   target_mem = alloca (len);
9331
9332   /* Enable the automatic memory restoration from breakpoints while
9333      we read the memory.  Otherwise we could say about our temporary
9334      breakpoints they are permanent.  */
9335   cleanup = save_current_space_and_thread ();
9336
9337   switch_to_program_space_and_thread (loc->pspace);
9338   make_show_memory_breakpoints_cleanup (0);
9339
9340   if (target_read_memory (loc->address, target_mem, len) == 0
9341       && memcmp (target_mem, bpoint, len) == 0)
9342     retval = 1;
9343
9344   do_cleanups (cleanup);
9345
9346   return retval;
9347 }
9348
9349 /* Build a command list for the dprintf corresponding to the current
9350    settings of the dprintf style options.  */
9351
9352 static void
9353 update_dprintf_command_list (struct breakpoint *b)
9354 {
9355   char *dprintf_args = b->extra_string;
9356   char *printf_line = NULL;
9357
9358   if (!dprintf_args)
9359     return;
9360
9361   dprintf_args = skip_spaces (dprintf_args);
9362
9363   /* Allow a comma, as it may have terminated a location, but don't
9364      insist on it.  */
9365   if (*dprintf_args == ',')
9366     ++dprintf_args;
9367   dprintf_args = skip_spaces (dprintf_args);
9368
9369   if (*dprintf_args != '"')
9370     error (_("Bad format string, missing '\"'."));
9371
9372   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9373     printf_line = xstrprintf ("printf %s", dprintf_args);
9374   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9375     {
9376       if (!dprintf_function)
9377         error (_("No function supplied for dprintf call"));
9378
9379       if (dprintf_channel && strlen (dprintf_channel) > 0)
9380         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9381                                   dprintf_function,
9382                                   dprintf_channel,
9383                                   dprintf_args);
9384       else
9385         printf_line = xstrprintf ("call (void) %s (%s)",
9386                                   dprintf_function,
9387                                   dprintf_args);
9388     }
9389   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9390     {
9391       if (target_can_run_breakpoint_commands ())
9392         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9393       else
9394         {
9395           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9396           printf_line = xstrprintf ("printf %s", dprintf_args);
9397         }
9398     }
9399   else
9400     internal_error (__FILE__, __LINE__,
9401                     _("Invalid dprintf style."));
9402
9403   gdb_assert (printf_line != NULL);
9404   /* Manufacture a printf sequence.  */
9405   {
9406     struct command_line *printf_cmd_line
9407       = xmalloc (sizeof (struct command_line));
9408
9409     printf_cmd_line = xmalloc (sizeof (struct command_line));
9410     printf_cmd_line->control_type = simple_control;
9411     printf_cmd_line->body_count = 0;
9412     printf_cmd_line->body_list = NULL;
9413     printf_cmd_line->next = NULL;
9414     printf_cmd_line->line = printf_line;
9415
9416     breakpoint_set_commands (b, printf_cmd_line);
9417   }
9418 }
9419
9420 /* Update all dprintf commands, making their command lists reflect
9421    current style settings.  */
9422
9423 static void
9424 update_dprintf_commands (char *args, int from_tty,
9425                          struct cmd_list_element *c)
9426 {
9427   struct breakpoint *b;
9428
9429   ALL_BREAKPOINTS (b)
9430     {
9431       if (b->type == bp_dprintf)
9432         update_dprintf_command_list (b);
9433     }
9434 }
9435
9436 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9437    as textual description of the location, and COND_STRING
9438    as condition expression.  */
9439
9440 static void
9441 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9442                      struct symtabs_and_lines sals, char *addr_string,
9443                      char *filter, char *cond_string,
9444                      char *extra_string,
9445                      enum bptype type, enum bpdisp disposition,
9446                      int thread, int task, int ignore_count,
9447                      const struct breakpoint_ops *ops, int from_tty,
9448                      int enabled, int internal, unsigned flags,
9449                      int display_canonical)
9450 {
9451   int i;
9452
9453   if (type == bp_hardware_breakpoint)
9454     {
9455       int target_resources_ok;
9456
9457       i = hw_breakpoint_used_count ();
9458       target_resources_ok =
9459         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9460                                             i + 1, 0);
9461       if (target_resources_ok == 0)
9462         error (_("No hardware breakpoint support in the target."));
9463       else if (target_resources_ok < 0)
9464         error (_("Hardware breakpoints used exceeds limit."));
9465     }
9466
9467   gdb_assert (sals.nelts > 0);
9468
9469   for (i = 0; i < sals.nelts; ++i)
9470     {
9471       struct symtab_and_line sal = sals.sals[i];
9472       struct bp_location *loc;
9473
9474       if (from_tty)
9475         {
9476           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9477           if (!loc_gdbarch)
9478             loc_gdbarch = gdbarch;
9479
9480           describe_other_breakpoints (loc_gdbarch,
9481                                       sal.pspace, sal.pc, sal.section, thread);
9482         }
9483
9484       if (i == 0)
9485         {
9486           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9487           b->thread = thread;
9488           b->task = task;
9489
9490           b->cond_string = cond_string;
9491           b->extra_string = extra_string;
9492           b->ignore_count = ignore_count;
9493           b->enable_state = enabled ? bp_enabled : bp_disabled;
9494           b->disposition = disposition;
9495
9496           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9497             b->loc->inserted = 1;
9498
9499           if (type == bp_static_tracepoint)
9500             {
9501               struct tracepoint *t = (struct tracepoint *) b;
9502               struct static_tracepoint_marker marker;
9503
9504               if (strace_marker_p (b))
9505                 {
9506                   /* We already know the marker exists, otherwise, we
9507                      wouldn't see a sal for it.  */
9508                   char *p = &addr_string[3];
9509                   char *endp;
9510                   char *marker_str;
9511
9512                   p = skip_spaces (p);
9513
9514                   endp = skip_to_space (p);
9515
9516                   marker_str = savestring (p, endp - p);
9517                   t->static_trace_marker_id = marker_str;
9518
9519                   printf_filtered (_("Probed static tracepoint "
9520                                      "marker \"%s\"\n"),
9521                                    t->static_trace_marker_id);
9522                 }
9523               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9524                 {
9525                   t->static_trace_marker_id = xstrdup (marker.str_id);
9526                   release_static_tracepoint_marker (&marker);
9527
9528                   printf_filtered (_("Probed static tracepoint "
9529                                      "marker \"%s\"\n"),
9530                                    t->static_trace_marker_id);
9531                 }
9532               else
9533                 warning (_("Couldn't determine the static "
9534                            "tracepoint marker to probe"));
9535             }
9536
9537           loc = b->loc;
9538         }
9539       else
9540         {
9541           loc = add_location_to_breakpoint (b, &sal);
9542           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9543             loc->inserted = 1;
9544         }
9545
9546       if (bp_loc_is_permanent (loc))
9547         make_breakpoint_permanent (b);
9548
9549       if (b->cond_string)
9550         {
9551           const char *arg = b->cond_string;
9552
9553           loc->cond = parse_exp_1 (&arg, loc->address,
9554                                    block_for_pc (loc->address), 0);
9555           if (*arg)
9556               error (_("Garbage '%s' follows condition"), arg);
9557         }
9558
9559       /* Dynamic printf requires and uses additional arguments on the
9560          command line, otherwise it's an error.  */
9561       if (type == bp_dprintf)
9562         {
9563           if (b->extra_string)
9564             update_dprintf_command_list (b);
9565           else
9566             error (_("Format string required"));
9567         }
9568       else if (b->extra_string)
9569         error (_("Garbage '%s' at end of command"), b->extra_string);
9570     }
9571
9572   b->display_canonical = display_canonical;
9573   if (addr_string)
9574     b->addr_string = addr_string;
9575   else
9576     /* addr_string has to be used or breakpoint_re_set will delete
9577        me.  */
9578     b->addr_string
9579       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9580   b->filter = filter;
9581 }
9582
9583 static void
9584 create_breakpoint_sal (struct gdbarch *gdbarch,
9585                        struct symtabs_and_lines sals, char *addr_string,
9586                        char *filter, char *cond_string,
9587                        char *extra_string,
9588                        enum bptype type, enum bpdisp disposition,
9589                        int thread, int task, int ignore_count,
9590                        const struct breakpoint_ops *ops, int from_tty,
9591                        int enabled, int internal, unsigned flags,
9592                        int display_canonical)
9593 {
9594   struct breakpoint *b;
9595   struct cleanup *old_chain;
9596
9597   if (is_tracepoint_type (type))
9598     {
9599       struct tracepoint *t;
9600
9601       t = XCNEW (struct tracepoint);
9602       b = &t->base;
9603     }
9604   else
9605     b = XNEW (struct breakpoint);
9606
9607   old_chain = make_cleanup (xfree, b);
9608
9609   init_breakpoint_sal (b, gdbarch,
9610                        sals, addr_string,
9611                        filter, cond_string, extra_string,
9612                        type, disposition,
9613                        thread, task, ignore_count,
9614                        ops, from_tty,
9615                        enabled, internal, flags,
9616                        display_canonical);
9617   discard_cleanups (old_chain);
9618
9619   install_breakpoint (internal, b, 0);
9620 }
9621
9622 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9623    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9624    value.  COND_STRING, if not NULL, specified the condition to be
9625    used for all breakpoints.  Essentially the only case where
9626    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9627    function.  In that case, it's still not possible to specify
9628    separate conditions for different overloaded functions, so
9629    we take just a single condition string.
9630    
9631    NOTE: If the function succeeds, the caller is expected to cleanup
9632    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9633    array contents).  If the function fails (error() is called), the
9634    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9635    COND and SALS arrays and each of those arrays contents.  */
9636
9637 static void
9638 create_breakpoints_sal (struct gdbarch *gdbarch,
9639                         struct linespec_result *canonical,
9640                         char *cond_string, char *extra_string,
9641                         enum bptype type, enum bpdisp disposition,
9642                         int thread, int task, int ignore_count,
9643                         const struct breakpoint_ops *ops, int from_tty,
9644                         int enabled, int internal, unsigned flags)
9645 {
9646   int i;
9647   struct linespec_sals *lsal;
9648
9649   if (canonical->pre_expanded)
9650     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9651
9652   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9653     {
9654       /* Note that 'addr_string' can be NULL in the case of a plain
9655          'break', without arguments.  */
9656       char *addr_string = (canonical->addr_string
9657                            ? xstrdup (canonical->addr_string)
9658                            : NULL);
9659       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9660       struct cleanup *inner = make_cleanup (xfree, addr_string);
9661
9662       make_cleanup (xfree, filter_string);
9663       create_breakpoint_sal (gdbarch, lsal->sals,
9664                              addr_string,
9665                              filter_string,
9666                              cond_string, extra_string,
9667                              type, disposition,
9668                              thread, task, ignore_count, ops,
9669                              from_tty, enabled, internal, flags,
9670                              canonical->special_display);
9671       discard_cleanups (inner);
9672     }
9673 }
9674
9675 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9676    followed by conditionals.  On return, SALS contains an array of SAL
9677    addresses found.  ADDR_STRING contains a vector of (canonical)
9678    address strings.  ADDRESS points to the end of the SAL.
9679
9680    The array and the line spec strings are allocated on the heap, it is
9681    the caller's responsibility to free them.  */
9682
9683 static void
9684 parse_breakpoint_sals (char **address,
9685                        struct linespec_result *canonical)
9686 {
9687   /* If no arg given, or if first arg is 'if ', use the default
9688      breakpoint.  */
9689   if ((*address) == NULL
9690       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9691     {
9692       /* The last displayed codepoint, if it's valid, is our default breakpoint
9693          address.  */
9694       if (last_displayed_sal_is_valid ())
9695         {
9696           struct linespec_sals lsal;
9697           struct symtab_and_line sal;
9698           CORE_ADDR pc;
9699
9700           init_sal (&sal);              /* Initialize to zeroes.  */
9701           lsal.sals.sals = (struct symtab_and_line *)
9702             xmalloc (sizeof (struct symtab_and_line));
9703
9704           /* Set sal's pspace, pc, symtab, and line to the values
9705              corresponding to the last call to print_frame_info.
9706              Be sure to reinitialize LINE with NOTCURRENT == 0
9707              as the breakpoint line number is inappropriate otherwise.
9708              find_pc_line would adjust PC, re-set it back.  */
9709           get_last_displayed_sal (&sal);
9710           pc = sal.pc;
9711           sal = find_pc_line (pc, 0);
9712
9713           /* "break" without arguments is equivalent to "break *PC"
9714              where PC is the last displayed codepoint's address.  So
9715              make sure to set sal.explicit_pc to prevent GDB from
9716              trying to expand the list of sals to include all other
9717              instances with the same symtab and line.  */
9718           sal.pc = pc;
9719           sal.explicit_pc = 1;
9720
9721           lsal.sals.sals[0] = sal;
9722           lsal.sals.nelts = 1;
9723           lsal.canonical = NULL;
9724
9725           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9726         }
9727       else
9728         error (_("No default breakpoint address now."));
9729     }
9730   else
9731     {
9732       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9733
9734       /* Force almost all breakpoints to be in terms of the
9735          current_source_symtab (which is decode_line_1's default).
9736          This should produce the results we want almost all of the
9737          time while leaving default_breakpoint_* alone.
9738
9739          ObjC: However, don't match an Objective-C method name which
9740          may have a '+' or '-' succeeded by a '['.  */
9741       if (last_displayed_sal_is_valid ()
9742           && (!cursal.symtab
9743               || ((strchr ("+-", (*address)[0]) != NULL)
9744                   && ((*address)[1] != '['))))
9745         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9746                           get_last_displayed_symtab (),
9747                           get_last_displayed_line (),
9748                           canonical, NULL, NULL);
9749       else
9750         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9751                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9752     }
9753 }
9754
9755
9756 /* Convert each SAL into a real PC.  Verify that the PC can be
9757    inserted as a breakpoint.  If it can't throw an error.  */
9758
9759 static void
9760 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9761 {    
9762   int i;
9763
9764   for (i = 0; i < sals->nelts; i++)
9765     resolve_sal_pc (&sals->sals[i]);
9766 }
9767
9768 /* Fast tracepoints may have restrictions on valid locations.  For
9769    instance, a fast tracepoint using a jump instead of a trap will
9770    likely have to overwrite more bytes than a trap would, and so can
9771    only be placed where the instruction is longer than the jump, or a
9772    multi-instruction sequence does not have a jump into the middle of
9773    it, etc.  */
9774
9775 static void
9776 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9777                             struct symtabs_and_lines *sals)
9778 {
9779   int i, rslt;
9780   struct symtab_and_line *sal;
9781   char *msg;
9782   struct cleanup *old_chain;
9783
9784   for (i = 0; i < sals->nelts; i++)
9785     {
9786       struct gdbarch *sarch;
9787
9788       sal = &sals->sals[i];
9789
9790       sarch = get_sal_arch (*sal);
9791       /* We fall back to GDBARCH if there is no architecture
9792          associated with SAL.  */
9793       if (sarch == NULL)
9794         sarch = gdbarch;
9795       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9796                                                NULL, &msg);
9797       old_chain = make_cleanup (xfree, msg);
9798
9799       if (!rslt)
9800         error (_("May not have a fast tracepoint at 0x%s%s"),
9801                paddress (sarch, sal->pc), (msg ? msg : ""));
9802
9803       do_cleanups (old_chain);
9804     }
9805 }
9806
9807 /* Issue an invalid thread ID error.  */
9808
9809 static void ATTRIBUTE_NORETURN
9810 invalid_thread_id_error (int id)
9811 {
9812   error (_("Unknown thread %d."), id);
9813 }
9814
9815 /* Given TOK, a string specification of condition and thread, as
9816    accepted by the 'break' command, extract the condition
9817    string and thread number and set *COND_STRING and *THREAD.
9818    PC identifies the context at which the condition should be parsed.
9819    If no condition is found, *COND_STRING is set to NULL.
9820    If no thread is found, *THREAD is set to -1.  */
9821
9822 static void
9823 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9824                            char **cond_string, int *thread, int *task,
9825                            char **rest)
9826 {
9827   *cond_string = NULL;
9828   *thread = -1;
9829   *task = 0;
9830   *rest = NULL;
9831
9832   while (tok && *tok)
9833     {
9834       const char *end_tok;
9835       int toklen;
9836       const char *cond_start = NULL;
9837       const char *cond_end = NULL;
9838
9839       tok = skip_spaces_const (tok);
9840
9841       if ((*tok == '"' || *tok == ',') && rest)
9842         {
9843           *rest = savestring (tok, strlen (tok));
9844           return;
9845         }
9846
9847       end_tok = skip_to_space_const (tok);
9848
9849       toklen = end_tok - tok;
9850
9851       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9852         {
9853           struct expression *expr;
9854
9855           tok = cond_start = end_tok + 1;
9856           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9857           xfree (expr);
9858           cond_end = tok;
9859           *cond_string = savestring (cond_start, cond_end - cond_start);
9860         }
9861       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9862         {
9863           char *tmptok;
9864
9865           tok = end_tok + 1;
9866           *thread = strtol (tok, &tmptok, 0);
9867           if (tok == tmptok)
9868             error (_("Junk after thread keyword."));
9869           if (!valid_thread_id (*thread))
9870             invalid_thread_id_error (*thread);
9871           tok = tmptok;
9872         }
9873       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9874         {
9875           char *tmptok;
9876
9877           tok = end_tok + 1;
9878           *task = strtol (tok, &tmptok, 0);
9879           if (tok == tmptok)
9880             error (_("Junk after task keyword."));
9881           if (!valid_task_id (*task))
9882             error (_("Unknown task %d."), *task);
9883           tok = tmptok;
9884         }
9885       else if (rest)
9886         {
9887           *rest = savestring (tok, strlen (tok));
9888           return;
9889         }
9890       else
9891         error (_("Junk at end of arguments."));
9892     }
9893 }
9894
9895 /* Decode a static tracepoint marker spec.  */
9896
9897 static struct symtabs_and_lines
9898 decode_static_tracepoint_spec (char **arg_p)
9899 {
9900   VEC(static_tracepoint_marker_p) *markers = NULL;
9901   struct symtabs_and_lines sals;
9902   struct cleanup *old_chain;
9903   char *p = &(*arg_p)[3];
9904   char *endp;
9905   char *marker_str;
9906   int i;
9907
9908   p = skip_spaces (p);
9909
9910   endp = skip_to_space (p);
9911
9912   marker_str = savestring (p, endp - p);
9913   old_chain = make_cleanup (xfree, marker_str);
9914
9915   markers = target_static_tracepoint_markers_by_strid (marker_str);
9916   if (VEC_empty(static_tracepoint_marker_p, markers))
9917     error (_("No known static tracepoint marker named %s"), marker_str);
9918
9919   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9920   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9921
9922   for (i = 0; i < sals.nelts; i++)
9923     {
9924       struct static_tracepoint_marker *marker;
9925
9926       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9927
9928       init_sal (&sals.sals[i]);
9929
9930       sals.sals[i] = find_pc_line (marker->address, 0);
9931       sals.sals[i].pc = marker->address;
9932
9933       release_static_tracepoint_marker (marker);
9934     }
9935
9936   do_cleanups (old_chain);
9937
9938   *arg_p = endp;
9939   return sals;
9940 }
9941
9942 /* Set a breakpoint.  This function is shared between CLI and MI
9943    functions for setting a breakpoint.  This function has two major
9944    modes of operations, selected by the PARSE_ARG parameter.  If
9945    non-zero, the function will parse ARG, extracting location,
9946    condition, thread and extra string.  Otherwise, ARG is just the
9947    breakpoint's location, with condition, thread, and extra string
9948    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9949    If INTERNAL is non-zero, the breakpoint number will be allocated
9950    from the internal breakpoint count.  Returns true if any breakpoint
9951    was created; false otherwise.  */
9952
9953 int
9954 create_breakpoint (struct gdbarch *gdbarch,
9955                    char *arg, char *cond_string,
9956                    int thread, char *extra_string,
9957                    int parse_arg,
9958                    int tempflag, enum bptype type_wanted,
9959                    int ignore_count,
9960                    enum auto_boolean pending_break_support,
9961                    const struct breakpoint_ops *ops,
9962                    int from_tty, int enabled, int internal,
9963                    unsigned flags)
9964 {
9965   volatile struct gdb_exception e;
9966   char *copy_arg = NULL;
9967   char *addr_start = arg;
9968   struct linespec_result canonical;
9969   struct cleanup *old_chain;
9970   struct cleanup *bkpt_chain = NULL;
9971   int pending = 0;
9972   int task = 0;
9973   int prev_bkpt_count = breakpoint_count;
9974
9975   gdb_assert (ops != NULL);
9976
9977   init_linespec_result (&canonical);
9978
9979   TRY_CATCH (e, RETURN_MASK_ALL)
9980     {
9981       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9982                                      addr_start, &copy_arg);
9983     }
9984
9985   /* If caller is interested in rc value from parse, set value.  */
9986   switch (e.reason)
9987     {
9988     case GDB_NO_ERROR:
9989       if (VEC_empty (linespec_sals, canonical.sals))
9990         return 0;
9991       break;
9992     case RETURN_ERROR:
9993       switch (e.error)
9994         {
9995         case NOT_FOUND_ERROR:
9996
9997           /* If pending breakpoint support is turned off, throw
9998              error.  */
9999
10000           if (pending_break_support == AUTO_BOOLEAN_FALSE)
10001             throw_exception (e);
10002
10003           exception_print (gdb_stderr, e);
10004
10005           /* If pending breakpoint support is auto query and the user
10006              selects no, then simply return the error code.  */
10007           if (pending_break_support == AUTO_BOOLEAN_AUTO
10008               && !nquery (_("Make %s pending on future shared library load? "),
10009                           bptype_string (type_wanted)))
10010             return 0;
10011
10012           /* At this point, either the user was queried about setting
10013              a pending breakpoint and selected yes, or pending
10014              breakpoint behavior is on and thus a pending breakpoint
10015              is defaulted on behalf of the user.  */
10016           {
10017             struct linespec_sals lsal;
10018
10019             copy_arg = xstrdup (addr_start);
10020             lsal.canonical = xstrdup (copy_arg);
10021             lsal.sals.nelts = 1;
10022             lsal.sals.sals = XNEW (struct symtab_and_line);
10023             init_sal (&lsal.sals.sals[0]);
10024             pending = 1;
10025             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10026           }
10027           break;
10028         default:
10029           throw_exception (e);
10030         }
10031       break;
10032     default:
10033       throw_exception (e);
10034     }
10035
10036   /* Create a chain of things that always need to be cleaned up.  */
10037   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10038
10039   /* ----------------------------- SNIP -----------------------------
10040      Anything added to the cleanup chain beyond this point is assumed
10041      to be part of a breakpoint.  If the breakpoint create succeeds
10042      then the memory is not reclaimed.  */
10043   bkpt_chain = make_cleanup (null_cleanup, 0);
10044
10045   /* Resolve all line numbers to PC's and verify that the addresses
10046      are ok for the target.  */
10047   if (!pending)
10048     {
10049       int ix;
10050       struct linespec_sals *iter;
10051
10052       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10053         breakpoint_sals_to_pc (&iter->sals);
10054     }
10055
10056   /* Fast tracepoints may have additional restrictions on location.  */
10057   if (!pending && type_wanted == bp_fast_tracepoint)
10058     {
10059       int ix;
10060       struct linespec_sals *iter;
10061
10062       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10063         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10064     }
10065
10066   /* Verify that condition can be parsed, before setting any
10067      breakpoints.  Allocate a separate condition expression for each
10068      breakpoint.  */
10069   if (!pending)
10070     {
10071       if (parse_arg)
10072         {
10073           char *rest;
10074           struct linespec_sals *lsal;
10075
10076           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10077
10078           /* Here we only parse 'arg' to separate condition
10079              from thread number, so parsing in context of first
10080              sal is OK.  When setting the breakpoint we'll
10081              re-parse it in context of each sal.  */
10082
10083           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10084                                      &thread, &task, &rest);
10085           if (cond_string)
10086             make_cleanup (xfree, cond_string);
10087           if (rest)
10088             make_cleanup (xfree, rest);
10089           if (rest)
10090             extra_string = rest;
10091         }
10092       else
10093         {
10094           if (*arg != '\0')
10095             error (_("Garbage '%s' at end of location"), arg);
10096
10097           /* Create a private copy of condition string.  */
10098           if (cond_string)
10099             {
10100               cond_string = xstrdup (cond_string);
10101               make_cleanup (xfree, cond_string);
10102             }
10103           /* Create a private copy of any extra string.  */
10104           if (extra_string)
10105             {
10106               extra_string = xstrdup (extra_string);
10107               make_cleanup (xfree, extra_string);
10108             }
10109         }
10110
10111       ops->create_breakpoints_sal (gdbarch, &canonical,
10112                                    cond_string, extra_string, type_wanted,
10113                                    tempflag ? disp_del : disp_donttouch,
10114                                    thread, task, ignore_count, ops,
10115                                    from_tty, enabled, internal, flags);
10116     }
10117   else
10118     {
10119       struct breakpoint *b;
10120
10121       make_cleanup (xfree, copy_arg);
10122
10123       if (is_tracepoint_type (type_wanted))
10124         {
10125           struct tracepoint *t;
10126
10127           t = XCNEW (struct tracepoint);
10128           b = &t->base;
10129         }
10130       else
10131         b = XNEW (struct breakpoint);
10132
10133       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10134
10135       b->addr_string = copy_arg;
10136       if (parse_arg)
10137         b->cond_string = NULL;
10138       else
10139         {
10140           /* Create a private copy of condition string.  */
10141           if (cond_string)
10142             {
10143               cond_string = xstrdup (cond_string);
10144               make_cleanup (xfree, cond_string);
10145             }
10146           b->cond_string = cond_string;
10147         }
10148       b->extra_string = NULL;
10149       b->ignore_count = ignore_count;
10150       b->disposition = tempflag ? disp_del : disp_donttouch;
10151       b->condition_not_parsed = 1;
10152       b->enable_state = enabled ? bp_enabled : bp_disabled;
10153       if ((type_wanted != bp_breakpoint
10154            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10155         b->pspace = current_program_space;
10156
10157       install_breakpoint (internal, b, 0);
10158     }
10159   
10160   if (VEC_length (linespec_sals, canonical.sals) > 1)
10161     {
10162       warning (_("Multiple breakpoints were set.\nUse the "
10163                  "\"delete\" command to delete unwanted breakpoints."));
10164       prev_breakpoint_count = prev_bkpt_count;
10165     }
10166
10167   /* That's it.  Discard the cleanups for data inserted into the
10168      breakpoint.  */
10169   discard_cleanups (bkpt_chain);
10170   /* But cleanup everything else.  */
10171   do_cleanups (old_chain);
10172
10173   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10174   update_global_location_list (UGLL_MAY_INSERT);
10175
10176   return 1;
10177 }
10178
10179 /* Set a breakpoint.
10180    ARG is a string describing breakpoint address,
10181    condition, and thread.
10182    FLAG specifies if a breakpoint is hardware on,
10183    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10184    and BP_TEMPFLAG.  */
10185
10186 static void
10187 break_command_1 (char *arg, int flag, int from_tty)
10188 {
10189   int tempflag = flag & BP_TEMPFLAG;
10190   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10191                              ? bp_hardware_breakpoint
10192                              : bp_breakpoint);
10193   struct breakpoint_ops *ops;
10194   const char *arg_cp = arg;
10195
10196   /* Matching breakpoints on probes.  */
10197   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10198     ops = &bkpt_probe_breakpoint_ops;
10199   else
10200     ops = &bkpt_breakpoint_ops;
10201
10202   create_breakpoint (get_current_arch (),
10203                      arg,
10204                      NULL, 0, NULL, 1 /* parse arg */,
10205                      tempflag, type_wanted,
10206                      0 /* Ignore count */,
10207                      pending_break_support,
10208                      ops,
10209                      from_tty,
10210                      1 /* enabled */,
10211                      0 /* internal */,
10212                      0);
10213 }
10214
10215 /* Helper function for break_command_1 and disassemble_command.  */
10216
10217 void
10218 resolve_sal_pc (struct symtab_and_line *sal)
10219 {
10220   CORE_ADDR pc;
10221
10222   if (sal->pc == 0 && sal->symtab != NULL)
10223     {
10224       if (!find_line_pc (sal->symtab, sal->line, &pc))
10225         error (_("No line %d in file \"%s\"."),
10226                sal->line, symtab_to_filename_for_display (sal->symtab));
10227       sal->pc = pc;
10228
10229       /* If this SAL corresponds to a breakpoint inserted using a line
10230          number, then skip the function prologue if necessary.  */
10231       if (sal->explicit_line)
10232         skip_prologue_sal (sal);
10233     }
10234
10235   if (sal->section == 0 && sal->symtab != NULL)
10236     {
10237       const struct blockvector *bv;
10238       const struct block *b;
10239       struct symbol *sym;
10240
10241       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10242       if (bv != NULL)
10243         {
10244           sym = block_linkage_function (b);
10245           if (sym != NULL)
10246             {
10247               fixup_symbol_section (sym, sal->symtab->objfile);
10248               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10249             }
10250           else
10251             {
10252               /* It really is worthwhile to have the section, so we'll
10253                  just have to look harder. This case can be executed
10254                  if we have line numbers but no functions (as can
10255                  happen in assembly source).  */
10256
10257               struct bound_minimal_symbol msym;
10258               struct cleanup *old_chain = save_current_space_and_thread ();
10259
10260               switch_to_program_space_and_thread (sal->pspace);
10261
10262               msym = lookup_minimal_symbol_by_pc (sal->pc);
10263               if (msym.minsym)
10264                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10265
10266               do_cleanups (old_chain);
10267             }
10268         }
10269     }
10270 }
10271
10272 void
10273 break_command (char *arg, int from_tty)
10274 {
10275   break_command_1 (arg, 0, from_tty);
10276 }
10277
10278 void
10279 tbreak_command (char *arg, int from_tty)
10280 {
10281   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10282 }
10283
10284 static void
10285 hbreak_command (char *arg, int from_tty)
10286 {
10287   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10288 }
10289
10290 static void
10291 thbreak_command (char *arg, int from_tty)
10292 {
10293   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10294 }
10295
10296 static void
10297 stop_command (char *arg, int from_tty)
10298 {
10299   printf_filtered (_("Specify the type of breakpoint to set.\n\
10300 Usage: stop in <function | address>\n\
10301        stop at <line>\n"));
10302 }
10303
10304 static void
10305 stopin_command (char *arg, int from_tty)
10306 {
10307   int badInput = 0;
10308
10309   if (arg == (char *) NULL)
10310     badInput = 1;
10311   else if (*arg != '*')
10312     {
10313       char *argptr = arg;
10314       int hasColon = 0;
10315
10316       /* Look for a ':'.  If this is a line number specification, then
10317          say it is bad, otherwise, it should be an address or
10318          function/method name.  */
10319       while (*argptr && !hasColon)
10320         {
10321           hasColon = (*argptr == ':');
10322           argptr++;
10323         }
10324
10325       if (hasColon)
10326         badInput = (*argptr != ':');    /* Not a class::method */
10327       else
10328         badInput = isdigit (*arg);      /* a simple line number */
10329     }
10330
10331   if (badInput)
10332     printf_filtered (_("Usage: stop in <function | address>\n"));
10333   else
10334     break_command_1 (arg, 0, from_tty);
10335 }
10336
10337 static void
10338 stopat_command (char *arg, int from_tty)
10339 {
10340   int badInput = 0;
10341
10342   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10343     badInput = 1;
10344   else
10345     {
10346       char *argptr = arg;
10347       int hasColon = 0;
10348
10349       /* Look for a ':'.  If there is a '::' then get out, otherwise
10350          it is probably a line number.  */
10351       while (*argptr && !hasColon)
10352         {
10353           hasColon = (*argptr == ':');
10354           argptr++;
10355         }
10356
10357       if (hasColon)
10358         badInput = (*argptr == ':');    /* we have class::method */
10359       else
10360         badInput = !isdigit (*arg);     /* not a line number */
10361     }
10362
10363   if (badInput)
10364     printf_filtered (_("Usage: stop at <line>\n"));
10365   else
10366     break_command_1 (arg, 0, from_tty);
10367 }
10368
10369 /* The dynamic printf command is mostly like a regular breakpoint, but
10370    with a prewired command list consisting of a single output command,
10371    built from extra arguments supplied on the dprintf command
10372    line.  */
10373
10374 static void
10375 dprintf_command (char *arg, int from_tty)
10376 {
10377   create_breakpoint (get_current_arch (),
10378                      arg,
10379                      NULL, 0, NULL, 1 /* parse arg */,
10380                      0, bp_dprintf,
10381                      0 /* Ignore count */,
10382                      pending_break_support,
10383                      &dprintf_breakpoint_ops,
10384                      from_tty,
10385                      1 /* enabled */,
10386                      0 /* internal */,
10387                      0);
10388 }
10389
10390 static void
10391 agent_printf_command (char *arg, int from_tty)
10392 {
10393   error (_("May only run agent-printf on the target"));
10394 }
10395
10396 /* Implement the "breakpoint_hit" breakpoint_ops method for
10397    ranged breakpoints.  */
10398
10399 static int
10400 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10401                                   struct address_space *aspace,
10402                                   CORE_ADDR bp_addr,
10403                                   const struct target_waitstatus *ws)
10404 {
10405   if (ws->kind != TARGET_WAITKIND_STOPPED
10406       || ws->value.sig != GDB_SIGNAL_TRAP)
10407     return 0;
10408
10409   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10410                                          bl->length, aspace, bp_addr);
10411 }
10412
10413 /* Implement the "resources_needed" breakpoint_ops method for
10414    ranged breakpoints.  */
10415
10416 static int
10417 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10418 {
10419   return target_ranged_break_num_registers ();
10420 }
10421
10422 /* Implement the "print_it" breakpoint_ops method for
10423    ranged breakpoints.  */
10424
10425 static enum print_stop_action
10426 print_it_ranged_breakpoint (bpstat bs)
10427 {
10428   struct breakpoint *b = bs->breakpoint_at;
10429   struct bp_location *bl = b->loc;
10430   struct ui_out *uiout = current_uiout;
10431
10432   gdb_assert (b->type == bp_hardware_breakpoint);
10433
10434   /* Ranged breakpoints have only one location.  */
10435   gdb_assert (bl && bl->next == NULL);
10436
10437   annotate_breakpoint (b->number);
10438   if (b->disposition == disp_del)
10439     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10440   else
10441     ui_out_text (uiout, "\nRanged breakpoint ");
10442   if (ui_out_is_mi_like_p (uiout))
10443     {
10444       ui_out_field_string (uiout, "reason",
10445                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10446       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10447     }
10448   ui_out_field_int (uiout, "bkptno", b->number);
10449   ui_out_text (uiout, ", ");
10450
10451   return PRINT_SRC_AND_LOC;
10452 }
10453
10454 /* Implement the "print_one" breakpoint_ops method for
10455    ranged breakpoints.  */
10456
10457 static void
10458 print_one_ranged_breakpoint (struct breakpoint *b,
10459                              struct bp_location **last_loc)
10460 {
10461   struct bp_location *bl = b->loc;
10462   struct value_print_options opts;
10463   struct ui_out *uiout = current_uiout;
10464
10465   /* Ranged breakpoints have only one location.  */
10466   gdb_assert (bl && bl->next == NULL);
10467
10468   get_user_print_options (&opts);
10469
10470   if (opts.addressprint)
10471     /* We don't print the address range here, it will be printed later
10472        by print_one_detail_ranged_breakpoint.  */
10473     ui_out_field_skip (uiout, "addr");
10474   annotate_field (5);
10475   print_breakpoint_location (b, bl);
10476   *last_loc = bl;
10477 }
10478
10479 /* Implement the "print_one_detail" breakpoint_ops method for
10480    ranged breakpoints.  */
10481
10482 static void
10483 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10484                                     struct ui_out *uiout)
10485 {
10486   CORE_ADDR address_start, address_end;
10487   struct bp_location *bl = b->loc;
10488   struct ui_file *stb = mem_fileopen ();
10489   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10490
10491   gdb_assert (bl);
10492
10493   address_start = bl->address;
10494   address_end = address_start + bl->length - 1;
10495
10496   ui_out_text (uiout, "\taddress range: ");
10497   fprintf_unfiltered (stb, "[%s, %s]",
10498                       print_core_address (bl->gdbarch, address_start),
10499                       print_core_address (bl->gdbarch, address_end));
10500   ui_out_field_stream (uiout, "addr", stb);
10501   ui_out_text (uiout, "\n");
10502
10503   do_cleanups (cleanup);
10504 }
10505
10506 /* Implement the "print_mention" breakpoint_ops method for
10507    ranged breakpoints.  */
10508
10509 static void
10510 print_mention_ranged_breakpoint (struct breakpoint *b)
10511 {
10512   struct bp_location *bl = b->loc;
10513   struct ui_out *uiout = current_uiout;
10514
10515   gdb_assert (bl);
10516   gdb_assert (b->type == bp_hardware_breakpoint);
10517
10518   if (ui_out_is_mi_like_p (uiout))
10519     return;
10520
10521   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10522                    b->number, paddress (bl->gdbarch, bl->address),
10523                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10524 }
10525
10526 /* Implement the "print_recreate" breakpoint_ops method for
10527    ranged breakpoints.  */
10528
10529 static void
10530 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10531 {
10532   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10533                       b->addr_string_range_end);
10534   print_recreate_thread (b, fp);
10535 }
10536
10537 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10538
10539 static struct breakpoint_ops ranged_breakpoint_ops;
10540
10541 /* Find the address where the end of the breakpoint range should be
10542    placed, given the SAL of the end of the range.  This is so that if
10543    the user provides a line number, the end of the range is set to the
10544    last instruction of the given line.  */
10545
10546 static CORE_ADDR
10547 find_breakpoint_range_end (struct symtab_and_line sal)
10548 {
10549   CORE_ADDR end;
10550
10551   /* If the user provided a PC value, use it.  Otherwise,
10552      find the address of the end of the given location.  */
10553   if (sal.explicit_pc)
10554     end = sal.pc;
10555   else
10556     {
10557       int ret;
10558       CORE_ADDR start;
10559
10560       ret = find_line_pc_range (sal, &start, &end);
10561       if (!ret)
10562         error (_("Could not find location of the end of the range."));
10563
10564       /* find_line_pc_range returns the start of the next line.  */
10565       end--;
10566     }
10567
10568   return end;
10569 }
10570
10571 /* Implement the "break-range" CLI command.  */
10572
10573 static void
10574 break_range_command (char *arg, int from_tty)
10575 {
10576   char *arg_start, *addr_string_start, *addr_string_end;
10577   struct linespec_result canonical_start, canonical_end;
10578   int bp_count, can_use_bp, length;
10579   CORE_ADDR end;
10580   struct breakpoint *b;
10581   struct symtab_and_line sal_start, sal_end;
10582   struct cleanup *cleanup_bkpt;
10583   struct linespec_sals *lsal_start, *lsal_end;
10584
10585   /* We don't support software ranged breakpoints.  */
10586   if (target_ranged_break_num_registers () < 0)
10587     error (_("This target does not support hardware ranged breakpoints."));
10588
10589   bp_count = hw_breakpoint_used_count ();
10590   bp_count += target_ranged_break_num_registers ();
10591   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10592                                                    bp_count, 0);
10593   if (can_use_bp < 0)
10594     error (_("Hardware breakpoints used exceeds limit."));
10595
10596   arg = skip_spaces (arg);
10597   if (arg == NULL || arg[0] == '\0')
10598     error(_("No address range specified."));
10599
10600   init_linespec_result (&canonical_start);
10601
10602   arg_start = arg;
10603   parse_breakpoint_sals (&arg, &canonical_start);
10604
10605   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10606
10607   if (arg[0] != ',')
10608     error (_("Too few arguments."));
10609   else if (VEC_empty (linespec_sals, canonical_start.sals))
10610     error (_("Could not find location of the beginning of the range."));
10611
10612   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10613
10614   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10615       || lsal_start->sals.nelts != 1)
10616     error (_("Cannot create a ranged breakpoint with multiple locations."));
10617
10618   sal_start = lsal_start->sals.sals[0];
10619   addr_string_start = savestring (arg_start, arg - arg_start);
10620   make_cleanup (xfree, addr_string_start);
10621
10622   arg++;        /* Skip the comma.  */
10623   arg = skip_spaces (arg);
10624
10625   /* Parse the end location.  */
10626
10627   init_linespec_result (&canonical_end);
10628   arg_start = arg;
10629
10630   /* We call decode_line_full directly here instead of using
10631      parse_breakpoint_sals because we need to specify the start location's
10632      symtab and line as the default symtab and line for the end of the
10633      range.  This makes it possible to have ranges like "foo.c:27, +14",
10634      where +14 means 14 lines from the start location.  */
10635   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10636                     sal_start.symtab, sal_start.line,
10637                     &canonical_end, NULL, NULL);
10638
10639   make_cleanup_destroy_linespec_result (&canonical_end);
10640
10641   if (VEC_empty (linespec_sals, canonical_end.sals))
10642     error (_("Could not find location of the end of the range."));
10643
10644   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10645   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10646       || lsal_end->sals.nelts != 1)
10647     error (_("Cannot create a ranged breakpoint with multiple locations."));
10648
10649   sal_end = lsal_end->sals.sals[0];
10650   addr_string_end = savestring (arg_start, arg - arg_start);
10651   make_cleanup (xfree, addr_string_end);
10652
10653   end = find_breakpoint_range_end (sal_end);
10654   if (sal_start.pc > end)
10655     error (_("Invalid address range, end precedes start."));
10656
10657   length = end - sal_start.pc + 1;
10658   if (length < 0)
10659     /* Length overflowed.  */
10660     error (_("Address range too large."));
10661   else if (length == 1)
10662     {
10663       /* This range is simple enough to be handled by
10664          the `hbreak' command.  */
10665       hbreak_command (addr_string_start, 1);
10666
10667       do_cleanups (cleanup_bkpt);
10668
10669       return;
10670     }
10671
10672   /* Now set up the breakpoint.  */
10673   b = set_raw_breakpoint (get_current_arch (), sal_start,
10674                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10675   set_breakpoint_count (breakpoint_count + 1);
10676   b->number = breakpoint_count;
10677   b->disposition = disp_donttouch;
10678   b->addr_string = xstrdup (addr_string_start);
10679   b->addr_string_range_end = xstrdup (addr_string_end);
10680   b->loc->length = length;
10681
10682   do_cleanups (cleanup_bkpt);
10683
10684   mention (b);
10685   observer_notify_breakpoint_created (b);
10686   update_global_location_list (UGLL_MAY_INSERT);
10687 }
10688
10689 /*  Return non-zero if EXP is verified as constant.  Returned zero
10690     means EXP is variable.  Also the constant detection may fail for
10691     some constant expressions and in such case still falsely return
10692     zero.  */
10693
10694 static int
10695 watchpoint_exp_is_const (const struct expression *exp)
10696 {
10697   int i = exp->nelts;
10698
10699   while (i > 0)
10700     {
10701       int oplenp, argsp;
10702
10703       /* We are only interested in the descriptor of each element.  */
10704       operator_length (exp, i, &oplenp, &argsp);
10705       i -= oplenp;
10706
10707       switch (exp->elts[i].opcode)
10708         {
10709         case BINOP_ADD:
10710         case BINOP_SUB:
10711         case BINOP_MUL:
10712         case BINOP_DIV:
10713         case BINOP_REM:
10714         case BINOP_MOD:
10715         case BINOP_LSH:
10716         case BINOP_RSH:
10717         case BINOP_LOGICAL_AND:
10718         case BINOP_LOGICAL_OR:
10719         case BINOP_BITWISE_AND:
10720         case BINOP_BITWISE_IOR:
10721         case BINOP_BITWISE_XOR:
10722         case BINOP_EQUAL:
10723         case BINOP_NOTEQUAL:
10724         case BINOP_LESS:
10725         case BINOP_GTR:
10726         case BINOP_LEQ:
10727         case BINOP_GEQ:
10728         case BINOP_REPEAT:
10729         case BINOP_COMMA:
10730         case BINOP_EXP:
10731         case BINOP_MIN:
10732         case BINOP_MAX:
10733         case BINOP_INTDIV:
10734         case BINOP_CONCAT:
10735         case TERNOP_COND:
10736         case TERNOP_SLICE:
10737
10738         case OP_LONG:
10739         case OP_DOUBLE:
10740         case OP_DECFLOAT:
10741         case OP_LAST:
10742         case OP_COMPLEX:
10743         case OP_STRING:
10744         case OP_ARRAY:
10745         case OP_TYPE:
10746         case OP_TYPEOF:
10747         case OP_DECLTYPE:
10748         case OP_TYPEID:
10749         case OP_NAME:
10750         case OP_OBJC_NSSTRING:
10751
10752         case UNOP_NEG:
10753         case UNOP_LOGICAL_NOT:
10754         case UNOP_COMPLEMENT:
10755         case UNOP_ADDR:
10756         case UNOP_HIGH:
10757         case UNOP_CAST:
10758
10759         case UNOP_CAST_TYPE:
10760         case UNOP_REINTERPRET_CAST:
10761         case UNOP_DYNAMIC_CAST:
10762           /* Unary, binary and ternary operators: We have to check
10763              their operands.  If they are constant, then so is the
10764              result of that operation.  For instance, if A and B are
10765              determined to be constants, then so is "A + B".
10766
10767              UNOP_IND is one exception to the rule above, because the
10768              value of *ADDR is not necessarily a constant, even when
10769              ADDR is.  */
10770           break;
10771
10772         case OP_VAR_VALUE:
10773           /* Check whether the associated symbol is a constant.
10774
10775              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10776              possible that a buggy compiler could mark a variable as
10777              constant even when it is not, and TYPE_CONST would return
10778              true in this case, while SYMBOL_CLASS wouldn't.
10779
10780              We also have to check for function symbols because they
10781              are always constant.  */
10782           {
10783             struct symbol *s = exp->elts[i + 2].symbol;
10784
10785             if (SYMBOL_CLASS (s) != LOC_BLOCK
10786                 && SYMBOL_CLASS (s) != LOC_CONST
10787                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10788               return 0;
10789             break;
10790           }
10791
10792         /* The default action is to return 0 because we are using
10793            the optimistic approach here: If we don't know something,
10794            then it is not a constant.  */
10795         default:
10796           return 0;
10797         }
10798     }
10799
10800   return 1;
10801 }
10802
10803 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10804
10805 static void
10806 dtor_watchpoint (struct breakpoint *self)
10807 {
10808   struct watchpoint *w = (struct watchpoint *) self;
10809
10810   xfree (w->cond_exp);
10811   xfree (w->exp);
10812   xfree (w->exp_string);
10813   xfree (w->exp_string_reparse);
10814   value_free (w->val);
10815
10816   base_breakpoint_ops.dtor (self);
10817 }
10818
10819 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10820
10821 static void
10822 re_set_watchpoint (struct breakpoint *b)
10823 {
10824   struct watchpoint *w = (struct watchpoint *) b;
10825
10826   /* Watchpoint can be either on expression using entirely global
10827      variables, or it can be on local variables.
10828
10829      Watchpoints of the first kind are never auto-deleted, and even
10830      persist across program restarts.  Since they can use variables
10831      from shared libraries, we need to reparse expression as libraries
10832      are loaded and unloaded.
10833
10834      Watchpoints on local variables can also change meaning as result
10835      of solib event.  For example, if a watchpoint uses both a local
10836      and a global variables in expression, it's a local watchpoint,
10837      but unloading of a shared library will make the expression
10838      invalid.  This is not a very common use case, but we still
10839      re-evaluate expression, to avoid surprises to the user.
10840
10841      Note that for local watchpoints, we re-evaluate it only if
10842      watchpoints frame id is still valid.  If it's not, it means the
10843      watchpoint is out of scope and will be deleted soon.  In fact,
10844      I'm not sure we'll ever be called in this case.
10845
10846      If a local watchpoint's frame id is still valid, then
10847      w->exp_valid_block is likewise valid, and we can safely use it.
10848
10849      Don't do anything about disabled watchpoints, since they will be
10850      reevaluated again when enabled.  */
10851   update_watchpoint (w, 1 /* reparse */);
10852 }
10853
10854 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10855
10856 static int
10857 insert_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_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10863                                    w->cond_exp);
10864 }
10865
10866 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10867
10868 static int
10869 remove_watchpoint (struct bp_location *bl)
10870 {
10871   struct watchpoint *w = (struct watchpoint *) bl->owner;
10872   int length = w->exact ? 1 : bl->length;
10873
10874   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10875                                    w->cond_exp);
10876 }
10877
10878 static int
10879 breakpoint_hit_watchpoint (const struct bp_location *bl,
10880                            struct address_space *aspace, CORE_ADDR bp_addr,
10881                            const struct target_waitstatus *ws)
10882 {
10883   struct breakpoint *b = bl->owner;
10884   struct watchpoint *w = (struct watchpoint *) b;
10885
10886   /* Continuable hardware watchpoints are treated as non-existent if the
10887      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10888      some data address).  Otherwise gdb won't stop on a break instruction
10889      in the code (not from a breakpoint) when a hardware watchpoint has
10890      been defined.  Also skip watchpoints which we know did not trigger
10891      (did not match the data address).  */
10892   if (is_hardware_watchpoint (b)
10893       && w->watchpoint_triggered == watch_triggered_no)
10894     return 0;
10895
10896   return 1;
10897 }
10898
10899 static void
10900 check_status_watchpoint (bpstat bs)
10901 {
10902   gdb_assert (is_watchpoint (bs->breakpoint_at));
10903
10904   bpstat_check_watchpoint (bs);
10905 }
10906
10907 /* Implement the "resources_needed" breakpoint_ops method for
10908    hardware watchpoints.  */
10909
10910 static int
10911 resources_needed_watchpoint (const struct bp_location *bl)
10912 {
10913   struct watchpoint *w = (struct watchpoint *) bl->owner;
10914   int length = w->exact? 1 : bl->length;
10915
10916   return target_region_ok_for_hw_watchpoint (bl->address, length);
10917 }
10918
10919 /* Implement the "works_in_software_mode" breakpoint_ops method for
10920    hardware watchpoints.  */
10921
10922 static int
10923 works_in_software_mode_watchpoint (const struct breakpoint *b)
10924 {
10925   /* Read and access watchpoints only work with hardware support.  */
10926   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10927 }
10928
10929 static enum print_stop_action
10930 print_it_watchpoint (bpstat bs)
10931 {
10932   struct cleanup *old_chain;
10933   struct breakpoint *b;
10934   struct ui_file *stb;
10935   enum print_stop_action result;
10936   struct watchpoint *w;
10937   struct ui_out *uiout = current_uiout;
10938
10939   gdb_assert (bs->bp_location_at != NULL);
10940
10941   b = bs->breakpoint_at;
10942   w = (struct watchpoint *) b;
10943
10944   stb = mem_fileopen ();
10945   old_chain = make_cleanup_ui_file_delete (stb);
10946
10947   switch (b->type)
10948     {
10949     case bp_watchpoint:
10950     case bp_hardware_watchpoint:
10951       annotate_watchpoint (b->number);
10952       if (ui_out_is_mi_like_p (uiout))
10953         ui_out_field_string
10954           (uiout, "reason",
10955            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10956       mention (b);
10957       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10958       ui_out_text (uiout, "\nOld value = ");
10959       watchpoint_value_print (bs->old_val, stb);
10960       ui_out_field_stream (uiout, "old", stb);
10961       ui_out_text (uiout, "\nNew value = ");
10962       watchpoint_value_print (w->val, stb);
10963       ui_out_field_stream (uiout, "new", stb);
10964       ui_out_text (uiout, "\n");
10965       /* More than one watchpoint may have been triggered.  */
10966       result = PRINT_UNKNOWN;
10967       break;
10968
10969     case bp_read_watchpoint:
10970       if (ui_out_is_mi_like_p (uiout))
10971         ui_out_field_string
10972           (uiout, "reason",
10973            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10974       mention (b);
10975       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10976       ui_out_text (uiout, "\nValue = ");
10977       watchpoint_value_print (w->val, stb);
10978       ui_out_field_stream (uiout, "value", stb);
10979       ui_out_text (uiout, "\n");
10980       result = PRINT_UNKNOWN;
10981       break;
10982
10983     case bp_access_watchpoint:
10984       if (bs->old_val != NULL)
10985         {
10986           annotate_watchpoint (b->number);
10987           if (ui_out_is_mi_like_p (uiout))
10988             ui_out_field_string
10989               (uiout, "reason",
10990                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10991           mention (b);
10992           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10993           ui_out_text (uiout, "\nOld value = ");
10994           watchpoint_value_print (bs->old_val, stb);
10995           ui_out_field_stream (uiout, "old", stb);
10996           ui_out_text (uiout, "\nNew value = ");
10997         }
10998       else
10999         {
11000           mention (b);
11001           if (ui_out_is_mi_like_p (uiout))
11002             ui_out_field_string
11003               (uiout, "reason",
11004                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11005           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11006           ui_out_text (uiout, "\nValue = ");
11007         }
11008       watchpoint_value_print (w->val, stb);
11009       ui_out_field_stream (uiout, "new", stb);
11010       ui_out_text (uiout, "\n");
11011       result = PRINT_UNKNOWN;
11012       break;
11013     default:
11014       result = PRINT_UNKNOWN;
11015     }
11016
11017   do_cleanups (old_chain);
11018   return result;
11019 }
11020
11021 /* Implement the "print_mention" breakpoint_ops method for hardware
11022    watchpoints.  */
11023
11024 static void
11025 print_mention_watchpoint (struct breakpoint *b)
11026 {
11027   struct cleanup *ui_out_chain;
11028   struct watchpoint *w = (struct watchpoint *) b;
11029   struct ui_out *uiout = current_uiout;
11030
11031   switch (b->type)
11032     {
11033     case bp_watchpoint:
11034       ui_out_text (uiout, "Watchpoint ");
11035       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11036       break;
11037     case bp_hardware_watchpoint:
11038       ui_out_text (uiout, "Hardware watchpoint ");
11039       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11040       break;
11041     case bp_read_watchpoint:
11042       ui_out_text (uiout, "Hardware read watchpoint ");
11043       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11044       break;
11045     case bp_access_watchpoint:
11046       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11047       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11048       break;
11049     default:
11050       internal_error (__FILE__, __LINE__,
11051                       _("Invalid hardware watchpoint type."));
11052     }
11053
11054   ui_out_field_int (uiout, "number", b->number);
11055   ui_out_text (uiout, ": ");
11056   ui_out_field_string (uiout, "exp", w->exp_string);
11057   do_cleanups (ui_out_chain);
11058 }
11059
11060 /* Implement the "print_recreate" breakpoint_ops method for
11061    watchpoints.  */
11062
11063 static void
11064 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11065 {
11066   struct watchpoint *w = (struct watchpoint *) b;
11067
11068   switch (b->type)
11069     {
11070     case bp_watchpoint:
11071     case bp_hardware_watchpoint:
11072       fprintf_unfiltered (fp, "watch");
11073       break;
11074     case bp_read_watchpoint:
11075       fprintf_unfiltered (fp, "rwatch");
11076       break;
11077     case bp_access_watchpoint:
11078       fprintf_unfiltered (fp, "awatch");
11079       break;
11080     default:
11081       internal_error (__FILE__, __LINE__,
11082                       _("Invalid watchpoint type."));
11083     }
11084
11085   fprintf_unfiltered (fp, " %s", w->exp_string);
11086   print_recreate_thread (b, fp);
11087 }
11088
11089 /* Implement the "explains_signal" breakpoint_ops method for
11090    watchpoints.  */
11091
11092 static int
11093 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11094 {
11095   /* A software watchpoint cannot cause a signal other than
11096      GDB_SIGNAL_TRAP.  */
11097   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11098     return 0;
11099
11100   return 1;
11101 }
11102
11103 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11104
11105 static struct breakpoint_ops watchpoint_breakpoint_ops;
11106
11107 /* Implement the "insert" breakpoint_ops method for
11108    masked hardware watchpoints.  */
11109
11110 static int
11111 insert_masked_watchpoint (struct bp_location *bl)
11112 {
11113   struct watchpoint *w = (struct watchpoint *) bl->owner;
11114
11115   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11116                                         bl->watchpoint_type);
11117 }
11118
11119 /* Implement the "remove" breakpoint_ops method for
11120    masked hardware watchpoints.  */
11121
11122 static int
11123 remove_masked_watchpoint (struct bp_location *bl)
11124 {
11125   struct watchpoint *w = (struct watchpoint *) bl->owner;
11126
11127   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11128                                         bl->watchpoint_type);
11129 }
11130
11131 /* Implement the "resources_needed" breakpoint_ops method for
11132    masked hardware watchpoints.  */
11133
11134 static int
11135 resources_needed_masked_watchpoint (const struct bp_location *bl)
11136 {
11137   struct watchpoint *w = (struct watchpoint *) bl->owner;
11138
11139   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11140 }
11141
11142 /* Implement the "works_in_software_mode" breakpoint_ops method for
11143    masked hardware watchpoints.  */
11144
11145 static int
11146 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11147 {
11148   return 0;
11149 }
11150
11151 /* Implement the "print_it" breakpoint_ops method for
11152    masked hardware watchpoints.  */
11153
11154 static enum print_stop_action
11155 print_it_masked_watchpoint (bpstat bs)
11156 {
11157   struct breakpoint *b = bs->breakpoint_at;
11158   struct ui_out *uiout = current_uiout;
11159
11160   /* Masked watchpoints have only one location.  */
11161   gdb_assert (b->loc && b->loc->next == NULL);
11162
11163   switch (b->type)
11164     {
11165     case bp_hardware_watchpoint:
11166       annotate_watchpoint (b->number);
11167       if (ui_out_is_mi_like_p (uiout))
11168         ui_out_field_string
11169           (uiout, "reason",
11170            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11171       break;
11172
11173     case bp_read_watchpoint:
11174       if (ui_out_is_mi_like_p (uiout))
11175         ui_out_field_string
11176           (uiout, "reason",
11177            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11178       break;
11179
11180     case bp_access_watchpoint:
11181       if (ui_out_is_mi_like_p (uiout))
11182         ui_out_field_string
11183           (uiout, "reason",
11184            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11185       break;
11186     default:
11187       internal_error (__FILE__, __LINE__,
11188                       _("Invalid hardware watchpoint type."));
11189     }
11190
11191   mention (b);
11192   ui_out_text (uiout, _("\n\
11193 Check the underlying instruction at PC for the memory\n\
11194 address and value which triggered this watchpoint.\n"));
11195   ui_out_text (uiout, "\n");
11196
11197   /* More than one watchpoint may have been triggered.  */
11198   return PRINT_UNKNOWN;
11199 }
11200
11201 /* Implement the "print_one_detail" breakpoint_ops method for
11202    masked hardware watchpoints.  */
11203
11204 static void
11205 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11206                                     struct ui_out *uiout)
11207 {
11208   struct watchpoint *w = (struct watchpoint *) b;
11209
11210   /* Masked watchpoints have only one location.  */
11211   gdb_assert (b->loc && b->loc->next == NULL);
11212
11213   ui_out_text (uiout, "\tmask ");
11214   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11215   ui_out_text (uiout, "\n");
11216 }
11217
11218 /* Implement the "print_mention" breakpoint_ops method for
11219    masked hardware watchpoints.  */
11220
11221 static void
11222 print_mention_masked_watchpoint (struct breakpoint *b)
11223 {
11224   struct watchpoint *w = (struct watchpoint *) b;
11225   struct ui_out *uiout = current_uiout;
11226   struct cleanup *ui_out_chain;
11227
11228   switch (b->type)
11229     {
11230     case bp_hardware_watchpoint:
11231       ui_out_text (uiout, "Masked hardware watchpoint ");
11232       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11233       break;
11234     case bp_read_watchpoint:
11235       ui_out_text (uiout, "Masked hardware read watchpoint ");
11236       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11237       break;
11238     case bp_access_watchpoint:
11239       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11240       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11241       break;
11242     default:
11243       internal_error (__FILE__, __LINE__,
11244                       _("Invalid hardware watchpoint type."));
11245     }
11246
11247   ui_out_field_int (uiout, "number", b->number);
11248   ui_out_text (uiout, ": ");
11249   ui_out_field_string (uiout, "exp", w->exp_string);
11250   do_cleanups (ui_out_chain);
11251 }
11252
11253 /* Implement the "print_recreate" breakpoint_ops method for
11254    masked hardware watchpoints.  */
11255
11256 static void
11257 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11258 {
11259   struct watchpoint *w = (struct watchpoint *) b;
11260   char tmp[40];
11261
11262   switch (b->type)
11263     {
11264     case bp_hardware_watchpoint:
11265       fprintf_unfiltered (fp, "watch");
11266       break;
11267     case bp_read_watchpoint:
11268       fprintf_unfiltered (fp, "rwatch");
11269       break;
11270     case bp_access_watchpoint:
11271       fprintf_unfiltered (fp, "awatch");
11272       break;
11273     default:
11274       internal_error (__FILE__, __LINE__,
11275                       _("Invalid hardware watchpoint type."));
11276     }
11277
11278   sprintf_vma (tmp, w->hw_wp_mask);
11279   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11280   print_recreate_thread (b, fp);
11281 }
11282
11283 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11284
11285 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11286
11287 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11288
11289 static int
11290 is_masked_watchpoint (const struct breakpoint *b)
11291 {
11292   return b->ops == &masked_watchpoint_breakpoint_ops;
11293 }
11294
11295 /* accessflag:  hw_write:  watch write, 
11296                 hw_read:   watch read, 
11297                 hw_access: watch access (read or write) */
11298 static void
11299 watch_command_1 (const char *arg, int accessflag, int from_tty,
11300                  int just_location, int internal)
11301 {
11302   volatile struct gdb_exception e;
11303   struct breakpoint *b, *scope_breakpoint = NULL;
11304   struct expression *exp;
11305   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11306   struct value *val, *mark, *result;
11307   int saved_bitpos = 0, saved_bitsize = 0;
11308   struct frame_info *frame;
11309   const char *exp_start = NULL;
11310   const char *exp_end = NULL;
11311   const char *tok, *end_tok;
11312   int toklen = -1;
11313   const char *cond_start = NULL;
11314   const char *cond_end = NULL;
11315   enum bptype bp_type;
11316   int thread = -1;
11317   int pc = 0;
11318   /* Flag to indicate whether we are going to use masks for
11319      the hardware watchpoint.  */
11320   int use_mask = 0;
11321   CORE_ADDR mask = 0;
11322   struct watchpoint *w;
11323   char *expression;
11324   struct cleanup *back_to;
11325
11326   /* Make sure that we actually have parameters to parse.  */
11327   if (arg != NULL && arg[0] != '\0')
11328     {
11329       const char *value_start;
11330
11331       exp_end = arg + strlen (arg);
11332
11333       /* Look for "parameter value" pairs at the end
11334          of the arguments string.  */
11335       for (tok = exp_end - 1; tok > arg; tok--)
11336         {
11337           /* Skip whitespace at the end of the argument list.  */
11338           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11339             tok--;
11340
11341           /* Find the beginning of the last token.
11342              This is the value of the parameter.  */
11343           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11344             tok--;
11345           value_start = tok + 1;
11346
11347           /* Skip whitespace.  */
11348           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11349             tok--;
11350
11351           end_tok = tok;
11352
11353           /* Find the beginning of the second to last token.
11354              This is the parameter itself.  */
11355           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11356             tok--;
11357           tok++;
11358           toklen = end_tok - tok + 1;
11359
11360           if (toklen == 6 && !strncmp (tok, "thread", 6))
11361             {
11362               /* At this point we've found a "thread" token, which means
11363                  the user is trying to set a watchpoint that triggers
11364                  only in a specific thread.  */
11365               char *endp;
11366
11367               if (thread != -1)
11368                 error(_("You can specify only one thread."));
11369
11370               /* Extract the thread ID from the next token.  */
11371               thread = strtol (value_start, &endp, 0);
11372
11373               /* Check if the user provided a valid numeric value for the
11374                  thread ID.  */
11375               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11376                 error (_("Invalid thread ID specification %s."), value_start);
11377
11378               /* Check if the thread actually exists.  */
11379               if (!valid_thread_id (thread))
11380                 invalid_thread_id_error (thread);
11381             }
11382           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11383             {
11384               /* We've found a "mask" token, which means the user wants to
11385                  create a hardware watchpoint that is going to have the mask
11386                  facility.  */
11387               struct value *mask_value, *mark;
11388
11389               if (use_mask)
11390                 error(_("You can specify only one mask."));
11391
11392               use_mask = just_location = 1;
11393
11394               mark = value_mark ();
11395               mask_value = parse_to_comma_and_eval (&value_start);
11396               mask = value_as_address (mask_value);
11397               value_free_to_mark (mark);
11398             }
11399           else
11400             /* We didn't recognize what we found.  We should stop here.  */
11401             break;
11402
11403           /* Truncate the string and get rid of the "parameter value" pair before
11404              the arguments string is parsed by the parse_exp_1 function.  */
11405           exp_end = tok;
11406         }
11407     }
11408   else
11409     exp_end = arg;
11410
11411   /* Parse the rest of the arguments.  From here on out, everything
11412      is in terms of a newly allocated string instead of the original
11413      ARG.  */
11414   innermost_block = NULL;
11415   expression = savestring (arg, exp_end - arg);
11416   back_to = make_cleanup (xfree, expression);
11417   exp_start = arg = expression;
11418   exp = parse_exp_1 (&arg, 0, 0, 0);
11419   exp_end = arg;
11420   /* Remove trailing whitespace from the expression before saving it.
11421      This makes the eventual display of the expression string a bit
11422      prettier.  */
11423   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11424     --exp_end;
11425
11426   /* Checking if the expression is not constant.  */
11427   if (watchpoint_exp_is_const (exp))
11428     {
11429       int len;
11430
11431       len = exp_end - exp_start;
11432       while (len > 0 && isspace (exp_start[len - 1]))
11433         len--;
11434       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11435     }
11436
11437   exp_valid_block = innermost_block;
11438   mark = value_mark ();
11439   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11440
11441   if (val != NULL && just_location)
11442     {
11443       saved_bitpos = value_bitpos (val);
11444       saved_bitsize = value_bitsize (val);
11445     }
11446
11447   if (just_location)
11448     {
11449       int ret;
11450
11451       exp_valid_block = NULL;
11452       val = value_addr (result);
11453       release_value (val);
11454       value_free_to_mark (mark);
11455
11456       if (use_mask)
11457         {
11458           ret = target_masked_watch_num_registers (value_as_address (val),
11459                                                    mask);
11460           if (ret == -1)
11461             error (_("This target does not support masked watchpoints."));
11462           else if (ret == -2)
11463             error (_("Invalid mask or memory region."));
11464         }
11465     }
11466   else if (val != NULL)
11467     release_value (val);
11468
11469   tok = skip_spaces_const (arg);
11470   end_tok = skip_to_space_const (tok);
11471
11472   toklen = end_tok - tok;
11473   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11474     {
11475       struct expression *cond;
11476
11477       innermost_block = NULL;
11478       tok = cond_start = end_tok + 1;
11479       cond = parse_exp_1 (&tok, 0, 0, 0);
11480
11481       /* The watchpoint expression may not be local, but the condition
11482          may still be.  E.g.: `watch global if local > 0'.  */
11483       cond_exp_valid_block = innermost_block;
11484
11485       xfree (cond);
11486       cond_end = tok;
11487     }
11488   if (*tok)
11489     error (_("Junk at end of command."));
11490
11491   frame = block_innermost_frame (exp_valid_block);
11492
11493   /* If the expression is "local", then set up a "watchpoint scope"
11494      breakpoint at the point where we've left the scope of the watchpoint
11495      expression.  Create the scope breakpoint before the watchpoint, so
11496      that we will encounter it first in bpstat_stop_status.  */
11497   if (exp_valid_block && frame)
11498     {
11499       if (frame_id_p (frame_unwind_caller_id (frame)))
11500         {
11501           scope_breakpoint
11502             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11503                                           frame_unwind_caller_pc (frame),
11504                                           bp_watchpoint_scope,
11505                                           &momentary_breakpoint_ops);
11506
11507           scope_breakpoint->enable_state = bp_enabled;
11508
11509           /* Automatically delete the breakpoint when it hits.  */
11510           scope_breakpoint->disposition = disp_del;
11511
11512           /* Only break in the proper frame (help with recursion).  */
11513           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11514
11515           /* Set the address at which we will stop.  */
11516           scope_breakpoint->loc->gdbarch
11517             = frame_unwind_caller_arch (frame);
11518           scope_breakpoint->loc->requested_address
11519             = frame_unwind_caller_pc (frame);
11520           scope_breakpoint->loc->address
11521             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11522                                          scope_breakpoint->loc->requested_address,
11523                                          scope_breakpoint->type);
11524         }
11525     }
11526
11527   /* Now set up the breakpoint.  We create all watchpoints as hardware
11528      watchpoints here even if hardware watchpoints are turned off, a call
11529      to update_watchpoint later in this function will cause the type to
11530      drop back to bp_watchpoint (software watchpoint) if required.  */
11531
11532   if (accessflag == hw_read)
11533     bp_type = bp_read_watchpoint;
11534   else if (accessflag == hw_access)
11535     bp_type = bp_access_watchpoint;
11536   else
11537     bp_type = bp_hardware_watchpoint;
11538
11539   w = XCNEW (struct watchpoint);
11540   b = &w->base;
11541   if (use_mask)
11542     init_raw_breakpoint_without_location (b, NULL, bp_type,
11543                                           &masked_watchpoint_breakpoint_ops);
11544   else
11545     init_raw_breakpoint_without_location (b, NULL, bp_type,
11546                                           &watchpoint_breakpoint_ops);
11547   b->thread = thread;
11548   b->disposition = disp_donttouch;
11549   b->pspace = current_program_space;
11550   w->exp = exp;
11551   w->exp_valid_block = exp_valid_block;
11552   w->cond_exp_valid_block = cond_exp_valid_block;
11553   if (just_location)
11554     {
11555       struct type *t = value_type (val);
11556       CORE_ADDR addr = value_as_address (val);
11557       char *name;
11558
11559       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11560       name = type_to_string (t);
11561
11562       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11563                                           core_addr_to_string (addr));
11564       xfree (name);
11565
11566       w->exp_string = xstrprintf ("-location %.*s",
11567                                   (int) (exp_end - exp_start), exp_start);
11568
11569       /* The above expression is in C.  */
11570       b->language = language_c;
11571     }
11572   else
11573     w->exp_string = savestring (exp_start, exp_end - exp_start);
11574
11575   if (use_mask)
11576     {
11577       w->hw_wp_mask = mask;
11578     }
11579   else
11580     {
11581       w->val = val;
11582       w->val_bitpos = saved_bitpos;
11583       w->val_bitsize = saved_bitsize;
11584       w->val_valid = 1;
11585     }
11586
11587   if (cond_start)
11588     b->cond_string = savestring (cond_start, cond_end - cond_start);
11589   else
11590     b->cond_string = 0;
11591
11592   if (frame)
11593     {
11594       w->watchpoint_frame = get_frame_id (frame);
11595       w->watchpoint_thread = inferior_ptid;
11596     }
11597   else
11598     {
11599       w->watchpoint_frame = null_frame_id;
11600       w->watchpoint_thread = null_ptid;
11601     }
11602
11603   if (scope_breakpoint != NULL)
11604     {
11605       /* The scope breakpoint is related to the watchpoint.  We will
11606          need to act on them together.  */
11607       b->related_breakpoint = scope_breakpoint;
11608       scope_breakpoint->related_breakpoint = b;
11609     }
11610
11611   if (!just_location)
11612     value_free_to_mark (mark);
11613
11614   TRY_CATCH (e, RETURN_MASK_ALL)
11615     {
11616       /* Finally update the new watchpoint.  This creates the locations
11617          that should be inserted.  */
11618       update_watchpoint (w, 1);
11619     }
11620   if (e.reason < 0)
11621     {
11622       delete_breakpoint (b);
11623       throw_exception (e);
11624     }
11625
11626   install_breakpoint (internal, b, 1);
11627   do_cleanups (back_to);
11628 }
11629
11630 /* Return count of debug registers needed to watch the given expression.
11631    If the watchpoint cannot be handled in hardware return zero.  */
11632
11633 static int
11634 can_use_hardware_watchpoint (struct value *v)
11635 {
11636   int found_memory_cnt = 0;
11637   struct value *head = v;
11638
11639   /* Did the user specifically forbid us to use hardware watchpoints? */
11640   if (!can_use_hw_watchpoints)
11641     return 0;
11642
11643   /* Make sure that the value of the expression depends only upon
11644      memory contents, and values computed from them within GDB.  If we
11645      find any register references or function calls, we can't use a
11646      hardware watchpoint.
11647
11648      The idea here is that evaluating an expression generates a series
11649      of values, one holding the value of every subexpression.  (The
11650      expression a*b+c has five subexpressions: a, b, a*b, c, and
11651      a*b+c.)  GDB's values hold almost enough information to establish
11652      the criteria given above --- they identify memory lvalues,
11653      register lvalues, computed values, etcetera.  So we can evaluate
11654      the expression, and then scan the chain of values that leaves
11655      behind to decide whether we can detect any possible change to the
11656      expression's final value using only hardware watchpoints.
11657
11658      However, I don't think that the values returned by inferior
11659      function calls are special in any way.  So this function may not
11660      notice that an expression involving an inferior function call
11661      can't be watched with hardware watchpoints.  FIXME.  */
11662   for (; v; v = value_next (v))
11663     {
11664       if (VALUE_LVAL (v) == lval_memory)
11665         {
11666           if (v != head && value_lazy (v))
11667             /* A lazy memory lvalue in the chain is one that GDB never
11668                needed to fetch; we either just used its address (e.g.,
11669                `a' in `a.b') or we never needed it at all (e.g., `a'
11670                in `a,b').  This doesn't apply to HEAD; if that is
11671                lazy then it was not readable, but watch it anyway.  */
11672             ;
11673           else
11674             {
11675               /* Ahh, memory we actually used!  Check if we can cover
11676                  it with hardware watchpoints.  */
11677               struct type *vtype = check_typedef (value_type (v));
11678
11679               /* We only watch structs and arrays if user asked for it
11680                  explicitly, never if they just happen to appear in a
11681                  middle of some value chain.  */
11682               if (v == head
11683                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11684                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11685                 {
11686                   CORE_ADDR vaddr = value_address (v);
11687                   int len;
11688                   int num_regs;
11689
11690                   len = (target_exact_watchpoints
11691                          && is_scalar_type_recursive (vtype))?
11692                     1 : TYPE_LENGTH (value_type (v));
11693
11694                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11695                   if (!num_regs)
11696                     return 0;
11697                   else
11698                     found_memory_cnt += num_regs;
11699                 }
11700             }
11701         }
11702       else if (VALUE_LVAL (v) != not_lval
11703                && deprecated_value_modifiable (v) == 0)
11704         return 0;       /* These are values from the history (e.g., $1).  */
11705       else if (VALUE_LVAL (v) == lval_register)
11706         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11707     }
11708
11709   /* The expression itself looks suitable for using a hardware
11710      watchpoint, but give the target machine a chance to reject it.  */
11711   return found_memory_cnt;
11712 }
11713
11714 void
11715 watch_command_wrapper (char *arg, int from_tty, int internal)
11716 {
11717   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11718 }
11719
11720 /* A helper function that looks for the "-location" argument and then
11721    calls watch_command_1.  */
11722
11723 static void
11724 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11725 {
11726   int just_location = 0;
11727
11728   if (arg
11729       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11730           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11731     {
11732       arg = skip_spaces (arg);
11733       just_location = 1;
11734     }
11735
11736   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11737 }
11738
11739 static void
11740 watch_command (char *arg, int from_tty)
11741 {
11742   watch_maybe_just_location (arg, hw_write, from_tty);
11743 }
11744
11745 void
11746 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11747 {
11748   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11749 }
11750
11751 static void
11752 rwatch_command (char *arg, int from_tty)
11753 {
11754   watch_maybe_just_location (arg, hw_read, from_tty);
11755 }
11756
11757 void
11758 awatch_command_wrapper (char *arg, int from_tty, int internal)
11759 {
11760   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11761 }
11762
11763 static void
11764 awatch_command (char *arg, int from_tty)
11765 {
11766   watch_maybe_just_location (arg, hw_access, from_tty);
11767 }
11768 \f
11769
11770 /* Helper routines for the until_command routine in infcmd.c.  Here
11771    because it uses the mechanisms of breakpoints.  */
11772
11773 struct until_break_command_continuation_args
11774 {
11775   struct breakpoint *breakpoint;
11776   struct breakpoint *breakpoint2;
11777   int thread_num;
11778 };
11779
11780 /* This function is called by fetch_inferior_event via the
11781    cmd_continuation pointer, to complete the until command.  It takes
11782    care of cleaning up the temporary breakpoints set up by the until
11783    command.  */
11784 static void
11785 until_break_command_continuation (void *arg, int err)
11786 {
11787   struct until_break_command_continuation_args *a = arg;
11788
11789   delete_breakpoint (a->breakpoint);
11790   if (a->breakpoint2)
11791     delete_breakpoint (a->breakpoint2);
11792   delete_longjmp_breakpoint (a->thread_num);
11793 }
11794
11795 void
11796 until_break_command (char *arg, int from_tty, int anywhere)
11797 {
11798   struct symtabs_and_lines sals;
11799   struct symtab_and_line sal;
11800   struct frame_info *frame;
11801   struct gdbarch *frame_gdbarch;
11802   struct frame_id stack_frame_id;
11803   struct frame_id caller_frame_id;
11804   struct breakpoint *breakpoint;
11805   struct breakpoint *breakpoint2 = NULL;
11806   struct cleanup *old_chain;
11807   int thread;
11808   struct thread_info *tp;
11809
11810   clear_proceed_status (0);
11811
11812   /* Set a breakpoint where the user wants it and at return from
11813      this function.  */
11814
11815   if (last_displayed_sal_is_valid ())
11816     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11817                           get_last_displayed_symtab (),
11818                           get_last_displayed_line ());
11819   else
11820     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11821                           (struct symtab *) NULL, 0);
11822
11823   if (sals.nelts != 1)
11824     error (_("Couldn't get information on specified line."));
11825
11826   sal = sals.sals[0];
11827   xfree (sals.sals);    /* malloc'd, so freed.  */
11828
11829   if (*arg)
11830     error (_("Junk at end of arguments."));
11831
11832   resolve_sal_pc (&sal);
11833
11834   tp = inferior_thread ();
11835   thread = tp->num;
11836
11837   old_chain = make_cleanup (null_cleanup, NULL);
11838
11839   /* Note linespec handling above invalidates the frame chain.
11840      Installing a breakpoint also invalidates the frame chain (as it
11841      may need to switch threads), so do any frame handling before
11842      that.  */
11843
11844   frame = get_selected_frame (NULL);
11845   frame_gdbarch = get_frame_arch (frame);
11846   stack_frame_id = get_stack_frame_id (frame);
11847   caller_frame_id = frame_unwind_caller_id (frame);
11848
11849   /* Keep within the current frame, or in frames called by the current
11850      one.  */
11851
11852   if (frame_id_p (caller_frame_id))
11853     {
11854       struct symtab_and_line sal2;
11855
11856       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11857       sal2.pc = frame_unwind_caller_pc (frame);
11858       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11859                                               sal2,
11860                                               caller_frame_id,
11861                                               bp_until);
11862       make_cleanup_delete_breakpoint (breakpoint2);
11863
11864       set_longjmp_breakpoint (tp, caller_frame_id);
11865       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11866     }
11867
11868   /* set_momentary_breakpoint could invalidate FRAME.  */
11869   frame = NULL;
11870
11871   if (anywhere)
11872     /* If the user told us to continue until a specified location,
11873        we don't specify a frame at which we need to stop.  */
11874     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11875                                            null_frame_id, bp_until);
11876   else
11877     /* Otherwise, specify the selected frame, because we want to stop
11878        only at the very same frame.  */
11879     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11880                                            stack_frame_id, bp_until);
11881   make_cleanup_delete_breakpoint (breakpoint);
11882
11883   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11884
11885   /* If we are running asynchronously, and proceed call above has
11886      actually managed to start the target, arrange for breakpoints to
11887      be deleted when the target stops.  Otherwise, we're already
11888      stopped and delete breakpoints via cleanup chain.  */
11889
11890   if (target_can_async_p () && is_running (inferior_ptid))
11891     {
11892       struct until_break_command_continuation_args *args;
11893       args = xmalloc (sizeof (*args));
11894
11895       args->breakpoint = breakpoint;
11896       args->breakpoint2 = breakpoint2;
11897       args->thread_num = thread;
11898
11899       discard_cleanups (old_chain);
11900       add_continuation (inferior_thread (),
11901                         until_break_command_continuation, args,
11902                         xfree);
11903     }
11904   else
11905     do_cleanups (old_chain);
11906 }
11907
11908 /* This function attempts to parse an optional "if <cond>" clause
11909    from the arg string.  If one is not found, it returns NULL.
11910
11911    Else, it returns a pointer to the condition string.  (It does not
11912    attempt to evaluate the string against a particular block.)  And,
11913    it updates arg to point to the first character following the parsed
11914    if clause in the arg string.  */
11915
11916 char *
11917 ep_parse_optional_if_clause (char **arg)
11918 {
11919   char *cond_string;
11920
11921   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11922     return NULL;
11923
11924   /* Skip the "if" keyword.  */
11925   (*arg) += 2;
11926
11927   /* Skip any extra leading whitespace, and record the start of the
11928      condition string.  */
11929   *arg = skip_spaces (*arg);
11930   cond_string = *arg;
11931
11932   /* Assume that the condition occupies the remainder of the arg
11933      string.  */
11934   (*arg) += strlen (cond_string);
11935
11936   return cond_string;
11937 }
11938
11939 /* Commands to deal with catching events, such as signals, exceptions,
11940    process start/exit, etc.  */
11941
11942 typedef enum
11943 {
11944   catch_fork_temporary, catch_vfork_temporary,
11945   catch_fork_permanent, catch_vfork_permanent
11946 }
11947 catch_fork_kind;
11948
11949 static void
11950 catch_fork_command_1 (char *arg, int from_tty, 
11951                       struct cmd_list_element *command)
11952 {
11953   struct gdbarch *gdbarch = get_current_arch ();
11954   char *cond_string = NULL;
11955   catch_fork_kind fork_kind;
11956   int tempflag;
11957
11958   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11959   tempflag = (fork_kind == catch_fork_temporary
11960               || fork_kind == catch_vfork_temporary);
11961
11962   if (!arg)
11963     arg = "";
11964   arg = skip_spaces (arg);
11965
11966   /* The allowed syntax is:
11967      catch [v]fork
11968      catch [v]fork if <cond>
11969
11970      First, check if there's an if clause.  */
11971   cond_string = ep_parse_optional_if_clause (&arg);
11972
11973   if ((*arg != '\0') && !isspace (*arg))
11974     error (_("Junk at end of arguments."));
11975
11976   /* If this target supports it, create a fork or vfork catchpoint
11977      and enable reporting of such events.  */
11978   switch (fork_kind)
11979     {
11980     case catch_fork_temporary:
11981     case catch_fork_permanent:
11982       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11983                                           &catch_fork_breakpoint_ops);
11984       break;
11985     case catch_vfork_temporary:
11986     case catch_vfork_permanent:
11987       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11988                                           &catch_vfork_breakpoint_ops);
11989       break;
11990     default:
11991       error (_("unsupported or unknown fork kind; cannot catch it"));
11992       break;
11993     }
11994 }
11995
11996 static void
11997 catch_exec_command_1 (char *arg, int from_tty, 
11998                       struct cmd_list_element *command)
11999 {
12000   struct exec_catchpoint *c;
12001   struct gdbarch *gdbarch = get_current_arch ();
12002   int tempflag;
12003   char *cond_string = NULL;
12004
12005   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12006
12007   if (!arg)
12008     arg = "";
12009   arg = skip_spaces (arg);
12010
12011   /* The allowed syntax is:
12012      catch exec
12013      catch exec if <cond>
12014
12015      First, check if there's an if clause.  */
12016   cond_string = ep_parse_optional_if_clause (&arg);
12017
12018   if ((*arg != '\0') && !isspace (*arg))
12019     error (_("Junk at end of arguments."));
12020
12021   c = XNEW (struct exec_catchpoint);
12022   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12023                    &catch_exec_breakpoint_ops);
12024   c->exec_pathname = NULL;
12025
12026   install_breakpoint (0, &c->base, 1);
12027 }
12028
12029 void
12030 init_ada_exception_breakpoint (struct breakpoint *b,
12031                                struct gdbarch *gdbarch,
12032                                struct symtab_and_line sal,
12033                                char *addr_string,
12034                                const struct breakpoint_ops *ops,
12035                                int tempflag,
12036                                int enabled,
12037                                int from_tty)
12038 {
12039   if (from_tty)
12040     {
12041       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12042       if (!loc_gdbarch)
12043         loc_gdbarch = gdbarch;
12044
12045       describe_other_breakpoints (loc_gdbarch,
12046                                   sal.pspace, sal.pc, sal.section, -1);
12047       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12048          version for exception catchpoints, because two catchpoints
12049          used for different exception names will use the same address.
12050          In this case, a "breakpoint ... also set at..." warning is
12051          unproductive.  Besides, the warning phrasing is also a bit
12052          inappropriate, we should use the word catchpoint, and tell
12053          the user what type of catchpoint it is.  The above is good
12054          enough for now, though.  */
12055     }
12056
12057   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12058
12059   b->enable_state = enabled ? bp_enabled : bp_disabled;
12060   b->disposition = tempflag ? disp_del : disp_donttouch;
12061   b->addr_string = addr_string;
12062   b->language = language_ada;
12063 }
12064
12065 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12066    filter list, or NULL if no filtering is required.  */
12067 static VEC(int) *
12068 catch_syscall_split_args (char *arg)
12069 {
12070   VEC(int) *result = NULL;
12071   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12072
12073   while (*arg != '\0')
12074     {
12075       int i, syscall_number;
12076       char *endptr;
12077       char cur_name[128];
12078       struct syscall s;
12079
12080       /* Skip whitespace.  */
12081       arg = skip_spaces (arg);
12082
12083       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12084         cur_name[i] = arg[i];
12085       cur_name[i] = '\0';
12086       arg += i;
12087
12088       /* Check if the user provided a syscall name or a number.  */
12089       syscall_number = (int) strtol (cur_name, &endptr, 0);
12090       if (*endptr == '\0')
12091         get_syscall_by_number (syscall_number, &s);
12092       else
12093         {
12094           /* We have a name.  Let's check if it's valid and convert it
12095              to a number.  */
12096           get_syscall_by_name (cur_name, &s);
12097
12098           if (s.number == UNKNOWN_SYSCALL)
12099             /* Here we have to issue an error instead of a warning,
12100                because GDB cannot do anything useful if there's no
12101                syscall number to be caught.  */
12102             error (_("Unknown syscall name '%s'."), cur_name);
12103         }
12104
12105       /* Ok, it's valid.  */
12106       VEC_safe_push (int, result, s.number);
12107     }
12108
12109   discard_cleanups (cleanup);
12110   return result;
12111 }
12112
12113 /* Implement the "catch syscall" command.  */
12114
12115 static void
12116 catch_syscall_command_1 (char *arg, int from_tty, 
12117                          struct cmd_list_element *command)
12118 {
12119   int tempflag;
12120   VEC(int) *filter;
12121   struct syscall s;
12122   struct gdbarch *gdbarch = get_current_arch ();
12123
12124   /* Checking if the feature if supported.  */
12125   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12126     error (_("The feature 'catch syscall' is not supported on \
12127 this architecture yet."));
12128
12129   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12130
12131   arg = skip_spaces (arg);
12132
12133   /* We need to do this first "dummy" translation in order
12134      to get the syscall XML file loaded or, most important,
12135      to display a warning to the user if there's no XML file
12136      for his/her architecture.  */
12137   get_syscall_by_number (0, &s);
12138
12139   /* The allowed syntax is:
12140      catch syscall
12141      catch syscall <name | number> [<name | number> ... <name | number>]
12142
12143      Let's check if there's a syscall name.  */
12144
12145   if (arg != NULL)
12146     filter = catch_syscall_split_args (arg);
12147   else
12148     filter = NULL;
12149
12150   create_syscall_event_catchpoint (tempflag, filter,
12151                                    &catch_syscall_breakpoint_ops);
12152 }
12153
12154 static void
12155 catch_command (char *arg, int from_tty)
12156 {
12157   error (_("Catch requires an event name."));
12158 }
12159 \f
12160
12161 static void
12162 tcatch_command (char *arg, int from_tty)
12163 {
12164   error (_("Catch requires an event name."));
12165 }
12166
12167 /* A qsort comparison function that sorts breakpoints in order.  */
12168
12169 static int
12170 compare_breakpoints (const void *a, const void *b)
12171 {
12172   const breakpoint_p *ba = a;
12173   uintptr_t ua = (uintptr_t) *ba;
12174   const breakpoint_p *bb = b;
12175   uintptr_t ub = (uintptr_t) *bb;
12176
12177   if ((*ba)->number < (*bb)->number)
12178     return -1;
12179   else if ((*ba)->number > (*bb)->number)
12180     return 1;
12181
12182   /* Now sort by address, in case we see, e..g, two breakpoints with
12183      the number 0.  */
12184   if (ua < ub)
12185     return -1;
12186   return ua > ub ? 1 : 0;
12187 }
12188
12189 /* Delete breakpoints by address or line.  */
12190
12191 static void
12192 clear_command (char *arg, int from_tty)
12193 {
12194   struct breakpoint *b, *prev;
12195   VEC(breakpoint_p) *found = 0;
12196   int ix;
12197   int default_match;
12198   struct symtabs_and_lines sals;
12199   struct symtab_and_line sal;
12200   int i;
12201   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12202
12203   if (arg)
12204     {
12205       sals = decode_line_with_current_source (arg,
12206                                               (DECODE_LINE_FUNFIRSTLINE
12207                                                | DECODE_LINE_LIST_MODE));
12208       make_cleanup (xfree, sals.sals);
12209       default_match = 0;
12210     }
12211   else
12212     {
12213       sals.sals = (struct symtab_and_line *)
12214         xmalloc (sizeof (struct symtab_and_line));
12215       make_cleanup (xfree, sals.sals);
12216       init_sal (&sal);          /* Initialize to zeroes.  */
12217
12218       /* Set sal's line, symtab, pc, and pspace to the values
12219          corresponding to the last call to print_frame_info.  If the
12220          codepoint is not valid, this will set all the fields to 0.  */
12221       get_last_displayed_sal (&sal);
12222       if (sal.symtab == 0)
12223         error (_("No source file specified."));
12224
12225       sals.sals[0] = sal;
12226       sals.nelts = 1;
12227
12228       default_match = 1;
12229     }
12230
12231   /* We don't call resolve_sal_pc here.  That's not as bad as it
12232      seems, because all existing breakpoints typically have both
12233      file/line and pc set.  So, if clear is given file/line, we can
12234      match this to existing breakpoint without obtaining pc at all.
12235
12236      We only support clearing given the address explicitly 
12237      present in breakpoint table.  Say, we've set breakpoint 
12238      at file:line.  There were several PC values for that file:line,
12239      due to optimization, all in one block.
12240
12241      We've picked one PC value.  If "clear" is issued with another
12242      PC corresponding to the same file:line, the breakpoint won't
12243      be cleared.  We probably can still clear the breakpoint, but 
12244      since the other PC value is never presented to user, user
12245      can only find it by guessing, and it does not seem important
12246      to support that.  */
12247
12248   /* For each line spec given, delete bps which correspond to it.  Do
12249      it in two passes, solely to preserve the current behavior that
12250      from_tty is forced true if we delete more than one
12251      breakpoint.  */
12252
12253   found = NULL;
12254   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12255   for (i = 0; i < sals.nelts; i++)
12256     {
12257       const char *sal_fullname;
12258
12259       /* If exact pc given, clear bpts at that pc.
12260          If line given (pc == 0), clear all bpts on specified line.
12261          If defaulting, clear all bpts on default line
12262          or at default pc.
12263
12264          defaulting    sal.pc != 0    tests to do
12265
12266          0              1             pc
12267          1              1             pc _and_ line
12268          0              0             line
12269          1              0             <can't happen> */
12270
12271       sal = sals.sals[i];
12272       sal_fullname = (sal.symtab == NULL
12273                       ? NULL : symtab_to_fullname (sal.symtab));
12274
12275       /* Find all matching breakpoints and add them to 'found'.  */
12276       ALL_BREAKPOINTS (b)
12277         {
12278           int match = 0;
12279           /* Are we going to delete b?  */
12280           if (b->type != bp_none && !is_watchpoint (b))
12281             {
12282               struct bp_location *loc = b->loc;
12283               for (; loc; loc = loc->next)
12284                 {
12285                   /* If the user specified file:line, don't allow a PC
12286                      match.  This matches historical gdb behavior.  */
12287                   int pc_match = (!sal.explicit_line
12288                                   && sal.pc
12289                                   && (loc->pspace == sal.pspace)
12290                                   && (loc->address == sal.pc)
12291                                   && (!section_is_overlay (loc->section)
12292                                       || loc->section == sal.section));
12293                   int line_match = 0;
12294
12295                   if ((default_match || sal.explicit_line)
12296                       && loc->symtab != NULL
12297                       && sal_fullname != NULL
12298                       && sal.pspace == loc->pspace
12299                       && loc->line_number == sal.line
12300                       && filename_cmp (symtab_to_fullname (loc->symtab),
12301                                        sal_fullname) == 0)
12302                     line_match = 1;
12303
12304                   if (pc_match || line_match)
12305                     {
12306                       match = 1;
12307                       break;
12308                     }
12309                 }
12310             }
12311
12312           if (match)
12313             VEC_safe_push(breakpoint_p, found, b);
12314         }
12315     }
12316
12317   /* Now go thru the 'found' chain and delete them.  */
12318   if (VEC_empty(breakpoint_p, found))
12319     {
12320       if (arg)
12321         error (_("No breakpoint at %s."), arg);
12322       else
12323         error (_("No breakpoint at this line."));
12324     }
12325
12326   /* Remove duplicates from the vec.  */
12327   qsort (VEC_address (breakpoint_p, found),
12328          VEC_length (breakpoint_p, found),
12329          sizeof (breakpoint_p),
12330          compare_breakpoints);
12331   prev = VEC_index (breakpoint_p, found, 0);
12332   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12333     {
12334       if (b == prev)
12335         {
12336           VEC_ordered_remove (breakpoint_p, found, ix);
12337           --ix;
12338         }
12339     }
12340
12341   if (VEC_length(breakpoint_p, found) > 1)
12342     from_tty = 1;       /* Always report if deleted more than one.  */
12343   if (from_tty)
12344     {
12345       if (VEC_length(breakpoint_p, found) == 1)
12346         printf_unfiltered (_("Deleted breakpoint "));
12347       else
12348         printf_unfiltered (_("Deleted breakpoints "));
12349     }
12350
12351   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12352     {
12353       if (from_tty)
12354         printf_unfiltered ("%d ", b->number);
12355       delete_breakpoint (b);
12356     }
12357   if (from_tty)
12358     putchar_unfiltered ('\n');
12359
12360   do_cleanups (cleanups);
12361 }
12362 \f
12363 /* Delete breakpoint in BS if they are `delete' breakpoints and
12364    all breakpoints that are marked for deletion, whether hit or not.
12365    This is called after any breakpoint is hit, or after errors.  */
12366
12367 void
12368 breakpoint_auto_delete (bpstat bs)
12369 {
12370   struct breakpoint *b, *b_tmp;
12371
12372   for (; bs; bs = bs->next)
12373     if (bs->breakpoint_at
12374         && bs->breakpoint_at->disposition == disp_del
12375         && bs->stop)
12376       delete_breakpoint (bs->breakpoint_at);
12377
12378   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12379   {
12380     if (b->disposition == disp_del_at_next_stop)
12381       delete_breakpoint (b);
12382   }
12383 }
12384
12385 /* A comparison function for bp_location AP and BP being interfaced to
12386    qsort.  Sort elements primarily by their ADDRESS (no matter what
12387    does breakpoint_address_is_meaningful say for its OWNER),
12388    secondarily by ordering first bp_permanent OWNERed elements and
12389    terciarily just ensuring the array is sorted stable way despite
12390    qsort being an unstable algorithm.  */
12391
12392 static int
12393 bp_location_compare (const void *ap, const void *bp)
12394 {
12395   struct bp_location *a = *(void **) ap;
12396   struct bp_location *b = *(void **) bp;
12397   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12398   int a_perm = a->owner->enable_state == bp_permanent;
12399   int b_perm = b->owner->enable_state == bp_permanent;
12400
12401   if (a->address != b->address)
12402     return (a->address > b->address) - (a->address < b->address);
12403
12404   /* Sort locations at the same address by their pspace number, keeping
12405      locations of the same inferior (in a multi-inferior environment)
12406      grouped.  */
12407
12408   if (a->pspace->num != b->pspace->num)
12409     return ((a->pspace->num > b->pspace->num)
12410             - (a->pspace->num < b->pspace->num));
12411
12412   /* Sort permanent breakpoints first.  */
12413   if (a_perm != b_perm)
12414     return (a_perm < b_perm) - (a_perm > b_perm);
12415
12416   /* Make the internal GDB representation stable across GDB runs
12417      where A and B memory inside GDB can differ.  Breakpoint locations of
12418      the same type at the same address can be sorted in arbitrary order.  */
12419
12420   if (a->owner->number != b->owner->number)
12421     return ((a->owner->number > b->owner->number)
12422             - (a->owner->number < b->owner->number));
12423
12424   return (a > b) - (a < b);
12425 }
12426
12427 /* Set bp_location_placed_address_before_address_max and
12428    bp_location_shadow_len_after_address_max according to the current
12429    content of the bp_location array.  */
12430
12431 static void
12432 bp_location_target_extensions_update (void)
12433 {
12434   struct bp_location *bl, **blp_tmp;
12435
12436   bp_location_placed_address_before_address_max = 0;
12437   bp_location_shadow_len_after_address_max = 0;
12438
12439   ALL_BP_LOCATIONS (bl, blp_tmp)
12440     {
12441       CORE_ADDR start, end, addr;
12442
12443       if (!bp_location_has_shadow (bl))
12444         continue;
12445
12446       start = bl->target_info.placed_address;
12447       end = start + bl->target_info.shadow_len;
12448
12449       gdb_assert (bl->address >= start);
12450       addr = bl->address - start;
12451       if (addr > bp_location_placed_address_before_address_max)
12452         bp_location_placed_address_before_address_max = addr;
12453
12454       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12455
12456       gdb_assert (bl->address < end);
12457       addr = end - bl->address;
12458       if (addr > bp_location_shadow_len_after_address_max)
12459         bp_location_shadow_len_after_address_max = addr;
12460     }
12461 }
12462
12463 /* Download tracepoint locations if they haven't been.  */
12464
12465 static void
12466 download_tracepoint_locations (void)
12467 {
12468   struct breakpoint *b;
12469   struct cleanup *old_chain;
12470
12471   if (!target_can_download_tracepoint ())
12472     return;
12473
12474   old_chain = save_current_space_and_thread ();
12475
12476   ALL_TRACEPOINTS (b)
12477     {
12478       struct bp_location *bl;
12479       struct tracepoint *t;
12480       int bp_location_downloaded = 0;
12481
12482       if ((b->type == bp_fast_tracepoint
12483            ? !may_insert_fast_tracepoints
12484            : !may_insert_tracepoints))
12485         continue;
12486
12487       for (bl = b->loc; bl; bl = bl->next)
12488         {
12489           /* In tracepoint, locations are _never_ duplicated, so
12490              should_be_inserted is equivalent to
12491              unduplicated_should_be_inserted.  */
12492           if (!should_be_inserted (bl) || bl->inserted)
12493             continue;
12494
12495           switch_to_program_space_and_thread (bl->pspace);
12496
12497           target_download_tracepoint (bl);
12498
12499           bl->inserted = 1;
12500           bp_location_downloaded = 1;
12501         }
12502       t = (struct tracepoint *) b;
12503       t->number_on_target = b->number;
12504       if (bp_location_downloaded)
12505         observer_notify_breakpoint_modified (b);
12506     }
12507
12508   do_cleanups (old_chain);
12509 }
12510
12511 /* Swap the insertion/duplication state between two locations.  */
12512
12513 static void
12514 swap_insertion (struct bp_location *left, struct bp_location *right)
12515 {
12516   const int left_inserted = left->inserted;
12517   const int left_duplicate = left->duplicate;
12518   const int left_needs_update = left->needs_update;
12519   const struct bp_target_info left_target_info = left->target_info;
12520
12521   /* Locations of tracepoints can never be duplicated.  */
12522   if (is_tracepoint (left->owner))
12523     gdb_assert (!left->duplicate);
12524   if (is_tracepoint (right->owner))
12525     gdb_assert (!right->duplicate);
12526
12527   left->inserted = right->inserted;
12528   left->duplicate = right->duplicate;
12529   left->needs_update = right->needs_update;
12530   left->target_info = right->target_info;
12531   right->inserted = left_inserted;
12532   right->duplicate = left_duplicate;
12533   right->needs_update = left_needs_update;
12534   right->target_info = left_target_info;
12535 }
12536
12537 /* Force the re-insertion of the locations at ADDRESS.  This is called
12538    once a new/deleted/modified duplicate location is found and we are evaluating
12539    conditions on the target's side.  Such conditions need to be updated on
12540    the target.  */
12541
12542 static void
12543 force_breakpoint_reinsertion (struct bp_location *bl)
12544 {
12545   struct bp_location **locp = NULL, **loc2p;
12546   struct bp_location *loc;
12547   CORE_ADDR address = 0;
12548   int pspace_num;
12549
12550   address = bl->address;
12551   pspace_num = bl->pspace->num;
12552
12553   /* This is only meaningful if the target is
12554      evaluating conditions and if the user has
12555      opted for condition evaluation on the target's
12556      side.  */
12557   if (gdb_evaluates_breakpoint_condition_p ()
12558       || !target_supports_evaluation_of_breakpoint_conditions ())
12559     return;
12560
12561   /* Flag all breakpoint locations with this address and
12562      the same program space as the location
12563      as "its condition has changed".  We need to
12564      update the conditions on the target's side.  */
12565   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12566     {
12567       loc = *loc2p;
12568
12569       if (!is_breakpoint (loc->owner)
12570           || pspace_num != loc->pspace->num)
12571         continue;
12572
12573       /* Flag the location appropriately.  We use a different state to
12574          let everyone know that we already updated the set of locations
12575          with addr bl->address and program space bl->pspace.  This is so
12576          we don't have to keep calling these functions just to mark locations
12577          that have already been marked.  */
12578       loc->condition_changed = condition_updated;
12579
12580       /* Free the agent expression bytecode as well.  We will compute
12581          it later on.  */
12582       if (loc->cond_bytecode)
12583         {
12584           free_agent_expr (loc->cond_bytecode);
12585           loc->cond_bytecode = NULL;
12586         }
12587     }
12588 }
12589 /* Called whether new breakpoints are created, or existing breakpoints
12590    deleted, to update the global location list and recompute which
12591    locations are duplicate of which.
12592
12593    The INSERT_MODE flag determines whether locations may not, may, or
12594    shall be inserted now.  See 'enum ugll_insert_mode' for more
12595    info.  */
12596
12597 static void
12598 update_global_location_list (enum ugll_insert_mode insert_mode)
12599 {
12600   struct breakpoint *b;
12601   struct bp_location **locp, *loc;
12602   struct cleanup *cleanups;
12603   /* Last breakpoint location address that was marked for update.  */
12604   CORE_ADDR last_addr = 0;
12605   /* Last breakpoint location program space that was marked for update.  */
12606   int last_pspace_num = -1;
12607
12608   /* Used in the duplicates detection below.  When iterating over all
12609      bp_locations, points to the first bp_location of a given address.
12610      Breakpoints and watchpoints of different types are never
12611      duplicates of each other.  Keep one pointer for each type of
12612      breakpoint/watchpoint, so we only need to loop over all locations
12613      once.  */
12614   struct bp_location *bp_loc_first;  /* breakpoint */
12615   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12616   struct bp_location *awp_loc_first; /* access watchpoint */
12617   struct bp_location *rwp_loc_first; /* read watchpoint */
12618
12619   /* Saved former bp_location array which we compare against the newly
12620      built bp_location from the current state of ALL_BREAKPOINTS.  */
12621   struct bp_location **old_location, **old_locp;
12622   unsigned old_location_count;
12623
12624   old_location = bp_location;
12625   old_location_count = bp_location_count;
12626   bp_location = NULL;
12627   bp_location_count = 0;
12628   cleanups = make_cleanup (xfree, old_location);
12629
12630   ALL_BREAKPOINTS (b)
12631     for (loc = b->loc; loc; loc = loc->next)
12632       bp_location_count++;
12633
12634   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12635   locp = bp_location;
12636   ALL_BREAKPOINTS (b)
12637     for (loc = b->loc; loc; loc = loc->next)
12638       *locp++ = loc;
12639   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12640          bp_location_compare);
12641
12642   bp_location_target_extensions_update ();
12643
12644   /* Identify bp_location instances that are no longer present in the
12645      new list, and therefore should be freed.  Note that it's not
12646      necessary that those locations should be removed from inferior --
12647      if there's another location at the same address (previously
12648      marked as duplicate), we don't need to remove/insert the
12649      location.
12650      
12651      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12652      and former bp_location array state respectively.  */
12653
12654   locp = bp_location;
12655   for (old_locp = old_location; old_locp < old_location + old_location_count;
12656        old_locp++)
12657     {
12658       struct bp_location *old_loc = *old_locp;
12659       struct bp_location **loc2p;
12660
12661       /* Tells if 'old_loc' is found among the new locations.  If
12662          not, we have to free it.  */
12663       int found_object = 0;
12664       /* Tells if the location should remain inserted in the target.  */
12665       int keep_in_target = 0;
12666       int removed = 0;
12667
12668       /* Skip LOCP entries which will definitely never be needed.
12669          Stop either at or being the one matching OLD_LOC.  */
12670       while (locp < bp_location + bp_location_count
12671              && (*locp)->address < old_loc->address)
12672         locp++;
12673
12674       for (loc2p = locp;
12675            (loc2p < bp_location + bp_location_count
12676             && (*loc2p)->address == old_loc->address);
12677            loc2p++)
12678         {
12679           /* Check if this is a new/duplicated location or a duplicated
12680              location that had its condition modified.  If so, we want to send
12681              its condition to the target if evaluation of conditions is taking
12682              place there.  */
12683           if ((*loc2p)->condition_changed == condition_modified
12684               && (last_addr != old_loc->address
12685                   || last_pspace_num != old_loc->pspace->num))
12686             {
12687               force_breakpoint_reinsertion (*loc2p);
12688               last_pspace_num = old_loc->pspace->num;
12689             }
12690
12691           if (*loc2p == old_loc)
12692             found_object = 1;
12693         }
12694
12695       /* We have already handled this address, update it so that we don't
12696          have to go through updates again.  */
12697       last_addr = old_loc->address;
12698
12699       /* Target-side condition evaluation: Handle deleted locations.  */
12700       if (!found_object)
12701         force_breakpoint_reinsertion (old_loc);
12702
12703       /* If this location is no longer present, and inserted, look if
12704          there's maybe a new location at the same address.  If so,
12705          mark that one inserted, and don't remove this one.  This is
12706          needed so that we don't have a time window where a breakpoint
12707          at certain location is not inserted.  */
12708
12709       if (old_loc->inserted)
12710         {
12711           /* If the location is inserted now, we might have to remove
12712              it.  */
12713
12714           if (found_object && should_be_inserted (old_loc))
12715             {
12716               /* The location is still present in the location list,
12717                  and still should be inserted.  Don't do anything.  */
12718               keep_in_target = 1;
12719             }
12720           else
12721             {
12722               /* This location still exists, but it won't be kept in the
12723                  target since it may have been disabled.  We proceed to
12724                  remove its target-side condition.  */
12725
12726               /* The location is either no longer present, or got
12727                  disabled.  See if there's another location at the
12728                  same address, in which case we don't need to remove
12729                  this one from the target.  */
12730
12731               /* OLD_LOC comes from existing struct breakpoint.  */
12732               if (breakpoint_address_is_meaningful (old_loc->owner))
12733                 {
12734                   for (loc2p = locp;
12735                        (loc2p < bp_location + bp_location_count
12736                         && (*loc2p)->address == old_loc->address);
12737                        loc2p++)
12738                     {
12739                       struct bp_location *loc2 = *loc2p;
12740
12741                       if (breakpoint_locations_match (loc2, old_loc))
12742                         {
12743                           /* Read watchpoint locations are switched to
12744                              access watchpoints, if the former are not
12745                              supported, but the latter are.  */
12746                           if (is_hardware_watchpoint (old_loc->owner))
12747                             {
12748                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12749                               loc2->watchpoint_type = old_loc->watchpoint_type;
12750                             }
12751
12752                           /* loc2 is a duplicated location. We need to check
12753                              if it should be inserted in case it will be
12754                              unduplicated.  */
12755                           if (loc2 != old_loc
12756                               && unduplicated_should_be_inserted (loc2))
12757                             {
12758                               swap_insertion (old_loc, loc2);
12759                               keep_in_target = 1;
12760                               break;
12761                             }
12762                         }
12763                     }
12764                 }
12765             }
12766
12767           if (!keep_in_target)
12768             {
12769               if (remove_breakpoint (old_loc, mark_uninserted))
12770                 {
12771                   /* This is just about all we can do.  We could keep
12772                      this location on the global list, and try to
12773                      remove it next time, but there's no particular
12774                      reason why we will succeed next time.
12775                      
12776                      Note that at this point, old_loc->owner is still
12777                      valid, as delete_breakpoint frees the breakpoint
12778                      only after calling us.  */
12779                   printf_filtered (_("warning: Error removing "
12780                                      "breakpoint %d\n"), 
12781                                    old_loc->owner->number);
12782                 }
12783               removed = 1;
12784             }
12785         }
12786
12787       if (!found_object)
12788         {
12789           if (removed && non_stop
12790               && breakpoint_address_is_meaningful (old_loc->owner)
12791               && !is_hardware_watchpoint (old_loc->owner))
12792             {
12793               /* This location was removed from the target.  In
12794                  non-stop mode, a race condition is possible where
12795                  we've removed a breakpoint, but stop events for that
12796                  breakpoint are already queued and will arrive later.
12797                  We apply an heuristic to be able to distinguish such
12798                  SIGTRAPs from other random SIGTRAPs: we keep this
12799                  breakpoint location for a bit, and will retire it
12800                  after we see some number of events.  The theory here
12801                  is that reporting of events should, "on the average",
12802                  be fair, so after a while we'll see events from all
12803                  threads that have anything of interest, and no longer
12804                  need to keep this breakpoint location around.  We
12805                  don't hold locations forever so to reduce chances of
12806                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12807                  SIGTRAP.
12808
12809                  The heuristic failing can be disastrous on
12810                  decr_pc_after_break targets.
12811
12812                  On decr_pc_after_break targets, like e.g., x86-linux,
12813                  if we fail to recognize a late breakpoint SIGTRAP,
12814                  because events_till_retirement has reached 0 too
12815                  soon, we'll fail to do the PC adjustment, and report
12816                  a random SIGTRAP to the user.  When the user resumes
12817                  the inferior, it will most likely immediately crash
12818                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12819                  corrupted, because of being resumed e.g., in the
12820                  middle of a multi-byte instruction, or skipped a
12821                  one-byte instruction.  This was actually seen happen
12822                  on native x86-linux, and should be less rare on
12823                  targets that do not support new thread events, like
12824                  remote, due to the heuristic depending on
12825                  thread_count.
12826
12827                  Mistaking a random SIGTRAP for a breakpoint trap
12828                  causes similar symptoms (PC adjustment applied when
12829                  it shouldn't), but then again, playing with SIGTRAPs
12830                  behind the debugger's back is asking for trouble.
12831
12832                  Since hardware watchpoint traps are always
12833                  distinguishable from other traps, so we don't need to
12834                  apply keep hardware watchpoint moribund locations
12835                  around.  We simply always ignore hardware watchpoint
12836                  traps we can no longer explain.  */
12837
12838               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12839               old_loc->owner = NULL;
12840
12841               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12842             }
12843           else
12844             {
12845               old_loc->owner = NULL;
12846               decref_bp_location (&old_loc);
12847             }
12848         }
12849     }
12850
12851   /* Rescan breakpoints at the same address and section, marking the
12852      first one as "first" and any others as "duplicates".  This is so
12853      that the bpt instruction is only inserted once.  If we have a
12854      permanent breakpoint at the same place as BPT, make that one the
12855      official one, and the rest as duplicates.  Permanent breakpoints
12856      are sorted first for the same address.
12857
12858      Do the same for hardware watchpoints, but also considering the
12859      watchpoint's type (regular/access/read) and length.  */
12860
12861   bp_loc_first = NULL;
12862   wp_loc_first = NULL;
12863   awp_loc_first = NULL;
12864   rwp_loc_first = NULL;
12865   ALL_BP_LOCATIONS (loc, locp)
12866     {
12867       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12868          non-NULL.  */
12869       struct bp_location **loc_first_p;
12870       b = loc->owner;
12871
12872       if (!unduplicated_should_be_inserted (loc)
12873           || !breakpoint_address_is_meaningful (b)
12874           /* Don't detect duplicate for tracepoint locations because they are
12875            never duplicated.  See the comments in field `duplicate' of
12876            `struct bp_location'.  */
12877           || is_tracepoint (b))
12878         {
12879           /* Clear the condition modification flag.  */
12880           loc->condition_changed = condition_unchanged;
12881           continue;
12882         }
12883
12884       /* Permanent breakpoint should always be inserted.  */
12885       if (b->enable_state == bp_permanent && ! loc->inserted)
12886         internal_error (__FILE__, __LINE__,
12887                         _("allegedly permanent breakpoint is not "
12888                         "actually inserted"));
12889
12890       if (b->type == bp_hardware_watchpoint)
12891         loc_first_p = &wp_loc_first;
12892       else if (b->type == bp_read_watchpoint)
12893         loc_first_p = &rwp_loc_first;
12894       else if (b->type == bp_access_watchpoint)
12895         loc_first_p = &awp_loc_first;
12896       else
12897         loc_first_p = &bp_loc_first;
12898
12899       if (*loc_first_p == NULL
12900           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12901           || !breakpoint_locations_match (loc, *loc_first_p))
12902         {
12903           *loc_first_p = loc;
12904           loc->duplicate = 0;
12905
12906           if (is_breakpoint (loc->owner) && loc->condition_changed)
12907             {
12908               loc->needs_update = 1;
12909               /* Clear the condition modification flag.  */
12910               loc->condition_changed = condition_unchanged;
12911             }
12912           continue;
12913         }
12914
12915
12916       /* This and the above ensure the invariant that the first location
12917          is not duplicated, and is the inserted one.
12918          All following are marked as duplicated, and are not inserted.  */
12919       if (loc->inserted)
12920         swap_insertion (loc, *loc_first_p);
12921       loc->duplicate = 1;
12922
12923       /* Clear the condition modification flag.  */
12924       loc->condition_changed = condition_unchanged;
12925
12926       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12927           && b->enable_state != bp_permanent)
12928         internal_error (__FILE__, __LINE__,
12929                         _("another breakpoint was inserted on top of "
12930                         "a permanent breakpoint"));
12931     }
12932
12933   if (insert_mode == UGLL_INSERT
12934       || (breakpoints_always_inserted_mode ()
12935           && (have_live_inferiors ()
12936               || (gdbarch_has_global_breakpoints (target_gdbarch ())))))
12937     {
12938       if (insert_mode != UGLL_DONT_INSERT)
12939         insert_breakpoint_locations ();
12940       else
12941         {
12942           /* Even though the caller told us to not insert new
12943              locations, we may still need to update conditions on the
12944              target's side of breakpoints that were already inserted
12945              if the target is evaluating breakpoint conditions.  We
12946              only update conditions for locations that are marked
12947              "needs_update".  */
12948           update_inserted_breakpoint_locations ();
12949         }
12950     }
12951
12952   if (insert_mode != UGLL_DONT_INSERT)
12953     download_tracepoint_locations ();
12954
12955   do_cleanups (cleanups);
12956 }
12957
12958 void
12959 breakpoint_retire_moribund (void)
12960 {
12961   struct bp_location *loc;
12962   int ix;
12963
12964   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12965     if (--(loc->events_till_retirement) == 0)
12966       {
12967         decref_bp_location (&loc);
12968         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12969         --ix;
12970       }
12971 }
12972
12973 static void
12974 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12975 {
12976   volatile struct gdb_exception e;
12977
12978   TRY_CATCH (e, RETURN_MASK_ERROR)
12979     update_global_location_list (insert_mode);
12980 }
12981
12982 /* Clear BKP from a BPS.  */
12983
12984 static void
12985 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12986 {
12987   bpstat bs;
12988
12989   for (bs = bps; bs; bs = bs->next)
12990     if (bs->breakpoint_at == bpt)
12991       {
12992         bs->breakpoint_at = NULL;
12993         bs->old_val = NULL;
12994         /* bs->commands will be freed later.  */
12995       }
12996 }
12997
12998 /* Callback for iterate_over_threads.  */
12999 static int
13000 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
13001 {
13002   struct breakpoint *bpt = data;
13003
13004   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
13005   return 0;
13006 }
13007
13008 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
13009    callbacks.  */
13010
13011 static void
13012 say_where (struct breakpoint *b)
13013 {
13014   struct value_print_options opts;
13015
13016   get_user_print_options (&opts);
13017
13018   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13019      single string.  */
13020   if (b->loc == NULL)
13021     {
13022       printf_filtered (_(" (%s) pending."), b->addr_string);
13023     }
13024   else
13025     {
13026       if (opts.addressprint || b->loc->symtab == NULL)
13027         {
13028           printf_filtered (" at ");
13029           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13030                           gdb_stdout);
13031         }
13032       if (b->loc->symtab != NULL)
13033         {
13034           /* If there is a single location, we can print the location
13035              more nicely.  */
13036           if (b->loc->next == NULL)
13037             printf_filtered (": file %s, line %d.",
13038                              symtab_to_filename_for_display (b->loc->symtab),
13039                              b->loc->line_number);
13040           else
13041             /* This is not ideal, but each location may have a
13042                different file name, and this at least reflects the
13043                real situation somewhat.  */
13044             printf_filtered (": %s.", b->addr_string);
13045         }
13046
13047       if (b->loc->next)
13048         {
13049           struct bp_location *loc = b->loc;
13050           int n = 0;
13051           for (; loc; loc = loc->next)
13052             ++n;
13053           printf_filtered (" (%d locations)", n);
13054         }
13055     }
13056 }
13057
13058 /* Default bp_location_ops methods.  */
13059
13060 static void
13061 bp_location_dtor (struct bp_location *self)
13062 {
13063   xfree (self->cond);
13064   if (self->cond_bytecode)
13065     free_agent_expr (self->cond_bytecode);
13066   xfree (self->function_name);
13067
13068   VEC_free (agent_expr_p, self->target_info.conditions);
13069   VEC_free (agent_expr_p, self->target_info.tcommands);
13070 }
13071
13072 static const struct bp_location_ops bp_location_ops =
13073 {
13074   bp_location_dtor
13075 };
13076
13077 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13078    inherit from.  */
13079
13080 static void
13081 base_breakpoint_dtor (struct breakpoint *self)
13082 {
13083   decref_counted_command_line (&self->commands);
13084   xfree (self->cond_string);
13085   xfree (self->extra_string);
13086   xfree (self->addr_string);
13087   xfree (self->filter);
13088   xfree (self->addr_string_range_end);
13089 }
13090
13091 static struct bp_location *
13092 base_breakpoint_allocate_location (struct breakpoint *self)
13093 {
13094   struct bp_location *loc;
13095
13096   loc = XNEW (struct bp_location);
13097   init_bp_location (loc, &bp_location_ops, self);
13098   return loc;
13099 }
13100
13101 static void
13102 base_breakpoint_re_set (struct breakpoint *b)
13103 {
13104   /* Nothing to re-set. */
13105 }
13106
13107 #define internal_error_pure_virtual_called() \
13108   gdb_assert_not_reached ("pure virtual function called")
13109
13110 static int
13111 base_breakpoint_insert_location (struct bp_location *bl)
13112 {
13113   internal_error_pure_virtual_called ();
13114 }
13115
13116 static int
13117 base_breakpoint_remove_location (struct bp_location *bl)
13118 {
13119   internal_error_pure_virtual_called ();
13120 }
13121
13122 static int
13123 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13124                                 struct address_space *aspace,
13125                                 CORE_ADDR bp_addr,
13126                                 const struct target_waitstatus *ws)
13127 {
13128   internal_error_pure_virtual_called ();
13129 }
13130
13131 static void
13132 base_breakpoint_check_status (bpstat bs)
13133 {
13134   /* Always stop.   */
13135 }
13136
13137 /* A "works_in_software_mode" breakpoint_ops method that just internal
13138    errors.  */
13139
13140 static int
13141 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13142 {
13143   internal_error_pure_virtual_called ();
13144 }
13145
13146 /* A "resources_needed" breakpoint_ops method that just internal
13147    errors.  */
13148
13149 static int
13150 base_breakpoint_resources_needed (const struct bp_location *bl)
13151 {
13152   internal_error_pure_virtual_called ();
13153 }
13154
13155 static enum print_stop_action
13156 base_breakpoint_print_it (bpstat bs)
13157 {
13158   internal_error_pure_virtual_called ();
13159 }
13160
13161 static void
13162 base_breakpoint_print_one_detail (const struct breakpoint *self,
13163                                   struct ui_out *uiout)
13164 {
13165   /* nothing */
13166 }
13167
13168 static void
13169 base_breakpoint_print_mention (struct breakpoint *b)
13170 {
13171   internal_error_pure_virtual_called ();
13172 }
13173
13174 static void
13175 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13176 {
13177   internal_error_pure_virtual_called ();
13178 }
13179
13180 static void
13181 base_breakpoint_create_sals_from_address (char **arg,
13182                                           struct linespec_result *canonical,
13183                                           enum bptype type_wanted,
13184                                           char *addr_start,
13185                                           char **copy_arg)
13186 {
13187   internal_error_pure_virtual_called ();
13188 }
13189
13190 static void
13191 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13192                                         struct linespec_result *c,
13193                                         char *cond_string,
13194                                         char *extra_string,
13195                                         enum bptype type_wanted,
13196                                         enum bpdisp disposition,
13197                                         int thread,
13198                                         int task, int ignore_count,
13199                                         const struct breakpoint_ops *o,
13200                                         int from_tty, int enabled,
13201                                         int internal, unsigned flags)
13202 {
13203   internal_error_pure_virtual_called ();
13204 }
13205
13206 static void
13207 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13208                                  struct symtabs_and_lines *sals)
13209 {
13210   internal_error_pure_virtual_called ();
13211 }
13212
13213 /* The default 'explains_signal' method.  */
13214
13215 static int
13216 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13217 {
13218   return 1;
13219 }
13220
13221 /* The default "after_condition_true" method.  */
13222
13223 static void
13224 base_breakpoint_after_condition_true (struct bpstats *bs)
13225 {
13226   /* Nothing to do.   */
13227 }
13228
13229 struct breakpoint_ops base_breakpoint_ops =
13230 {
13231   base_breakpoint_dtor,
13232   base_breakpoint_allocate_location,
13233   base_breakpoint_re_set,
13234   base_breakpoint_insert_location,
13235   base_breakpoint_remove_location,
13236   base_breakpoint_breakpoint_hit,
13237   base_breakpoint_check_status,
13238   base_breakpoint_resources_needed,
13239   base_breakpoint_works_in_software_mode,
13240   base_breakpoint_print_it,
13241   NULL,
13242   base_breakpoint_print_one_detail,
13243   base_breakpoint_print_mention,
13244   base_breakpoint_print_recreate,
13245   base_breakpoint_create_sals_from_address,
13246   base_breakpoint_create_breakpoints_sal,
13247   base_breakpoint_decode_linespec,
13248   base_breakpoint_explains_signal,
13249   base_breakpoint_after_condition_true,
13250 };
13251
13252 /* Default breakpoint_ops methods.  */
13253
13254 static void
13255 bkpt_re_set (struct breakpoint *b)
13256 {
13257   /* FIXME: is this still reachable?  */
13258   if (b->addr_string == NULL)
13259     {
13260       /* Anything without a string can't be re-set.  */
13261       delete_breakpoint (b);
13262       return;
13263     }
13264
13265   breakpoint_re_set_default (b);
13266 }
13267
13268 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13269    inserted DEST, so we can remove it later, in case SRC is removed
13270    first.  */
13271
13272 static void
13273 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13274                                      const struct bp_target_info *src)
13275 {
13276   dest->shadow_len = src->shadow_len;
13277   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13278   dest->placed_size = src->placed_size;
13279 }
13280
13281 static int
13282 bkpt_insert_location (struct bp_location *bl)
13283 {
13284   if (bl->loc_type == bp_loc_hardware_breakpoint)
13285     return target_insert_hw_breakpoint (bl->gdbarch,
13286                                         &bl->target_info);
13287   else
13288     {
13289       struct bp_target_info *bp_tgt = &bl->target_info;
13290       int ret;
13291       int sss_slot;
13292
13293       /* There is no need to insert a breakpoint if an unconditional
13294          raw/sss breakpoint is already inserted at that location.  */
13295       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13296                                               bp_tgt->placed_address);
13297       if (sss_slot >= 0)
13298         {
13299           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13300
13301           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13302           return 0;
13303         }
13304
13305       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13306     }
13307 }
13308
13309 static int
13310 bkpt_remove_location (struct bp_location *bl)
13311 {
13312   if (bl->loc_type == bp_loc_hardware_breakpoint)
13313     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13314   else
13315     {
13316       struct bp_target_info *bp_tgt = &bl->target_info;
13317       struct address_space *aspace = bp_tgt->placed_address_space;
13318       CORE_ADDR address = bp_tgt->placed_address;
13319
13320       /* Only remove the breakpoint if there is no raw/sss breakpoint
13321          still inserted at this location.  Otherwise, we would be
13322          effectively disabling the raw/sss breakpoint.  */
13323       if (single_step_breakpoint_inserted_here_p (aspace, address))
13324         return 0;
13325
13326       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13327     }
13328 }
13329
13330 static int
13331 bkpt_breakpoint_hit (const struct bp_location *bl,
13332                      struct address_space *aspace, CORE_ADDR bp_addr,
13333                      const struct target_waitstatus *ws)
13334 {
13335   if (ws->kind != TARGET_WAITKIND_STOPPED
13336       || ws->value.sig != GDB_SIGNAL_TRAP)
13337     return 0;
13338
13339   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13340                                  aspace, bp_addr))
13341     return 0;
13342
13343   if (overlay_debugging         /* unmapped overlay section */
13344       && section_is_overlay (bl->section)
13345       && !section_is_mapped (bl->section))
13346     return 0;
13347
13348   return 1;
13349 }
13350
13351 static int
13352 dprintf_breakpoint_hit (const struct bp_location *bl,
13353                         struct address_space *aspace, CORE_ADDR bp_addr,
13354                         const struct target_waitstatus *ws)
13355 {
13356   if (dprintf_style == dprintf_style_agent
13357       && target_can_run_breakpoint_commands ())
13358     {
13359       /* An agent-style dprintf never causes a stop.  If we see a trap
13360          for this address it must be for a breakpoint that happens to
13361          be set at the same address.  */
13362       return 0;
13363     }
13364
13365   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13366 }
13367
13368 static int
13369 bkpt_resources_needed (const struct bp_location *bl)
13370 {
13371   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13372
13373   return 1;
13374 }
13375
13376 static enum print_stop_action
13377 bkpt_print_it (bpstat bs)
13378 {
13379   struct breakpoint *b;
13380   const struct bp_location *bl;
13381   int bp_temp;
13382   struct ui_out *uiout = current_uiout;
13383
13384   gdb_assert (bs->bp_location_at != NULL);
13385
13386   bl = bs->bp_location_at;
13387   b = bs->breakpoint_at;
13388
13389   bp_temp = b->disposition == disp_del;
13390   if (bl->address != bl->requested_address)
13391     breakpoint_adjustment_warning (bl->requested_address,
13392                                    bl->address,
13393                                    b->number, 1);
13394   annotate_breakpoint (b->number);
13395   if (bp_temp)
13396     ui_out_text (uiout, "\nTemporary breakpoint ");
13397   else
13398     ui_out_text (uiout, "\nBreakpoint ");
13399   if (ui_out_is_mi_like_p (uiout))
13400     {
13401       ui_out_field_string (uiout, "reason",
13402                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13403       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13404     }
13405   ui_out_field_int (uiout, "bkptno", b->number);
13406   ui_out_text (uiout, ", ");
13407
13408   return PRINT_SRC_AND_LOC;
13409 }
13410
13411 static void
13412 bkpt_print_mention (struct breakpoint *b)
13413 {
13414   if (ui_out_is_mi_like_p (current_uiout))
13415     return;
13416
13417   switch (b->type)
13418     {
13419     case bp_breakpoint:
13420     case bp_gnu_ifunc_resolver:
13421       if (b->disposition == disp_del)
13422         printf_filtered (_("Temporary breakpoint"));
13423       else
13424         printf_filtered (_("Breakpoint"));
13425       printf_filtered (_(" %d"), b->number);
13426       if (b->type == bp_gnu_ifunc_resolver)
13427         printf_filtered (_(" at gnu-indirect-function resolver"));
13428       break;
13429     case bp_hardware_breakpoint:
13430       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13431       break;
13432     case bp_dprintf:
13433       printf_filtered (_("Dprintf %d"), b->number);
13434       break;
13435     }
13436
13437   say_where (b);
13438 }
13439
13440 static void
13441 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13442 {
13443   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13444     fprintf_unfiltered (fp, "tbreak");
13445   else if (tp->type == bp_breakpoint)
13446     fprintf_unfiltered (fp, "break");
13447   else if (tp->type == bp_hardware_breakpoint
13448            && tp->disposition == disp_del)
13449     fprintf_unfiltered (fp, "thbreak");
13450   else if (tp->type == bp_hardware_breakpoint)
13451     fprintf_unfiltered (fp, "hbreak");
13452   else
13453     internal_error (__FILE__, __LINE__,
13454                     _("unhandled breakpoint type %d"), (int) tp->type);
13455
13456   fprintf_unfiltered (fp, " %s", tp->addr_string);
13457   print_recreate_thread (tp, fp);
13458 }
13459
13460 static void
13461 bkpt_create_sals_from_address (char **arg,
13462                                struct linespec_result *canonical,
13463                                enum bptype type_wanted,
13464                                char *addr_start, char **copy_arg)
13465 {
13466   create_sals_from_address_default (arg, canonical, type_wanted,
13467                                     addr_start, copy_arg);
13468 }
13469
13470 static void
13471 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13472                              struct linespec_result *canonical,
13473                              char *cond_string,
13474                              char *extra_string,
13475                              enum bptype type_wanted,
13476                              enum bpdisp disposition,
13477                              int thread,
13478                              int task, int ignore_count,
13479                              const struct breakpoint_ops *ops,
13480                              int from_tty, int enabled,
13481                              int internal, unsigned flags)
13482 {
13483   create_breakpoints_sal_default (gdbarch, canonical,
13484                                   cond_string, extra_string,
13485                                   type_wanted,
13486                                   disposition, thread, task,
13487                                   ignore_count, ops, from_tty,
13488                                   enabled, internal, flags);
13489 }
13490
13491 static void
13492 bkpt_decode_linespec (struct breakpoint *b, char **s,
13493                       struct symtabs_and_lines *sals)
13494 {
13495   decode_linespec_default (b, s, sals);
13496 }
13497
13498 /* Virtual table for internal breakpoints.  */
13499
13500 static void
13501 internal_bkpt_re_set (struct breakpoint *b)
13502 {
13503   switch (b->type)
13504     {
13505       /* Delete overlay event and longjmp master breakpoints; they
13506          will be reset later by breakpoint_re_set.  */
13507     case bp_overlay_event:
13508     case bp_longjmp_master:
13509     case bp_std_terminate_master:
13510     case bp_exception_master:
13511       delete_breakpoint (b);
13512       break;
13513
13514       /* This breakpoint is special, it's set up when the inferior
13515          starts and we really don't want to touch it.  */
13516     case bp_shlib_event:
13517
13518       /* Like bp_shlib_event, this breakpoint type is special.  Once
13519          it is set up, we do not want to touch it.  */
13520     case bp_thread_event:
13521       break;
13522     }
13523 }
13524
13525 static void
13526 internal_bkpt_check_status (bpstat bs)
13527 {
13528   if (bs->breakpoint_at->type == bp_shlib_event)
13529     {
13530       /* If requested, stop when the dynamic linker notifies GDB of
13531          events.  This allows the user to get control and place
13532          breakpoints in initializer routines for dynamically loaded
13533          objects (among other things).  */
13534       bs->stop = stop_on_solib_events;
13535       bs->print = stop_on_solib_events;
13536     }
13537   else
13538     bs->stop = 0;
13539 }
13540
13541 static enum print_stop_action
13542 internal_bkpt_print_it (bpstat bs)
13543 {
13544   struct breakpoint *b;
13545
13546   b = bs->breakpoint_at;
13547
13548   switch (b->type)
13549     {
13550     case bp_shlib_event:
13551       /* Did we stop because the user set the stop_on_solib_events
13552          variable?  (If so, we report this as a generic, "Stopped due
13553          to shlib event" message.) */
13554       print_solib_event (0);
13555       break;
13556
13557     case bp_thread_event:
13558       /* Not sure how we will get here.
13559          GDB should not stop for these breakpoints.  */
13560       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13561       break;
13562
13563     case bp_overlay_event:
13564       /* By analogy with the thread event, GDB should not stop for these.  */
13565       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13566       break;
13567
13568     case bp_longjmp_master:
13569       /* These should never be enabled.  */
13570       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13571       break;
13572
13573     case bp_std_terminate_master:
13574       /* These should never be enabled.  */
13575       printf_filtered (_("std::terminate Master Breakpoint: "
13576                          "gdb should not stop!\n"));
13577       break;
13578
13579     case bp_exception_master:
13580       /* These should never be enabled.  */
13581       printf_filtered (_("Exception Master Breakpoint: "
13582                          "gdb should not stop!\n"));
13583       break;
13584     }
13585
13586   return PRINT_NOTHING;
13587 }
13588
13589 static void
13590 internal_bkpt_print_mention (struct breakpoint *b)
13591 {
13592   /* Nothing to mention.  These breakpoints are internal.  */
13593 }
13594
13595 /* Virtual table for momentary breakpoints  */
13596
13597 static void
13598 momentary_bkpt_re_set (struct breakpoint *b)
13599 {
13600   /* Keep temporary breakpoints, which can be encountered when we step
13601      over a dlopen call and solib_add is resetting the breakpoints.
13602      Otherwise these should have been blown away via the cleanup chain
13603      or by breakpoint_init_inferior when we rerun the executable.  */
13604 }
13605
13606 static void
13607 momentary_bkpt_check_status (bpstat bs)
13608 {
13609   /* Nothing.  The point of these breakpoints is causing a stop.  */
13610 }
13611
13612 static enum print_stop_action
13613 momentary_bkpt_print_it (bpstat bs)
13614 {
13615   struct ui_out *uiout = current_uiout;
13616
13617   if (ui_out_is_mi_like_p (uiout))
13618     {
13619       struct breakpoint *b = bs->breakpoint_at;
13620
13621       switch (b->type)
13622         {
13623         case bp_finish:
13624           ui_out_field_string
13625             (uiout, "reason",
13626              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13627           break;
13628
13629         case bp_until:
13630           ui_out_field_string
13631             (uiout, "reason",
13632              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13633           break;
13634         }
13635     }
13636
13637   return PRINT_UNKNOWN;
13638 }
13639
13640 static void
13641 momentary_bkpt_print_mention (struct breakpoint *b)
13642 {
13643   /* Nothing to mention.  These breakpoints are internal.  */
13644 }
13645
13646 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13647
13648    It gets cleared already on the removal of the first one of such placed
13649    breakpoints.  This is OK as they get all removed altogether.  */
13650
13651 static void
13652 longjmp_bkpt_dtor (struct breakpoint *self)
13653 {
13654   struct thread_info *tp = find_thread_id (self->thread);
13655
13656   if (tp)
13657     tp->initiating_frame = null_frame_id;
13658
13659   momentary_breakpoint_ops.dtor (self);
13660 }
13661
13662 /* Specific methods for probe breakpoints.  */
13663
13664 static int
13665 bkpt_probe_insert_location (struct bp_location *bl)
13666 {
13667   int v = bkpt_insert_location (bl);
13668
13669   if (v == 0)
13670     {
13671       /* The insertion was successful, now let's set the probe's semaphore
13672          if needed.  */
13673       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13674                                             bl->probe.objfile,
13675                                             bl->gdbarch);
13676     }
13677
13678   return v;
13679 }
13680
13681 static int
13682 bkpt_probe_remove_location (struct bp_location *bl)
13683 {
13684   /* Let's clear the semaphore before removing the location.  */
13685   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13686                                           bl->probe.objfile,
13687                                           bl->gdbarch);
13688
13689   return bkpt_remove_location (bl);
13690 }
13691
13692 static void
13693 bkpt_probe_create_sals_from_address (char **arg,
13694                                      struct linespec_result *canonical,
13695                                      enum bptype type_wanted,
13696                                      char *addr_start, char **copy_arg)
13697 {
13698   struct linespec_sals lsal;
13699
13700   lsal.sals = parse_probes (arg, canonical);
13701
13702   *copy_arg = xstrdup (canonical->addr_string);
13703   lsal.canonical = xstrdup (*copy_arg);
13704
13705   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13706 }
13707
13708 static void
13709 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13710                             struct symtabs_and_lines *sals)
13711 {
13712   *sals = parse_probes (s, NULL);
13713   if (!sals->sals)
13714     error (_("probe not found"));
13715 }
13716
13717 /* The breakpoint_ops structure to be used in tracepoints.  */
13718
13719 static void
13720 tracepoint_re_set (struct breakpoint *b)
13721 {
13722   breakpoint_re_set_default (b);
13723 }
13724
13725 static int
13726 tracepoint_breakpoint_hit (const struct bp_location *bl,
13727                            struct address_space *aspace, CORE_ADDR bp_addr,
13728                            const struct target_waitstatus *ws)
13729 {
13730   /* By definition, the inferior does not report stops at
13731      tracepoints.  */
13732   return 0;
13733 }
13734
13735 static void
13736 tracepoint_print_one_detail (const struct breakpoint *self,
13737                              struct ui_out *uiout)
13738 {
13739   struct tracepoint *tp = (struct tracepoint *) self;
13740   if (tp->static_trace_marker_id)
13741     {
13742       gdb_assert (self->type == bp_static_tracepoint);
13743
13744       ui_out_text (uiout, "\tmarker id is ");
13745       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13746                            tp->static_trace_marker_id);
13747       ui_out_text (uiout, "\n");
13748     }
13749 }
13750
13751 static void
13752 tracepoint_print_mention (struct breakpoint *b)
13753 {
13754   if (ui_out_is_mi_like_p (current_uiout))
13755     return;
13756
13757   switch (b->type)
13758     {
13759     case bp_tracepoint:
13760       printf_filtered (_("Tracepoint"));
13761       printf_filtered (_(" %d"), b->number);
13762       break;
13763     case bp_fast_tracepoint:
13764       printf_filtered (_("Fast tracepoint"));
13765       printf_filtered (_(" %d"), b->number);
13766       break;
13767     case bp_static_tracepoint:
13768       printf_filtered (_("Static tracepoint"));
13769       printf_filtered (_(" %d"), b->number);
13770       break;
13771     default:
13772       internal_error (__FILE__, __LINE__,
13773                       _("unhandled tracepoint type %d"), (int) b->type);
13774     }
13775
13776   say_where (b);
13777 }
13778
13779 static void
13780 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13781 {
13782   struct tracepoint *tp = (struct tracepoint *) self;
13783
13784   if (self->type == bp_fast_tracepoint)
13785     fprintf_unfiltered (fp, "ftrace");
13786   if (self->type == bp_static_tracepoint)
13787     fprintf_unfiltered (fp, "strace");
13788   else if (self->type == bp_tracepoint)
13789     fprintf_unfiltered (fp, "trace");
13790   else
13791     internal_error (__FILE__, __LINE__,
13792                     _("unhandled tracepoint type %d"), (int) self->type);
13793
13794   fprintf_unfiltered (fp, " %s", self->addr_string);
13795   print_recreate_thread (self, fp);
13796
13797   if (tp->pass_count)
13798     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13799 }
13800
13801 static void
13802 tracepoint_create_sals_from_address (char **arg,
13803                                      struct linespec_result *canonical,
13804                                      enum bptype type_wanted,
13805                                      char *addr_start, char **copy_arg)
13806 {
13807   create_sals_from_address_default (arg, canonical, type_wanted,
13808                                     addr_start, copy_arg);
13809 }
13810
13811 static void
13812 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13813                                    struct linespec_result *canonical,
13814                                    char *cond_string,
13815                                    char *extra_string,
13816                                    enum bptype type_wanted,
13817                                    enum bpdisp disposition,
13818                                    int thread,
13819                                    int task, int ignore_count,
13820                                    const struct breakpoint_ops *ops,
13821                                    int from_tty, int enabled,
13822                                    int internal, unsigned flags)
13823 {
13824   create_breakpoints_sal_default (gdbarch, canonical,
13825                                   cond_string, extra_string,
13826                                   type_wanted,
13827                                   disposition, thread, task,
13828                                   ignore_count, ops, from_tty,
13829                                   enabled, internal, flags);
13830 }
13831
13832 static void
13833 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13834                             struct symtabs_and_lines *sals)
13835 {
13836   decode_linespec_default (b, s, sals);
13837 }
13838
13839 struct breakpoint_ops tracepoint_breakpoint_ops;
13840
13841 /* The breakpoint_ops structure to be use on tracepoints placed in a
13842    static probe.  */
13843
13844 static void
13845 tracepoint_probe_create_sals_from_address (char **arg,
13846                                            struct linespec_result *canonical,
13847                                            enum bptype type_wanted,
13848                                            char *addr_start, char **copy_arg)
13849 {
13850   /* We use the same method for breakpoint on probes.  */
13851   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13852                                        addr_start, copy_arg);
13853 }
13854
13855 static void
13856 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13857                                   struct symtabs_and_lines *sals)
13858 {
13859   /* We use the same method for breakpoint on probes.  */
13860   bkpt_probe_decode_linespec (b, s, sals);
13861 }
13862
13863 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13864
13865 /* Dprintf breakpoint_ops methods.  */
13866
13867 static void
13868 dprintf_re_set (struct breakpoint *b)
13869 {
13870   breakpoint_re_set_default (b);
13871
13872   /* This breakpoint could have been pending, and be resolved now, and
13873      if so, we should now have the extra string.  If we don't, the
13874      dprintf was malformed when created, but we couldn't tell because
13875      we can't extract the extra string until the location is
13876      resolved.  */
13877   if (b->loc != NULL && b->extra_string == NULL)
13878     error (_("Format string required"));
13879
13880   /* 1 - connect to target 1, that can run breakpoint commands.
13881      2 - create a dprintf, which resolves fine.
13882      3 - disconnect from target 1
13883      4 - connect to target 2, that can NOT run breakpoint commands.
13884
13885      After steps #3/#4, you'll want the dprintf command list to
13886      be updated, because target 1 and 2 may well return different
13887      answers for target_can_run_breakpoint_commands().
13888      Given absence of finer grained resetting, we get to do
13889      it all the time.  */
13890   if (b->extra_string != NULL)
13891     update_dprintf_command_list (b);
13892 }
13893
13894 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13895
13896 static void
13897 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13898 {
13899   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13900                       tp->extra_string);
13901   print_recreate_thread (tp, fp);
13902 }
13903
13904 /* Implement the "after_condition_true" breakpoint_ops method for
13905    dprintf.
13906
13907    dprintf's are implemented with regular commands in their command
13908    list, but we run the commands here instead of before presenting the
13909    stop to the user, as dprintf's don't actually cause a stop.  This
13910    also makes it so that the commands of multiple dprintfs at the same
13911    address are all handled.  */
13912
13913 static void
13914 dprintf_after_condition_true (struct bpstats *bs)
13915 {
13916   struct cleanup *old_chain;
13917   struct bpstats tmp_bs = { NULL };
13918   struct bpstats *tmp_bs_p = &tmp_bs;
13919
13920   /* dprintf's never cause a stop.  This wasn't set in the
13921      check_status hook instead because that would make the dprintf's
13922      condition not be evaluated.  */
13923   bs->stop = 0;
13924
13925   /* Run the command list here.  Take ownership of it instead of
13926      copying.  We never want these commands to run later in
13927      bpstat_do_actions, if a breakpoint that causes a stop happens to
13928      be set at same address as this dprintf, or even if running the
13929      commands here throws.  */
13930   tmp_bs.commands = bs->commands;
13931   bs->commands = NULL;
13932   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13933
13934   bpstat_do_actions_1 (&tmp_bs_p);
13935
13936   /* 'tmp_bs.commands' will usually be NULL by now, but
13937      bpstat_do_actions_1 may return early without processing the whole
13938      list.  */
13939   do_cleanups (old_chain);
13940 }
13941
13942 /* The breakpoint_ops structure to be used on static tracepoints with
13943    markers (`-m').  */
13944
13945 static void
13946 strace_marker_create_sals_from_address (char **arg,
13947                                         struct linespec_result *canonical,
13948                                         enum bptype type_wanted,
13949                                         char *addr_start, char **copy_arg)
13950 {
13951   struct linespec_sals lsal;
13952
13953   lsal.sals = decode_static_tracepoint_spec (arg);
13954
13955   *copy_arg = savestring (addr_start, *arg - addr_start);
13956
13957   canonical->addr_string = xstrdup (*copy_arg);
13958   lsal.canonical = xstrdup (*copy_arg);
13959   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13960 }
13961
13962 static void
13963 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13964                                       struct linespec_result *canonical,
13965                                       char *cond_string,
13966                                       char *extra_string,
13967                                       enum bptype type_wanted,
13968                                       enum bpdisp disposition,
13969                                       int thread,
13970                                       int task, int ignore_count,
13971                                       const struct breakpoint_ops *ops,
13972                                       int from_tty, int enabled,
13973                                       int internal, unsigned flags)
13974 {
13975   int i;
13976   struct linespec_sals *lsal = VEC_index (linespec_sals,
13977                                           canonical->sals, 0);
13978
13979   /* If the user is creating a static tracepoint by marker id
13980      (strace -m MARKER_ID), then store the sals index, so that
13981      breakpoint_re_set can try to match up which of the newly
13982      found markers corresponds to this one, and, don't try to
13983      expand multiple locations for each sal, given than SALS
13984      already should contain all sals for MARKER_ID.  */
13985
13986   for (i = 0; i < lsal->sals.nelts; ++i)
13987     {
13988       struct symtabs_and_lines expanded;
13989       struct tracepoint *tp;
13990       struct cleanup *old_chain;
13991       char *addr_string;
13992
13993       expanded.nelts = 1;
13994       expanded.sals = &lsal->sals.sals[i];
13995
13996       addr_string = xstrdup (canonical->addr_string);
13997       old_chain = make_cleanup (xfree, addr_string);
13998
13999       tp = XCNEW (struct tracepoint);
14000       init_breakpoint_sal (&tp->base, gdbarch, expanded,
14001                            addr_string, NULL,
14002                            cond_string, extra_string,
14003                            type_wanted, disposition,
14004                            thread, task, ignore_count, ops,
14005                            from_tty, enabled, internal, flags,
14006                            canonical->special_display);
14007       /* Given that its possible to have multiple markers with
14008          the same string id, if the user is creating a static
14009          tracepoint by marker id ("strace -m MARKER_ID"), then
14010          store the sals index, so that breakpoint_re_set can
14011          try to match up which of the newly found markers
14012          corresponds to this one  */
14013       tp->static_trace_marker_id_idx = i;
14014
14015       install_breakpoint (internal, &tp->base, 0);
14016
14017       discard_cleanups (old_chain);
14018     }
14019 }
14020
14021 static void
14022 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14023                                struct symtabs_and_lines *sals)
14024 {
14025   struct tracepoint *tp = (struct tracepoint *) b;
14026
14027   *sals = decode_static_tracepoint_spec (s);
14028   if (sals->nelts > tp->static_trace_marker_id_idx)
14029     {
14030       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14031       sals->nelts = 1;
14032     }
14033   else
14034     error (_("marker %s not found"), tp->static_trace_marker_id);
14035 }
14036
14037 static struct breakpoint_ops strace_marker_breakpoint_ops;
14038
14039 static int
14040 strace_marker_p (struct breakpoint *b)
14041 {
14042   return b->ops == &strace_marker_breakpoint_ops;
14043 }
14044
14045 /* Delete a breakpoint and clean up all traces of it in the data
14046    structures.  */
14047
14048 void
14049 delete_breakpoint (struct breakpoint *bpt)
14050 {
14051   struct breakpoint *b;
14052
14053   gdb_assert (bpt != NULL);
14054
14055   /* Has this bp already been deleted?  This can happen because
14056      multiple lists can hold pointers to bp's.  bpstat lists are
14057      especial culprits.
14058
14059      One example of this happening is a watchpoint's scope bp.  When
14060      the scope bp triggers, we notice that the watchpoint is out of
14061      scope, and delete it.  We also delete its scope bp.  But the
14062      scope bp is marked "auto-deleting", and is already on a bpstat.
14063      That bpstat is then checked for auto-deleting bp's, which are
14064      deleted.
14065
14066      A real solution to this problem might involve reference counts in
14067      bp's, and/or giving them pointers back to their referencing
14068      bpstat's, and teaching delete_breakpoint to only free a bp's
14069      storage when no more references were extent.  A cheaper bandaid
14070      was chosen.  */
14071   if (bpt->type == bp_none)
14072     return;
14073
14074   /* At least avoid this stale reference until the reference counting
14075      of breakpoints gets resolved.  */
14076   if (bpt->related_breakpoint != bpt)
14077     {
14078       struct breakpoint *related;
14079       struct watchpoint *w;
14080
14081       if (bpt->type == bp_watchpoint_scope)
14082         w = (struct watchpoint *) bpt->related_breakpoint;
14083       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14084         w = (struct watchpoint *) bpt;
14085       else
14086         w = NULL;
14087       if (w != NULL)
14088         watchpoint_del_at_next_stop (w);
14089
14090       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14091       for (related = bpt; related->related_breakpoint != bpt;
14092            related = related->related_breakpoint);
14093       related->related_breakpoint = bpt->related_breakpoint;
14094       bpt->related_breakpoint = bpt;
14095     }
14096
14097   /* watch_command_1 creates a watchpoint but only sets its number if
14098      update_watchpoint succeeds in creating its bp_locations.  If there's
14099      a problem in that process, we'll be asked to delete the half-created
14100      watchpoint.  In that case, don't announce the deletion.  */
14101   if (bpt->number)
14102     observer_notify_breakpoint_deleted (bpt);
14103
14104   if (breakpoint_chain == bpt)
14105     breakpoint_chain = bpt->next;
14106
14107   ALL_BREAKPOINTS (b)
14108     if (b->next == bpt)
14109     {
14110       b->next = bpt->next;
14111       break;
14112     }
14113
14114   /* Be sure no bpstat's are pointing at the breakpoint after it's
14115      been freed.  */
14116   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14117      in all threads for now.  Note that we cannot just remove bpstats
14118      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14119      commands are associated with the bpstat; if we remove it here,
14120      then the later call to bpstat_do_actions (&stop_bpstat); in
14121      event-top.c won't do anything, and temporary breakpoints with
14122      commands won't work.  */
14123
14124   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14125
14126   /* Now that breakpoint is removed from breakpoint list, update the
14127      global location list.  This will remove locations that used to
14128      belong to this breakpoint.  Do this before freeing the breakpoint
14129      itself, since remove_breakpoint looks at location's owner.  It
14130      might be better design to have location completely
14131      self-contained, but it's not the case now.  */
14132   update_global_location_list (UGLL_DONT_INSERT);
14133
14134   bpt->ops->dtor (bpt);
14135   /* On the chance that someone will soon try again to delete this
14136      same bp, we mark it as deleted before freeing its storage.  */
14137   bpt->type = bp_none;
14138   xfree (bpt);
14139 }
14140
14141 static void
14142 do_delete_breakpoint_cleanup (void *b)
14143 {
14144   delete_breakpoint (b);
14145 }
14146
14147 struct cleanup *
14148 make_cleanup_delete_breakpoint (struct breakpoint *b)
14149 {
14150   return make_cleanup (do_delete_breakpoint_cleanup, b);
14151 }
14152
14153 /* Iterator function to call a user-provided callback function once
14154    for each of B and its related breakpoints.  */
14155
14156 static void
14157 iterate_over_related_breakpoints (struct breakpoint *b,
14158                                   void (*function) (struct breakpoint *,
14159                                                     void *),
14160                                   void *data)
14161 {
14162   struct breakpoint *related;
14163
14164   related = b;
14165   do
14166     {
14167       struct breakpoint *next;
14168
14169       /* FUNCTION may delete RELATED.  */
14170       next = related->related_breakpoint;
14171
14172       if (next == related)
14173         {
14174           /* RELATED is the last ring entry.  */
14175           function (related, data);
14176
14177           /* FUNCTION may have deleted it, so we'd never reach back to
14178              B.  There's nothing left to do anyway, so just break
14179              out.  */
14180           break;
14181         }
14182       else
14183         function (related, data);
14184
14185       related = next;
14186     }
14187   while (related != b);
14188 }
14189
14190 static void
14191 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14192 {
14193   delete_breakpoint (b);
14194 }
14195
14196 /* A callback for map_breakpoint_numbers that calls
14197    delete_breakpoint.  */
14198
14199 static void
14200 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14201 {
14202   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14203 }
14204
14205 void
14206 delete_command (char *arg, int from_tty)
14207 {
14208   struct breakpoint *b, *b_tmp;
14209
14210   dont_repeat ();
14211
14212   if (arg == 0)
14213     {
14214       int breaks_to_delete = 0;
14215
14216       /* Delete all breakpoints if no argument.  Do not delete
14217          internal breakpoints, these have to be deleted with an
14218          explicit breakpoint number argument.  */
14219       ALL_BREAKPOINTS (b)
14220         if (user_breakpoint_p (b))
14221           {
14222             breaks_to_delete = 1;
14223             break;
14224           }
14225
14226       /* Ask user only if there are some breakpoints to delete.  */
14227       if (!from_tty
14228           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14229         {
14230           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14231             if (user_breakpoint_p (b))
14232               delete_breakpoint (b);
14233         }
14234     }
14235   else
14236     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14237 }
14238
14239 static int
14240 all_locations_are_pending (struct bp_location *loc)
14241 {
14242   for (; loc; loc = loc->next)
14243     if (!loc->shlib_disabled
14244         && !loc->pspace->executing_startup)
14245       return 0;
14246   return 1;
14247 }
14248
14249 /* Subroutine of update_breakpoint_locations to simplify it.
14250    Return non-zero if multiple fns in list LOC have the same name.
14251    Null names are ignored.  */
14252
14253 static int
14254 ambiguous_names_p (struct bp_location *loc)
14255 {
14256   struct bp_location *l;
14257   htab_t htab = htab_create_alloc (13, htab_hash_string,
14258                                    (int (*) (const void *, 
14259                                              const void *)) streq,
14260                                    NULL, xcalloc, xfree);
14261
14262   for (l = loc; l != NULL; l = l->next)
14263     {
14264       const char **slot;
14265       const char *name = l->function_name;
14266
14267       /* Allow for some names to be NULL, ignore them.  */
14268       if (name == NULL)
14269         continue;
14270
14271       slot = (const char **) htab_find_slot (htab, (const void *) name,
14272                                              INSERT);
14273       /* NOTE: We can assume slot != NULL here because xcalloc never
14274          returns NULL.  */
14275       if (*slot != NULL)
14276         {
14277           htab_delete (htab);
14278           return 1;
14279         }
14280       *slot = name;
14281     }
14282
14283   htab_delete (htab);
14284   return 0;
14285 }
14286
14287 /* When symbols change, it probably means the sources changed as well,
14288    and it might mean the static tracepoint markers are no longer at
14289    the same address or line numbers they used to be at last we
14290    checked.  Losing your static tracepoints whenever you rebuild is
14291    undesirable.  This function tries to resync/rematch gdb static
14292    tracepoints with the markers on the target, for static tracepoints
14293    that have not been set by marker id.  Static tracepoint that have
14294    been set by marker id are reset by marker id in breakpoint_re_set.
14295    The heuristic is:
14296
14297    1) For a tracepoint set at a specific address, look for a marker at
14298    the old PC.  If one is found there, assume to be the same marker.
14299    If the name / string id of the marker found is different from the
14300    previous known name, assume that means the user renamed the marker
14301    in the sources, and output a warning.
14302
14303    2) For a tracepoint set at a given line number, look for a marker
14304    at the new address of the old line number.  If one is found there,
14305    assume to be the same marker.  If the name / string id of the
14306    marker found is different from the previous known name, assume that
14307    means the user renamed the marker in the sources, and output a
14308    warning.
14309
14310    3) If a marker is no longer found at the same address or line, it
14311    may mean the marker no longer exists.  But it may also just mean
14312    the code changed a bit.  Maybe the user added a few lines of code
14313    that made the marker move up or down (in line number terms).  Ask
14314    the target for info about the marker with the string id as we knew
14315    it.  If found, update line number and address in the matching
14316    static tracepoint.  This will get confused if there's more than one
14317    marker with the same ID (possible in UST, although unadvised
14318    precisely because it confuses tools).  */
14319
14320 static struct symtab_and_line
14321 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14322 {
14323   struct tracepoint *tp = (struct tracepoint *) b;
14324   struct static_tracepoint_marker marker;
14325   CORE_ADDR pc;
14326
14327   pc = sal.pc;
14328   if (sal.line)
14329     find_line_pc (sal.symtab, sal.line, &pc);
14330
14331   if (target_static_tracepoint_marker_at (pc, &marker))
14332     {
14333       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14334         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14335                  b->number,
14336                  tp->static_trace_marker_id, marker.str_id);
14337
14338       xfree (tp->static_trace_marker_id);
14339       tp->static_trace_marker_id = xstrdup (marker.str_id);
14340       release_static_tracepoint_marker (&marker);
14341
14342       return sal;
14343     }
14344
14345   /* Old marker wasn't found on target at lineno.  Try looking it up
14346      by string ID.  */
14347   if (!sal.explicit_pc
14348       && sal.line != 0
14349       && sal.symtab != NULL
14350       && tp->static_trace_marker_id != NULL)
14351     {
14352       VEC(static_tracepoint_marker_p) *markers;
14353
14354       markers
14355         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14356
14357       if (!VEC_empty(static_tracepoint_marker_p, markers))
14358         {
14359           struct symtab_and_line sal2;
14360           struct symbol *sym;
14361           struct static_tracepoint_marker *tpmarker;
14362           struct ui_out *uiout = current_uiout;
14363
14364           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14365
14366           xfree (tp->static_trace_marker_id);
14367           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14368
14369           warning (_("marker for static tracepoint %d (%s) not "
14370                      "found at previous line number"),
14371                    b->number, tp->static_trace_marker_id);
14372
14373           init_sal (&sal2);
14374
14375           sal2.pc = tpmarker->address;
14376
14377           sal2 = find_pc_line (tpmarker->address, 0);
14378           sym = find_pc_sect_function (tpmarker->address, NULL);
14379           ui_out_text (uiout, "Now in ");
14380           if (sym)
14381             {
14382               ui_out_field_string (uiout, "func",
14383                                    SYMBOL_PRINT_NAME (sym));
14384               ui_out_text (uiout, " at ");
14385             }
14386           ui_out_field_string (uiout, "file",
14387                                symtab_to_filename_for_display (sal2.symtab));
14388           ui_out_text (uiout, ":");
14389
14390           if (ui_out_is_mi_like_p (uiout))
14391             {
14392               const char *fullname = symtab_to_fullname (sal2.symtab);
14393
14394               ui_out_field_string (uiout, "fullname", fullname);
14395             }
14396
14397           ui_out_field_int (uiout, "line", sal2.line);
14398           ui_out_text (uiout, "\n");
14399
14400           b->loc->line_number = sal2.line;
14401           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14402
14403           xfree (b->addr_string);
14404           b->addr_string = xstrprintf ("%s:%d",
14405                                    symtab_to_filename_for_display (sal2.symtab),
14406                                        b->loc->line_number);
14407
14408           /* Might be nice to check if function changed, and warn if
14409              so.  */
14410
14411           release_static_tracepoint_marker (tpmarker);
14412         }
14413     }
14414   return sal;
14415 }
14416
14417 /* Returns 1 iff locations A and B are sufficiently same that
14418    we don't need to report breakpoint as changed.  */
14419
14420 static int
14421 locations_are_equal (struct bp_location *a, struct bp_location *b)
14422 {
14423   while (a && b)
14424     {
14425       if (a->address != b->address)
14426         return 0;
14427
14428       if (a->shlib_disabled != b->shlib_disabled)
14429         return 0;
14430
14431       if (a->enabled != b->enabled)
14432         return 0;
14433
14434       a = a->next;
14435       b = b->next;
14436     }
14437
14438   if ((a == NULL) != (b == NULL))
14439     return 0;
14440
14441   return 1;
14442 }
14443
14444 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14445    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14446    a ranged breakpoint.  */
14447
14448 void
14449 update_breakpoint_locations (struct breakpoint *b,
14450                              struct symtabs_and_lines sals,
14451                              struct symtabs_and_lines sals_end)
14452 {
14453   int i;
14454   struct bp_location *existing_locations = b->loc;
14455
14456   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14457     {
14458       /* Ranged breakpoints have only one start location and one end
14459          location.  */
14460       b->enable_state = bp_disabled;
14461       update_global_location_list (UGLL_MAY_INSERT);
14462       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14463                            "multiple locations found\n"),
14464                          b->number);
14465       return;
14466     }
14467
14468   /* If there's no new locations, and all existing locations are
14469      pending, don't do anything.  This optimizes the common case where
14470      all locations are in the same shared library, that was unloaded.
14471      We'd like to retain the location, so that when the library is
14472      loaded again, we don't loose the enabled/disabled status of the
14473      individual locations.  */
14474   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14475     return;
14476
14477   b->loc = NULL;
14478
14479   for (i = 0; i < sals.nelts; ++i)
14480     {
14481       struct bp_location *new_loc;
14482
14483       switch_to_program_space_and_thread (sals.sals[i].pspace);
14484
14485       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14486
14487       /* Reparse conditions, they might contain references to the
14488          old symtab.  */
14489       if (b->cond_string != NULL)
14490         {
14491           const char *s;
14492           volatile struct gdb_exception e;
14493
14494           s = b->cond_string;
14495           TRY_CATCH (e, RETURN_MASK_ERROR)
14496             {
14497               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14498                                            block_for_pc (sals.sals[i].pc), 
14499                                            0);
14500             }
14501           if (e.reason < 0)
14502             {
14503               warning (_("failed to reevaluate condition "
14504                          "for breakpoint %d: %s"), 
14505                        b->number, e.message);
14506               new_loc->enabled = 0;
14507             }
14508         }
14509
14510       if (sals_end.nelts)
14511         {
14512           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14513
14514           new_loc->length = end - sals.sals[0].pc + 1;
14515         }
14516     }
14517
14518   /* Update locations of permanent breakpoints.  */
14519   if (b->enable_state == bp_permanent)
14520     make_breakpoint_permanent (b);
14521
14522   /* If possible, carry over 'disable' status from existing
14523      breakpoints.  */
14524   {
14525     struct bp_location *e = existing_locations;
14526     /* If there are multiple breakpoints with the same function name,
14527        e.g. for inline functions, comparing function names won't work.
14528        Instead compare pc addresses; this is just a heuristic as things
14529        may have moved, but in practice it gives the correct answer
14530        often enough until a better solution is found.  */
14531     int have_ambiguous_names = ambiguous_names_p (b->loc);
14532
14533     for (; e; e = e->next)
14534       {
14535         if (!e->enabled && e->function_name)
14536           {
14537             struct bp_location *l = b->loc;
14538             if (have_ambiguous_names)
14539               {
14540                 for (; l; l = l->next)
14541                   if (breakpoint_locations_match (e, l))
14542                     {
14543                       l->enabled = 0;
14544                       break;
14545                     }
14546               }
14547             else
14548               {
14549                 for (; l; l = l->next)
14550                   if (l->function_name
14551                       && strcmp (e->function_name, l->function_name) == 0)
14552                     {
14553                       l->enabled = 0;
14554                       break;
14555                     }
14556               }
14557           }
14558       }
14559   }
14560
14561   if (!locations_are_equal (existing_locations, b->loc))
14562     observer_notify_breakpoint_modified (b);
14563
14564   update_global_location_list (UGLL_MAY_INSERT);
14565 }
14566
14567 /* Find the SaL locations corresponding to the given ADDR_STRING.
14568    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14569
14570 static struct symtabs_and_lines
14571 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14572 {
14573   char *s;
14574   struct symtabs_and_lines sals = {0};
14575   volatile struct gdb_exception e;
14576
14577   gdb_assert (b->ops != NULL);
14578   s = addr_string;
14579
14580   TRY_CATCH (e, RETURN_MASK_ERROR)
14581     {
14582       b->ops->decode_linespec (b, &s, &sals);
14583     }
14584   if (e.reason < 0)
14585     {
14586       int not_found_and_ok = 0;
14587       /* For pending breakpoints, it's expected that parsing will
14588          fail until the right shared library is loaded.  User has
14589          already told to create pending breakpoints and don't need
14590          extra messages.  If breakpoint is in bp_shlib_disabled
14591          state, then user already saw the message about that
14592          breakpoint being disabled, and don't want to see more
14593          errors.  */
14594       if (e.error == NOT_FOUND_ERROR
14595           && (b->condition_not_parsed 
14596               || (b->loc && b->loc->shlib_disabled)
14597               || (b->loc && b->loc->pspace->executing_startup)
14598               || b->enable_state == bp_disabled))
14599         not_found_and_ok = 1;
14600
14601       if (!not_found_and_ok)
14602         {
14603           /* We surely don't want to warn about the same breakpoint
14604              10 times.  One solution, implemented here, is disable
14605              the breakpoint on error.  Another solution would be to
14606              have separate 'warning emitted' flag.  Since this
14607              happens only when a binary has changed, I don't know
14608              which approach is better.  */
14609           b->enable_state = bp_disabled;
14610           throw_exception (e);
14611         }
14612     }
14613
14614   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14615     {
14616       int i;
14617
14618       for (i = 0; i < sals.nelts; ++i)
14619         resolve_sal_pc (&sals.sals[i]);
14620       if (b->condition_not_parsed && s && s[0])
14621         {
14622           char *cond_string, *extra_string;
14623           int thread, task;
14624
14625           find_condition_and_thread (s, sals.sals[0].pc,
14626                                      &cond_string, &thread, &task,
14627                                      &extra_string);
14628           if (cond_string)
14629             b->cond_string = cond_string;
14630           b->thread = thread;
14631           b->task = task;
14632           if (extra_string)
14633             b->extra_string = extra_string;
14634           b->condition_not_parsed = 0;
14635         }
14636
14637       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14638         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14639
14640       *found = 1;
14641     }
14642   else
14643     *found = 0;
14644
14645   return sals;
14646 }
14647
14648 /* The default re_set method, for typical hardware or software
14649    breakpoints.  Reevaluate the breakpoint and recreate its
14650    locations.  */
14651
14652 static void
14653 breakpoint_re_set_default (struct breakpoint *b)
14654 {
14655   int found;
14656   struct symtabs_and_lines sals, sals_end;
14657   struct symtabs_and_lines expanded = {0};
14658   struct symtabs_and_lines expanded_end = {0};
14659
14660   sals = addr_string_to_sals (b, b->addr_string, &found);
14661   if (found)
14662     {
14663       make_cleanup (xfree, sals.sals);
14664       expanded = sals;
14665     }
14666
14667   if (b->addr_string_range_end)
14668     {
14669       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14670       if (found)
14671         {
14672           make_cleanup (xfree, sals_end.sals);
14673           expanded_end = sals_end;
14674         }
14675     }
14676
14677   update_breakpoint_locations (b, expanded, expanded_end);
14678 }
14679
14680 /* Default method for creating SALs from an address string.  It basically
14681    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14682
14683 static void
14684 create_sals_from_address_default (char **arg,
14685                                   struct linespec_result *canonical,
14686                                   enum bptype type_wanted,
14687                                   char *addr_start, char **copy_arg)
14688 {
14689   parse_breakpoint_sals (arg, canonical);
14690 }
14691
14692 /* Call create_breakpoints_sal for the given arguments.  This is the default
14693    function for the `create_breakpoints_sal' method of
14694    breakpoint_ops.  */
14695
14696 static void
14697 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14698                                 struct linespec_result *canonical,
14699                                 char *cond_string,
14700                                 char *extra_string,
14701                                 enum bptype type_wanted,
14702                                 enum bpdisp disposition,
14703                                 int thread,
14704                                 int task, int ignore_count,
14705                                 const struct breakpoint_ops *ops,
14706                                 int from_tty, int enabled,
14707                                 int internal, unsigned flags)
14708 {
14709   create_breakpoints_sal (gdbarch, canonical, cond_string,
14710                           extra_string,
14711                           type_wanted, disposition,
14712                           thread, task, ignore_count, ops, from_tty,
14713                           enabled, internal, flags);
14714 }
14715
14716 /* Decode the line represented by S by calling decode_line_full.  This is the
14717    default function for the `decode_linespec' method of breakpoint_ops.  */
14718
14719 static void
14720 decode_linespec_default (struct breakpoint *b, char **s,
14721                          struct symtabs_and_lines *sals)
14722 {
14723   struct linespec_result canonical;
14724
14725   init_linespec_result (&canonical);
14726   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14727                     (struct symtab *) NULL, 0,
14728                     &canonical, multiple_symbols_all,
14729                     b->filter);
14730
14731   /* We should get 0 or 1 resulting SALs.  */
14732   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14733
14734   if (VEC_length (linespec_sals, canonical.sals) > 0)
14735     {
14736       struct linespec_sals *lsal;
14737
14738       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14739       *sals = lsal->sals;
14740       /* Arrange it so the destructor does not free the
14741          contents.  */
14742       lsal->sals.sals = NULL;
14743     }
14744
14745   destroy_linespec_result (&canonical);
14746 }
14747
14748 /* Prepare the global context for a re-set of breakpoint B.  */
14749
14750 static struct cleanup *
14751 prepare_re_set_context (struct breakpoint *b)
14752 {
14753   struct cleanup *cleanups;
14754
14755   input_radix = b->input_radix;
14756   cleanups = save_current_space_and_thread ();
14757   if (b->pspace != NULL)
14758     switch_to_program_space_and_thread (b->pspace);
14759   set_language (b->language);
14760
14761   return cleanups;
14762 }
14763
14764 /* Reset a breakpoint given it's struct breakpoint * BINT.
14765    The value we return ends up being the return value from catch_errors.
14766    Unused in this case.  */
14767
14768 static int
14769 breakpoint_re_set_one (void *bint)
14770 {
14771   /* Get past catch_errs.  */
14772   struct breakpoint *b = (struct breakpoint *) bint;
14773   struct cleanup *cleanups;
14774
14775   cleanups = prepare_re_set_context (b);
14776   b->ops->re_set (b);
14777   do_cleanups (cleanups);
14778   return 0;
14779 }
14780
14781 /* Re-set all breakpoints after symbols have been re-loaded.  */
14782 void
14783 breakpoint_re_set (void)
14784 {
14785   struct breakpoint *b, *b_tmp;
14786   enum language save_language;
14787   int save_input_radix;
14788   struct cleanup *old_chain;
14789
14790   save_language = current_language->la_language;
14791   save_input_radix = input_radix;
14792   old_chain = save_current_program_space ();
14793
14794   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14795   {
14796     /* Format possible error msg.  */
14797     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14798                                 b->number);
14799     struct cleanup *cleanups = make_cleanup (xfree, message);
14800     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14801     do_cleanups (cleanups);
14802   }
14803   set_language (save_language);
14804   input_radix = save_input_radix;
14805
14806   jit_breakpoint_re_set ();
14807
14808   do_cleanups (old_chain);
14809
14810   create_overlay_event_breakpoint ();
14811   create_longjmp_master_breakpoint ();
14812   create_std_terminate_master_breakpoint ();
14813   create_exception_master_breakpoint ();
14814 }
14815 \f
14816 /* Reset the thread number of this breakpoint:
14817
14818    - If the breakpoint is for all threads, leave it as-is.
14819    - Else, reset it to the current thread for inferior_ptid.  */
14820 void
14821 breakpoint_re_set_thread (struct breakpoint *b)
14822 {
14823   if (b->thread != -1)
14824     {
14825       if (in_thread_list (inferior_ptid))
14826         b->thread = pid_to_thread_id (inferior_ptid);
14827
14828       /* We're being called after following a fork.  The new fork is
14829          selected as current, and unless this was a vfork will have a
14830          different program space from the original thread.  Reset that
14831          as well.  */
14832       b->loc->pspace = current_program_space;
14833     }
14834 }
14835
14836 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14837    If from_tty is nonzero, it prints a message to that effect,
14838    which ends with a period (no newline).  */
14839
14840 void
14841 set_ignore_count (int bptnum, int count, int from_tty)
14842 {
14843   struct breakpoint *b;
14844
14845   if (count < 0)
14846     count = 0;
14847
14848   ALL_BREAKPOINTS (b)
14849     if (b->number == bptnum)
14850     {
14851       if (is_tracepoint (b))
14852         {
14853           if (from_tty && count != 0)
14854             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14855                              bptnum);
14856           return;
14857         }
14858       
14859       b->ignore_count = count;
14860       if (from_tty)
14861         {
14862           if (count == 0)
14863             printf_filtered (_("Will stop next time "
14864                                "breakpoint %d is reached."),
14865                              bptnum);
14866           else if (count == 1)
14867             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14868                              bptnum);
14869           else
14870             printf_filtered (_("Will ignore next %d "
14871                                "crossings of breakpoint %d."),
14872                              count, bptnum);
14873         }
14874       observer_notify_breakpoint_modified (b);
14875       return;
14876     }
14877
14878   error (_("No breakpoint number %d."), bptnum);
14879 }
14880
14881 /* Command to set ignore-count of breakpoint N to COUNT.  */
14882
14883 static void
14884 ignore_command (char *args, int from_tty)
14885 {
14886   char *p = args;
14887   int num;
14888
14889   if (p == 0)
14890     error_no_arg (_("a breakpoint number"));
14891
14892   num = get_number (&p);
14893   if (num == 0)
14894     error (_("bad breakpoint number: '%s'"), args);
14895   if (*p == 0)
14896     error (_("Second argument (specified ignore-count) is missing."));
14897
14898   set_ignore_count (num,
14899                     longest_to_int (value_as_long (parse_and_eval (p))),
14900                     from_tty);
14901   if (from_tty)
14902     printf_filtered ("\n");
14903 }
14904 \f
14905 /* Call FUNCTION on each of the breakpoints
14906    whose numbers are given in ARGS.  */
14907
14908 static void
14909 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14910                                                       void *),
14911                         void *data)
14912 {
14913   int num;
14914   struct breakpoint *b, *tmp;
14915   int match;
14916   struct get_number_or_range_state state;
14917
14918   if (args == 0)
14919     error_no_arg (_("one or more breakpoint numbers"));
14920
14921   init_number_or_range (&state, args);
14922
14923   while (!state.finished)
14924     {
14925       const char *p = state.string;
14926
14927       match = 0;
14928
14929       num = get_number_or_range (&state);
14930       if (num == 0)
14931         {
14932           warning (_("bad breakpoint number at or near '%s'"), p);
14933         }
14934       else
14935         {
14936           ALL_BREAKPOINTS_SAFE (b, tmp)
14937             if (b->number == num)
14938               {
14939                 match = 1;
14940                 function (b, data);
14941                 break;
14942               }
14943           if (match == 0)
14944             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14945         }
14946     }
14947 }
14948
14949 static struct bp_location *
14950 find_location_by_number (char *number)
14951 {
14952   char *dot = strchr (number, '.');
14953   char *p1;
14954   int bp_num;
14955   int loc_num;
14956   struct breakpoint *b;
14957   struct bp_location *loc;  
14958
14959   *dot = '\0';
14960
14961   p1 = number;
14962   bp_num = get_number (&p1);
14963   if (bp_num == 0)
14964     error (_("Bad breakpoint number '%s'"), number);
14965
14966   ALL_BREAKPOINTS (b)
14967     if (b->number == bp_num)
14968       {
14969         break;
14970       }
14971
14972   if (!b || b->number != bp_num)
14973     error (_("Bad breakpoint number '%s'"), number);
14974   
14975   p1 = dot+1;
14976   loc_num = get_number (&p1);
14977   if (loc_num == 0)
14978     error (_("Bad breakpoint location number '%s'"), number);
14979
14980   --loc_num;
14981   loc = b->loc;
14982   for (;loc_num && loc; --loc_num, loc = loc->next)
14983     ;
14984   if (!loc)
14985     error (_("Bad breakpoint location number '%s'"), dot+1);
14986     
14987   return loc;  
14988 }
14989
14990
14991 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14992    If from_tty is nonzero, it prints a message to that effect,
14993    which ends with a period (no newline).  */
14994
14995 void
14996 disable_breakpoint (struct breakpoint *bpt)
14997 {
14998   /* Never disable a watchpoint scope breakpoint; we want to
14999      hit them when we leave scope so we can delete both the
15000      watchpoint and its scope breakpoint at that time.  */
15001   if (bpt->type == bp_watchpoint_scope)
15002     return;
15003
15004   /* You can't disable permanent breakpoints.  */
15005   if (bpt->enable_state == bp_permanent)
15006     return;
15007
15008   bpt->enable_state = bp_disabled;
15009
15010   /* Mark breakpoint locations modified.  */
15011   mark_breakpoint_modified (bpt);
15012
15013   if (target_supports_enable_disable_tracepoint ()
15014       && current_trace_status ()->running && is_tracepoint (bpt))
15015     {
15016       struct bp_location *location;
15017      
15018       for (location = bpt->loc; location; location = location->next)
15019         target_disable_tracepoint (location);
15020     }
15021
15022   update_global_location_list (UGLL_DONT_INSERT);
15023
15024   observer_notify_breakpoint_modified (bpt);
15025 }
15026
15027 /* A callback for iterate_over_related_breakpoints.  */
15028
15029 static void
15030 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15031 {
15032   disable_breakpoint (b);
15033 }
15034
15035 /* A callback for map_breakpoint_numbers that calls
15036    disable_breakpoint.  */
15037
15038 static void
15039 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15040 {
15041   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15042 }
15043
15044 static void
15045 disable_command (char *args, int from_tty)
15046 {
15047   if (args == 0)
15048     {
15049       struct breakpoint *bpt;
15050
15051       ALL_BREAKPOINTS (bpt)
15052         if (user_breakpoint_p (bpt))
15053           disable_breakpoint (bpt);
15054     }
15055   else
15056     {
15057       char *num = extract_arg (&args);
15058
15059       while (num)
15060         {
15061           if (strchr (num, '.'))
15062             {
15063               struct bp_location *loc = find_location_by_number (num);
15064
15065               if (loc)
15066                 {
15067                   if (loc->enabled)
15068                     {
15069                       loc->enabled = 0;
15070                       mark_breakpoint_location_modified (loc);
15071                     }
15072                   if (target_supports_enable_disable_tracepoint ()
15073                       && current_trace_status ()->running && loc->owner
15074                       && is_tracepoint (loc->owner))
15075                     target_disable_tracepoint (loc);
15076                 }
15077               update_global_location_list (UGLL_DONT_INSERT);
15078             }
15079           else
15080             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15081           num = extract_arg (&args);
15082         }
15083     }
15084 }
15085
15086 static void
15087 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15088                         int count)
15089 {
15090   int target_resources_ok;
15091
15092   if (bpt->type == bp_hardware_breakpoint)
15093     {
15094       int i;
15095       i = hw_breakpoint_used_count ();
15096       target_resources_ok = 
15097         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15098                                             i + 1, 0);
15099       if (target_resources_ok == 0)
15100         error (_("No hardware breakpoint support in the target."));
15101       else if (target_resources_ok < 0)
15102         error (_("Hardware breakpoints used exceeds limit."));
15103     }
15104
15105   if (is_watchpoint (bpt))
15106     {
15107       /* Initialize it just to avoid a GCC false warning.  */
15108       enum enable_state orig_enable_state = 0;
15109       volatile struct gdb_exception e;
15110
15111       TRY_CATCH (e, RETURN_MASK_ALL)
15112         {
15113           struct watchpoint *w = (struct watchpoint *) bpt;
15114
15115           orig_enable_state = bpt->enable_state;
15116           bpt->enable_state = bp_enabled;
15117           update_watchpoint (w, 1 /* reparse */);
15118         }
15119       if (e.reason < 0)
15120         {
15121           bpt->enable_state = orig_enable_state;
15122           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15123                              bpt->number);
15124           return;
15125         }
15126     }
15127
15128   if (bpt->enable_state != bp_permanent)
15129     bpt->enable_state = bp_enabled;
15130
15131   bpt->enable_state = bp_enabled;
15132
15133   /* Mark breakpoint locations modified.  */
15134   mark_breakpoint_modified (bpt);
15135
15136   if (target_supports_enable_disable_tracepoint ()
15137       && current_trace_status ()->running && is_tracepoint (bpt))
15138     {
15139       struct bp_location *location;
15140
15141       for (location = bpt->loc; location; location = location->next)
15142         target_enable_tracepoint (location);
15143     }
15144
15145   bpt->disposition = disposition;
15146   bpt->enable_count = count;
15147   update_global_location_list (UGLL_MAY_INSERT);
15148
15149   observer_notify_breakpoint_modified (bpt);
15150 }
15151
15152
15153 void
15154 enable_breakpoint (struct breakpoint *bpt)
15155 {
15156   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15157 }
15158
15159 static void
15160 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15161 {
15162   enable_breakpoint (bpt);
15163 }
15164
15165 /* A callback for map_breakpoint_numbers that calls
15166    enable_breakpoint.  */
15167
15168 static void
15169 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15170 {
15171   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15172 }
15173
15174 /* The enable command enables the specified breakpoints (or all defined
15175    breakpoints) so they once again become (or continue to be) effective
15176    in stopping the inferior.  */
15177
15178 static void
15179 enable_command (char *args, int from_tty)
15180 {
15181   if (args == 0)
15182     {
15183       struct breakpoint *bpt;
15184
15185       ALL_BREAKPOINTS (bpt)
15186         if (user_breakpoint_p (bpt))
15187           enable_breakpoint (bpt);
15188     }
15189   else
15190     {
15191       char *num = extract_arg (&args);
15192
15193       while (num)
15194         {
15195           if (strchr (num, '.'))
15196             {
15197               struct bp_location *loc = find_location_by_number (num);
15198
15199               if (loc)
15200                 {
15201                   if (!loc->enabled)
15202                     {
15203                       loc->enabled = 1;
15204                       mark_breakpoint_location_modified (loc);
15205                     }
15206                   if (target_supports_enable_disable_tracepoint ()
15207                       && current_trace_status ()->running && loc->owner
15208                       && is_tracepoint (loc->owner))
15209                     target_enable_tracepoint (loc);
15210                 }
15211               update_global_location_list (UGLL_MAY_INSERT);
15212             }
15213           else
15214             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15215           num = extract_arg (&args);
15216         }
15217     }
15218 }
15219
15220 /* This struct packages up disposition data for application to multiple
15221    breakpoints.  */
15222
15223 struct disp_data
15224 {
15225   enum bpdisp disp;
15226   int count;
15227 };
15228
15229 static void
15230 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15231 {
15232   struct disp_data disp_data = *(struct disp_data *) arg;
15233
15234   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15235 }
15236
15237 static void
15238 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15239 {
15240   struct disp_data disp = { disp_disable, 1 };
15241
15242   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15243 }
15244
15245 static void
15246 enable_once_command (char *args, int from_tty)
15247 {
15248   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15249 }
15250
15251 static void
15252 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15253 {
15254   struct disp_data disp = { disp_disable, *(int *) countptr };
15255
15256   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15257 }
15258
15259 static void
15260 enable_count_command (char *args, int from_tty)
15261 {
15262   int count = get_number (&args);
15263
15264   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15265 }
15266
15267 static void
15268 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15269 {
15270   struct disp_data disp = { disp_del, 1 };
15271
15272   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15273 }
15274
15275 static void
15276 enable_delete_command (char *args, int from_tty)
15277 {
15278   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15279 }
15280 \f
15281 static void
15282 set_breakpoint_cmd (char *args, int from_tty)
15283 {
15284 }
15285
15286 static void
15287 show_breakpoint_cmd (char *args, int from_tty)
15288 {
15289 }
15290
15291 /* Invalidate last known value of any hardware watchpoint if
15292    the memory which that value represents has been written to by
15293    GDB itself.  */
15294
15295 static void
15296 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15297                                       CORE_ADDR addr, ssize_t len,
15298                                       const bfd_byte *data)
15299 {
15300   struct breakpoint *bp;
15301
15302   ALL_BREAKPOINTS (bp)
15303     if (bp->enable_state == bp_enabled
15304         && bp->type == bp_hardware_watchpoint)
15305       {
15306         struct watchpoint *wp = (struct watchpoint *) bp;
15307
15308         if (wp->val_valid && wp->val)
15309           {
15310             struct bp_location *loc;
15311
15312             for (loc = bp->loc; loc != NULL; loc = loc->next)
15313               if (loc->loc_type == bp_loc_hardware_watchpoint
15314                   && loc->address + loc->length > addr
15315                   && addr + len > loc->address)
15316                 {
15317                   value_free (wp->val);
15318                   wp->val = NULL;
15319                   wp->val_valid = 0;
15320                 }
15321           }
15322       }
15323 }
15324
15325 /* Create and insert a raw software breakpoint at PC.  Return an
15326    identifier, which should be used to remove the breakpoint later.
15327    In general, places which call this should be using something on the
15328    breakpoint chain instead; this function should be eliminated
15329    someday.  */
15330
15331 void *
15332 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15333                                   struct address_space *aspace, CORE_ADDR pc)
15334 {
15335   struct bp_target_info *bp_tgt;
15336   struct bp_location *bl;
15337
15338   bp_tgt = XCNEW (struct bp_target_info);
15339
15340   bp_tgt->placed_address_space = aspace;
15341   bp_tgt->placed_address = pc;
15342
15343   /* If an unconditional non-raw breakpoint is already inserted at
15344      that location, there's no need to insert another.  However, with
15345      target-side evaluation of breakpoint conditions, if the
15346      breakpoint that is currently inserted on the target is
15347      conditional, we need to make it unconditional.  Note that a
15348      breakpoint with target-side commands is not reported even if
15349      unconditional, so we need to remove the commands from the target
15350      as well.  */
15351   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15352   if (bl != NULL
15353       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15354       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15355     {
15356       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15357       return bp_tgt;
15358     }
15359
15360   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15361     {
15362       /* Could not insert the breakpoint.  */
15363       xfree (bp_tgt);
15364       return NULL;
15365     }
15366
15367   return bp_tgt;
15368 }
15369
15370 /* Remove a breakpoint BP inserted by
15371    deprecated_insert_raw_breakpoint.  */
15372
15373 int
15374 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15375 {
15376   struct bp_target_info *bp_tgt = bp;
15377   struct address_space *aspace = bp_tgt->placed_address_space;
15378   CORE_ADDR address = bp_tgt->placed_address;
15379   struct bp_location *bl;
15380   int ret;
15381
15382   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15383
15384   /* Only remove the raw breakpoint if there are no other non-raw
15385      breakpoints still inserted at this location.  Otherwise, we would
15386      be effectively disabling those breakpoints.  */
15387   if (bl == NULL)
15388     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15389   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15390            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15391     {
15392       /* The target is evaluating conditions, and when we inserted the
15393          software single-step breakpoint, we had made the breakpoint
15394          unconditional and command-less on the target side.  Reinsert
15395          to restore the conditions/commands.  */
15396       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15397     }
15398   else
15399     ret = 0;
15400
15401   xfree (bp_tgt);
15402
15403   return ret;
15404 }
15405
15406 /* Create and insert a breakpoint for software single step.  */
15407
15408 void
15409 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15410                                struct address_space *aspace, 
15411                                CORE_ADDR next_pc)
15412 {
15413   void **bpt_p;
15414
15415   if (single_step_breakpoints[0] == NULL)
15416     {
15417       bpt_p = &single_step_breakpoints[0];
15418       single_step_gdbarch[0] = gdbarch;
15419     }
15420   else
15421     {
15422       gdb_assert (single_step_breakpoints[1] == NULL);
15423       bpt_p = &single_step_breakpoints[1];
15424       single_step_gdbarch[1] = gdbarch;
15425     }
15426
15427   /* NOTE drow/2006-04-11: A future improvement to this function would
15428      be to only create the breakpoints once, and actually put them on
15429      the breakpoint chain.  That would let us use set_raw_breakpoint.
15430      We could adjust the addresses each time they were needed.  Doing
15431      this requires corresponding changes elsewhere where single step
15432      breakpoints are handled, however.  So, for now, we use this.  */
15433
15434   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15435   if (*bpt_p == NULL)
15436     error (_("Could not insert single-step breakpoint at %s"),
15437              paddress (gdbarch, next_pc));
15438 }
15439
15440 /* Check if the breakpoints used for software single stepping
15441    were inserted or not.  */
15442
15443 int
15444 single_step_breakpoints_inserted (void)
15445 {
15446   return (single_step_breakpoints[0] != NULL
15447           || single_step_breakpoints[1] != NULL);
15448 }
15449
15450 /* Remove and delete any breakpoints used for software single step.  */
15451
15452 void
15453 remove_single_step_breakpoints (void)
15454 {
15455   gdb_assert (single_step_breakpoints[0] != NULL);
15456
15457   /* See insert_single_step_breakpoint for more about this deprecated
15458      call.  */
15459   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15460                                     single_step_breakpoints[0]);
15461   single_step_gdbarch[0] = NULL;
15462   single_step_breakpoints[0] = NULL;
15463
15464   if (single_step_breakpoints[1] != NULL)
15465     {
15466       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15467                                         single_step_breakpoints[1]);
15468       single_step_gdbarch[1] = NULL;
15469       single_step_breakpoints[1] = NULL;
15470     }
15471 }
15472
15473 /* Delete software single step breakpoints without removing them from
15474    the inferior.  This is intended to be used if the inferior's address
15475    space where they were inserted is already gone, e.g. after exit or
15476    exec.  */
15477
15478 void
15479 cancel_single_step_breakpoints (void)
15480 {
15481   int i;
15482
15483   for (i = 0; i < 2; i++)
15484     if (single_step_breakpoints[i])
15485       {
15486         xfree (single_step_breakpoints[i]);
15487         single_step_breakpoints[i] = NULL;
15488         single_step_gdbarch[i] = NULL;
15489       }
15490 }
15491
15492 /* Detach software single-step breakpoints from INFERIOR_PTID without
15493    removing them.  */
15494
15495 static void
15496 detach_single_step_breakpoints (void)
15497 {
15498   int i;
15499
15500   for (i = 0; i < 2; i++)
15501     if (single_step_breakpoints[i])
15502       target_remove_breakpoint (single_step_gdbarch[i],
15503                                 single_step_breakpoints[i]);
15504 }
15505
15506 /* Find the software single-step breakpoint that inserted at PC.
15507    Returns its slot if found, and -1 if not found.  */
15508
15509 static int
15510 find_single_step_breakpoint (struct address_space *aspace,
15511                              CORE_ADDR pc)
15512 {
15513   int i;
15514
15515   for (i = 0; i < 2; i++)
15516     {
15517       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15518       if (bp_tgt
15519           && breakpoint_address_match (bp_tgt->placed_address_space,
15520                                        bp_tgt->placed_address,
15521                                        aspace, pc))
15522         return i;
15523     }
15524
15525   return -1;
15526 }
15527
15528 /* Check whether a software single-step breakpoint is inserted at
15529    PC.  */
15530
15531 int
15532 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15533                                         CORE_ADDR pc)
15534 {
15535   return find_single_step_breakpoint (aspace, pc) >= 0;
15536 }
15537
15538 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15539    non-zero otherwise.  */
15540 static int
15541 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15542 {
15543   if (syscall_catchpoint_p (bp)
15544       && bp->enable_state != bp_disabled
15545       && bp->enable_state != bp_call_disabled)
15546     return 1;
15547   else
15548     return 0;
15549 }
15550
15551 int
15552 catch_syscall_enabled (void)
15553 {
15554   struct catch_syscall_inferior_data *inf_data
15555     = get_catch_syscall_inferior_data (current_inferior ());
15556
15557   return inf_data->total_syscalls_count != 0;
15558 }
15559
15560 int
15561 catching_syscall_number (int syscall_number)
15562 {
15563   struct breakpoint *bp;
15564
15565   ALL_BREAKPOINTS (bp)
15566     if (is_syscall_catchpoint_enabled (bp))
15567       {
15568         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15569
15570         if (c->syscalls_to_be_caught)
15571           {
15572             int i, iter;
15573             for (i = 0;
15574                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15575                  i++)
15576               if (syscall_number == iter)
15577                 return 1;
15578           }
15579         else
15580           return 1;
15581       }
15582
15583   return 0;
15584 }
15585
15586 /* Complete syscall names.  Used by "catch syscall".  */
15587 static VEC (char_ptr) *
15588 catch_syscall_completer (struct cmd_list_element *cmd,
15589                          const char *text, const char *word)
15590 {
15591   const char **list = get_syscall_names ();
15592   VEC (char_ptr) *retlist
15593     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15594
15595   xfree (list);
15596   return retlist;
15597 }
15598
15599 /* Tracepoint-specific operations.  */
15600
15601 /* Set tracepoint count to NUM.  */
15602 static void
15603 set_tracepoint_count (int num)
15604 {
15605   tracepoint_count = num;
15606   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15607 }
15608
15609 static void
15610 trace_command (char *arg, int from_tty)
15611 {
15612   struct breakpoint_ops *ops;
15613   const char *arg_cp = arg;
15614
15615   if (arg && probe_linespec_to_ops (&arg_cp))
15616     ops = &tracepoint_probe_breakpoint_ops;
15617   else
15618     ops = &tracepoint_breakpoint_ops;
15619
15620   create_breakpoint (get_current_arch (),
15621                      arg,
15622                      NULL, 0, NULL, 1 /* parse arg */,
15623                      0 /* tempflag */,
15624                      bp_tracepoint /* type_wanted */,
15625                      0 /* Ignore count */,
15626                      pending_break_support,
15627                      ops,
15628                      from_tty,
15629                      1 /* enabled */,
15630                      0 /* internal */, 0);
15631 }
15632
15633 static void
15634 ftrace_command (char *arg, int from_tty)
15635 {
15636   create_breakpoint (get_current_arch (),
15637                      arg,
15638                      NULL, 0, NULL, 1 /* parse arg */,
15639                      0 /* tempflag */,
15640                      bp_fast_tracepoint /* type_wanted */,
15641                      0 /* Ignore count */,
15642                      pending_break_support,
15643                      &tracepoint_breakpoint_ops,
15644                      from_tty,
15645                      1 /* enabled */,
15646                      0 /* internal */, 0);
15647 }
15648
15649 /* strace command implementation.  Creates a static tracepoint.  */
15650
15651 static void
15652 strace_command (char *arg, int from_tty)
15653 {
15654   struct breakpoint_ops *ops;
15655
15656   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15657      or with a normal static tracepoint.  */
15658   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15659     ops = &strace_marker_breakpoint_ops;
15660   else
15661     ops = &tracepoint_breakpoint_ops;
15662
15663   create_breakpoint (get_current_arch (),
15664                      arg,
15665                      NULL, 0, NULL, 1 /* parse arg */,
15666                      0 /* tempflag */,
15667                      bp_static_tracepoint /* type_wanted */,
15668                      0 /* Ignore count */,
15669                      pending_break_support,
15670                      ops,
15671                      from_tty,
15672                      1 /* enabled */,
15673                      0 /* internal */, 0);
15674 }
15675
15676 /* Set up a fake reader function that gets command lines from a linked
15677    list that was acquired during tracepoint uploading.  */
15678
15679 static struct uploaded_tp *this_utp;
15680 static int next_cmd;
15681
15682 static char *
15683 read_uploaded_action (void)
15684 {
15685   char *rslt;
15686
15687   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15688
15689   next_cmd++;
15690
15691   return rslt;
15692 }
15693
15694 /* Given information about a tracepoint as recorded on a target (which
15695    can be either a live system or a trace file), attempt to create an
15696    equivalent GDB tracepoint.  This is not a reliable process, since
15697    the target does not necessarily have all the information used when
15698    the tracepoint was originally defined.  */
15699   
15700 struct tracepoint *
15701 create_tracepoint_from_upload (struct uploaded_tp *utp)
15702 {
15703   char *addr_str, small_buf[100];
15704   struct tracepoint *tp;
15705
15706   if (utp->at_string)
15707     addr_str = utp->at_string;
15708   else
15709     {
15710       /* In the absence of a source location, fall back to raw
15711          address.  Since there is no way to confirm that the address
15712          means the same thing as when the trace was started, warn the
15713          user.  */
15714       warning (_("Uploaded tracepoint %d has no "
15715                  "source location, using raw address"),
15716                utp->number);
15717       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15718       addr_str = small_buf;
15719     }
15720
15721   /* There's not much we can do with a sequence of bytecodes.  */
15722   if (utp->cond && !utp->cond_string)
15723     warning (_("Uploaded tracepoint %d condition "
15724                "has no source form, ignoring it"),
15725              utp->number);
15726
15727   if (!create_breakpoint (get_current_arch (),
15728                           addr_str,
15729                           utp->cond_string, -1, NULL,
15730                           0 /* parse cond/thread */,
15731                           0 /* tempflag */,
15732                           utp->type /* type_wanted */,
15733                           0 /* Ignore count */,
15734                           pending_break_support,
15735                           &tracepoint_breakpoint_ops,
15736                           0 /* from_tty */,
15737                           utp->enabled /* enabled */,
15738                           0 /* internal */,
15739                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15740     return NULL;
15741
15742   /* Get the tracepoint we just created.  */
15743   tp = get_tracepoint (tracepoint_count);
15744   gdb_assert (tp != NULL);
15745
15746   if (utp->pass > 0)
15747     {
15748       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15749                  tp->base.number);
15750
15751       trace_pass_command (small_buf, 0);
15752     }
15753
15754   /* If we have uploaded versions of the original commands, set up a
15755      special-purpose "reader" function and call the usual command line
15756      reader, then pass the result to the breakpoint command-setting
15757      function.  */
15758   if (!VEC_empty (char_ptr, utp->cmd_strings))
15759     {
15760       struct command_line *cmd_list;
15761
15762       this_utp = utp;
15763       next_cmd = 0;
15764
15765       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15766
15767       breakpoint_set_commands (&tp->base, cmd_list);
15768     }
15769   else if (!VEC_empty (char_ptr, utp->actions)
15770            || !VEC_empty (char_ptr, utp->step_actions))
15771     warning (_("Uploaded tracepoint %d actions "
15772                "have no source form, ignoring them"),
15773              utp->number);
15774
15775   /* Copy any status information that might be available.  */
15776   tp->base.hit_count = utp->hit_count;
15777   tp->traceframe_usage = utp->traceframe_usage;
15778
15779   return tp;
15780 }
15781   
15782 /* Print information on tracepoint number TPNUM_EXP, or all if
15783    omitted.  */
15784
15785 static void
15786 tracepoints_info (char *args, int from_tty)
15787 {
15788   struct ui_out *uiout = current_uiout;
15789   int num_printed;
15790
15791   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15792
15793   if (num_printed == 0)
15794     {
15795       if (args == NULL || *args == '\0')
15796         ui_out_message (uiout, 0, "No tracepoints.\n");
15797       else
15798         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15799     }
15800
15801   default_collect_info ();
15802 }
15803
15804 /* The 'enable trace' command enables tracepoints.
15805    Not supported by all targets.  */
15806 static void
15807 enable_trace_command (char *args, int from_tty)
15808 {
15809   enable_command (args, from_tty);
15810 }
15811
15812 /* The 'disable trace' command disables tracepoints.
15813    Not supported by all targets.  */
15814 static void
15815 disable_trace_command (char *args, int from_tty)
15816 {
15817   disable_command (args, from_tty);
15818 }
15819
15820 /* Remove a tracepoint (or all if no argument).  */
15821 static void
15822 delete_trace_command (char *arg, int from_tty)
15823 {
15824   struct breakpoint *b, *b_tmp;
15825
15826   dont_repeat ();
15827
15828   if (arg == 0)
15829     {
15830       int breaks_to_delete = 0;
15831
15832       /* Delete all breakpoints if no argument.
15833          Do not delete internal or call-dummy breakpoints, these
15834          have to be deleted with an explicit breakpoint number 
15835          argument.  */
15836       ALL_TRACEPOINTS (b)
15837         if (is_tracepoint (b) && user_breakpoint_p (b))
15838           {
15839             breaks_to_delete = 1;
15840             break;
15841           }
15842
15843       /* Ask user only if there are some breakpoints to delete.  */
15844       if (!from_tty
15845           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15846         {
15847           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15848             if (is_tracepoint (b) && user_breakpoint_p (b))
15849               delete_breakpoint (b);
15850         }
15851     }
15852   else
15853     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15854 }
15855
15856 /* Helper function for trace_pass_command.  */
15857
15858 static void
15859 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15860 {
15861   tp->pass_count = count;
15862   observer_notify_breakpoint_modified (&tp->base);
15863   if (from_tty)
15864     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15865                      tp->base.number, count);
15866 }
15867
15868 /* Set passcount for tracepoint.
15869
15870    First command argument is passcount, second is tracepoint number.
15871    If tracepoint number omitted, apply to most recently defined.
15872    Also accepts special argument "all".  */
15873
15874 static void
15875 trace_pass_command (char *args, int from_tty)
15876 {
15877   struct tracepoint *t1;
15878   unsigned int count;
15879
15880   if (args == 0 || *args == 0)
15881     error (_("passcount command requires an "
15882              "argument (count + optional TP num)"));
15883
15884   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15885
15886   args = skip_spaces (args);
15887   if (*args && strncasecmp (args, "all", 3) == 0)
15888     {
15889       struct breakpoint *b;
15890
15891       args += 3;                        /* Skip special argument "all".  */
15892       if (*args)
15893         error (_("Junk at end of arguments."));
15894
15895       ALL_TRACEPOINTS (b)
15896       {
15897         t1 = (struct tracepoint *) b;
15898         trace_pass_set_count (t1, count, from_tty);
15899       }
15900     }
15901   else if (*args == '\0')
15902     {
15903       t1 = get_tracepoint_by_number (&args, NULL);
15904       if (t1)
15905         trace_pass_set_count (t1, count, from_tty);
15906     }
15907   else
15908     {
15909       struct get_number_or_range_state state;
15910
15911       init_number_or_range (&state, args);
15912       while (!state.finished)
15913         {
15914           t1 = get_tracepoint_by_number (&args, &state);
15915           if (t1)
15916             trace_pass_set_count (t1, count, from_tty);
15917         }
15918     }
15919 }
15920
15921 struct tracepoint *
15922 get_tracepoint (int num)
15923 {
15924   struct breakpoint *t;
15925
15926   ALL_TRACEPOINTS (t)
15927     if (t->number == num)
15928       return (struct tracepoint *) t;
15929
15930   return NULL;
15931 }
15932
15933 /* Find the tracepoint with the given target-side number (which may be
15934    different from the tracepoint number after disconnecting and
15935    reconnecting).  */
15936
15937 struct tracepoint *
15938 get_tracepoint_by_number_on_target (int num)
15939 {
15940   struct breakpoint *b;
15941
15942   ALL_TRACEPOINTS (b)
15943     {
15944       struct tracepoint *t = (struct tracepoint *) b;
15945
15946       if (t->number_on_target == num)
15947         return t;
15948     }
15949
15950   return NULL;
15951 }
15952
15953 /* Utility: parse a tracepoint number and look it up in the list.
15954    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15955    If the argument is missing, the most recent tracepoint
15956    (tracepoint_count) is returned.  */
15957
15958 struct tracepoint *
15959 get_tracepoint_by_number (char **arg,
15960                           struct get_number_or_range_state *state)
15961 {
15962   struct breakpoint *t;
15963   int tpnum;
15964   char *instring = arg == NULL ? NULL : *arg;
15965
15966   if (state)
15967     {
15968       gdb_assert (!state->finished);
15969       tpnum = get_number_or_range (state);
15970     }
15971   else if (arg == NULL || *arg == NULL || ! **arg)
15972     tpnum = tracepoint_count;
15973   else
15974     tpnum = get_number (arg);
15975
15976   if (tpnum <= 0)
15977     {
15978       if (instring && *instring)
15979         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15980                          instring);
15981       else
15982         printf_filtered (_("No previous tracepoint\n"));
15983       return NULL;
15984     }
15985
15986   ALL_TRACEPOINTS (t)
15987     if (t->number == tpnum)
15988     {
15989       return (struct tracepoint *) t;
15990     }
15991
15992   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15993   return NULL;
15994 }
15995
15996 void
15997 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15998 {
15999   if (b->thread != -1)
16000     fprintf_unfiltered (fp, " thread %d", b->thread);
16001
16002   if (b->task != 0)
16003     fprintf_unfiltered (fp, " task %d", b->task);
16004
16005   fprintf_unfiltered (fp, "\n");
16006 }
16007
16008 /* Save information on user settable breakpoints (watchpoints, etc) to
16009    a new script file named FILENAME.  If FILTER is non-NULL, call it
16010    on each breakpoint and only include the ones for which it returns
16011    non-zero.  */
16012
16013 static void
16014 save_breakpoints (char *filename, int from_tty,
16015                   int (*filter) (const struct breakpoint *))
16016 {
16017   struct breakpoint *tp;
16018   int any = 0;
16019   struct cleanup *cleanup;
16020   struct ui_file *fp;
16021   int extra_trace_bits = 0;
16022
16023   if (filename == 0 || *filename == 0)
16024     error (_("Argument required (file name in which to save)"));
16025
16026   /* See if we have anything to save.  */
16027   ALL_BREAKPOINTS (tp)
16028   {
16029     /* Skip internal and momentary breakpoints.  */
16030     if (!user_breakpoint_p (tp))
16031       continue;
16032
16033     /* If we have a filter, only save the breakpoints it accepts.  */
16034     if (filter && !filter (tp))
16035       continue;
16036
16037     any = 1;
16038
16039     if (is_tracepoint (tp))
16040       {
16041         extra_trace_bits = 1;
16042
16043         /* We can stop searching.  */
16044         break;
16045       }
16046   }
16047
16048   if (!any)
16049     {
16050       warning (_("Nothing to save."));
16051       return;
16052     }
16053
16054   filename = tilde_expand (filename);
16055   cleanup = make_cleanup (xfree, filename);
16056   fp = gdb_fopen (filename, "w");
16057   if (!fp)
16058     error (_("Unable to open file '%s' for saving (%s)"),
16059            filename, safe_strerror (errno));
16060   make_cleanup_ui_file_delete (fp);
16061
16062   if (extra_trace_bits)
16063     save_trace_state_variables (fp);
16064
16065   ALL_BREAKPOINTS (tp)
16066   {
16067     /* Skip internal and momentary breakpoints.  */
16068     if (!user_breakpoint_p (tp))
16069       continue;
16070
16071     /* If we have a filter, only save the breakpoints it accepts.  */
16072     if (filter && !filter (tp))
16073       continue;
16074
16075     tp->ops->print_recreate (tp, fp);
16076
16077     /* Note, we can't rely on tp->number for anything, as we can't
16078        assume the recreated breakpoint numbers will match.  Use $bpnum
16079        instead.  */
16080
16081     if (tp->cond_string)
16082       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
16083
16084     if (tp->ignore_count)
16085       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
16086
16087     if (tp->type != bp_dprintf && tp->commands)
16088       {
16089         volatile struct gdb_exception ex;       
16090
16091         fprintf_unfiltered (fp, "  commands\n");
16092         
16093         ui_out_redirect (current_uiout, fp);
16094         TRY_CATCH (ex, RETURN_MASK_ALL)
16095           {
16096             print_command_lines (current_uiout, tp->commands->commands, 2);
16097           }
16098         ui_out_redirect (current_uiout, NULL);
16099
16100         if (ex.reason < 0)
16101           throw_exception (ex);
16102
16103         fprintf_unfiltered (fp, "  end\n");
16104       }
16105
16106     if (tp->enable_state == bp_disabled)
16107       fprintf_unfiltered (fp, "disable\n");
16108
16109     /* If this is a multi-location breakpoint, check if the locations
16110        should be individually disabled.  Watchpoint locations are
16111        special, and not user visible.  */
16112     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
16113       {
16114         struct bp_location *loc;
16115         int n = 1;
16116
16117         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
16118           if (!loc->enabled)
16119             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
16120       }
16121   }
16122
16123   if (extra_trace_bits && *default_collect)
16124     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
16125
16126   if (from_tty)
16127     printf_filtered (_("Saved to file '%s'.\n"), filename);
16128   do_cleanups (cleanup);
16129 }
16130
16131 /* The `save breakpoints' command.  */
16132
16133 static void
16134 save_breakpoints_command (char *args, int from_tty)
16135 {
16136   save_breakpoints (args, from_tty, NULL);
16137 }
16138
16139 /* The `save tracepoints' command.  */
16140
16141 static void
16142 save_tracepoints_command (char *args, int from_tty)
16143 {
16144   save_breakpoints (args, from_tty, is_tracepoint);
16145 }
16146
16147 /* Create a vector of all tracepoints.  */
16148
16149 VEC(breakpoint_p) *
16150 all_tracepoints (void)
16151 {
16152   VEC(breakpoint_p) *tp_vec = 0;
16153   struct breakpoint *tp;
16154
16155   ALL_TRACEPOINTS (tp)
16156   {
16157     VEC_safe_push (breakpoint_p, tp_vec, tp);
16158   }
16159
16160   return tp_vec;
16161 }
16162
16163 \f
16164 /* This help string is used for the break, hbreak, tbreak and thbreak
16165    commands.  It is defined as a macro to prevent duplication.
16166    COMMAND should be a string constant containing the name of the
16167    command.  */
16168 #define BREAK_ARGS_HELP(command) \
16169 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16170 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16171 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16172 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16173 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16174 If a line number is specified, break at start of code for that line.\n\
16175 If a function is specified, break at start of code for that function.\n\
16176 If an address is specified, break at that exact address.\n\
16177 With no LOCATION, uses current execution address of the selected\n\
16178 stack frame.  This is useful for breaking on return to a stack frame.\n\
16179 \n\
16180 THREADNUM is the number from \"info threads\".\n\
16181 CONDITION is a boolean expression.\n\
16182 \n\
16183 Multiple breakpoints at one place are permitted, and useful if their\n\
16184 conditions are different.\n\
16185 \n\
16186 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16187
16188 /* List of subcommands for "catch".  */
16189 static struct cmd_list_element *catch_cmdlist;
16190
16191 /* List of subcommands for "tcatch".  */
16192 static struct cmd_list_element *tcatch_cmdlist;
16193
16194 void
16195 add_catch_command (char *name, char *docstring,
16196                    cmd_sfunc_ftype *sfunc,
16197                    completer_ftype *completer,
16198                    void *user_data_catch,
16199                    void *user_data_tcatch)
16200 {
16201   struct cmd_list_element *command;
16202
16203   command = add_cmd (name, class_breakpoint, NULL, docstring,
16204                      &catch_cmdlist);
16205   set_cmd_sfunc (command, sfunc);
16206   set_cmd_context (command, user_data_catch);
16207   set_cmd_completer (command, completer);
16208
16209   command = add_cmd (name, class_breakpoint, NULL, docstring,
16210                      &tcatch_cmdlist);
16211   set_cmd_sfunc (command, sfunc);
16212   set_cmd_context (command, user_data_tcatch);
16213   set_cmd_completer (command, completer);
16214 }
16215
16216 static void
16217 clear_syscall_counts (struct inferior *inf)
16218 {
16219   struct catch_syscall_inferior_data *inf_data
16220     = get_catch_syscall_inferior_data (inf);
16221
16222   inf_data->total_syscalls_count = 0;
16223   inf_data->any_syscall_count = 0;
16224   VEC_free (int, inf_data->syscalls_counts);
16225 }
16226
16227 static void
16228 save_command (char *arg, int from_tty)
16229 {
16230   printf_unfiltered (_("\"save\" must be followed by "
16231                        "the name of a save subcommand.\n"));
16232   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16233 }
16234
16235 struct breakpoint *
16236 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16237                           void *data)
16238 {
16239   struct breakpoint *b, *b_tmp;
16240
16241   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16242     {
16243       if ((*callback) (b, data))
16244         return b;
16245     }
16246
16247   return NULL;
16248 }
16249
16250 /* Zero if any of the breakpoint's locations could be a location where
16251    functions have been inlined, nonzero otherwise.  */
16252
16253 static int
16254 is_non_inline_function (struct breakpoint *b)
16255 {
16256   /* The shared library event breakpoint is set on the address of a
16257      non-inline function.  */
16258   if (b->type == bp_shlib_event)
16259     return 1;
16260
16261   return 0;
16262 }
16263
16264 /* Nonzero if the specified PC cannot be a location where functions
16265    have been inlined.  */
16266
16267 int
16268 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16269                            const struct target_waitstatus *ws)
16270 {
16271   struct breakpoint *b;
16272   struct bp_location *bl;
16273
16274   ALL_BREAKPOINTS (b)
16275     {
16276       if (!is_non_inline_function (b))
16277         continue;
16278
16279       for (bl = b->loc; bl != NULL; bl = bl->next)
16280         {
16281           if (!bl->shlib_disabled
16282               && bpstat_check_location (bl, aspace, pc, ws))
16283             return 1;
16284         }
16285     }
16286
16287   return 0;
16288 }
16289
16290 /* Remove any references to OBJFILE which is going to be freed.  */
16291
16292 void
16293 breakpoint_free_objfile (struct objfile *objfile)
16294 {
16295   struct bp_location **locp, *loc;
16296
16297   ALL_BP_LOCATIONS (loc, locp)
16298     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16299       loc->symtab = NULL;
16300 }
16301
16302 void
16303 initialize_breakpoint_ops (void)
16304 {
16305   static int initialized = 0;
16306
16307   struct breakpoint_ops *ops;
16308
16309   if (initialized)
16310     return;
16311   initialized = 1;
16312
16313   /* The breakpoint_ops structure to be inherit by all kinds of
16314      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16315      internal and momentary breakpoints, etc.).  */
16316   ops = &bkpt_base_breakpoint_ops;
16317   *ops = base_breakpoint_ops;
16318   ops->re_set = bkpt_re_set;
16319   ops->insert_location = bkpt_insert_location;
16320   ops->remove_location = bkpt_remove_location;
16321   ops->breakpoint_hit = bkpt_breakpoint_hit;
16322   ops->create_sals_from_address = bkpt_create_sals_from_address;
16323   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16324   ops->decode_linespec = bkpt_decode_linespec;
16325
16326   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16327   ops = &bkpt_breakpoint_ops;
16328   *ops = bkpt_base_breakpoint_ops;
16329   ops->re_set = bkpt_re_set;
16330   ops->resources_needed = bkpt_resources_needed;
16331   ops->print_it = bkpt_print_it;
16332   ops->print_mention = bkpt_print_mention;
16333   ops->print_recreate = bkpt_print_recreate;
16334
16335   /* Ranged breakpoints.  */
16336   ops = &ranged_breakpoint_ops;
16337   *ops = bkpt_breakpoint_ops;
16338   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16339   ops->resources_needed = resources_needed_ranged_breakpoint;
16340   ops->print_it = print_it_ranged_breakpoint;
16341   ops->print_one = print_one_ranged_breakpoint;
16342   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16343   ops->print_mention = print_mention_ranged_breakpoint;
16344   ops->print_recreate = print_recreate_ranged_breakpoint;
16345
16346   /* Internal breakpoints.  */
16347   ops = &internal_breakpoint_ops;
16348   *ops = bkpt_base_breakpoint_ops;
16349   ops->re_set = internal_bkpt_re_set;
16350   ops->check_status = internal_bkpt_check_status;
16351   ops->print_it = internal_bkpt_print_it;
16352   ops->print_mention = internal_bkpt_print_mention;
16353
16354   /* Momentary breakpoints.  */
16355   ops = &momentary_breakpoint_ops;
16356   *ops = bkpt_base_breakpoint_ops;
16357   ops->re_set = momentary_bkpt_re_set;
16358   ops->check_status = momentary_bkpt_check_status;
16359   ops->print_it = momentary_bkpt_print_it;
16360   ops->print_mention = momentary_bkpt_print_mention;
16361
16362   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16363   ops = &longjmp_breakpoint_ops;
16364   *ops = momentary_breakpoint_ops;
16365   ops->dtor = longjmp_bkpt_dtor;
16366
16367   /* Probe breakpoints.  */
16368   ops = &bkpt_probe_breakpoint_ops;
16369   *ops = bkpt_breakpoint_ops;
16370   ops->insert_location = bkpt_probe_insert_location;
16371   ops->remove_location = bkpt_probe_remove_location;
16372   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16373   ops->decode_linespec = bkpt_probe_decode_linespec;
16374
16375   /* Watchpoints.  */
16376   ops = &watchpoint_breakpoint_ops;
16377   *ops = base_breakpoint_ops;
16378   ops->dtor = dtor_watchpoint;
16379   ops->re_set = re_set_watchpoint;
16380   ops->insert_location = insert_watchpoint;
16381   ops->remove_location = remove_watchpoint;
16382   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16383   ops->check_status = check_status_watchpoint;
16384   ops->resources_needed = resources_needed_watchpoint;
16385   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16386   ops->print_it = print_it_watchpoint;
16387   ops->print_mention = print_mention_watchpoint;
16388   ops->print_recreate = print_recreate_watchpoint;
16389   ops->explains_signal = explains_signal_watchpoint;
16390
16391   /* Masked watchpoints.  */
16392   ops = &masked_watchpoint_breakpoint_ops;
16393   *ops = watchpoint_breakpoint_ops;
16394   ops->insert_location = insert_masked_watchpoint;
16395   ops->remove_location = remove_masked_watchpoint;
16396   ops->resources_needed = resources_needed_masked_watchpoint;
16397   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16398   ops->print_it = print_it_masked_watchpoint;
16399   ops->print_one_detail = print_one_detail_masked_watchpoint;
16400   ops->print_mention = print_mention_masked_watchpoint;
16401   ops->print_recreate = print_recreate_masked_watchpoint;
16402
16403   /* Tracepoints.  */
16404   ops = &tracepoint_breakpoint_ops;
16405   *ops = base_breakpoint_ops;
16406   ops->re_set = tracepoint_re_set;
16407   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16408   ops->print_one_detail = tracepoint_print_one_detail;
16409   ops->print_mention = tracepoint_print_mention;
16410   ops->print_recreate = tracepoint_print_recreate;
16411   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16412   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16413   ops->decode_linespec = tracepoint_decode_linespec;
16414
16415   /* Probe tracepoints.  */
16416   ops = &tracepoint_probe_breakpoint_ops;
16417   *ops = tracepoint_breakpoint_ops;
16418   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16419   ops->decode_linespec = tracepoint_probe_decode_linespec;
16420
16421   /* Static tracepoints with marker (`-m').  */
16422   ops = &strace_marker_breakpoint_ops;
16423   *ops = tracepoint_breakpoint_ops;
16424   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16425   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16426   ops->decode_linespec = strace_marker_decode_linespec;
16427
16428   /* Fork catchpoints.  */
16429   ops = &catch_fork_breakpoint_ops;
16430   *ops = base_breakpoint_ops;
16431   ops->insert_location = insert_catch_fork;
16432   ops->remove_location = remove_catch_fork;
16433   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16434   ops->print_it = print_it_catch_fork;
16435   ops->print_one = print_one_catch_fork;
16436   ops->print_mention = print_mention_catch_fork;
16437   ops->print_recreate = print_recreate_catch_fork;
16438
16439   /* Vfork catchpoints.  */
16440   ops = &catch_vfork_breakpoint_ops;
16441   *ops = base_breakpoint_ops;
16442   ops->insert_location = insert_catch_vfork;
16443   ops->remove_location = remove_catch_vfork;
16444   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16445   ops->print_it = print_it_catch_vfork;
16446   ops->print_one = print_one_catch_vfork;
16447   ops->print_mention = print_mention_catch_vfork;
16448   ops->print_recreate = print_recreate_catch_vfork;
16449
16450   /* Exec catchpoints.  */
16451   ops = &catch_exec_breakpoint_ops;
16452   *ops = base_breakpoint_ops;
16453   ops->dtor = dtor_catch_exec;
16454   ops->insert_location = insert_catch_exec;
16455   ops->remove_location = remove_catch_exec;
16456   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16457   ops->print_it = print_it_catch_exec;
16458   ops->print_one = print_one_catch_exec;
16459   ops->print_mention = print_mention_catch_exec;
16460   ops->print_recreate = print_recreate_catch_exec;
16461
16462   /* Syscall catchpoints.  */
16463   ops = &catch_syscall_breakpoint_ops;
16464   *ops = base_breakpoint_ops;
16465   ops->dtor = dtor_catch_syscall;
16466   ops->insert_location = insert_catch_syscall;
16467   ops->remove_location = remove_catch_syscall;
16468   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16469   ops->print_it = print_it_catch_syscall;
16470   ops->print_one = print_one_catch_syscall;
16471   ops->print_mention = print_mention_catch_syscall;
16472   ops->print_recreate = print_recreate_catch_syscall;
16473
16474   /* Solib-related catchpoints.  */
16475   ops = &catch_solib_breakpoint_ops;
16476   *ops = base_breakpoint_ops;
16477   ops->dtor = dtor_catch_solib;
16478   ops->insert_location = insert_catch_solib;
16479   ops->remove_location = remove_catch_solib;
16480   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16481   ops->check_status = check_status_catch_solib;
16482   ops->print_it = print_it_catch_solib;
16483   ops->print_one = print_one_catch_solib;
16484   ops->print_mention = print_mention_catch_solib;
16485   ops->print_recreate = print_recreate_catch_solib;
16486
16487   ops = &dprintf_breakpoint_ops;
16488   *ops = bkpt_base_breakpoint_ops;
16489   ops->re_set = dprintf_re_set;
16490   ops->resources_needed = bkpt_resources_needed;
16491   ops->print_it = bkpt_print_it;
16492   ops->print_mention = bkpt_print_mention;
16493   ops->print_recreate = dprintf_print_recreate;
16494   ops->after_condition_true = dprintf_after_condition_true;
16495   ops->breakpoint_hit = dprintf_breakpoint_hit;
16496 }
16497
16498 /* Chain containing all defined "enable breakpoint" subcommands.  */
16499
16500 static struct cmd_list_element *enablebreaklist = NULL;
16501
16502 void
16503 _initialize_breakpoint (void)
16504 {
16505   struct cmd_list_element *c;
16506
16507   initialize_breakpoint_ops ();
16508
16509   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16510   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16511   observer_attach_inferior_exit (clear_syscall_counts);
16512   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16513
16514   breakpoint_objfile_key
16515     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16516
16517   catch_syscall_inferior_data
16518     = register_inferior_data_with_cleanup (NULL,
16519                                            catch_syscall_inferior_data_cleanup);
16520
16521   breakpoint_chain = 0;
16522   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16523      before a breakpoint is set.  */
16524   breakpoint_count = 0;
16525
16526   tracepoint_count = 0;
16527
16528   add_com ("ignore", class_breakpoint, ignore_command, _("\
16529 Set ignore-count of breakpoint number N to COUNT.\n\
16530 Usage is `ignore N COUNT'."));
16531   if (xdb_commands)
16532     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16533
16534   add_com ("commands", class_breakpoint, commands_command, _("\
16535 Set commands to be executed when a breakpoint is hit.\n\
16536 Give breakpoint number as argument after \"commands\".\n\
16537 With no argument, the targeted breakpoint is the last one set.\n\
16538 The commands themselves follow starting on the next line.\n\
16539 Type a line containing \"end\" to indicate the end of them.\n\
16540 Give \"silent\" as the first line to make the breakpoint silent;\n\
16541 then no output is printed when it is hit, except what the commands print."));
16542
16543   c = add_com ("condition", class_breakpoint, condition_command, _("\
16544 Specify breakpoint number N to break only if COND is true.\n\
16545 Usage is `condition N COND', where N is an integer and COND is an\n\
16546 expression to be evaluated whenever breakpoint N is reached."));
16547   set_cmd_completer (c, condition_completer);
16548
16549   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16550 Set a temporary breakpoint.\n\
16551 Like \"break\" except the breakpoint is only temporary,\n\
16552 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16553 by using \"enable delete\" on the breakpoint number.\n\
16554 \n"
16555 BREAK_ARGS_HELP ("tbreak")));
16556   set_cmd_completer (c, location_completer);
16557
16558   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16559 Set a hardware assisted breakpoint.\n\
16560 Like \"break\" except the breakpoint requires hardware support,\n\
16561 some target hardware may not have this support.\n\
16562 \n"
16563 BREAK_ARGS_HELP ("hbreak")));
16564   set_cmd_completer (c, location_completer);
16565
16566   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16567 Set a temporary hardware assisted breakpoint.\n\
16568 Like \"hbreak\" except the breakpoint is only temporary,\n\
16569 so it will be deleted when hit.\n\
16570 \n"
16571 BREAK_ARGS_HELP ("thbreak")));
16572   set_cmd_completer (c, location_completer);
16573
16574   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16575 Enable some breakpoints.\n\
16576 Give breakpoint numbers (separated by spaces) as arguments.\n\
16577 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16578 This is used to cancel the effect of the \"disable\" command.\n\
16579 With a subcommand you can enable temporarily."),
16580                   &enablelist, "enable ", 1, &cmdlist);
16581   if (xdb_commands)
16582     add_com ("ab", class_breakpoint, enable_command, _("\
16583 Enable some breakpoints.\n\
16584 Give breakpoint numbers (separated by spaces) as arguments.\n\
16585 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16586 This is used to cancel the effect of the \"disable\" command.\n\
16587 With a subcommand you can enable temporarily."));
16588
16589   add_com_alias ("en", "enable", class_breakpoint, 1);
16590
16591   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16592 Enable some breakpoints.\n\
16593 Give breakpoint numbers (separated by spaces) as arguments.\n\
16594 This is used to cancel the effect of the \"disable\" command.\n\
16595 May be abbreviated to simply \"enable\".\n"),
16596                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16597
16598   add_cmd ("once", no_class, enable_once_command, _("\
16599 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16600 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16601            &enablebreaklist);
16602
16603   add_cmd ("delete", no_class, enable_delete_command, _("\
16604 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16605 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16606            &enablebreaklist);
16607
16608   add_cmd ("count", no_class, enable_count_command, _("\
16609 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16610 If a breakpoint is hit while enabled in this fashion,\n\
16611 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16612            &enablebreaklist);
16613
16614   add_cmd ("delete", no_class, enable_delete_command, _("\
16615 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16616 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16617            &enablelist);
16618
16619   add_cmd ("once", no_class, enable_once_command, _("\
16620 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16621 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16622            &enablelist);
16623
16624   add_cmd ("count", no_class, enable_count_command, _("\
16625 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16626 If a breakpoint is hit while enabled in this fashion,\n\
16627 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16628            &enablelist);
16629
16630   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16631 Disable some breakpoints.\n\
16632 Arguments are breakpoint numbers with spaces in between.\n\
16633 To disable all breakpoints, give no argument.\n\
16634 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16635                   &disablelist, "disable ", 1, &cmdlist);
16636   add_com_alias ("dis", "disable", class_breakpoint, 1);
16637   add_com_alias ("disa", "disable", class_breakpoint, 1);
16638   if (xdb_commands)
16639     add_com ("sb", class_breakpoint, disable_command, _("\
16640 Disable some breakpoints.\n\
16641 Arguments are breakpoint numbers with spaces in between.\n\
16642 To disable all breakpoints, give no argument.\n\
16643 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16644
16645   add_cmd ("breakpoints", class_alias, disable_command, _("\
16646 Disable some breakpoints.\n\
16647 Arguments are breakpoint numbers with spaces in between.\n\
16648 To disable all breakpoints, give no argument.\n\
16649 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16650 This command may be abbreviated \"disable\"."),
16651            &disablelist);
16652
16653   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16654 Delete some breakpoints or auto-display expressions.\n\
16655 Arguments are breakpoint numbers with spaces in between.\n\
16656 To delete all breakpoints, give no argument.\n\
16657 \n\
16658 Also a prefix command for deletion of other GDB objects.\n\
16659 The \"unset\" command is also an alias for \"delete\"."),
16660                   &deletelist, "delete ", 1, &cmdlist);
16661   add_com_alias ("d", "delete", class_breakpoint, 1);
16662   add_com_alias ("del", "delete", class_breakpoint, 1);
16663   if (xdb_commands)
16664     add_com ("db", class_breakpoint, delete_command, _("\
16665 Delete some breakpoints.\n\
16666 Arguments are breakpoint numbers with spaces in between.\n\
16667 To delete all breakpoints, give no argument.\n"));
16668
16669   add_cmd ("breakpoints", class_alias, delete_command, _("\
16670 Delete some breakpoints or auto-display expressions.\n\
16671 Arguments are breakpoint numbers with spaces in between.\n\
16672 To delete all breakpoints, give no argument.\n\
16673 This command may be abbreviated \"delete\"."),
16674            &deletelist);
16675
16676   add_com ("clear", class_breakpoint, clear_command, _("\
16677 Clear breakpoint at specified line or function.\n\
16678 Argument may be line number, function name, or \"*\" and an address.\n\
16679 If line number is specified, all breakpoints in that line are cleared.\n\
16680 If function is specified, breakpoints at beginning of function are cleared.\n\
16681 If an address is specified, breakpoints at that address are cleared.\n\
16682 \n\
16683 With no argument, clears all breakpoints in the line that the selected frame\n\
16684 is executing in.\n\
16685 \n\
16686 See also the \"delete\" command which clears breakpoints by number."));
16687   add_com_alias ("cl", "clear", class_breakpoint, 1);
16688
16689   c = add_com ("break", class_breakpoint, break_command, _("\
16690 Set breakpoint at specified line or function.\n"
16691 BREAK_ARGS_HELP ("break")));
16692   set_cmd_completer (c, location_completer);
16693
16694   add_com_alias ("b", "break", class_run, 1);
16695   add_com_alias ("br", "break", class_run, 1);
16696   add_com_alias ("bre", "break", class_run, 1);
16697   add_com_alias ("brea", "break", class_run, 1);
16698
16699   if (xdb_commands)
16700    add_com_alias ("ba", "break", class_breakpoint, 1);
16701
16702   if (dbx_commands)
16703     {
16704       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16705 Break in function/address or break at a line in the current file."),
16706                              &stoplist, "stop ", 1, &cmdlist);
16707       add_cmd ("in", class_breakpoint, stopin_command,
16708                _("Break in function or address."), &stoplist);
16709       add_cmd ("at", class_breakpoint, stopat_command,
16710                _("Break at a line in the current file."), &stoplist);
16711       add_com ("status", class_info, breakpoints_info, _("\
16712 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16713 The \"Type\" column indicates one of:\n\
16714 \tbreakpoint     - normal breakpoint\n\
16715 \twatchpoint     - watchpoint\n\
16716 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16717 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16718 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16719 address and file/line number respectively.\n\
16720 \n\
16721 Convenience variable \"$_\" and default examine address for \"x\"\n\
16722 are set to the address of the last breakpoint listed unless the command\n\
16723 is prefixed with \"server \".\n\n\
16724 Convenience variable \"$bpnum\" contains the number of the last\n\
16725 breakpoint set."));
16726     }
16727
16728   add_info ("breakpoints", breakpoints_info, _("\
16729 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16730 The \"Type\" column indicates one of:\n\
16731 \tbreakpoint     - normal breakpoint\n\
16732 \twatchpoint     - watchpoint\n\
16733 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16734 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16735 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16736 address and file/line number respectively.\n\
16737 \n\
16738 Convenience variable \"$_\" and default examine address for \"x\"\n\
16739 are set to the address of the last breakpoint listed unless the command\n\
16740 is prefixed with \"server \".\n\n\
16741 Convenience variable \"$bpnum\" contains the number of the last\n\
16742 breakpoint set."));
16743
16744   add_info_alias ("b", "breakpoints", 1);
16745
16746   if (xdb_commands)
16747     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16748 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16749 The \"Type\" column indicates one of:\n\
16750 \tbreakpoint     - normal breakpoint\n\
16751 \twatchpoint     - watchpoint\n\
16752 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16753 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16754 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16755 address and file/line number respectively.\n\
16756 \n\
16757 Convenience variable \"$_\" and default examine address for \"x\"\n\
16758 are set to the address of the last breakpoint listed unless the command\n\
16759 is prefixed with \"server \".\n\n\
16760 Convenience variable \"$bpnum\" contains the number of the last\n\
16761 breakpoint set."));
16762
16763   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16764 Status of all breakpoints, or breakpoint number NUMBER.\n\
16765 The \"Type\" column indicates one of:\n\
16766 \tbreakpoint     - normal breakpoint\n\
16767 \twatchpoint     - watchpoint\n\
16768 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16769 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16770 \tuntil          - internal breakpoint used by the \"until\" command\n\
16771 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16772 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16773 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16774 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16775 address and file/line number respectively.\n\
16776 \n\
16777 Convenience variable \"$_\" and default examine address for \"x\"\n\
16778 are set to the address of the last breakpoint listed unless the command\n\
16779 is prefixed with \"server \".\n\n\
16780 Convenience variable \"$bpnum\" contains the number of the last\n\
16781 breakpoint set."),
16782            &maintenanceinfolist);
16783
16784   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16785 Set catchpoints to catch events."),
16786                   &catch_cmdlist, "catch ",
16787                   0/*allow-unknown*/, &cmdlist);
16788
16789   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16790 Set temporary catchpoints to catch events."),
16791                   &tcatch_cmdlist, "tcatch ",
16792                   0/*allow-unknown*/, &cmdlist);
16793
16794   add_catch_command ("fork", _("Catch calls to fork."),
16795                      catch_fork_command_1,
16796                      NULL,
16797                      (void *) (uintptr_t) catch_fork_permanent,
16798                      (void *) (uintptr_t) catch_fork_temporary);
16799   add_catch_command ("vfork", _("Catch calls to vfork."),
16800                      catch_fork_command_1,
16801                      NULL,
16802                      (void *) (uintptr_t) catch_vfork_permanent,
16803                      (void *) (uintptr_t) catch_vfork_temporary);
16804   add_catch_command ("exec", _("Catch calls to exec."),
16805                      catch_exec_command_1,
16806                      NULL,
16807                      CATCH_PERMANENT,
16808                      CATCH_TEMPORARY);
16809   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16810 Usage: catch load [REGEX]\n\
16811 If REGEX is given, only stop for libraries matching the regular expression."),
16812                      catch_load_command_1,
16813                      NULL,
16814                      CATCH_PERMANENT,
16815                      CATCH_TEMPORARY);
16816   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16817 Usage: catch unload [REGEX]\n\
16818 If REGEX is given, only stop for libraries matching the regular expression."),
16819                      catch_unload_command_1,
16820                      NULL,
16821                      CATCH_PERMANENT,
16822                      CATCH_TEMPORARY);
16823   add_catch_command ("syscall", _("\
16824 Catch system calls by their names and/or numbers.\n\
16825 Arguments say which system calls to catch.  If no arguments\n\
16826 are given, every system call will be caught.\n\
16827 Arguments, if given, should be one or more system call names\n\
16828 (if your system supports that), or system call numbers."),
16829                      catch_syscall_command_1,
16830                      catch_syscall_completer,
16831                      CATCH_PERMANENT,
16832                      CATCH_TEMPORARY);
16833
16834   c = add_com ("watch", class_breakpoint, watch_command, _("\
16835 Set a watchpoint for an expression.\n\
16836 Usage: watch [-l|-location] EXPRESSION\n\
16837 A watchpoint stops execution of your program whenever the value of\n\
16838 an expression changes.\n\
16839 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16840 the memory to which it refers."));
16841   set_cmd_completer (c, expression_completer);
16842
16843   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16844 Set a read watchpoint for an expression.\n\
16845 Usage: rwatch [-l|-location] EXPRESSION\n\
16846 A watchpoint stops execution of your program whenever the value of\n\
16847 an expression is read.\n\
16848 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16849 the memory to which it refers."));
16850   set_cmd_completer (c, expression_completer);
16851
16852   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16853 Set a watchpoint for an expression.\n\
16854 Usage: awatch [-l|-location] EXPRESSION\n\
16855 A watchpoint stops execution of your program whenever the value of\n\
16856 an expression is either read or written.\n\
16857 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16858 the memory to which it refers."));
16859   set_cmd_completer (c, expression_completer);
16860
16861   add_info ("watchpoints", watchpoints_info, _("\
16862 Status of specified watchpoints (all watchpoints if no argument)."));
16863
16864   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16865      respond to changes - contrary to the description.  */
16866   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16867                             &can_use_hw_watchpoints, _("\
16868 Set debugger's willingness to use watchpoint hardware."), _("\
16869 Show debugger's willingness to use watchpoint hardware."), _("\
16870 If zero, gdb will not use hardware for new watchpoints, even if\n\
16871 such is available.  (However, any hardware watchpoints that were\n\
16872 created before setting this to nonzero, will continue to use watchpoint\n\
16873 hardware.)"),
16874                             NULL,
16875                             show_can_use_hw_watchpoints,
16876                             &setlist, &showlist);
16877
16878   can_use_hw_watchpoints = 1;
16879
16880   /* Tracepoint manipulation commands.  */
16881
16882   c = add_com ("trace", class_breakpoint, trace_command, _("\
16883 Set a tracepoint at specified line or function.\n\
16884 \n"
16885 BREAK_ARGS_HELP ("trace") "\n\
16886 Do \"help tracepoints\" for info on other tracepoint commands."));
16887   set_cmd_completer (c, location_completer);
16888
16889   add_com_alias ("tp", "trace", class_alias, 0);
16890   add_com_alias ("tr", "trace", class_alias, 1);
16891   add_com_alias ("tra", "trace", class_alias, 1);
16892   add_com_alias ("trac", "trace", class_alias, 1);
16893
16894   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16895 Set a fast tracepoint at specified line or function.\n\
16896 \n"
16897 BREAK_ARGS_HELP ("ftrace") "\n\
16898 Do \"help tracepoints\" for info on other tracepoint commands."));
16899   set_cmd_completer (c, location_completer);
16900
16901   c = add_com ("strace", class_breakpoint, strace_command, _("\
16902 Set a static tracepoint at specified line, function or marker.\n\
16903 \n\
16904 strace [LOCATION] [if CONDITION]\n\
16905 LOCATION may be a line number, function name, \"*\" and an address,\n\
16906 or -m MARKER_ID.\n\
16907 If a line number is specified, probe the marker at start of code\n\
16908 for that line.  If a function is specified, probe the marker at start\n\
16909 of code for that function.  If an address is specified, probe the marker\n\
16910 at that exact address.  If a marker id is specified, probe the marker\n\
16911 with that name.  With no LOCATION, uses current execution address of\n\
16912 the selected stack frame.\n\
16913 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16914 This collects arbitrary user data passed in the probe point call to the\n\
16915 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16916 by printing the $_sdata variable like any other convenience variable.\n\
16917 \n\
16918 CONDITION is a boolean expression.\n\
16919 \n\
16920 Multiple tracepoints at one place are permitted, and useful if their\n\
16921 conditions are different.\n\
16922 \n\
16923 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16924 Do \"help tracepoints\" for info on other tracepoint commands."));
16925   set_cmd_completer (c, location_completer);
16926
16927   add_info ("tracepoints", tracepoints_info, _("\
16928 Status of specified tracepoints (all tracepoints if no argument).\n\
16929 Convenience variable \"$tpnum\" contains the number of the\n\
16930 last tracepoint set."));
16931
16932   add_info_alias ("tp", "tracepoints", 1);
16933
16934   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16935 Delete specified tracepoints.\n\
16936 Arguments are tracepoint numbers, separated by spaces.\n\
16937 No argument means delete all tracepoints."),
16938            &deletelist);
16939   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16940
16941   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16942 Disable specified tracepoints.\n\
16943 Arguments are tracepoint numbers, separated by spaces.\n\
16944 No argument means disable all tracepoints."),
16945            &disablelist);
16946   deprecate_cmd (c, "disable");
16947
16948   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16949 Enable specified tracepoints.\n\
16950 Arguments are tracepoint numbers, separated by spaces.\n\
16951 No argument means enable all tracepoints."),
16952            &enablelist);
16953   deprecate_cmd (c, "enable");
16954
16955   add_com ("passcount", class_trace, trace_pass_command, _("\
16956 Set the passcount for a tracepoint.\n\
16957 The trace will end when the tracepoint has been passed 'count' times.\n\
16958 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16959 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16960
16961   add_prefix_cmd ("save", class_breakpoint, save_command,
16962                   _("Save breakpoint definitions as a script."),
16963                   &save_cmdlist, "save ",
16964                   0/*allow-unknown*/, &cmdlist);
16965
16966   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16967 Save current breakpoint definitions as a script.\n\
16968 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16969 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16970 session to restore them."),
16971                &save_cmdlist);
16972   set_cmd_completer (c, filename_completer);
16973
16974   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16975 Save current tracepoint definitions as a script.\n\
16976 Use the 'source' command in another debug session to restore them."),
16977                &save_cmdlist);
16978   set_cmd_completer (c, filename_completer);
16979
16980   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16981   deprecate_cmd (c, "save tracepoints");
16982
16983   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16984 Breakpoint specific settings\n\
16985 Configure various breakpoint-specific variables such as\n\
16986 pending breakpoint behavior"),
16987                   &breakpoint_set_cmdlist, "set breakpoint ",
16988                   0/*allow-unknown*/, &setlist);
16989   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16990 Breakpoint specific settings\n\
16991 Configure various breakpoint-specific variables such as\n\
16992 pending breakpoint behavior"),
16993                   &breakpoint_show_cmdlist, "show breakpoint ",
16994                   0/*allow-unknown*/, &showlist);
16995
16996   add_setshow_auto_boolean_cmd ("pending", no_class,
16997                                 &pending_break_support, _("\
16998 Set debugger's behavior regarding pending breakpoints."), _("\
16999 Show debugger's behavior regarding pending breakpoints."), _("\
17000 If on, an unrecognized breakpoint location will cause gdb to create a\n\
17001 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
17002 an error.  If auto, an unrecognized breakpoint location results in a\n\
17003 user-query to see if a pending breakpoint should be created."),
17004                                 NULL,
17005                                 show_pending_break_support,
17006                                 &breakpoint_set_cmdlist,
17007                                 &breakpoint_show_cmdlist);
17008
17009   pending_break_support = AUTO_BOOLEAN_AUTO;
17010
17011   add_setshow_boolean_cmd ("auto-hw", no_class,
17012                            &automatic_hardware_breakpoints, _("\
17013 Set automatic usage of hardware breakpoints."), _("\
17014 Show automatic usage of hardware breakpoints."), _("\
17015 If set, the debugger will automatically use hardware breakpoints for\n\
17016 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
17017 a warning will be emitted for such breakpoints."),
17018                            NULL,
17019                            show_automatic_hardware_breakpoints,
17020                            &breakpoint_set_cmdlist,
17021                            &breakpoint_show_cmdlist);
17022
17023   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
17024                                 &always_inserted_mode, _("\
17025 Set mode for inserting breakpoints."), _("\
17026 Show mode for inserting breakpoints."), _("\
17027 When this mode is off, breakpoints are inserted in inferior when it is\n\
17028 resumed, and removed when execution stops.  When this mode is on,\n\
17029 breakpoints are inserted immediately and removed only when the user\n\
17030 deletes the breakpoint.  When this mode is auto (which is the default),\n\
17031 the behaviour depends on the non-stop setting (see help set non-stop).\n\
17032 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
17033 behaves as if always-inserted mode is on; if gdb is controlling the\n\
17034 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
17035                                 NULL,
17036                                 &show_always_inserted_mode,
17037                                 &breakpoint_set_cmdlist,
17038                                 &breakpoint_show_cmdlist);
17039
17040   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
17041                         condition_evaluation_enums,
17042                         &condition_evaluation_mode_1, _("\
17043 Set mode of breakpoint condition evaluation."), _("\
17044 Show mode of breakpoint condition evaluation."), _("\
17045 When this is set to \"host\", breakpoint conditions will be\n\
17046 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
17047 breakpoint conditions will be downloaded to the target (if the target\n\
17048 supports such feature) and conditions will be evaluated on the target's side.\n\
17049 If this is set to \"auto\" (default), this will be automatically set to\n\
17050 \"target\" if it supports condition evaluation, otherwise it will\n\
17051 be set to \"gdb\""),
17052                            &set_condition_evaluation_mode,
17053                            &show_condition_evaluation_mode,
17054                            &breakpoint_set_cmdlist,
17055                            &breakpoint_show_cmdlist);
17056
17057   add_com ("break-range", class_breakpoint, break_range_command, _("\
17058 Set a breakpoint for an address range.\n\
17059 break-range START-LOCATION, END-LOCATION\n\
17060 where START-LOCATION and END-LOCATION can be one of the following:\n\
17061   LINENUM, for that line in the current file,\n\
17062   FILE:LINENUM, for that line in that file,\n\
17063   +OFFSET, for that number of lines after the current line\n\
17064            or the start of the range\n\
17065   FUNCTION, for the first line in that function,\n\
17066   FILE:FUNCTION, to distinguish among like-named static functions.\n\
17067   *ADDRESS, for the instruction at that address.\n\
17068 \n\
17069 The breakpoint will stop execution of the inferior whenever it executes\n\
17070 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
17071 range (including START-LOCATION and END-LOCATION)."));
17072
17073   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
17074 Set a dynamic printf at specified line or function.\n\
17075 dprintf location,format string,arg1,arg2,...\n\
17076 location may be a line number, function name, or \"*\" and an address.\n\
17077 If a line number is specified, break at start of code for that line.\n\
17078 If a function is specified, break at start of code for that function."));
17079   set_cmd_completer (c, location_completer);
17080
17081   add_setshow_enum_cmd ("dprintf-style", class_support,
17082                         dprintf_style_enums, &dprintf_style, _("\
17083 Set the style of usage for dynamic printf."), _("\
17084 Show the style of usage for dynamic printf."), _("\
17085 This setting chooses how GDB will do a dynamic printf.\n\
17086 If the value is \"gdb\", then the printing is done by GDB to its own\n\
17087 console, as with the \"printf\" command.\n\
17088 If the value is \"call\", the print is done by calling a function in your\n\
17089 program; by default printf(), but you can choose a different function or\n\
17090 output stream by setting dprintf-function and dprintf-channel."),
17091                         update_dprintf_commands, NULL,
17092                         &setlist, &showlist);
17093
17094   dprintf_function = xstrdup ("printf");
17095   add_setshow_string_cmd ("dprintf-function", class_support,
17096                           &dprintf_function, _("\
17097 Set the function to use for dynamic printf"), _("\
17098 Show the function to use for dynamic printf"), NULL,
17099                           update_dprintf_commands, NULL,
17100                           &setlist, &showlist);
17101
17102   dprintf_channel = xstrdup ("");
17103   add_setshow_string_cmd ("dprintf-channel", class_support,
17104                           &dprintf_channel, _("\
17105 Set the channel to use for dynamic printf"), _("\
17106 Show the channel to use for dynamic printf"), NULL,
17107                           update_dprintf_commands, NULL,
17108                           &setlist, &showlist);
17109
17110   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
17111                            &disconnected_dprintf, _("\
17112 Set whether dprintf continues after GDB disconnects."), _("\
17113 Show whether dprintf continues after GDB disconnects."), _("\
17114 Use this to let dprintf commands continue to hit and produce output\n\
17115 even if GDB disconnects or detaches from the target."),
17116                            NULL,
17117                            NULL,
17118                            &setlist, &showlist);
17119
17120   add_com ("agent-printf", class_vars, agent_printf_command, _("\
17121 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
17122 (target agent only) This is useful for formatted output in user-defined commands."));
17123
17124   automatic_hardware_breakpoints = 1;
17125
17126   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
17127   observer_attach_thread_exit (remove_threaded_breakpoints);
17128 }