Introduce 'enum remove_bp_reason'
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2016 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 "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "continuations.h"
64 #include "stack.h"
65 #include "skip.h"
66 #include "ax-gdb.h"
67 #include "dummy-frame.h"
68 #include "interps.h"
69 #include "format.h"
70 #include "location.h"
71 #include "thread-fsm.h"
72 #include "tid-parse.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "extension.h"
83
84 /* Enums for exception-handling support.  */
85 enum exception_event_kind
86 {
87   EX_EVENT_THROW,
88   EX_EVENT_RETHROW,
89   EX_EVENT_CATCH
90 };
91
92 /* Prototypes for local functions.  */
93
94 static void enable_delete_command (char *, int);
95
96 static void enable_once_command (char *, int);
97
98 static void enable_count_command (char *, int);
99
100 static void disable_command (char *, int);
101
102 static void enable_command (char *, int);
103
104 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
105                                                       void *),
106                                     void *);
107
108 static void ignore_command (char *, int);
109
110 static int breakpoint_re_set_one (void *);
111
112 static void breakpoint_re_set_default (struct breakpoint *);
113
114 static void
115   create_sals_from_location_default (const struct event_location *location,
116                                      struct linespec_result *canonical,
117                                      enum bptype type_wanted);
118
119 static void create_breakpoints_sal_default (struct gdbarch *,
120                                             struct linespec_result *,
121                                             char *, char *, enum bptype,
122                                             enum bpdisp, int, int,
123                                             int,
124                                             const struct breakpoint_ops *,
125                                             int, int, int, unsigned);
126
127 static void decode_location_default (struct breakpoint *b,
128                                      const struct event_location *location,
129                                      struct program_space *search_pspace,
130                                      struct symtabs_and_lines *sals);
131
132 static void clear_command (char *, int);
133
134 static void catch_command (char *, int);
135
136 static int can_use_hardware_watchpoint (struct value *);
137
138 static void break_command_1 (char *, int, int);
139
140 static void mention (struct breakpoint *);
141
142 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
143                                                                enum bptype,
144                                                                const struct breakpoint_ops *);
145 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
146                                                        const struct symtab_and_line *);
147
148 /* This function is used in gdbtk sources and thus can not be made
149    static.  */
150 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
151                                        struct symtab_and_line,
152                                        enum bptype,
153                                        const struct breakpoint_ops *);
154
155 static struct breakpoint *
156   momentary_breakpoint_from_master (struct breakpoint *orig,
157                                     enum bptype type,
158                                     const struct breakpoint_ops *ops,
159                                     int loc_enabled);
160
161 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
162
163 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
164                                             CORE_ADDR bpaddr,
165                                             enum bptype bptype);
166
167 static void describe_other_breakpoints (struct gdbarch *,
168                                         struct program_space *, CORE_ADDR,
169                                         struct obj_section *, int);
170
171 static int watchpoint_locations_match (struct bp_location *loc1,
172                                        struct bp_location *loc2);
173
174 static int breakpoint_location_address_match (struct bp_location *bl,
175                                               struct address_space *aspace,
176                                               CORE_ADDR addr);
177
178 static int breakpoint_location_address_range_overlap (struct bp_location *,
179                                                       struct address_space *,
180                                                       CORE_ADDR, int);
181
182 static void breakpoints_info (char *, int);
183
184 static void watchpoints_info (char *, int);
185
186 static int breakpoint_1 (char *, int, 
187                          int (*) (const struct breakpoint *));
188
189 static int breakpoint_cond_eval (void *);
190
191 static void cleanup_executing_breakpoints (void *);
192
193 static void commands_command (char *, int);
194
195 static void condition_command (char *, int);
196
197 /* Why are we removing the breakpoint from the target?  */
198
199 enum remove_bp_reason
200 {
201   /* A regular remove.  Remove the breakpoint and forget everything
202      about it.  */
203   REMOVE_BREAKPOINT,
204
205   /* Detach the breakpoints from a fork child.  */
206   DETACH_BREAKPOINT,
207 };
208
209 static int remove_breakpoint (struct bp_location *);
210 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
211
212 static enum print_stop_action print_bp_stop_message (bpstat bs);
213
214 static int watchpoint_check (void *);
215
216 static void maintenance_info_breakpoints (char *, int);
217
218 static int hw_breakpoint_used_count (void);
219
220 static int hw_watchpoint_use_count (struct breakpoint *);
221
222 static int hw_watchpoint_used_count_others (struct breakpoint *except,
223                                             enum bptype type,
224                                             int *other_type_used);
225
226 static void hbreak_command (char *, int);
227
228 static void thbreak_command (char *, int);
229
230 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
231                                     int count);
232
233 static void stop_command (char *arg, int from_tty);
234
235 static void stopin_command (char *arg, int from_tty);
236
237 static void stopat_command (char *arg, int from_tty);
238
239 static void tcatch_command (char *arg, int from_tty);
240
241 static void free_bp_location (struct bp_location *loc);
242 static void incref_bp_location (struct bp_location *loc);
243 static void decref_bp_location (struct bp_location **loc);
244
245 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
246
247 /* update_global_location_list's modes of operation wrt to whether to
248    insert locations now.  */
249 enum ugll_insert_mode
250 {
251   /* Don't insert any breakpoint locations into the inferior, only
252      remove already-inserted locations that no longer should be
253      inserted.  Functions that delete a breakpoint or breakpoints
254      should specify this mode, so that deleting a breakpoint doesn't
255      have the side effect of inserting the locations of other
256      breakpoints that are marked not-inserted, but should_be_inserted
257      returns true on them.
258
259      This behavior is useful is situations close to tear-down -- e.g.,
260      after an exec, while the target still has execution, but
261      breakpoint shadows of the previous executable image should *NOT*
262      be restored to the new image; or before detaching, where the
263      target still has execution and wants to delete breakpoints from
264      GDB's lists, and all breakpoints had already been removed from
265      the inferior.  */
266   UGLL_DONT_INSERT,
267
268   /* May insert breakpoints iff breakpoints_should_be_inserted_now
269      claims breakpoints should be inserted now.  */
270   UGLL_MAY_INSERT,
271
272   /* Insert locations now, irrespective of
273      breakpoints_should_be_inserted_now.  E.g., say all threads are
274      stopped right now, and the user did "continue".  We need to
275      insert breakpoints _before_ resuming the target, but
276      UGLL_MAY_INSERT wouldn't insert them, because
277      breakpoints_should_be_inserted_now returns false at that point,
278      as no thread is running yet.  */
279   UGLL_INSERT
280 };
281
282 static void update_global_location_list (enum ugll_insert_mode);
283
284 static void update_global_location_list_nothrow (enum ugll_insert_mode);
285
286 static int is_hardware_watchpoint (const struct breakpoint *bpt);
287
288 static void insert_breakpoint_locations (void);
289
290 static void tracepoints_info (char *, int);
291
292 static void delete_trace_command (char *, int);
293
294 static void enable_trace_command (char *, int);
295
296 static void disable_trace_command (char *, int);
297
298 static void trace_pass_command (char *, int);
299
300 static void set_tracepoint_count (int num);
301
302 static int is_masked_watchpoint (const struct breakpoint *b);
303
304 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
305
306 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
307    otherwise.  */
308
309 static int strace_marker_p (struct breakpoint *b);
310
311 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
312    that are implemented on top of software or hardware breakpoints
313    (user breakpoints, internal and momentary breakpoints, etc.).  */
314 static struct breakpoint_ops bkpt_base_breakpoint_ops;
315
316 /* Internal breakpoints class type.  */
317 static struct breakpoint_ops internal_breakpoint_ops;
318
319 /* Momentary breakpoints class type.  */
320 static struct breakpoint_ops momentary_breakpoint_ops;
321
322 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
323 static struct breakpoint_ops longjmp_breakpoint_ops;
324
325 /* The breakpoint_ops structure to be used in regular user created
326    breakpoints.  */
327 struct breakpoint_ops bkpt_breakpoint_ops;
328
329 /* Breakpoints set on probes.  */
330 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
331
332 /* Dynamic printf class type.  */
333 struct breakpoint_ops dprintf_breakpoint_ops;
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 keeps breakpoints inserted even if the inferior is
455    stopped, and immediately inserts any new breakpoints as soon as
456    they're created.  If off (default), GDB keeps breakpoints off of
457    the target as long as possible.  That is, it delays inserting
458    breakpoints until the next resume, and removes them again when the
459    target fully stops.  This is a bit safer in case GDB crashes while
460    processing user input.  */
461 static int always_inserted_mode = 0;
462
463 static void
464 show_always_inserted_mode (struct ui_file *file, int from_tty,
465                      struct cmd_list_element *c, const char *value)
466 {
467   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
468                     value);
469 }
470
471 /* See breakpoint.h.  */
472
473 int
474 breakpoints_should_be_inserted_now (void)
475 {
476   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
477     {
478       /* If breakpoints are global, they should be inserted even if no
479          thread under gdb's control is running, or even if there are
480          no threads under GDB's control yet.  */
481       return 1;
482     }
483   else if (target_has_execution)
484     {
485       struct thread_info *tp;
486
487       if (always_inserted_mode)
488         {
489           /* The user wants breakpoints inserted even if all threads
490              are stopped.  */
491           return 1;
492         }
493
494       if (threads_are_executing ())
495         return 1;
496
497       /* Don't remove breakpoints yet if, even though all threads are
498          stopped, we still have events to process.  */
499       ALL_NON_EXITED_THREADS (tp)
500         if (tp->resumed
501             && tp->suspend.waitstatus_pending_p)
502           return 1;
503     }
504   return 0;
505 }
506
507 static const char condition_evaluation_both[] = "host or target";
508
509 /* Modes for breakpoint condition evaluation.  */
510 static const char condition_evaluation_auto[] = "auto";
511 static const char condition_evaluation_host[] = "host";
512 static const char condition_evaluation_target[] = "target";
513 static const char *const condition_evaluation_enums[] = {
514   condition_evaluation_auto,
515   condition_evaluation_host,
516   condition_evaluation_target,
517   NULL
518 };
519
520 /* Global that holds the current mode for breakpoint condition evaluation.  */
521 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
522
523 /* Global that we use to display information to the user (gets its value from
524    condition_evaluation_mode_1.  */
525 static const char *condition_evaluation_mode = condition_evaluation_auto;
526
527 /* Translate a condition evaluation mode MODE into either "host"
528    or "target".  This is used mostly to translate from "auto" to the
529    real setting that is being used.  It returns the translated
530    evaluation mode.  */
531
532 static const char *
533 translate_condition_evaluation_mode (const char *mode)
534 {
535   if (mode == condition_evaluation_auto)
536     {
537       if (target_supports_evaluation_of_breakpoint_conditions ())
538         return condition_evaluation_target;
539       else
540         return condition_evaluation_host;
541     }
542   else
543     return mode;
544 }
545
546 /* Discovers what condition_evaluation_auto translates to.  */
547
548 static const char *
549 breakpoint_condition_evaluation_mode (void)
550 {
551   return translate_condition_evaluation_mode (condition_evaluation_mode);
552 }
553
554 /* Return true if GDB should evaluate breakpoint conditions or false
555    otherwise.  */
556
557 static int
558 gdb_evaluates_breakpoint_condition_p (void)
559 {
560   const char *mode = breakpoint_condition_evaluation_mode ();
561
562   return (mode == condition_evaluation_host);
563 }
564
565 void _initialize_breakpoint (void);
566
567 /* Are we executing breakpoint commands?  */
568 static int executing_breakpoint_commands;
569
570 /* Are overlay event breakpoints enabled? */
571 static int overlay_events_enabled;
572
573 /* See description in breakpoint.h. */
574 int target_exact_watchpoints = 0;
575
576 /* Walk the following statement or block through all breakpoints.
577    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
578    current breakpoint.  */
579
580 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
581
582 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
583         for (B = breakpoint_chain;      \
584              B ? (TMP=B->next, 1): 0;   \
585              B = TMP)
586
587 /* Similar iterator for the low-level breakpoints.  SAFE variant is
588    not provided so update_global_location_list must not be called
589    while executing the block of ALL_BP_LOCATIONS.  */
590
591 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
592         for (BP_TMP = bp_location;                                      \
593              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
594              BP_TMP++)
595
596 /* Iterates through locations with address ADDRESS for the currently selected
597    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
598    to where the loop should start from.
599    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
600    appropriate location to start with.  */
601
602 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
603         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
604              BP_LOCP_TMP = BP_LOCP_START;                               \
605              BP_LOCP_START                                              \
606              && (BP_LOCP_TMP < bp_location + bp_location_count          \
607              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
608              BP_LOCP_TMP++)
609
610 /* Iterator for tracepoints only.  */
611
612 #define ALL_TRACEPOINTS(B)  \
613   for (B = breakpoint_chain; B; B = B->next)  \
614     if (is_tracepoint (B))
615
616 /* Chains of all breakpoints defined.  */
617
618 struct breakpoint *breakpoint_chain;
619
620 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
621
622 static struct bp_location **bp_location;
623
624 /* Number of elements of BP_LOCATION.  */
625
626 static unsigned bp_location_count;
627
628 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
629    ADDRESS for the current elements of BP_LOCATION which get a valid
630    result from bp_location_has_shadow.  You can use it for roughly
631    limiting the subrange of BP_LOCATION to scan for shadow bytes for
632    an address you need to read.  */
633
634 static CORE_ADDR bp_location_placed_address_before_address_max;
635
636 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
637    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
638    BP_LOCATION which get a valid result from bp_location_has_shadow.
639    You can use it for roughly limiting the subrange of BP_LOCATION to
640    scan for shadow bytes for an address you need to read.  */
641
642 static CORE_ADDR bp_location_shadow_len_after_address_max;
643
644 /* The locations that no longer correspond to any breakpoint, unlinked
645    from bp_location array, but for which a hit may still be reported
646    by a target.  */
647 VEC(bp_location_p) *moribund_locations = NULL;
648
649 /* Number of last breakpoint made.  */
650
651 static int breakpoint_count;
652
653 /* The value of `breakpoint_count' before the last command that
654    created breakpoints.  If the last (break-like) command created more
655    than one breakpoint, then the difference between BREAKPOINT_COUNT
656    and PREV_BREAKPOINT_COUNT is more than one.  */
657 static int prev_breakpoint_count;
658
659 /* Number of last tracepoint made.  */
660
661 static int tracepoint_count;
662
663 static struct cmd_list_element *breakpoint_set_cmdlist;
664 static struct cmd_list_element *breakpoint_show_cmdlist;
665 struct cmd_list_element *save_cmdlist;
666
667 /* See declaration at breakpoint.h.  */
668
669 struct breakpoint *
670 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
671                     void *user_data)
672 {
673   struct breakpoint *b = NULL;
674
675   ALL_BREAKPOINTS (b)
676     {
677       if (func (b, user_data) != 0)
678         break;
679     }
680
681   return b;
682 }
683
684 /* Return whether a breakpoint is an active enabled breakpoint.  */
685 static int
686 breakpoint_enabled (struct breakpoint *b)
687 {
688   return (b->enable_state == bp_enabled);
689 }
690
691 /* Set breakpoint count to NUM.  */
692
693 static void
694 set_breakpoint_count (int num)
695 {
696   prev_breakpoint_count = breakpoint_count;
697   breakpoint_count = num;
698   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
699 }
700
701 /* Used by `start_rbreak_breakpoints' below, to record the current
702    breakpoint count before "rbreak" creates any breakpoint.  */
703 static int rbreak_start_breakpoint_count;
704
705 /* Called at the start an "rbreak" command to record the first
706    breakpoint made.  */
707
708 void
709 start_rbreak_breakpoints (void)
710 {
711   rbreak_start_breakpoint_count = breakpoint_count;
712 }
713
714 /* Called at the end of an "rbreak" command to record the last
715    breakpoint made.  */
716
717 void
718 end_rbreak_breakpoints (void)
719 {
720   prev_breakpoint_count = rbreak_start_breakpoint_count;
721 }
722
723 /* Used in run_command to zero the hit count when a new run starts.  */
724
725 void
726 clear_breakpoint_hit_counts (void)
727 {
728   struct breakpoint *b;
729
730   ALL_BREAKPOINTS (b)
731     b->hit_count = 0;
732 }
733
734 /* Allocate a new counted_command_line with reference count of 1.
735    The new structure owns COMMANDS.  */
736
737 static struct counted_command_line *
738 alloc_counted_command_line (struct command_line *commands)
739 {
740   struct counted_command_line *result = XNEW (struct counted_command_line);
741
742   result->refc = 1;
743   result->commands = commands;
744
745   return result;
746 }
747
748 /* Increment reference count.  This does nothing if CMD is NULL.  */
749
750 static void
751 incref_counted_command_line (struct counted_command_line *cmd)
752 {
753   if (cmd)
754     ++cmd->refc;
755 }
756
757 /* Decrement reference count.  If the reference count reaches 0,
758    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
759    nothing if *CMDP is NULL.  */
760
761 static void
762 decref_counted_command_line (struct counted_command_line **cmdp)
763 {
764   if (*cmdp)
765     {
766       if (--(*cmdp)->refc == 0)
767         {
768           free_command_lines (&(*cmdp)->commands);
769           xfree (*cmdp);
770         }
771       *cmdp = NULL;
772     }
773 }
774
775 /* A cleanup function that calls decref_counted_command_line.  */
776
777 static void
778 do_cleanup_counted_command_line (void *arg)
779 {
780   decref_counted_command_line ((struct counted_command_line **) arg);
781 }
782
783 /* Create a cleanup that calls decref_counted_command_line on the
784    argument.  */
785
786 static struct cleanup *
787 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
788 {
789   return make_cleanup (do_cleanup_counted_command_line, cmdp);
790 }
791
792 \f
793 /* Return the breakpoint with the specified number, or NULL
794    if the number does not refer to an existing breakpoint.  */
795
796 struct breakpoint *
797 get_breakpoint (int num)
798 {
799   struct breakpoint *b;
800
801   ALL_BREAKPOINTS (b)
802     if (b->number == num)
803       return b;
804   
805   return NULL;
806 }
807
808 \f
809
810 /* Mark locations as "conditions have changed" in case the target supports
811    evaluating conditions on its side.  */
812
813 static void
814 mark_breakpoint_modified (struct breakpoint *b)
815 {
816   struct bp_location *loc;
817
818   /* This is only meaningful if the target is
819      evaluating conditions and if the user has
820      opted for condition evaluation on the target's
821      side.  */
822   if (gdb_evaluates_breakpoint_condition_p ()
823       || !target_supports_evaluation_of_breakpoint_conditions ())
824     return;
825
826   if (!is_breakpoint (b))
827     return;
828
829   for (loc = b->loc; loc; loc = loc->next)
830     loc->condition_changed = condition_modified;
831 }
832
833 /* Mark location as "conditions have changed" in case the target supports
834    evaluating conditions on its side.  */
835
836 static void
837 mark_breakpoint_location_modified (struct bp_location *loc)
838 {
839   /* This is only meaningful if the target is
840      evaluating conditions and if the user has
841      opted for condition evaluation on the target's
842      side.  */
843   if (gdb_evaluates_breakpoint_condition_p ()
844       || !target_supports_evaluation_of_breakpoint_conditions ())
845
846     return;
847
848   if (!is_breakpoint (loc->owner))
849     return;
850
851   loc->condition_changed = condition_modified;
852 }
853
854 /* Sets the condition-evaluation mode using the static global
855    condition_evaluation_mode.  */
856
857 static void
858 set_condition_evaluation_mode (char *args, int from_tty,
859                                struct cmd_list_element *c)
860 {
861   const char *old_mode, *new_mode;
862
863   if ((condition_evaluation_mode_1 == condition_evaluation_target)
864       && !target_supports_evaluation_of_breakpoint_conditions ())
865     {
866       condition_evaluation_mode_1 = condition_evaluation_mode;
867       warning (_("Target does not support breakpoint condition evaluation.\n"
868                  "Using host evaluation mode instead."));
869       return;
870     }
871
872   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
873   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
874
875   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
876      settings was "auto".  */
877   condition_evaluation_mode = condition_evaluation_mode_1;
878
879   /* Only update the mode if the user picked a different one.  */
880   if (new_mode != old_mode)
881     {
882       struct bp_location *loc, **loc_tmp;
883       /* If the user switched to a different evaluation mode, we
884          need to synch the changes with the target as follows:
885
886          "host" -> "target": Send all (valid) conditions to the target.
887          "target" -> "host": Remove all the conditions from the target.
888       */
889
890       if (new_mode == condition_evaluation_target)
891         {
892           /* Mark everything modified and synch conditions with the
893              target.  */
894           ALL_BP_LOCATIONS (loc, loc_tmp)
895             mark_breakpoint_location_modified (loc);
896         }
897       else
898         {
899           /* Manually mark non-duplicate locations to synch conditions
900              with the target.  We do this to remove all the conditions the
901              target knows about.  */
902           ALL_BP_LOCATIONS (loc, loc_tmp)
903             if (is_breakpoint (loc->owner) && loc->inserted)
904               loc->needs_update = 1;
905         }
906
907       /* Do the update.  */
908       update_global_location_list (UGLL_MAY_INSERT);
909     }
910
911   return;
912 }
913
914 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
915    what "auto" is translating to.  */
916
917 static void
918 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
919                                 struct cmd_list_element *c, const char *value)
920 {
921   if (condition_evaluation_mode == condition_evaluation_auto)
922     fprintf_filtered (file,
923                       _("Breakpoint condition evaluation "
924                         "mode is %s (currently %s).\n"),
925                       value,
926                       breakpoint_condition_evaluation_mode ());
927   else
928     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
929                       value);
930 }
931
932 /* A comparison function for bp_location AP and BP that is used by
933    bsearch.  This comparison function only cares about addresses, unlike
934    the more general bp_location_compare function.  */
935
936 static int
937 bp_location_compare_addrs (const void *ap, const void *bp)
938 {
939   const struct bp_location *a = *(const struct bp_location **) ap;
940   const struct bp_location *b = *(const struct bp_location **) bp;
941
942   if (a->address == b->address)
943     return 0;
944   else
945     return ((a->address > b->address) - (a->address < b->address));
946 }
947
948 /* Helper function to skip all bp_locations with addresses
949    less than ADDRESS.  It returns the first bp_location that
950    is greater than or equal to ADDRESS.  If none is found, just
951    return NULL.  */
952
953 static struct bp_location **
954 get_first_locp_gte_addr (CORE_ADDR address)
955 {
956   struct bp_location dummy_loc;
957   struct bp_location *dummy_locp = &dummy_loc;
958   struct bp_location **locp_found = NULL;
959
960   /* Initialize the dummy location's address field.  */
961   memset (&dummy_loc, 0, sizeof (struct bp_location));
962   dummy_loc.address = address;
963
964   /* Find a close match to the first location at ADDRESS.  */
965   locp_found = ((struct bp_location **)
966                 bsearch (&dummy_locp, bp_location, bp_location_count,
967                          sizeof (struct bp_location **),
968                          bp_location_compare_addrs));
969
970   /* Nothing was found, nothing left to do.  */
971   if (locp_found == NULL)
972     return NULL;
973
974   /* We may have found a location that is at ADDRESS but is not the first in the
975      location's list.  Go backwards (if possible) and locate the first one.  */
976   while ((locp_found - 1) >= bp_location
977          && (*(locp_found - 1))->address == address)
978     locp_found--;
979
980   return locp_found;
981 }
982
983 void
984 set_breakpoint_condition (struct breakpoint *b, const char *exp,
985                           int from_tty)
986 {
987   xfree (b->cond_string);
988   b->cond_string = NULL;
989
990   if (is_watchpoint (b))
991     {
992       struct watchpoint *w = (struct watchpoint *) b;
993
994       xfree (w->cond_exp);
995       w->cond_exp = NULL;
996     }
997   else
998     {
999       struct bp_location *loc;
1000
1001       for (loc = b->loc; loc; loc = loc->next)
1002         {
1003           xfree (loc->cond);
1004           loc->cond = NULL;
1005
1006           /* No need to free the condition agent expression
1007              bytecode (if we have one).  We will handle this
1008              when we go through update_global_location_list.  */
1009         }
1010     }
1011
1012   if (*exp == 0)
1013     {
1014       if (from_tty)
1015         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1016     }
1017   else
1018     {
1019       const char *arg = exp;
1020
1021       /* I don't know if it matters whether this is the string the user
1022          typed in or the decompiled expression.  */
1023       b->cond_string = xstrdup (arg);
1024       b->condition_not_parsed = 0;
1025
1026       if (is_watchpoint (b))
1027         {
1028           struct watchpoint *w = (struct watchpoint *) b;
1029
1030           innermost_block = NULL;
1031           arg = exp;
1032           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1033           if (*arg)
1034             error (_("Junk at end of expression"));
1035           w->cond_exp_valid_block = innermost_block;
1036         }
1037       else
1038         {
1039           struct bp_location *loc;
1040
1041           for (loc = b->loc; loc; loc = loc->next)
1042             {
1043               arg = exp;
1044               loc->cond =
1045                 parse_exp_1 (&arg, loc->address,
1046                              block_for_pc (loc->address), 0);
1047               if (*arg)
1048                 error (_("Junk at end of expression"));
1049             }
1050         }
1051     }
1052   mark_breakpoint_modified (b);
1053
1054   observer_notify_breakpoint_modified (b);
1055 }
1056
1057 /* Completion for the "condition" command.  */
1058
1059 static VEC (char_ptr) *
1060 condition_completer (struct cmd_list_element *cmd,
1061                      const char *text, const char *word)
1062 {
1063   const char *space;
1064
1065   text = skip_spaces_const (text);
1066   space = skip_to_space_const (text);
1067   if (*space == '\0')
1068     {
1069       int len;
1070       struct breakpoint *b;
1071       VEC (char_ptr) *result = NULL;
1072
1073       if (text[0] == '$')
1074         {
1075           /* We don't support completion of history indices.  */
1076           if (isdigit (text[1]))
1077             return NULL;
1078           return complete_internalvar (&text[1]);
1079         }
1080
1081       /* We're completing the breakpoint number.  */
1082       len = strlen (text);
1083
1084       ALL_BREAKPOINTS (b)
1085         {
1086           char number[50];
1087
1088           xsnprintf (number, sizeof (number), "%d", b->number);
1089
1090           if (strncmp (number, text, len) == 0)
1091             VEC_safe_push (char_ptr, result, xstrdup (number));
1092         }
1093
1094       return result;
1095     }
1096
1097   /* We're completing the expression part.  */
1098   text = skip_spaces_const (space);
1099   return expression_completer (cmd, text, word);
1100 }
1101
1102 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1103
1104 static void
1105 condition_command (char *arg, int from_tty)
1106 {
1107   struct breakpoint *b;
1108   char *p;
1109   int bnum;
1110
1111   if (arg == 0)
1112     error_no_arg (_("breakpoint number"));
1113
1114   p = arg;
1115   bnum = get_number (&p);
1116   if (bnum == 0)
1117     error (_("Bad breakpoint argument: '%s'"), arg);
1118
1119   ALL_BREAKPOINTS (b)
1120     if (b->number == bnum)
1121       {
1122         /* Check if this breakpoint has a "stop" method implemented in an
1123            extension language.  This method and conditions entered into GDB
1124            from the CLI are mutually exclusive.  */
1125         const struct extension_language_defn *extlang
1126           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1127
1128         if (extlang != NULL)
1129           {
1130             error (_("Only one stop condition allowed.  There is currently"
1131                      " a %s stop condition defined for this breakpoint."),
1132                    ext_lang_capitalized_name (extlang));
1133           }
1134         set_breakpoint_condition (b, p, from_tty);
1135
1136         if (is_breakpoint (b))
1137           update_global_location_list (UGLL_MAY_INSERT);
1138
1139         return;
1140       }
1141
1142   error (_("No breakpoint number %d."), bnum);
1143 }
1144
1145 /* Check that COMMAND do not contain commands that are suitable
1146    only for tracepoints and not suitable for ordinary breakpoints.
1147    Throw if any such commands is found.  */
1148
1149 static void
1150 check_no_tracepoint_commands (struct command_line *commands)
1151 {
1152   struct command_line *c;
1153
1154   for (c = commands; c; c = c->next)
1155     {
1156       int i;
1157
1158       if (c->control_type == while_stepping_control)
1159         error (_("The 'while-stepping' command can "
1160                  "only be used for tracepoints"));
1161
1162       for (i = 0; i < c->body_count; ++i)
1163         check_no_tracepoint_commands ((c->body_list)[i]);
1164
1165       /* Not that command parsing removes leading whitespace and comment
1166          lines and also empty lines.  So, we only need to check for
1167          command directly.  */
1168       if (strstr (c->line, "collect ") == c->line)
1169         error (_("The 'collect' command can only be used for tracepoints"));
1170
1171       if (strstr (c->line, "teval ") == c->line)
1172         error (_("The 'teval' command can only be used for tracepoints"));
1173     }
1174 }
1175
1176 /* Encapsulate tests for different types of tracepoints.  */
1177
1178 static int
1179 is_tracepoint_type (enum bptype type)
1180 {
1181   return (type == bp_tracepoint
1182           || type == bp_fast_tracepoint
1183           || type == bp_static_tracepoint);
1184 }
1185
1186 int
1187 is_tracepoint (const struct breakpoint *b)
1188 {
1189   return is_tracepoint_type (b->type);
1190 }
1191
1192 /* A helper function that validates that COMMANDS are valid for a
1193    breakpoint.  This function will throw an exception if a problem is
1194    found.  */
1195
1196 static void
1197 validate_commands_for_breakpoint (struct breakpoint *b,
1198                                   struct command_line *commands)
1199 {
1200   if (is_tracepoint (b))
1201     {
1202       struct tracepoint *t = (struct tracepoint *) b;
1203       struct command_line *c;
1204       struct command_line *while_stepping = 0;
1205
1206       /* Reset the while-stepping step count.  The previous commands
1207          might have included a while-stepping action, while the new
1208          ones might not.  */
1209       t->step_count = 0;
1210
1211       /* We need to verify that each top-level element of commands is
1212          valid for tracepoints, that there's at most one
1213          while-stepping element, and that the while-stepping's body
1214          has valid tracing commands excluding nested while-stepping.
1215          We also need to validate the tracepoint action line in the
1216          context of the tracepoint --- validate_actionline actually
1217          has side effects, like setting the tracepoint's
1218          while-stepping STEP_COUNT, in addition to checking if the
1219          collect/teval actions parse and make sense in the
1220          tracepoint's context.  */
1221       for (c = commands; c; c = c->next)
1222         {
1223           if (c->control_type == while_stepping_control)
1224             {
1225               if (b->type == bp_fast_tracepoint)
1226                 error (_("The 'while-stepping' command "
1227                          "cannot be used for fast tracepoint"));
1228               else if (b->type == bp_static_tracepoint)
1229                 error (_("The 'while-stepping' command "
1230                          "cannot be used for static tracepoint"));
1231
1232               if (while_stepping)
1233                 error (_("The 'while-stepping' command "
1234                          "can be used only once"));
1235               else
1236                 while_stepping = c;
1237             }
1238
1239           validate_actionline (c->line, b);
1240         }
1241       if (while_stepping)
1242         {
1243           struct command_line *c2;
1244
1245           gdb_assert (while_stepping->body_count == 1);
1246           c2 = while_stepping->body_list[0];
1247           for (; c2; c2 = c2->next)
1248             {
1249               if (c2->control_type == while_stepping_control)
1250                 error (_("The 'while-stepping' command cannot be nested"));
1251             }
1252         }
1253     }
1254   else
1255     {
1256       check_no_tracepoint_commands (commands);
1257     }
1258 }
1259
1260 /* Return a vector of all the static tracepoints set at ADDR.  The
1261    caller is responsible for releasing the vector.  */
1262
1263 VEC(breakpoint_p) *
1264 static_tracepoints_here (CORE_ADDR addr)
1265 {
1266   struct breakpoint *b;
1267   VEC(breakpoint_p) *found = 0;
1268   struct bp_location *loc;
1269
1270   ALL_BREAKPOINTS (b)
1271     if (b->type == bp_static_tracepoint)
1272       {
1273         for (loc = b->loc; loc; loc = loc->next)
1274           if (loc->address == addr)
1275             VEC_safe_push(breakpoint_p, found, b);
1276       }
1277
1278   return found;
1279 }
1280
1281 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1282    validate that only allowed commands are included.  */
1283
1284 void
1285 breakpoint_set_commands (struct breakpoint *b, 
1286                          struct command_line *commands)
1287 {
1288   validate_commands_for_breakpoint (b, commands);
1289
1290   decref_counted_command_line (&b->commands);
1291   b->commands = alloc_counted_command_line (commands);
1292   observer_notify_breakpoint_modified (b);
1293 }
1294
1295 /* Set the internal `silent' flag on the breakpoint.  Note that this
1296    is not the same as the "silent" that may appear in the breakpoint's
1297    commands.  */
1298
1299 void
1300 breakpoint_set_silent (struct breakpoint *b, int silent)
1301 {
1302   int old_silent = b->silent;
1303
1304   b->silent = silent;
1305   if (old_silent != silent)
1306     observer_notify_breakpoint_modified (b);
1307 }
1308
1309 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1310    breakpoint work for any thread.  */
1311
1312 void
1313 breakpoint_set_thread (struct breakpoint *b, int thread)
1314 {
1315   int old_thread = b->thread;
1316
1317   b->thread = thread;
1318   if (old_thread != thread)
1319     observer_notify_breakpoint_modified (b);
1320 }
1321
1322 /* Set the task for this breakpoint.  If TASK is 0, make the
1323    breakpoint work for any task.  */
1324
1325 void
1326 breakpoint_set_task (struct breakpoint *b, int task)
1327 {
1328   int old_task = b->task;
1329
1330   b->task = task;
1331   if (old_task != task)
1332     observer_notify_breakpoint_modified (b);
1333 }
1334
1335 void
1336 check_tracepoint_command (char *line, void *closure)
1337 {
1338   struct breakpoint *b = (struct breakpoint *) closure;
1339
1340   validate_actionline (line, b);
1341 }
1342
1343 /* A structure used to pass information through
1344    map_breakpoint_numbers.  */
1345
1346 struct commands_info
1347 {
1348   /* True if the command was typed at a tty.  */
1349   int from_tty;
1350
1351   /* The breakpoint range spec.  */
1352   char *arg;
1353
1354   /* Non-NULL if the body of the commands are being read from this
1355      already-parsed command.  */
1356   struct command_line *control;
1357
1358   /* The command lines read from the user, or NULL if they have not
1359      yet been read.  */
1360   struct counted_command_line *cmd;
1361 };
1362
1363 /* A callback for map_breakpoint_numbers that sets the commands for
1364    commands_command.  */
1365
1366 static void
1367 do_map_commands_command (struct breakpoint *b, void *data)
1368 {
1369   struct commands_info *info = (struct commands_info *) data;
1370
1371   if (info->cmd == NULL)
1372     {
1373       struct command_line *l;
1374
1375       if (info->control != NULL)
1376         l = copy_command_lines (info->control->body_list[0]);
1377       else
1378         {
1379           struct cleanup *old_chain;
1380           char *str;
1381
1382           str = xstrprintf (_("Type commands for breakpoint(s) "
1383                               "%s, one per line."),
1384                             info->arg);
1385
1386           old_chain = make_cleanup (xfree, str);
1387
1388           l = read_command_lines (str,
1389                                   info->from_tty, 1,
1390                                   (is_tracepoint (b)
1391                                    ? check_tracepoint_command : 0),
1392                                   b);
1393
1394           do_cleanups (old_chain);
1395         }
1396
1397       info->cmd = alloc_counted_command_line (l);
1398     }
1399
1400   /* If a breakpoint was on the list more than once, we don't need to
1401      do anything.  */
1402   if (b->commands != info->cmd)
1403     {
1404       validate_commands_for_breakpoint (b, info->cmd->commands);
1405       incref_counted_command_line (info->cmd);
1406       decref_counted_command_line (&b->commands);
1407       b->commands = info->cmd;
1408       observer_notify_breakpoint_modified (b);
1409     }
1410 }
1411
1412 static void
1413 commands_command_1 (char *arg, int from_tty, 
1414                     struct command_line *control)
1415 {
1416   struct cleanup *cleanups;
1417   struct commands_info info;
1418
1419   info.from_tty = from_tty;
1420   info.control = control;
1421   info.cmd = NULL;
1422   /* If we read command lines from the user, then `info' will hold an
1423      extra reference to the commands that we must clean up.  */
1424   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1425
1426   if (arg == NULL || !*arg)
1427     {
1428       if (breakpoint_count - prev_breakpoint_count > 1)
1429         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1430                           breakpoint_count);
1431       else if (breakpoint_count > 0)
1432         arg = xstrprintf ("%d", breakpoint_count);
1433       else
1434         {
1435           /* So that we don't try to free the incoming non-NULL
1436              argument in the cleanup below.  Mapping breakpoint
1437              numbers will fail in this case.  */
1438           arg = NULL;
1439         }
1440     }
1441   else
1442     /* The command loop has some static state, so we need to preserve
1443        our argument.  */
1444     arg = xstrdup (arg);
1445
1446   if (arg != NULL)
1447     make_cleanup (xfree, arg);
1448
1449   info.arg = arg;
1450
1451   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1452
1453   if (info.cmd == NULL)
1454     error (_("No breakpoints specified."));
1455
1456   do_cleanups (cleanups);
1457 }
1458
1459 static void
1460 commands_command (char *arg, int from_tty)
1461 {
1462   commands_command_1 (arg, from_tty, NULL);
1463 }
1464
1465 /* Like commands_command, but instead of reading the commands from
1466    input stream, takes them from an already parsed command structure.
1467
1468    This is used by cli-script.c to DTRT with breakpoint commands
1469    that are part of if and while bodies.  */
1470 enum command_control_type
1471 commands_from_control_command (char *arg, struct command_line *cmd)
1472 {
1473   commands_command_1 (arg, 0, cmd);
1474   return simple_control;
1475 }
1476
1477 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1478
1479 static int
1480 bp_location_has_shadow (struct bp_location *bl)
1481 {
1482   if (bl->loc_type != bp_loc_software_breakpoint)
1483     return 0;
1484   if (!bl->inserted)
1485     return 0;
1486   if (bl->target_info.shadow_len == 0)
1487     /* BL isn't valid, or doesn't shadow memory.  */
1488     return 0;
1489   return 1;
1490 }
1491
1492 /* Update BUF, which is LEN bytes read from the target address
1493    MEMADDR, by replacing a memory breakpoint with its shadowed
1494    contents.
1495
1496    If READBUF is not NULL, this buffer must not overlap with the of
1497    the breakpoint location's shadow_contents buffer.  Otherwise, a
1498    failed assertion internal error will be raised.  */
1499
1500 static void
1501 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1502                             const gdb_byte *writebuf_org,
1503                             ULONGEST memaddr, LONGEST len,
1504                             struct bp_target_info *target_info,
1505                             struct gdbarch *gdbarch)
1506 {
1507   /* Now do full processing of the found relevant range of elements.  */
1508   CORE_ADDR bp_addr = 0;
1509   int bp_size = 0;
1510   int bptoffset = 0;
1511
1512   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1513                                  current_program_space->aspace, 0))
1514     {
1515       /* The breakpoint is inserted in a different address space.  */
1516       return;
1517     }
1518
1519   /* Addresses and length of the part of the breakpoint that
1520      we need to copy.  */
1521   bp_addr = target_info->placed_address;
1522   bp_size = target_info->shadow_len;
1523
1524   if (bp_addr + bp_size <= memaddr)
1525     {
1526       /* The breakpoint is entirely before the chunk of memory we are
1527          reading.  */
1528       return;
1529     }
1530
1531   if (bp_addr >= memaddr + len)
1532     {
1533       /* The breakpoint is entirely after the chunk of memory we are
1534          reading.  */
1535       return;
1536     }
1537
1538   /* Offset within shadow_contents.  */
1539   if (bp_addr < memaddr)
1540     {
1541       /* Only copy the second part of the breakpoint.  */
1542       bp_size -= memaddr - bp_addr;
1543       bptoffset = memaddr - bp_addr;
1544       bp_addr = memaddr;
1545     }
1546
1547   if (bp_addr + bp_size > memaddr + len)
1548     {
1549       /* Only copy the first part of the breakpoint.  */
1550       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1551     }
1552
1553   if (readbuf != NULL)
1554     {
1555       /* Verify that the readbuf buffer does not overlap with the
1556          shadow_contents buffer.  */
1557       gdb_assert (target_info->shadow_contents >= readbuf + len
1558                   || readbuf >= (target_info->shadow_contents
1559                                  + target_info->shadow_len));
1560
1561       /* Update the read buffer with this inserted breakpoint's
1562          shadow.  */
1563       memcpy (readbuf + bp_addr - memaddr,
1564               target_info->shadow_contents + bptoffset, bp_size);
1565     }
1566   else
1567     {
1568       const unsigned char *bp;
1569       CORE_ADDR addr = target_info->reqstd_address;
1570       int placed_size;
1571
1572       /* Update the shadow with what we want to write to memory.  */
1573       memcpy (target_info->shadow_contents + bptoffset,
1574               writebuf_org + bp_addr - memaddr, bp_size);
1575
1576       /* Determine appropriate breakpoint contents and size for this
1577          address.  */
1578       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1579
1580       /* Update the final write buffer with this inserted
1581          breakpoint's INSN.  */
1582       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1583     }
1584 }
1585
1586 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1587    by replacing any memory breakpoints with their shadowed contents.
1588
1589    If READBUF is not NULL, this buffer must not overlap with any of
1590    the breakpoint location's shadow_contents buffers.  Otherwise,
1591    a failed assertion internal error will be raised.
1592
1593    The range of shadowed area by each bp_location is:
1594      bl->address - bp_location_placed_address_before_address_max
1595      up to bl->address + bp_location_shadow_len_after_address_max
1596    The range we were requested to resolve shadows for is:
1597      memaddr ... memaddr + len
1598    Thus the safe cutoff boundaries for performance optimization are
1599      memaddr + len <= (bl->address
1600                        - bp_location_placed_address_before_address_max)
1601    and:
1602      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1603
1604 void
1605 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1606                         const gdb_byte *writebuf_org,
1607                         ULONGEST memaddr, LONGEST len)
1608 {
1609   /* Left boundary, right boundary and median element of our binary
1610      search.  */
1611   unsigned bc_l, bc_r, bc;
1612
1613   /* Find BC_L which is a leftmost element which may affect BUF
1614      content.  It is safe to report lower value but a failure to
1615      report higher one.  */
1616
1617   bc_l = 0;
1618   bc_r = bp_location_count;
1619   while (bc_l + 1 < bc_r)
1620     {
1621       struct bp_location *bl;
1622
1623       bc = (bc_l + bc_r) / 2;
1624       bl = bp_location[bc];
1625
1626       /* Check first BL->ADDRESS will not overflow due to the added
1627          constant.  Then advance the left boundary only if we are sure
1628          the BC element can in no way affect the BUF content (MEMADDR
1629          to MEMADDR + LEN range).
1630
1631          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1632          offset so that we cannot miss a breakpoint with its shadow
1633          range tail still reaching MEMADDR.  */
1634
1635       if ((bl->address + bp_location_shadow_len_after_address_max
1636            >= bl->address)
1637           && (bl->address + bp_location_shadow_len_after_address_max
1638               <= memaddr))
1639         bc_l = bc;
1640       else
1641         bc_r = bc;
1642     }
1643
1644   /* Due to the binary search above, we need to make sure we pick the
1645      first location that's at BC_L's address.  E.g., if there are
1646      multiple locations at the same address, BC_L may end up pointing
1647      at a duplicate location, and miss the "master"/"inserted"
1648      location.  Say, given locations L1, L2 and L3 at addresses A and
1649      B:
1650
1651       L1@A, L2@A, L3@B, ...
1652
1653      BC_L could end up pointing at location L2, while the "master"
1654      location could be L1.  Since the `loc->inserted' flag is only set
1655      on "master" locations, we'd forget to restore the shadow of L1
1656      and L2.  */
1657   while (bc_l > 0
1658          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1659     bc_l--;
1660
1661   /* Now do full processing of the found relevant range of elements.  */
1662
1663   for (bc = bc_l; bc < bp_location_count; bc++)
1664   {
1665     struct bp_location *bl = bp_location[bc];
1666
1667     /* bp_location array has BL->OWNER always non-NULL.  */
1668     if (bl->owner->type == bp_none)
1669       warning (_("reading through apparently deleted breakpoint #%d?"),
1670                bl->owner->number);
1671
1672     /* Performance optimization: any further element can no longer affect BUF
1673        content.  */
1674
1675     if (bl->address >= bp_location_placed_address_before_address_max
1676         && memaddr + len <= (bl->address
1677                              - bp_location_placed_address_before_address_max))
1678       break;
1679
1680     if (!bp_location_has_shadow (bl))
1681       continue;
1682
1683     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1684                                 memaddr, len, &bl->target_info, bl->gdbarch);
1685   }
1686 }
1687
1688 \f
1689
1690 /* Return true if BPT is either a software breakpoint or a hardware
1691    breakpoint.  */
1692
1693 int
1694 is_breakpoint (const struct breakpoint *bpt)
1695 {
1696   return (bpt->type == bp_breakpoint
1697           || bpt->type == bp_hardware_breakpoint
1698           || bpt->type == bp_dprintf);
1699 }
1700
1701 /* Return true if BPT is of any hardware watchpoint kind.  */
1702
1703 static int
1704 is_hardware_watchpoint (const struct breakpoint *bpt)
1705 {
1706   return (bpt->type == bp_hardware_watchpoint
1707           || bpt->type == bp_read_watchpoint
1708           || bpt->type == bp_access_watchpoint);
1709 }
1710
1711 /* Return true if BPT is of any watchpoint kind, hardware or
1712    software.  */
1713
1714 int
1715 is_watchpoint (const struct breakpoint *bpt)
1716 {
1717   return (is_hardware_watchpoint (bpt)
1718           || bpt->type == bp_watchpoint);
1719 }
1720
1721 /* Returns true if the current thread and its running state are safe
1722    to evaluate or update watchpoint B.  Watchpoints on local
1723    expressions need to be evaluated in the context of the thread that
1724    was current when the watchpoint was created, and, that thread needs
1725    to be stopped to be able to select the correct frame context.
1726    Watchpoints on global expressions can be evaluated on any thread,
1727    and in any state.  It is presently left to the target allowing
1728    memory accesses when threads are running.  */
1729
1730 static int
1731 watchpoint_in_thread_scope (struct watchpoint *b)
1732 {
1733   return (b->base.pspace == current_program_space
1734           && (ptid_equal (b->watchpoint_thread, null_ptid)
1735               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1736                   && !is_executing (inferior_ptid))));
1737 }
1738
1739 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1740    associated bp_watchpoint_scope breakpoint.  */
1741
1742 static void
1743 watchpoint_del_at_next_stop (struct watchpoint *w)
1744 {
1745   struct breakpoint *b = &w->base;
1746
1747   if (b->related_breakpoint != b)
1748     {
1749       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1750       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1751       b->related_breakpoint->disposition = disp_del_at_next_stop;
1752       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1753       b->related_breakpoint = b;
1754     }
1755   b->disposition = disp_del_at_next_stop;
1756 }
1757
1758 /* Extract a bitfield value from value VAL using the bit parameters contained in
1759    watchpoint W.  */
1760
1761 static struct value *
1762 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1763 {
1764   struct value *bit_val;
1765
1766   if (val == NULL)
1767     return NULL;
1768
1769   bit_val = allocate_value (value_type (val));
1770
1771   unpack_value_bitfield (bit_val,
1772                          w->val_bitpos,
1773                          w->val_bitsize,
1774                          value_contents_for_printing (val),
1775                          value_offset (val),
1776                          val);
1777
1778   return bit_val;
1779 }
1780
1781 /* Allocate a dummy location and add it to B, which must be a software
1782    watchpoint.  This is required because even if a software watchpoint
1783    is not watching any memory, bpstat_stop_status requires a location
1784    to be able to report stops.  */
1785
1786 static void
1787 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1788                                             struct program_space *pspace)
1789 {
1790   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1791
1792   b->loc = allocate_bp_location (b);
1793   b->loc->pspace = pspace;
1794   b->loc->address = -1;
1795   b->loc->length = -1;
1796 }
1797
1798 /* Returns true if B is a software watchpoint that is not watching any
1799    memory (e.g., "watch $pc").  */
1800
1801 static int
1802 is_no_memory_software_watchpoint (struct breakpoint *b)
1803 {
1804   return (b->type == bp_watchpoint
1805           && b->loc != NULL
1806           && b->loc->next == NULL
1807           && b->loc->address == -1
1808           && b->loc->length == -1);
1809 }
1810
1811 /* Assuming that B is a watchpoint:
1812    - Reparse watchpoint expression, if REPARSE is non-zero
1813    - Evaluate expression and store the result in B->val
1814    - Evaluate the condition if there is one, and store the result
1815      in b->loc->cond.
1816    - Update the list of values that must be watched in B->loc.
1817
1818    If the watchpoint disposition is disp_del_at_next_stop, then do
1819    nothing.  If this is local watchpoint that is out of scope, delete
1820    it.
1821
1822    Even with `set breakpoint always-inserted on' the watchpoints are
1823    removed + inserted on each stop here.  Normal breakpoints must
1824    never be removed because they might be missed by a running thread
1825    when debugging in non-stop mode.  On the other hand, hardware
1826    watchpoints (is_hardware_watchpoint; processed here) are specific
1827    to each LWP since they are stored in each LWP's hardware debug
1828    registers.  Therefore, such LWP must be stopped first in order to
1829    be able to modify its hardware watchpoints.
1830
1831    Hardware watchpoints must be reset exactly once after being
1832    presented to the user.  It cannot be done sooner, because it would
1833    reset the data used to present the watchpoint hit to the user.  And
1834    it must not be done later because it could display the same single
1835    watchpoint hit during multiple GDB stops.  Note that the latter is
1836    relevant only to the hardware watchpoint types bp_read_watchpoint
1837    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1838    not user-visible - its hit is suppressed if the memory content has
1839    not changed.
1840
1841    The following constraints influence the location where we can reset
1842    hardware watchpoints:
1843
1844    * target_stopped_by_watchpoint and target_stopped_data_address are
1845      called several times when GDB stops.
1846
1847    [linux] 
1848    * Multiple hardware watchpoints can be hit at the same time,
1849      causing GDB to stop.  GDB only presents one hardware watchpoint
1850      hit at a time as the reason for stopping, and all the other hits
1851      are presented later, one after the other, each time the user
1852      requests the execution to be resumed.  Execution is not resumed
1853      for the threads still having pending hit event stored in
1854      LWP_INFO->STATUS.  While the watchpoint is already removed from
1855      the inferior on the first stop the thread hit event is kept being
1856      reported from its cached value by linux_nat_stopped_data_address
1857      until the real thread resume happens after the watchpoint gets
1858      presented and thus its LWP_INFO->STATUS gets reset.
1859
1860    Therefore the hardware watchpoint hit can get safely reset on the
1861    watchpoint removal from inferior.  */
1862
1863 static void
1864 update_watchpoint (struct watchpoint *b, int reparse)
1865 {
1866   int within_current_scope;
1867   struct frame_id saved_frame_id;
1868   int frame_saved;
1869
1870   /* If this is a local watchpoint, we only want to check if the
1871      watchpoint frame is in scope if the current thread is the thread
1872      that was used to create the watchpoint.  */
1873   if (!watchpoint_in_thread_scope (b))
1874     return;
1875
1876   if (b->base.disposition == disp_del_at_next_stop)
1877     return;
1878  
1879   frame_saved = 0;
1880
1881   /* Determine if the watchpoint is within scope.  */
1882   if (b->exp_valid_block == NULL)
1883     within_current_scope = 1;
1884   else
1885     {
1886       struct frame_info *fi = get_current_frame ();
1887       struct gdbarch *frame_arch = get_frame_arch (fi);
1888       CORE_ADDR frame_pc = get_frame_pc (fi);
1889
1890       /* If we're at a point where the stack has been destroyed
1891          (e.g. in a function epilogue), unwinding may not work
1892          properly. Do not attempt to recreate locations at this
1893          point.  See similar comments in watchpoint_check.  */
1894       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1895         return;
1896
1897       /* Save the current frame's ID so we can restore it after
1898          evaluating the watchpoint expression on its own frame.  */
1899       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1900          took a frame parameter, so that we didn't have to change the
1901          selected frame.  */
1902       frame_saved = 1;
1903       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1904
1905       fi = frame_find_by_id (b->watchpoint_frame);
1906       within_current_scope = (fi != NULL);
1907       if (within_current_scope)
1908         select_frame (fi);
1909     }
1910
1911   /* We don't free locations.  They are stored in the bp_location array
1912      and update_global_location_list will eventually delete them and
1913      remove breakpoints if needed.  */
1914   b->base.loc = NULL;
1915
1916   if (within_current_scope && reparse)
1917     {
1918       const char *s;
1919
1920       if (b->exp)
1921         {
1922           xfree (b->exp);
1923           b->exp = NULL;
1924         }
1925       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1926       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1927       /* If the meaning of expression itself changed, the old value is
1928          no longer relevant.  We don't want to report a watchpoint hit
1929          to the user when the old value and the new value may actually
1930          be completely different objects.  */
1931       value_free (b->val);
1932       b->val = NULL;
1933       b->val_valid = 0;
1934
1935       /* Note that unlike with breakpoints, the watchpoint's condition
1936          expression is stored in the breakpoint object, not in the
1937          locations (re)created below.  */
1938       if (b->base.cond_string != NULL)
1939         {
1940           if (b->cond_exp != NULL)
1941             {
1942               xfree (b->cond_exp);
1943               b->cond_exp = NULL;
1944             }
1945
1946           s = b->base.cond_string;
1947           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1948         }
1949     }
1950
1951   /* If we failed to parse the expression, for example because
1952      it refers to a global variable in a not-yet-loaded shared library,
1953      don't try to insert watchpoint.  We don't automatically delete
1954      such watchpoint, though, since failure to parse expression
1955      is different from out-of-scope watchpoint.  */
1956   if (!target_has_execution)
1957     {
1958       /* Without execution, memory can't change.  No use to try and
1959          set watchpoint locations.  The watchpoint will be reset when
1960          the target gains execution, through breakpoint_re_set.  */
1961       if (!can_use_hw_watchpoints)
1962         {
1963           if (b->base.ops->works_in_software_mode (&b->base))
1964             b->base.type = bp_watchpoint;
1965           else
1966             error (_("Can't set read/access watchpoint when "
1967                      "hardware watchpoints are disabled."));
1968         }
1969     }
1970   else if (within_current_scope && b->exp)
1971     {
1972       int pc = 0;
1973       struct value *val_chain, *v, *result, *next;
1974       struct program_space *frame_pspace;
1975
1976       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1977
1978       /* Avoid setting b->val if it's already set.  The meaning of
1979          b->val is 'the last value' user saw, and we should update
1980          it only if we reported that last value to user.  As it
1981          happens, the code that reports it updates b->val directly.
1982          We don't keep track of the memory value for masked
1983          watchpoints.  */
1984       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1985         {
1986           if (b->val_bitsize != 0)
1987             {
1988               v = extract_bitfield_from_watchpoint_value (b, v);
1989               if (v != NULL)
1990                 release_value (v);
1991             }
1992           b->val = v;
1993           b->val_valid = 1;
1994         }
1995
1996       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1997
1998       /* Look at each value on the value chain.  */
1999       for (v = val_chain; v; v = value_next (v))
2000         {
2001           /* If it's a memory location, and GDB actually needed
2002              its contents to evaluate the expression, then we
2003              must watch it.  If the first value returned is
2004              still lazy, that means an error occurred reading it;
2005              watch it anyway in case it becomes readable.  */
2006           if (VALUE_LVAL (v) == lval_memory
2007               && (v == val_chain || ! value_lazy (v)))
2008             {
2009               struct type *vtype = check_typedef (value_type (v));
2010
2011               /* We only watch structs and arrays if user asked
2012                  for it explicitly, never if they just happen to
2013                  appear in the middle of some value chain.  */
2014               if (v == result
2015                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
2016                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
2017                 {
2018                   CORE_ADDR addr;
2019                   enum target_hw_bp_type type;
2020                   struct bp_location *loc, **tmp;
2021                   int bitpos = 0, bitsize = 0;
2022
2023                   if (value_bitsize (v) != 0)
2024                     {
2025                       /* Extract the bit parameters out from the bitfield
2026                          sub-expression.  */
2027                       bitpos = value_bitpos (v);
2028                       bitsize = value_bitsize (v);
2029                     }
2030                   else if (v == result && b->val_bitsize != 0)
2031                     {
2032                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2033                         lvalue whose bit parameters are saved in the fields
2034                         VAL_BITPOS and VAL_BITSIZE.  */
2035                       bitpos = b->val_bitpos;
2036                       bitsize = b->val_bitsize;
2037                     }
2038
2039                   addr = value_address (v);
2040                   if (bitsize != 0)
2041                     {
2042                       /* Skip the bytes that don't contain the bitfield.  */
2043                       addr += bitpos / 8;
2044                     }
2045
2046                   type = hw_write;
2047                   if (b->base.type == bp_read_watchpoint)
2048                     type = hw_read;
2049                   else if (b->base.type == bp_access_watchpoint)
2050                     type = hw_access;
2051
2052                   loc = allocate_bp_location (&b->base);
2053                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2054                     ;
2055                   *tmp = loc;
2056                   loc->gdbarch = get_type_arch (value_type (v));
2057
2058                   loc->pspace = frame_pspace;
2059                   loc->address = addr;
2060
2061                   if (bitsize != 0)
2062                     {
2063                       /* Just cover the bytes that make up the bitfield.  */
2064                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2065                     }
2066                   else
2067                     loc->length = TYPE_LENGTH (value_type (v));
2068
2069                   loc->watchpoint_type = type;
2070                 }
2071             }
2072         }
2073
2074       /* Change the type of breakpoint between hardware assisted or
2075          an ordinary watchpoint depending on the hardware support
2076          and free hardware slots.  REPARSE is set when the inferior
2077          is started.  */
2078       if (reparse)
2079         {
2080           int reg_cnt;
2081           enum bp_loc_type loc_type;
2082           struct bp_location *bl;
2083
2084           reg_cnt = can_use_hardware_watchpoint (val_chain);
2085
2086           if (reg_cnt)
2087             {
2088               int i, target_resources_ok, other_type_used;
2089               enum bptype type;
2090
2091               /* Use an exact watchpoint when there's only one memory region to be
2092                  watched, and only one debug register is needed to watch it.  */
2093               b->exact = target_exact_watchpoints && reg_cnt == 1;
2094
2095               /* We need to determine how many resources are already
2096                  used for all other hardware watchpoints plus this one
2097                  to see if we still have enough resources to also fit
2098                  this watchpoint in as well.  */
2099
2100               /* If this is a software watchpoint, we try to turn it
2101                  to a hardware one -- count resources as if B was of
2102                  hardware watchpoint type.  */
2103               type = b->base.type;
2104               if (type == bp_watchpoint)
2105                 type = bp_hardware_watchpoint;
2106
2107               /* This watchpoint may or may not have been placed on
2108                  the list yet at this point (it won't be in the list
2109                  if we're trying to create it for the first time,
2110                  through watch_command), so always account for it
2111                  manually.  */
2112
2113               /* Count resources used by all watchpoints except B.  */
2114               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2115
2116               /* Add in the resources needed for B.  */
2117               i += hw_watchpoint_use_count (&b->base);
2118
2119               target_resources_ok
2120                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2121               if (target_resources_ok <= 0)
2122                 {
2123                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2124
2125                   if (target_resources_ok == 0 && !sw_mode)
2126                     error (_("Target does not support this type of "
2127                              "hardware watchpoint."));
2128                   else if (target_resources_ok < 0 && !sw_mode)
2129                     error (_("There are not enough available hardware "
2130                              "resources for this watchpoint."));
2131
2132                   /* Downgrade to software watchpoint.  */
2133                   b->base.type = bp_watchpoint;
2134                 }
2135               else
2136                 {
2137                   /* If this was a software watchpoint, we've just
2138                      found we have enough resources to turn it to a
2139                      hardware watchpoint.  Otherwise, this is a
2140                      nop.  */
2141                   b->base.type = type;
2142                 }
2143             }
2144           else if (!b->base.ops->works_in_software_mode (&b->base))
2145             {
2146               if (!can_use_hw_watchpoints)
2147                 error (_("Can't set read/access watchpoint when "
2148                          "hardware watchpoints are disabled."));
2149               else
2150                 error (_("Expression cannot be implemented with "
2151                          "read/access watchpoint."));
2152             }
2153           else
2154             b->base.type = bp_watchpoint;
2155
2156           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2157                       : bp_loc_hardware_watchpoint);
2158           for (bl = b->base.loc; bl; bl = bl->next)
2159             bl->loc_type = loc_type;
2160         }
2161
2162       for (v = val_chain; v; v = next)
2163         {
2164           next = value_next (v);
2165           if (v != b->val)
2166             value_free (v);
2167         }
2168
2169       /* If a software watchpoint is not watching any memory, then the
2170          above left it without any location set up.  But,
2171          bpstat_stop_status requires a location to be able to report
2172          stops, so make sure there's at least a dummy one.  */
2173       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2174         software_watchpoint_add_no_memory_location (&b->base, frame_pspace);
2175     }
2176   else if (!within_current_scope)
2177     {
2178       printf_filtered (_("\
2179 Watchpoint %d deleted because the program has left the block\n\
2180 in which its expression is valid.\n"),
2181                        b->base.number);
2182       watchpoint_del_at_next_stop (b);
2183     }
2184
2185   /* Restore the selected frame.  */
2186   if (frame_saved)
2187     select_frame (frame_find_by_id (saved_frame_id));
2188 }
2189
2190
2191 /* Returns 1 iff breakpoint location should be
2192    inserted in the inferior.  We don't differentiate the type of BL's owner
2193    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2194    breakpoint_ops is not defined, because in insert_bp_location,
2195    tracepoint's insert_location will not be called.  */
2196 static int
2197 should_be_inserted (struct bp_location *bl)
2198 {
2199   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2200     return 0;
2201
2202   if (bl->owner->disposition == disp_del_at_next_stop)
2203     return 0;
2204
2205   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2206     return 0;
2207
2208   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2209     return 0;
2210
2211   /* This is set for example, when we're attached to the parent of a
2212      vfork, and have detached from the child.  The child is running
2213      free, and we expect it to do an exec or exit, at which point the
2214      OS makes the parent schedulable again (and the target reports
2215      that the vfork is done).  Until the child is done with the shared
2216      memory region, do not insert breakpoints in the parent, otherwise
2217      the child could still trip on the parent's breakpoints.  Since
2218      the parent is blocked anyway, it won't miss any breakpoint.  */
2219   if (bl->pspace->breakpoints_not_allowed)
2220     return 0;
2221
2222   /* Don't insert a breakpoint if we're trying to step past its
2223      location, except if the breakpoint is a single-step breakpoint,
2224      and the breakpoint's thread is the thread which is stepping past
2225      a breakpoint.  */
2226   if ((bl->loc_type == bp_loc_software_breakpoint
2227        || bl->loc_type == bp_loc_hardware_breakpoint)
2228       && stepping_past_instruction_at (bl->pspace->aspace,
2229                                        bl->address)
2230       /* The single-step breakpoint may be inserted at the location
2231          we're trying to step if the instruction branches to itself.
2232          However, the instruction won't be executed at all and it may
2233          break the semantics of the instruction, for example, the
2234          instruction is a conditional branch or updates some flags.
2235          We can't fix it unless GDB is able to emulate the instruction
2236          or switch to displaced stepping.  */
2237       && !(bl->owner->type == bp_single_step
2238            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2239     {
2240       if (debug_infrun)
2241         {
2242           fprintf_unfiltered (gdb_stdlog,
2243                               "infrun: skipping breakpoint: "
2244                               "stepping past insn at: %s\n",
2245                               paddress (bl->gdbarch, bl->address));
2246         }
2247       return 0;
2248     }
2249
2250   /* Don't insert watchpoints if we're trying to step past the
2251      instruction that triggered one.  */
2252   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2253       && stepping_past_nonsteppable_watchpoint ())
2254     {
2255       if (debug_infrun)
2256         {
2257           fprintf_unfiltered (gdb_stdlog,
2258                               "infrun: stepping past non-steppable watchpoint. "
2259                               "skipping watchpoint at %s:%d\n",
2260                               paddress (bl->gdbarch, bl->address),
2261                               bl->length);
2262         }
2263       return 0;
2264     }
2265
2266   return 1;
2267 }
2268
2269 /* Same as should_be_inserted but does the check assuming
2270    that the location is not duplicated.  */
2271
2272 static int
2273 unduplicated_should_be_inserted (struct bp_location *bl)
2274 {
2275   int result;
2276   const int save_duplicate = bl->duplicate;
2277
2278   bl->duplicate = 0;
2279   result = should_be_inserted (bl);
2280   bl->duplicate = save_duplicate;
2281   return result;
2282 }
2283
2284 /* Parses a conditional described by an expression COND into an
2285    agent expression bytecode suitable for evaluation
2286    by the bytecode interpreter.  Return NULL if there was
2287    any error during parsing.  */
2288
2289 static struct agent_expr *
2290 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2291 {
2292   struct agent_expr *aexpr = NULL;
2293
2294   if (!cond)
2295     return NULL;
2296
2297   /* We don't want to stop processing, so catch any errors
2298      that may show up.  */
2299   TRY
2300     {
2301       aexpr = gen_eval_for_expr (scope, cond);
2302     }
2303
2304   CATCH (ex, RETURN_MASK_ERROR)
2305     {
2306       /* If we got here, it means the condition could not be parsed to a valid
2307          bytecode expression and thus can't be evaluated on the target's side.
2308          It's no use iterating through the conditions.  */
2309       return NULL;
2310     }
2311   END_CATCH
2312
2313   /* We have a valid agent expression.  */
2314   return aexpr;
2315 }
2316
2317 /* Based on location BL, create a list of breakpoint conditions to be
2318    passed on to the target.  If we have duplicated locations with different
2319    conditions, we will add such conditions to the list.  The idea is that the
2320    target will evaluate the list of conditions and will only notify GDB when
2321    one of them is true.  */
2322
2323 static void
2324 build_target_condition_list (struct bp_location *bl)
2325 {
2326   struct bp_location **locp = NULL, **loc2p;
2327   int null_condition_or_parse_error = 0;
2328   int modified = bl->needs_update;
2329   struct bp_location *loc;
2330
2331   /* Release conditions left over from a previous insert.  */
2332   VEC_free (agent_expr_p, bl->target_info.conditions);
2333
2334   /* This is only meaningful if the target is
2335      evaluating conditions and if the user has
2336      opted for condition evaluation on the target's
2337      side.  */
2338   if (gdb_evaluates_breakpoint_condition_p ()
2339       || !target_supports_evaluation_of_breakpoint_conditions ())
2340     return;
2341
2342   /* Do a first pass to check for locations with no assigned
2343      conditions or conditions that fail to parse to a valid agent expression
2344      bytecode.  If any of these happen, then it's no use to send conditions
2345      to the target since this location will always trigger and generate a
2346      response back to GDB.  */
2347   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2348     {
2349       loc = (*loc2p);
2350       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2351         {
2352           if (modified)
2353             {
2354               struct agent_expr *aexpr;
2355
2356               /* Re-parse the conditions since something changed.  In that
2357                  case we already freed the condition bytecodes (see
2358                  force_breakpoint_reinsertion).  We just
2359                  need to parse the condition to bytecodes again.  */
2360               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2361               loc->cond_bytecode = aexpr;
2362             }
2363
2364           /* If we have a NULL bytecode expression, it means something
2365              went wrong or we have a null condition expression.  */
2366           if (!loc->cond_bytecode)
2367             {
2368               null_condition_or_parse_error = 1;
2369               break;
2370             }
2371         }
2372     }
2373
2374   /* If any of these happened, it means we will have to evaluate the conditions
2375      for the location's address on gdb's side.  It is no use keeping bytecodes
2376      for all the other duplicate locations, thus we free all of them here.
2377
2378      This is so we have a finer control over which locations' conditions are
2379      being evaluated by GDB or the remote stub.  */
2380   if (null_condition_or_parse_error)
2381     {
2382       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2383         {
2384           loc = (*loc2p);
2385           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2386             {
2387               /* Only go as far as the first NULL bytecode is
2388                  located.  */
2389               if (!loc->cond_bytecode)
2390                 return;
2391
2392               free_agent_expr (loc->cond_bytecode);
2393               loc->cond_bytecode = NULL;
2394             }
2395         }
2396     }
2397
2398   /* No NULL conditions or failed bytecode generation.  Build a condition list
2399      for this location's address.  */
2400   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2401     {
2402       loc = (*loc2p);
2403       if (loc->cond
2404           && is_breakpoint (loc->owner)
2405           && loc->pspace->num == bl->pspace->num
2406           && loc->owner->enable_state == bp_enabled
2407           && loc->enabled)
2408         /* Add the condition to the vector.  This will be used later to send the
2409            conditions to the target.  */
2410         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2411                        loc->cond_bytecode);
2412     }
2413
2414   return;
2415 }
2416
2417 /* Parses a command described by string CMD into an agent expression
2418    bytecode suitable for evaluation by the bytecode interpreter.
2419    Return NULL if there was any error during parsing.  */
2420
2421 static struct agent_expr *
2422 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2423 {
2424   struct cleanup *old_cleanups = 0;
2425   struct expression *expr, **argvec;
2426   struct agent_expr *aexpr = NULL;
2427   const char *cmdrest;
2428   const char *format_start, *format_end;
2429   struct format_piece *fpieces;
2430   int nargs;
2431   struct gdbarch *gdbarch = get_current_arch ();
2432
2433   if (!cmd)
2434     return NULL;
2435
2436   cmdrest = cmd;
2437
2438   if (*cmdrest == ',')
2439     ++cmdrest;
2440   cmdrest = skip_spaces_const (cmdrest);
2441
2442   if (*cmdrest++ != '"')
2443     error (_("No format string following the location"));
2444
2445   format_start = cmdrest;
2446
2447   fpieces = parse_format_string (&cmdrest);
2448
2449   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2450
2451   format_end = cmdrest;
2452
2453   if (*cmdrest++ != '"')
2454     error (_("Bad format string, non-terminated '\"'."));
2455   
2456   cmdrest = skip_spaces_const (cmdrest);
2457
2458   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2459     error (_("Invalid argument syntax"));
2460
2461   if (*cmdrest == ',')
2462     cmdrest++;
2463   cmdrest = skip_spaces_const (cmdrest);
2464
2465   /* For each argument, make an expression.  */
2466
2467   argvec = (struct expression **) alloca (strlen (cmd)
2468                                          * sizeof (struct expression *));
2469
2470   nargs = 0;
2471   while (*cmdrest != '\0')
2472     {
2473       const char *cmd1;
2474
2475       cmd1 = cmdrest;
2476       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2477       argvec[nargs++] = expr;
2478       cmdrest = cmd1;
2479       if (*cmdrest == ',')
2480         ++cmdrest;
2481     }
2482
2483   /* We don't want to stop processing, so catch any errors
2484      that may show up.  */
2485   TRY
2486     {
2487       aexpr = gen_printf (scope, gdbarch, 0, 0,
2488                           format_start, format_end - format_start,
2489                           fpieces, nargs, argvec);
2490     }
2491   CATCH (ex, RETURN_MASK_ERROR)
2492     {
2493       /* If we got here, it means the command could not be parsed to a valid
2494          bytecode expression and thus can't be evaluated on the target's side.
2495          It's no use iterating through the other commands.  */
2496       aexpr = NULL;
2497     }
2498   END_CATCH
2499
2500   do_cleanups (old_cleanups);
2501
2502   /* We have a valid agent expression, return it.  */
2503   return aexpr;
2504 }
2505
2506 /* Based on location BL, create a list of breakpoint commands to be
2507    passed on to the target.  If we have duplicated locations with
2508    different commands, we will add any such to the list.  */
2509
2510 static void
2511 build_target_command_list (struct bp_location *bl)
2512 {
2513   struct bp_location **locp = NULL, **loc2p;
2514   int null_command_or_parse_error = 0;
2515   int modified = bl->needs_update;
2516   struct bp_location *loc;
2517
2518   /* Release commands left over from a previous insert.  */
2519   VEC_free (agent_expr_p, bl->target_info.tcommands);
2520
2521   if (!target_can_run_breakpoint_commands ())
2522     return;
2523
2524   /* For now, limit to agent-style dprintf breakpoints.  */
2525   if (dprintf_style != dprintf_style_agent)
2526     return;
2527
2528   /* For now, if we have any duplicate location that isn't a dprintf,
2529      don't install the target-side commands, as that would make the
2530      breakpoint not be reported to the core, and we'd lose
2531      control.  */
2532   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2533     {
2534       loc = (*loc2p);
2535       if (is_breakpoint (loc->owner)
2536           && loc->pspace->num == bl->pspace->num
2537           && loc->owner->type != bp_dprintf)
2538         return;
2539     }
2540
2541   /* Do a first pass to check for locations with no assigned
2542      conditions or conditions that fail to parse to a valid agent expression
2543      bytecode.  If any of these happen, then it's no use to send conditions
2544      to the target since this location will always trigger and generate a
2545      response back to GDB.  */
2546   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2547     {
2548       loc = (*loc2p);
2549       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2550         {
2551           if (modified)
2552             {
2553               struct agent_expr *aexpr;
2554
2555               /* Re-parse the commands since something changed.  In that
2556                  case we already freed the command bytecodes (see
2557                  force_breakpoint_reinsertion).  We just
2558                  need to parse the command to bytecodes again.  */
2559               aexpr = parse_cmd_to_aexpr (bl->address,
2560                                           loc->owner->extra_string);
2561               loc->cmd_bytecode = aexpr;
2562             }
2563
2564           /* If we have a NULL bytecode expression, it means something
2565              went wrong or we have a null command expression.  */
2566           if (!loc->cmd_bytecode)
2567             {
2568               null_command_or_parse_error = 1;
2569               break;
2570             }
2571         }
2572     }
2573
2574   /* If anything failed, then we're not doing target-side commands,
2575      and so clean up.  */
2576   if (null_command_or_parse_error)
2577     {
2578       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2579         {
2580           loc = (*loc2p);
2581           if (is_breakpoint (loc->owner)
2582               && loc->pspace->num == bl->pspace->num)
2583             {
2584               /* Only go as far as the first NULL bytecode is
2585                  located.  */
2586               if (loc->cmd_bytecode == NULL)
2587                 return;
2588
2589               free_agent_expr (loc->cmd_bytecode);
2590               loc->cmd_bytecode = NULL;
2591             }
2592         }
2593     }
2594
2595   /* No NULL commands or failed bytecode generation.  Build a command list
2596      for this location's address.  */
2597   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2598     {
2599       loc = (*loc2p);
2600       if (loc->owner->extra_string
2601           && is_breakpoint (loc->owner)
2602           && loc->pspace->num == bl->pspace->num
2603           && loc->owner->enable_state == bp_enabled
2604           && loc->enabled)
2605         /* Add the command to the vector.  This will be used later
2606            to send the commands to the target.  */
2607         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2608                        loc->cmd_bytecode);
2609     }
2610
2611   bl->target_info.persist = 0;
2612   /* Maybe flag this location as persistent.  */
2613   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2614     bl->target_info.persist = 1;
2615 }
2616
2617 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2618    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2619    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2620    Returns 0 for success, 1 if the bp_location type is not supported or
2621    -1 for failure.
2622
2623    NOTE drow/2003-09-09: This routine could be broken down to an
2624    object-style method for each breakpoint or catchpoint type.  */
2625 static int
2626 insert_bp_location (struct bp_location *bl,
2627                     struct ui_file *tmp_error_stream,
2628                     int *disabled_breaks,
2629                     int *hw_breakpoint_error,
2630                     int *hw_bp_error_explained_already)
2631 {
2632   enum errors bp_err = GDB_NO_ERROR;
2633   const char *bp_err_message = NULL;
2634
2635   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2636     return 0;
2637
2638   /* Note we don't initialize bl->target_info, as that wipes out
2639      the breakpoint location's shadow_contents if the breakpoint
2640      is still inserted at that location.  This in turn breaks
2641      target_read_memory which depends on these buffers when
2642      a memory read is requested at the breakpoint location:
2643      Once the target_info has been wiped, we fail to see that
2644      we have a breakpoint inserted at that address and thus
2645      read the breakpoint instead of returning the data saved in
2646      the breakpoint location's shadow contents.  */
2647   bl->target_info.reqstd_address = bl->address;
2648   bl->target_info.placed_address_space = bl->pspace->aspace;
2649   bl->target_info.length = bl->length;
2650
2651   /* When working with target-side conditions, we must pass all the conditions
2652      for the same breakpoint address down to the target since GDB will not
2653      insert those locations.  With a list of breakpoint conditions, the target
2654      can decide when to stop and notify GDB.  */
2655
2656   if (is_breakpoint (bl->owner))
2657     {
2658       build_target_condition_list (bl);
2659       build_target_command_list (bl);
2660       /* Reset the modification marker.  */
2661       bl->needs_update = 0;
2662     }
2663
2664   if (bl->loc_type == bp_loc_software_breakpoint
2665       || bl->loc_type == bp_loc_hardware_breakpoint)
2666     {
2667       if (bl->owner->type != bp_hardware_breakpoint)
2668         {
2669           /* If the explicitly specified breakpoint type
2670              is not hardware breakpoint, check the memory map to see
2671              if the breakpoint address is in read only memory or not.
2672
2673              Two important cases are:
2674              - location type is not hardware breakpoint, memory
2675              is readonly.  We change the type of the location to
2676              hardware breakpoint.
2677              - location type is hardware breakpoint, memory is
2678              read-write.  This means we've previously made the
2679              location hardware one, but then the memory map changed,
2680              so we undo.
2681              
2682              When breakpoints are removed, remove_breakpoints will use
2683              location types we've just set here, the only possible
2684              problem is that memory map has changed during running
2685              program, but it's not going to work anyway with current
2686              gdb.  */
2687           struct mem_region *mr 
2688             = lookup_mem_region (bl->target_info.reqstd_address);
2689           
2690           if (mr)
2691             {
2692               if (automatic_hardware_breakpoints)
2693                 {
2694                   enum bp_loc_type new_type;
2695                   
2696                   if (mr->attrib.mode != MEM_RW)
2697                     new_type = bp_loc_hardware_breakpoint;
2698                   else 
2699                     new_type = bp_loc_software_breakpoint;
2700                   
2701                   if (new_type != bl->loc_type)
2702                     {
2703                       static int said = 0;
2704
2705                       bl->loc_type = new_type;
2706                       if (!said)
2707                         {
2708                           fprintf_filtered (gdb_stdout,
2709                                             _("Note: automatically using "
2710                                               "hardware breakpoints for "
2711                                               "read-only addresses.\n"));
2712                           said = 1;
2713                         }
2714                     }
2715                 }
2716               else if (bl->loc_type == bp_loc_software_breakpoint
2717                        && mr->attrib.mode != MEM_RW)
2718                 {
2719                   fprintf_unfiltered (tmp_error_stream,
2720                                       _("Cannot insert breakpoint %d.\n"
2721                                         "Cannot set software breakpoint "
2722                                         "at read-only address %s\n"),
2723                                       bl->owner->number,
2724                                       paddress (bl->gdbarch, bl->address));
2725                   return 1;
2726                 }
2727             }
2728         }
2729         
2730       /* First check to see if we have to handle an overlay.  */
2731       if (overlay_debugging == ovly_off
2732           || bl->section == NULL
2733           || !(section_is_overlay (bl->section)))
2734         {
2735           /* No overlay handling: just set the breakpoint.  */
2736           TRY
2737             {
2738               int val;
2739
2740               val = bl->owner->ops->insert_location (bl);
2741               if (val)
2742                 bp_err = GENERIC_ERROR;
2743             }
2744           CATCH (e, RETURN_MASK_ALL)
2745             {
2746               bp_err = e.error;
2747               bp_err_message = e.message;
2748             }
2749           END_CATCH
2750         }
2751       else
2752         {
2753           /* This breakpoint is in an overlay section.
2754              Shall we set a breakpoint at the LMA?  */
2755           if (!overlay_events_enabled)
2756             {
2757               /* Yes -- overlay event support is not active, 
2758                  so we must try to set a breakpoint at the LMA.
2759                  This will not work for a hardware breakpoint.  */
2760               if (bl->loc_type == bp_loc_hardware_breakpoint)
2761                 warning (_("hardware breakpoint %d not supported in overlay!"),
2762                          bl->owner->number);
2763               else
2764                 {
2765                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2766                                                              bl->section);
2767                   /* Set a software (trap) breakpoint at the LMA.  */
2768                   bl->overlay_target_info = bl->target_info;
2769                   bl->overlay_target_info.reqstd_address = addr;
2770
2771                   /* No overlay handling: just set the breakpoint.  */
2772                   TRY
2773                     {
2774                       int val;
2775
2776                       val = target_insert_breakpoint (bl->gdbarch,
2777                                                       &bl->overlay_target_info);
2778                       if (val)
2779                         bp_err = GENERIC_ERROR;
2780                     }
2781                   CATCH (e, RETURN_MASK_ALL)
2782                     {
2783                       bp_err = e.error;
2784                       bp_err_message = e.message;
2785                     }
2786                   END_CATCH
2787
2788                   if (bp_err != GDB_NO_ERROR)
2789                     fprintf_unfiltered (tmp_error_stream,
2790                                         "Overlay breakpoint %d "
2791                                         "failed: in ROM?\n",
2792                                         bl->owner->number);
2793                 }
2794             }
2795           /* Shall we set a breakpoint at the VMA? */
2796           if (section_is_mapped (bl->section))
2797             {
2798               /* Yes.  This overlay section is mapped into memory.  */
2799               TRY
2800                 {
2801                   int val;
2802
2803                   val = bl->owner->ops->insert_location (bl);
2804                   if (val)
2805                     bp_err = GENERIC_ERROR;
2806                 }
2807               CATCH (e, RETURN_MASK_ALL)
2808                 {
2809                   bp_err = e.error;
2810                   bp_err_message = e.message;
2811                 }
2812               END_CATCH
2813             }
2814           else
2815             {
2816               /* No.  This breakpoint will not be inserted.  
2817                  No error, but do not mark the bp as 'inserted'.  */
2818               return 0;
2819             }
2820         }
2821
2822       if (bp_err != GDB_NO_ERROR)
2823         {
2824           /* Can't set the breakpoint.  */
2825
2826           /* In some cases, we might not be able to insert a
2827              breakpoint in a shared library that has already been
2828              removed, but we have not yet processed the shlib unload
2829              event.  Unfortunately, some targets that implement
2830              breakpoint insertion themselves can't tell why the
2831              breakpoint insertion failed (e.g., the remote target
2832              doesn't define error codes), so we must treat generic
2833              errors as memory errors.  */
2834           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2835               && bl->loc_type == bp_loc_software_breakpoint
2836               && (solib_name_from_address (bl->pspace, bl->address)
2837                   || shared_objfile_contains_address_p (bl->pspace,
2838                                                         bl->address)))
2839             {
2840               /* See also: disable_breakpoints_in_shlibs.  */
2841               bl->shlib_disabled = 1;
2842               observer_notify_breakpoint_modified (bl->owner);
2843               if (!*disabled_breaks)
2844                 {
2845                   fprintf_unfiltered (tmp_error_stream, 
2846                                       "Cannot insert breakpoint %d.\n", 
2847                                       bl->owner->number);
2848                   fprintf_unfiltered (tmp_error_stream, 
2849                                       "Temporarily disabling shared "
2850                                       "library breakpoints:\n");
2851                 }
2852               *disabled_breaks = 1;
2853               fprintf_unfiltered (tmp_error_stream,
2854                                   "breakpoint #%d\n", bl->owner->number);
2855               return 0;
2856             }
2857           else
2858             {
2859               if (bl->loc_type == bp_loc_hardware_breakpoint)
2860                 {
2861                   *hw_breakpoint_error = 1;
2862                   *hw_bp_error_explained_already = bp_err_message != NULL;
2863                   fprintf_unfiltered (tmp_error_stream,
2864                                       "Cannot insert hardware breakpoint %d%s",
2865                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2866                   if (bp_err_message != NULL)
2867                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2868                 }
2869               else
2870                 {
2871                   if (bp_err_message == NULL)
2872                     {
2873                       char *message
2874                         = memory_error_message (TARGET_XFER_E_IO,
2875                                                 bl->gdbarch, bl->address);
2876                       struct cleanup *old_chain = make_cleanup (xfree, message);
2877
2878                       fprintf_unfiltered (tmp_error_stream,
2879                                           "Cannot insert breakpoint %d.\n"
2880                                           "%s\n",
2881                                           bl->owner->number, message);
2882                       do_cleanups (old_chain);
2883                     }
2884                   else
2885                     {
2886                       fprintf_unfiltered (tmp_error_stream,
2887                                           "Cannot insert breakpoint %d: %s\n",
2888                                           bl->owner->number,
2889                                           bp_err_message);
2890                     }
2891                 }
2892               return 1;
2893
2894             }
2895         }
2896       else
2897         bl->inserted = 1;
2898
2899       return 0;
2900     }
2901
2902   else if (bl->loc_type == bp_loc_hardware_watchpoint
2903            /* NOTE drow/2003-09-08: This state only exists for removing
2904               watchpoints.  It's not clear that it's necessary...  */
2905            && bl->owner->disposition != disp_del_at_next_stop)
2906     {
2907       int val;
2908
2909       gdb_assert (bl->owner->ops != NULL
2910                   && bl->owner->ops->insert_location != NULL);
2911
2912       val = bl->owner->ops->insert_location (bl);
2913
2914       /* If trying to set a read-watchpoint, and it turns out it's not
2915          supported, try emulating one with an access watchpoint.  */
2916       if (val == 1 && bl->watchpoint_type == hw_read)
2917         {
2918           struct bp_location *loc, **loc_temp;
2919
2920           /* But don't try to insert it, if there's already another
2921              hw_access location that would be considered a duplicate
2922              of this one.  */
2923           ALL_BP_LOCATIONS (loc, loc_temp)
2924             if (loc != bl
2925                 && loc->watchpoint_type == hw_access
2926                 && watchpoint_locations_match (bl, loc))
2927               {
2928                 bl->duplicate = 1;
2929                 bl->inserted = 1;
2930                 bl->target_info = loc->target_info;
2931                 bl->watchpoint_type = hw_access;
2932                 val = 0;
2933                 break;
2934               }
2935
2936           if (val == 1)
2937             {
2938               bl->watchpoint_type = hw_access;
2939               val = bl->owner->ops->insert_location (bl);
2940
2941               if (val)
2942                 /* Back to the original value.  */
2943                 bl->watchpoint_type = hw_read;
2944             }
2945         }
2946
2947       bl->inserted = (val == 0);
2948     }
2949
2950   else if (bl->owner->type == bp_catchpoint)
2951     {
2952       int val;
2953
2954       gdb_assert (bl->owner->ops != NULL
2955                   && bl->owner->ops->insert_location != NULL);
2956
2957       val = bl->owner->ops->insert_location (bl);
2958       if (val)
2959         {
2960           bl->owner->enable_state = bp_disabled;
2961
2962           if (val == 1)
2963             warning (_("\
2964 Error inserting catchpoint %d: Your system does not support this type\n\
2965 of catchpoint."), bl->owner->number);
2966           else
2967             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2968         }
2969
2970       bl->inserted = (val == 0);
2971
2972       /* We've already printed an error message if there was a problem
2973          inserting this catchpoint, and we've disabled the catchpoint,
2974          so just return success.  */
2975       return 0;
2976     }
2977
2978   return 0;
2979 }
2980
2981 /* This function is called when program space PSPACE is about to be
2982    deleted.  It takes care of updating breakpoints to not reference
2983    PSPACE anymore.  */
2984
2985 void
2986 breakpoint_program_space_exit (struct program_space *pspace)
2987 {
2988   struct breakpoint *b, *b_temp;
2989   struct bp_location *loc, **loc_temp;
2990
2991   /* Remove any breakpoint that was set through this program space.  */
2992   ALL_BREAKPOINTS_SAFE (b, b_temp)
2993     {
2994       if (b->pspace == pspace)
2995         delete_breakpoint (b);
2996     }
2997
2998   /* Breakpoints set through other program spaces could have locations
2999      bound to PSPACE as well.  Remove those.  */
3000   ALL_BP_LOCATIONS (loc, loc_temp)
3001     {
3002       struct bp_location *tmp;
3003
3004       if (loc->pspace == pspace)
3005         {
3006           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
3007           if (loc->owner->loc == loc)
3008             loc->owner->loc = loc->next;
3009           else
3010             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3011               if (tmp->next == loc)
3012                 {
3013                   tmp->next = loc->next;
3014                   break;
3015                 }
3016         }
3017     }
3018
3019   /* Now update the global location list to permanently delete the
3020      removed locations above.  */
3021   update_global_location_list (UGLL_DONT_INSERT);
3022 }
3023
3024 /* Make sure all breakpoints are inserted in inferior.
3025    Throws exception on any error.
3026    A breakpoint that is already inserted won't be inserted
3027    again, so calling this function twice is safe.  */
3028 void
3029 insert_breakpoints (void)
3030 {
3031   struct breakpoint *bpt;
3032
3033   ALL_BREAKPOINTS (bpt)
3034     if (is_hardware_watchpoint (bpt))
3035       {
3036         struct watchpoint *w = (struct watchpoint *) bpt;
3037
3038         update_watchpoint (w, 0 /* don't reparse.  */);
3039       }
3040
3041   /* Updating watchpoints creates new locations, so update the global
3042      location list.  Explicitly tell ugll to insert locations and
3043      ignore breakpoints_always_inserted_mode.  */
3044   update_global_location_list (UGLL_INSERT);
3045 }
3046
3047 /* Invoke CALLBACK for each of bp_location.  */
3048
3049 void
3050 iterate_over_bp_locations (walk_bp_location_callback callback)
3051 {
3052   struct bp_location *loc, **loc_tmp;
3053
3054   ALL_BP_LOCATIONS (loc, loc_tmp)
3055     {
3056       callback (loc, NULL);
3057     }
3058 }
3059
3060 /* This is used when we need to synch breakpoint conditions between GDB and the
3061    target.  It is the case with deleting and disabling of breakpoints when using
3062    always-inserted mode.  */
3063
3064 static void
3065 update_inserted_breakpoint_locations (void)
3066 {
3067   struct bp_location *bl, **blp_tmp;
3068   int error_flag = 0;
3069   int val = 0;
3070   int disabled_breaks = 0;
3071   int hw_breakpoint_error = 0;
3072   int hw_bp_details_reported = 0;
3073
3074   struct ui_file *tmp_error_stream = mem_fileopen ();
3075   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3076
3077   /* Explicitly mark the warning -- this will only be printed if
3078      there was an error.  */
3079   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3080
3081   save_current_space_and_thread ();
3082
3083   ALL_BP_LOCATIONS (bl, blp_tmp)
3084     {
3085       /* We only want to update software breakpoints and hardware
3086          breakpoints.  */
3087       if (!is_breakpoint (bl->owner))
3088         continue;
3089
3090       /* We only want to update locations that are already inserted
3091          and need updating.  This is to avoid unwanted insertion during
3092          deletion of breakpoints.  */
3093       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3094         continue;
3095
3096       switch_to_program_space_and_thread (bl->pspace);
3097
3098       /* For targets that support global breakpoints, there's no need
3099          to select an inferior to insert breakpoint to.  In fact, even
3100          if we aren't attached to any process yet, we should still
3101          insert breakpoints.  */
3102       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3103           && ptid_equal (inferior_ptid, null_ptid))
3104         continue;
3105
3106       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3107                                     &hw_breakpoint_error, &hw_bp_details_reported);
3108       if (val)
3109         error_flag = val;
3110     }
3111
3112   if (error_flag)
3113     {
3114       target_terminal_ours_for_output ();
3115       error_stream (tmp_error_stream);
3116     }
3117
3118   do_cleanups (cleanups);
3119 }
3120
3121 /* Used when starting or continuing the program.  */
3122
3123 static void
3124 insert_breakpoint_locations (void)
3125 {
3126   struct breakpoint *bpt;
3127   struct bp_location *bl, **blp_tmp;
3128   int error_flag = 0;
3129   int val = 0;
3130   int disabled_breaks = 0;
3131   int hw_breakpoint_error = 0;
3132   int hw_bp_error_explained_already = 0;
3133
3134   struct ui_file *tmp_error_stream = mem_fileopen ();
3135   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3136   
3137   /* Explicitly mark the warning -- this will only be printed if
3138      there was an error.  */
3139   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3140
3141   save_current_space_and_thread ();
3142
3143   ALL_BP_LOCATIONS (bl, blp_tmp)
3144     {
3145       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3146         continue;
3147
3148       /* There is no point inserting thread-specific breakpoints if
3149          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3150          has BL->OWNER always non-NULL.  */
3151       if (bl->owner->thread != -1
3152           && !valid_global_thread_id (bl->owner->thread))
3153         continue;
3154
3155       switch_to_program_space_and_thread (bl->pspace);
3156
3157       /* For targets that support global breakpoints, there's no need
3158          to select an inferior to insert breakpoint to.  In fact, even
3159          if we aren't attached to any process yet, we should still
3160          insert breakpoints.  */
3161       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3162           && ptid_equal (inferior_ptid, null_ptid))
3163         continue;
3164
3165       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3166                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3167       if (val)
3168         error_flag = val;
3169     }
3170
3171   /* If we failed to insert all locations of a watchpoint, remove
3172      them, as half-inserted watchpoint is of limited use.  */
3173   ALL_BREAKPOINTS (bpt)  
3174     {
3175       int some_failed = 0;
3176       struct bp_location *loc;
3177
3178       if (!is_hardware_watchpoint (bpt))
3179         continue;
3180
3181       if (!breakpoint_enabled (bpt))
3182         continue;
3183
3184       if (bpt->disposition == disp_del_at_next_stop)
3185         continue;
3186       
3187       for (loc = bpt->loc; loc; loc = loc->next)
3188         if (!loc->inserted && should_be_inserted (loc))
3189           {
3190             some_failed = 1;
3191             break;
3192           }
3193       if (some_failed)
3194         {
3195           for (loc = bpt->loc; loc; loc = loc->next)
3196             if (loc->inserted)
3197               remove_breakpoint (loc);
3198
3199           hw_breakpoint_error = 1;
3200           fprintf_unfiltered (tmp_error_stream,
3201                               "Could not insert hardware watchpoint %d.\n", 
3202                               bpt->number);
3203           error_flag = -1;
3204         }
3205     }
3206
3207   if (error_flag)
3208     {
3209       /* If a hardware breakpoint or watchpoint was inserted, add a
3210          message about possibly exhausted resources.  */
3211       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3212         {
3213           fprintf_unfiltered (tmp_error_stream, 
3214                               "Could not insert hardware breakpoints:\n\
3215 You may have requested too many hardware breakpoints/watchpoints.\n");
3216         }
3217       target_terminal_ours_for_output ();
3218       error_stream (tmp_error_stream);
3219     }
3220
3221   do_cleanups (cleanups);
3222 }
3223
3224 /* Used when the program stops.
3225    Returns zero if successful, or non-zero if there was a problem
3226    removing a breakpoint location.  */
3227
3228 int
3229 remove_breakpoints (void)
3230 {
3231   struct bp_location *bl, **blp_tmp;
3232   int val = 0;
3233
3234   ALL_BP_LOCATIONS (bl, blp_tmp)
3235   {
3236     if (bl->inserted && !is_tracepoint (bl->owner))
3237       val |= remove_breakpoint (bl);
3238   }
3239   return val;
3240 }
3241
3242 /* When a thread exits, remove breakpoints that are related to
3243    that thread.  */
3244
3245 static void
3246 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3247 {
3248   struct breakpoint *b, *b_tmp;
3249
3250   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3251     {
3252       if (b->thread == tp->global_num && user_breakpoint_p (b))
3253         {
3254           b->disposition = disp_del_at_next_stop;
3255
3256           printf_filtered (_("\
3257 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3258                            b->number, print_thread_id (tp));
3259
3260           /* Hide it from the user.  */
3261           b->number = 0;
3262        }
3263     }
3264 }
3265
3266 /* Remove breakpoints of process PID.  */
3267
3268 int
3269 remove_breakpoints_pid (int pid)
3270 {
3271   struct bp_location *bl, **blp_tmp;
3272   int val;
3273   struct inferior *inf = find_inferior_pid (pid);
3274
3275   ALL_BP_LOCATIONS (bl, blp_tmp)
3276   {
3277     if (bl->pspace != inf->pspace)
3278       continue;
3279
3280     if (bl->inserted && !bl->target_info.persist)
3281       {
3282         val = remove_breakpoint (bl);
3283         if (val != 0)
3284           return val;
3285       }
3286   }
3287   return 0;
3288 }
3289
3290 int
3291 reattach_breakpoints (int pid)
3292 {
3293   struct cleanup *old_chain;
3294   struct bp_location *bl, **blp_tmp;
3295   int val;
3296   struct ui_file *tmp_error_stream;
3297   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3298   struct inferior *inf;
3299   struct thread_info *tp;
3300
3301   tp = any_live_thread_of_process (pid);
3302   if (tp == NULL)
3303     return 1;
3304
3305   inf = find_inferior_pid (pid);
3306   old_chain = save_inferior_ptid ();
3307
3308   inferior_ptid = tp->ptid;
3309
3310   tmp_error_stream = mem_fileopen ();
3311   make_cleanup_ui_file_delete (tmp_error_stream);
3312
3313   ALL_BP_LOCATIONS (bl, blp_tmp)
3314   {
3315     if (bl->pspace != inf->pspace)
3316       continue;
3317
3318     if (bl->inserted)
3319       {
3320         bl->inserted = 0;
3321         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3322         if (val != 0)
3323           {
3324             do_cleanups (old_chain);
3325             return val;
3326           }
3327       }
3328   }
3329   do_cleanups (old_chain);
3330   return 0;
3331 }
3332
3333 static int internal_breakpoint_number = -1;
3334
3335 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3336    If INTERNAL is non-zero, the breakpoint number will be populated
3337    from internal_breakpoint_number and that variable decremented.
3338    Otherwise the breakpoint number will be populated from
3339    breakpoint_count and that value incremented.  Internal breakpoints
3340    do not set the internal var bpnum.  */
3341 static void
3342 set_breakpoint_number (int internal, struct breakpoint *b)
3343 {
3344   if (internal)
3345     b->number = internal_breakpoint_number--;
3346   else
3347     {
3348       set_breakpoint_count (breakpoint_count + 1);
3349       b->number = breakpoint_count;
3350     }
3351 }
3352
3353 static struct breakpoint *
3354 create_internal_breakpoint (struct gdbarch *gdbarch,
3355                             CORE_ADDR address, enum bptype type,
3356                             const struct breakpoint_ops *ops)
3357 {
3358   struct symtab_and_line sal;
3359   struct breakpoint *b;
3360
3361   init_sal (&sal);              /* Initialize to zeroes.  */
3362
3363   sal.pc = address;
3364   sal.section = find_pc_overlay (sal.pc);
3365   sal.pspace = current_program_space;
3366
3367   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3368   b->number = internal_breakpoint_number--;
3369   b->disposition = disp_donttouch;
3370
3371   return b;
3372 }
3373
3374 static const char *const longjmp_names[] =
3375   {
3376     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3377   };
3378 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3379
3380 /* Per-objfile data private to breakpoint.c.  */
3381 struct breakpoint_objfile_data
3382 {
3383   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3384   struct bound_minimal_symbol overlay_msym;
3385
3386   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3387   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3388
3389   /* True if we have looked for longjmp probes.  */
3390   int longjmp_searched;
3391
3392   /* SystemTap probe points for longjmp (if any).  */
3393   VEC (probe_p) *longjmp_probes;
3394
3395   /* Minimal symbol for "std::terminate()" (if any).  */
3396   struct bound_minimal_symbol terminate_msym;
3397
3398   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3399   struct bound_minimal_symbol exception_msym;
3400
3401   /* True if we have looked for exception probes.  */
3402   int exception_searched;
3403
3404   /* SystemTap probe points for unwinding (if any).  */
3405   VEC (probe_p) *exception_probes;
3406 };
3407
3408 static const struct objfile_data *breakpoint_objfile_key;
3409
3410 /* Minimal symbol not found sentinel.  */
3411 static struct minimal_symbol msym_not_found;
3412
3413 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3414
3415 static int
3416 msym_not_found_p (const struct minimal_symbol *msym)
3417 {
3418   return msym == &msym_not_found;
3419 }
3420
3421 /* Return per-objfile data needed by breakpoint.c.
3422    Allocate the data if necessary.  */
3423
3424 static struct breakpoint_objfile_data *
3425 get_breakpoint_objfile_data (struct objfile *objfile)
3426 {
3427   struct breakpoint_objfile_data *bp_objfile_data;
3428
3429   bp_objfile_data = ((struct breakpoint_objfile_data *)
3430                      objfile_data (objfile, breakpoint_objfile_key));
3431   if (bp_objfile_data == NULL)
3432     {
3433       bp_objfile_data =
3434         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3435
3436       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3437       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3438     }
3439   return bp_objfile_data;
3440 }
3441
3442 static void
3443 free_breakpoint_probes (struct objfile *obj, void *data)
3444 {
3445   struct breakpoint_objfile_data *bp_objfile_data
3446     = (struct breakpoint_objfile_data *) data;
3447
3448   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3449   VEC_free (probe_p, bp_objfile_data->exception_probes);
3450 }
3451
3452 static void
3453 create_overlay_event_breakpoint (void)
3454 {
3455   struct objfile *objfile;
3456   const char *const func_name = "_ovly_debug_event";
3457
3458   ALL_OBJFILES (objfile)
3459     {
3460       struct breakpoint *b;
3461       struct breakpoint_objfile_data *bp_objfile_data;
3462       CORE_ADDR addr;
3463       struct explicit_location explicit_loc;
3464
3465       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3466
3467       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3468         continue;
3469
3470       if (bp_objfile_data->overlay_msym.minsym == NULL)
3471         {
3472           struct bound_minimal_symbol m;
3473
3474           m = lookup_minimal_symbol_text (func_name, objfile);
3475           if (m.minsym == NULL)
3476             {
3477               /* Avoid future lookups in this objfile.  */
3478               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3479               continue;
3480             }
3481           bp_objfile_data->overlay_msym = m;
3482         }
3483
3484       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3485       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3486                                       bp_overlay_event,
3487                                       &internal_breakpoint_ops);
3488       initialize_explicit_location (&explicit_loc);
3489       explicit_loc.function_name = ASTRDUP (func_name);
3490       b->location = new_explicit_location (&explicit_loc);
3491
3492       if (overlay_debugging == ovly_auto)
3493         {
3494           b->enable_state = bp_enabled;
3495           overlay_events_enabled = 1;
3496         }
3497       else
3498        {
3499          b->enable_state = bp_disabled;
3500          overlay_events_enabled = 0;
3501        }
3502     }
3503 }
3504
3505 static void
3506 create_longjmp_master_breakpoint (void)
3507 {
3508   struct program_space *pspace;
3509   struct cleanup *old_chain;
3510
3511   old_chain = save_current_program_space ();
3512
3513   ALL_PSPACES (pspace)
3514   {
3515     struct objfile *objfile;
3516
3517     set_current_program_space (pspace);
3518
3519     ALL_OBJFILES (objfile)
3520     {
3521       int i;
3522       struct gdbarch *gdbarch;
3523       struct breakpoint_objfile_data *bp_objfile_data;
3524
3525       gdbarch = get_objfile_arch (objfile);
3526
3527       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3528
3529       if (!bp_objfile_data->longjmp_searched)
3530         {
3531           VEC (probe_p) *ret;
3532
3533           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3534           if (ret != NULL)
3535             {
3536               /* We are only interested in checking one element.  */
3537               struct probe *p = VEC_index (probe_p, ret, 0);
3538
3539               if (!can_evaluate_probe_arguments (p))
3540                 {
3541                   /* We cannot use the probe interface here, because it does
3542                      not know how to evaluate arguments.  */
3543                   VEC_free (probe_p, ret);
3544                   ret = NULL;
3545                 }
3546             }
3547           bp_objfile_data->longjmp_probes = ret;
3548           bp_objfile_data->longjmp_searched = 1;
3549         }
3550
3551       if (bp_objfile_data->longjmp_probes != NULL)
3552         {
3553           int i;
3554           struct probe *probe;
3555           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3556
3557           for (i = 0;
3558                VEC_iterate (probe_p,
3559                             bp_objfile_data->longjmp_probes,
3560                             i, probe);
3561                ++i)
3562             {
3563               struct breakpoint *b;
3564
3565               b = create_internal_breakpoint (gdbarch,
3566                                               get_probe_address (probe,
3567                                                                  objfile),
3568                                               bp_longjmp_master,
3569                                               &internal_breakpoint_ops);
3570               b->location
3571                 = new_probe_location ("-probe-stap libc:longjmp");
3572               b->enable_state = bp_disabled;
3573             }
3574
3575           continue;
3576         }
3577
3578       if (!gdbarch_get_longjmp_target_p (gdbarch))
3579         continue;
3580
3581       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3582         {
3583           struct breakpoint *b;
3584           const char *func_name;
3585           CORE_ADDR addr;
3586           struct explicit_location explicit_loc;
3587
3588           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3589             continue;
3590
3591           func_name = longjmp_names[i];
3592           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3593             {
3594               struct bound_minimal_symbol m;
3595
3596               m = lookup_minimal_symbol_text (func_name, objfile);
3597               if (m.minsym == NULL)
3598                 {
3599                   /* Prevent future lookups in this objfile.  */
3600                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3601                   continue;
3602                 }
3603               bp_objfile_data->longjmp_msym[i] = m;
3604             }
3605
3606           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3607           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3608                                           &internal_breakpoint_ops);
3609           initialize_explicit_location (&explicit_loc);
3610           explicit_loc.function_name = ASTRDUP (func_name);
3611           b->location = new_explicit_location (&explicit_loc);
3612           b->enable_state = bp_disabled;
3613         }
3614     }
3615   }
3616
3617   do_cleanups (old_chain);
3618 }
3619
3620 /* Create a master std::terminate breakpoint.  */
3621 static void
3622 create_std_terminate_master_breakpoint (void)
3623 {
3624   struct program_space *pspace;
3625   struct cleanup *old_chain;
3626   const char *const func_name = "std::terminate()";
3627
3628   old_chain = save_current_program_space ();
3629
3630   ALL_PSPACES (pspace)
3631   {
3632     struct objfile *objfile;
3633     CORE_ADDR addr;
3634
3635     set_current_program_space (pspace);
3636
3637     ALL_OBJFILES (objfile)
3638     {
3639       struct breakpoint *b;
3640       struct breakpoint_objfile_data *bp_objfile_data;
3641       struct explicit_location explicit_loc;
3642
3643       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3644
3645       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3646         continue;
3647
3648       if (bp_objfile_data->terminate_msym.minsym == NULL)
3649         {
3650           struct bound_minimal_symbol m;
3651
3652           m = lookup_minimal_symbol (func_name, NULL, objfile);
3653           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3654                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3655             {
3656               /* Prevent future lookups in this objfile.  */
3657               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3658               continue;
3659             }
3660           bp_objfile_data->terminate_msym = m;
3661         }
3662
3663       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3664       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3665                                       bp_std_terminate_master,
3666                                       &internal_breakpoint_ops);
3667       initialize_explicit_location (&explicit_loc);
3668       explicit_loc.function_name = ASTRDUP (func_name);
3669       b->location = new_explicit_location (&explicit_loc);
3670       b->enable_state = bp_disabled;
3671     }
3672   }
3673
3674   do_cleanups (old_chain);
3675 }
3676
3677 /* Install a master breakpoint on the unwinder's debug hook.  */
3678
3679 static void
3680 create_exception_master_breakpoint (void)
3681 {
3682   struct objfile *objfile;
3683   const char *const func_name = "_Unwind_DebugHook";
3684
3685   ALL_OBJFILES (objfile)
3686     {
3687       struct breakpoint *b;
3688       struct gdbarch *gdbarch;
3689       struct breakpoint_objfile_data *bp_objfile_data;
3690       CORE_ADDR addr;
3691       struct explicit_location explicit_loc;
3692
3693       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3694
3695       /* We prefer the SystemTap probe point if it exists.  */
3696       if (!bp_objfile_data->exception_searched)
3697         {
3698           VEC (probe_p) *ret;
3699
3700           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3701
3702           if (ret != NULL)
3703             {
3704               /* We are only interested in checking one element.  */
3705               struct probe *p = VEC_index (probe_p, ret, 0);
3706
3707               if (!can_evaluate_probe_arguments (p))
3708                 {
3709                   /* We cannot use the probe interface here, because it does
3710                      not know how to evaluate arguments.  */
3711                   VEC_free (probe_p, ret);
3712                   ret = NULL;
3713                 }
3714             }
3715           bp_objfile_data->exception_probes = ret;
3716           bp_objfile_data->exception_searched = 1;
3717         }
3718
3719       if (bp_objfile_data->exception_probes != NULL)
3720         {
3721           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3722           int i;
3723           struct probe *probe;
3724
3725           for (i = 0;
3726                VEC_iterate (probe_p,
3727                             bp_objfile_data->exception_probes,
3728                             i, probe);
3729                ++i)
3730             {
3731               struct breakpoint *b;
3732
3733               b = create_internal_breakpoint (gdbarch,
3734                                               get_probe_address (probe,
3735                                                                  objfile),
3736                                               bp_exception_master,
3737                                               &internal_breakpoint_ops);
3738               b->location
3739                 = new_probe_location ("-probe-stap libgcc:unwind");
3740               b->enable_state = bp_disabled;
3741             }
3742
3743           continue;
3744         }
3745
3746       /* Otherwise, try the hook function.  */
3747
3748       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3749         continue;
3750
3751       gdbarch = get_objfile_arch (objfile);
3752
3753       if (bp_objfile_data->exception_msym.minsym == NULL)
3754         {
3755           struct bound_minimal_symbol debug_hook;
3756
3757           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3758           if (debug_hook.minsym == NULL)
3759             {
3760               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3761               continue;
3762             }
3763
3764           bp_objfile_data->exception_msym = debug_hook;
3765         }
3766
3767       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3768       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3769                                                  &current_target);
3770       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3771                                       &internal_breakpoint_ops);
3772       initialize_explicit_location (&explicit_loc);
3773       explicit_loc.function_name = ASTRDUP (func_name);
3774       b->location = new_explicit_location (&explicit_loc);
3775       b->enable_state = bp_disabled;
3776     }
3777 }
3778
3779 /* Does B have a location spec?  */
3780
3781 static int
3782 breakpoint_event_location_empty_p (const struct breakpoint *b)
3783 {
3784   return b->location != NULL && event_location_empty_p (b->location);
3785 }
3786
3787 void
3788 update_breakpoints_after_exec (void)
3789 {
3790   struct breakpoint *b, *b_tmp;
3791   struct bp_location *bploc, **bplocp_tmp;
3792
3793   /* We're about to delete breakpoints from GDB's lists.  If the
3794      INSERTED flag is true, GDB will try to lift the breakpoints by
3795      writing the breakpoints' "shadow contents" back into memory.  The
3796      "shadow contents" are NOT valid after an exec, so GDB should not
3797      do that.  Instead, the target is responsible from marking
3798      breakpoints out as soon as it detects an exec.  We don't do that
3799      here instead, because there may be other attempts to delete
3800      breakpoints after detecting an exec and before reaching here.  */
3801   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3802     if (bploc->pspace == current_program_space)
3803       gdb_assert (!bploc->inserted);
3804
3805   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3806   {
3807     if (b->pspace != current_program_space)
3808       continue;
3809
3810     /* Solib breakpoints must be explicitly reset after an exec().  */
3811     if (b->type == bp_shlib_event)
3812       {
3813         delete_breakpoint (b);
3814         continue;
3815       }
3816
3817     /* JIT breakpoints must be explicitly reset after an exec().  */
3818     if (b->type == bp_jit_event)
3819       {
3820         delete_breakpoint (b);
3821         continue;
3822       }
3823
3824     /* Thread event breakpoints must be set anew after an exec(),
3825        as must overlay event and longjmp master breakpoints.  */
3826     if (b->type == bp_thread_event || b->type == bp_overlay_event
3827         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3828         || b->type == bp_exception_master)
3829       {
3830         delete_breakpoint (b);
3831         continue;
3832       }
3833
3834     /* Step-resume breakpoints are meaningless after an exec().  */
3835     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3836       {
3837         delete_breakpoint (b);
3838         continue;
3839       }
3840
3841     /* Just like single-step breakpoints.  */
3842     if (b->type == bp_single_step)
3843       {
3844         delete_breakpoint (b);
3845         continue;
3846       }
3847
3848     /* Longjmp and longjmp-resume breakpoints are also meaningless
3849        after an exec.  */
3850     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3851         || b->type == bp_longjmp_call_dummy
3852         || b->type == bp_exception || b->type == bp_exception_resume)
3853       {
3854         delete_breakpoint (b);
3855         continue;
3856       }
3857
3858     if (b->type == bp_catchpoint)
3859       {
3860         /* For now, none of the bp_catchpoint breakpoints need to
3861            do anything at this point.  In the future, if some of
3862            the catchpoints need to something, we will need to add
3863            a new method, and call this method from here.  */
3864         continue;
3865       }
3866
3867     /* bp_finish is a special case.  The only way we ought to be able
3868        to see one of these when an exec() has happened, is if the user
3869        caught a vfork, and then said "finish".  Ordinarily a finish just
3870        carries them to the call-site of the current callee, by setting
3871        a temporary bp there and resuming.  But in this case, the finish
3872        will carry them entirely through the vfork & exec.
3873
3874        We don't want to allow a bp_finish to remain inserted now.  But
3875        we can't safely delete it, 'cause finish_command has a handle to
3876        the bp on a bpstat, and will later want to delete it.  There's a
3877        chance (and I've seen it happen) that if we delete the bp_finish
3878        here, that its storage will get reused by the time finish_command
3879        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3880        We really must allow finish_command to delete a bp_finish.
3881
3882        In the absence of a general solution for the "how do we know
3883        it's safe to delete something others may have handles to?"
3884        problem, what we'll do here is just uninsert the bp_finish, and
3885        let finish_command delete it.
3886
3887        (We know the bp_finish is "doomed" in the sense that it's
3888        momentary, and will be deleted as soon as finish_command sees
3889        the inferior stopped.  So it doesn't matter that the bp's
3890        address is probably bogus in the new a.out, unlike e.g., the
3891        solib breakpoints.)  */
3892
3893     if (b->type == bp_finish)
3894       {
3895         continue;
3896       }
3897
3898     /* Without a symbolic address, we have little hope of the
3899        pre-exec() address meaning the same thing in the post-exec()
3900        a.out.  */
3901     if (breakpoint_event_location_empty_p (b))
3902       {
3903         delete_breakpoint (b);
3904         continue;
3905       }
3906   }
3907 }
3908
3909 int
3910 detach_breakpoints (ptid_t ptid)
3911 {
3912   struct bp_location *bl, **blp_tmp;
3913   int val = 0;
3914   struct cleanup *old_chain = save_inferior_ptid ();
3915   struct inferior *inf = current_inferior ();
3916
3917   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3918     error (_("Cannot detach breakpoints of inferior_ptid"));
3919
3920   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3921   inferior_ptid = ptid;
3922   ALL_BP_LOCATIONS (bl, blp_tmp)
3923   {
3924     if (bl->pspace != inf->pspace)
3925       continue;
3926
3927     /* This function must physically remove breakpoints locations
3928        from the specified ptid, without modifying the breakpoint
3929        package's state.  Locations of type bp_loc_other are only
3930        maintained at GDB side.  So, there is no need to remove
3931        these bp_loc_other locations.  Moreover, removing these
3932        would modify the breakpoint package's state.  */
3933     if (bl->loc_type == bp_loc_other)
3934       continue;
3935
3936     if (bl->inserted)
3937       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3938   }
3939
3940   do_cleanups (old_chain);
3941   return val;
3942 }
3943
3944 /* Remove the breakpoint location BL from the current address space.
3945    Note that this is used to detach breakpoints from a child fork.
3946    When we get here, the child isn't in the inferior list, and neither
3947    do we have objects to represent its address space --- we should
3948    *not* look at bl->pspace->aspace here.  */
3949
3950 static int
3951 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3952 {
3953   int val;
3954
3955   /* BL is never in moribund_locations by our callers.  */
3956   gdb_assert (bl->owner != NULL);
3957
3958   /* The type of none suggests that owner is actually deleted.
3959      This should not ever happen.  */
3960   gdb_assert (bl->owner->type != bp_none);
3961
3962   if (bl->loc_type == bp_loc_software_breakpoint
3963       || bl->loc_type == bp_loc_hardware_breakpoint)
3964     {
3965       /* "Normal" instruction breakpoint: either the standard
3966          trap-instruction bp (bp_breakpoint), or a
3967          bp_hardware_breakpoint.  */
3968
3969       /* First check to see if we have to handle an overlay.  */
3970       if (overlay_debugging == ovly_off
3971           || bl->section == NULL
3972           || !(section_is_overlay (bl->section)))
3973         {
3974           /* No overlay handling: just remove the breakpoint.  */
3975
3976           /* If we're trying to uninsert a memory breakpoint that we
3977              know is set in a dynamic object that is marked
3978              shlib_disabled, then either the dynamic object was
3979              removed with "remove-symbol-file" or with
3980              "nosharedlibrary".  In the former case, we don't know
3981              whether another dynamic object might have loaded over the
3982              breakpoint's address -- the user might well let us know
3983              about it next with add-symbol-file (the whole point of
3984              add-symbol-file is letting the user manually maintain a
3985              list of dynamically loaded objects).  If we have the
3986              breakpoint's shadow memory, that is, this is a software
3987              breakpoint managed by GDB, check whether the breakpoint
3988              is still inserted in memory, to avoid overwriting wrong
3989              code with stale saved shadow contents.  Note that HW
3990              breakpoints don't have shadow memory, as they're
3991              implemented using a mechanism that is not dependent on
3992              being able to modify the target's memory, and as such
3993              they should always be removed.  */
3994           if (bl->shlib_disabled
3995               && bl->target_info.shadow_len != 0
3996               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3997             val = 0;
3998           else
3999             val = bl->owner->ops->remove_location (bl);
4000         }
4001       else
4002         {
4003           /* This breakpoint is in an overlay section.
4004              Did we set a breakpoint at the LMA?  */
4005           if (!overlay_events_enabled)
4006               {
4007                 /* Yes -- overlay event support is not active, so we
4008                    should have set a breakpoint at the LMA.  Remove it.  
4009                 */
4010                 /* Ignore any failures: if the LMA is in ROM, we will
4011                    have already warned when we failed to insert it.  */
4012                 if (bl->loc_type == bp_loc_hardware_breakpoint)
4013                   target_remove_hw_breakpoint (bl->gdbarch,
4014                                                &bl->overlay_target_info);
4015                 else
4016                   target_remove_breakpoint (bl->gdbarch,
4017                                             &bl->overlay_target_info);
4018               }
4019           /* Did we set a breakpoint at the VMA? 
4020              If so, we will have marked the breakpoint 'inserted'.  */
4021           if (bl->inserted)
4022             {
4023               /* Yes -- remove it.  Previously we did not bother to
4024                  remove the breakpoint if the section had been
4025                  unmapped, but let's not rely on that being safe.  We
4026                  don't know what the overlay manager might do.  */
4027
4028               /* However, we should remove *software* breakpoints only
4029                  if the section is still mapped, or else we overwrite
4030                  wrong code with the saved shadow contents.  */
4031               if (bl->loc_type == bp_loc_hardware_breakpoint
4032                   || section_is_mapped (bl->section))
4033                 val = bl->owner->ops->remove_location (bl);
4034               else
4035                 val = 0;
4036             }
4037           else
4038             {
4039               /* No -- not inserted, so no need to remove.  No error.  */
4040               val = 0;
4041             }
4042         }
4043
4044       /* In some cases, we might not be able to remove a breakpoint in
4045          a shared library that has already been removed, but we have
4046          not yet processed the shlib unload event.  Similarly for an
4047          unloaded add-symbol-file object - the user might not yet have
4048          had the chance to remove-symbol-file it.  shlib_disabled will
4049          be set if the library/object has already been removed, but
4050          the breakpoint hasn't been uninserted yet, e.g., after
4051          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4052          always-inserted mode.  */
4053       if (val
4054           && (bl->loc_type == bp_loc_software_breakpoint
4055               && (bl->shlib_disabled
4056                   || solib_name_from_address (bl->pspace, bl->address)
4057                   || shared_objfile_contains_address_p (bl->pspace,
4058                                                         bl->address))))
4059         val = 0;
4060
4061       if (val)
4062         return val;
4063       bl->inserted = (reason == DETACH_BREAKPOINT);
4064     }
4065   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4066     {
4067       gdb_assert (bl->owner->ops != NULL
4068                   && bl->owner->ops->remove_location != NULL);
4069
4070       bl->inserted = (reason == DETACH_BREAKPOINT);
4071       bl->owner->ops->remove_location (bl);
4072
4073       /* Failure to remove any of the hardware watchpoints comes here.  */
4074       if (reason == REMOVE_BREAKPOINT && bl->inserted)
4075         warning (_("Could not remove hardware watchpoint %d."),
4076                  bl->owner->number);
4077     }
4078   else if (bl->owner->type == bp_catchpoint
4079            && breakpoint_enabled (bl->owner)
4080            && !bl->duplicate)
4081     {
4082       gdb_assert (bl->owner->ops != NULL
4083                   && bl->owner->ops->remove_location != NULL);
4084
4085       val = bl->owner->ops->remove_location (bl);
4086       if (val)
4087         return val;
4088
4089       bl->inserted = (reason == DETACH_BREAKPOINT);
4090     }
4091
4092   return 0;
4093 }
4094
4095 static int
4096 remove_breakpoint (struct bp_location *bl)
4097 {
4098   int ret;
4099   struct cleanup *old_chain;
4100
4101   /* BL is never in moribund_locations by our callers.  */
4102   gdb_assert (bl->owner != NULL);
4103
4104   /* The type of none suggests that owner is actually deleted.
4105      This should not ever happen.  */
4106   gdb_assert (bl->owner->type != bp_none);
4107
4108   old_chain = save_current_space_and_thread ();
4109
4110   switch_to_program_space_and_thread (bl->pspace);
4111
4112   ret = remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4113
4114   do_cleanups (old_chain);
4115   return ret;
4116 }
4117
4118 /* Clear the "inserted" flag in all breakpoints.  */
4119
4120 void
4121 mark_breakpoints_out (void)
4122 {
4123   struct bp_location *bl, **blp_tmp;
4124
4125   ALL_BP_LOCATIONS (bl, blp_tmp)
4126     if (bl->pspace == current_program_space)
4127       bl->inserted = 0;
4128 }
4129
4130 /* Clear the "inserted" flag in all breakpoints and delete any
4131    breakpoints which should go away between runs of the program.
4132
4133    Plus other such housekeeping that has to be done for breakpoints
4134    between runs.
4135
4136    Note: this function gets called at the end of a run (by
4137    generic_mourn_inferior) and when a run begins (by
4138    init_wait_for_inferior).  */
4139
4140
4141
4142 void
4143 breakpoint_init_inferior (enum inf_context context)
4144 {
4145   struct breakpoint *b, *b_tmp;
4146   struct bp_location *bl;
4147   int ix;
4148   struct program_space *pspace = current_program_space;
4149
4150   /* If breakpoint locations are shared across processes, then there's
4151      nothing to do.  */
4152   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4153     return;
4154
4155   mark_breakpoints_out ();
4156
4157   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4158   {
4159     if (b->loc && b->loc->pspace != pspace)
4160       continue;
4161
4162     switch (b->type)
4163       {
4164       case bp_call_dummy:
4165       case bp_longjmp_call_dummy:
4166
4167         /* If the call dummy breakpoint is at the entry point it will
4168            cause problems when the inferior is rerun, so we better get
4169            rid of it.  */
4170
4171       case bp_watchpoint_scope:
4172
4173         /* Also get rid of scope breakpoints.  */
4174
4175       case bp_shlib_event:
4176
4177         /* Also remove solib event breakpoints.  Their addresses may
4178            have changed since the last time we ran the program.
4179            Actually we may now be debugging against different target;
4180            and so the solib backend that installed this breakpoint may
4181            not be used in by the target.  E.g.,
4182
4183            (gdb) file prog-linux
4184            (gdb) run               # native linux target
4185            ...
4186            (gdb) kill
4187            (gdb) file prog-win.exe
4188            (gdb) tar rem :9999     # remote Windows gdbserver.
4189         */
4190
4191       case bp_step_resume:
4192
4193         /* Also remove step-resume breakpoints.  */
4194
4195       case bp_single_step:
4196
4197         /* Also remove single-step breakpoints.  */
4198
4199         delete_breakpoint (b);
4200         break;
4201
4202       case bp_watchpoint:
4203       case bp_hardware_watchpoint:
4204       case bp_read_watchpoint:
4205       case bp_access_watchpoint:
4206         {
4207           struct watchpoint *w = (struct watchpoint *) b;
4208
4209           /* Likewise for watchpoints on local expressions.  */
4210           if (w->exp_valid_block != NULL)
4211             delete_breakpoint (b);
4212           else
4213             {
4214               /* Get rid of existing locations, which are no longer
4215                  valid.  New ones will be created in
4216                  update_watchpoint, when the inferior is restarted.
4217                  The next update_global_location_list call will
4218                  garbage collect them.  */
4219               b->loc = NULL;
4220
4221               if (context == inf_starting)
4222                 {
4223                   /* Reset val field to force reread of starting value in
4224                      insert_breakpoints.  */
4225                   if (w->val)
4226                     value_free (w->val);
4227                   w->val = NULL;
4228                   w->val_valid = 0;
4229                 }
4230             }
4231         }
4232         break;
4233       default:
4234         break;
4235       }
4236   }
4237
4238   /* Get rid of the moribund locations.  */
4239   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4240     decref_bp_location (&bl);
4241   VEC_free (bp_location_p, moribund_locations);
4242 }
4243
4244 /* These functions concern about actual breakpoints inserted in the
4245    target --- to e.g. check if we need to do decr_pc adjustment or if
4246    we need to hop over the bkpt --- so we check for address space
4247    match, not program space.  */
4248
4249 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4250    exists at PC.  It returns ordinary_breakpoint_here if it's an
4251    ordinary breakpoint, or permanent_breakpoint_here if it's a
4252    permanent breakpoint.
4253    - When continuing from a location with an ordinary breakpoint, we
4254      actually single step once before calling insert_breakpoints.
4255    - When continuing from a location with a permanent breakpoint, we
4256      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4257      the target, to advance the PC past the breakpoint.  */
4258
4259 enum breakpoint_here
4260 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4261 {
4262   struct bp_location *bl, **blp_tmp;
4263   int any_breakpoint_here = 0;
4264
4265   ALL_BP_LOCATIONS (bl, blp_tmp)
4266     {
4267       if (bl->loc_type != bp_loc_software_breakpoint
4268           && bl->loc_type != bp_loc_hardware_breakpoint)
4269         continue;
4270
4271       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4272       if ((breakpoint_enabled (bl->owner)
4273            || bl->permanent)
4274           && breakpoint_location_address_match (bl, aspace, pc))
4275         {
4276           if (overlay_debugging 
4277               && section_is_overlay (bl->section)
4278               && !section_is_mapped (bl->section))
4279             continue;           /* unmapped overlay -- can't be a match */
4280           else if (bl->permanent)
4281             return permanent_breakpoint_here;
4282           else
4283             any_breakpoint_here = 1;
4284         }
4285     }
4286
4287   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4288 }
4289
4290 /* See breakpoint.h.  */
4291
4292 int
4293 breakpoint_in_range_p (struct address_space *aspace,
4294                        CORE_ADDR addr, ULONGEST len)
4295 {
4296   struct bp_location *bl, **blp_tmp;
4297
4298   ALL_BP_LOCATIONS (bl, blp_tmp)
4299     {
4300       if (bl->loc_type != bp_loc_software_breakpoint
4301           && bl->loc_type != bp_loc_hardware_breakpoint)
4302         continue;
4303
4304       if ((breakpoint_enabled (bl->owner)
4305            || bl->permanent)
4306           && breakpoint_location_address_range_overlap (bl, aspace,
4307                                                         addr, len))
4308         {
4309           if (overlay_debugging
4310               && section_is_overlay (bl->section)
4311               && !section_is_mapped (bl->section))
4312             {
4313               /* Unmapped overlay -- can't be a match.  */
4314               continue;
4315             }
4316
4317           return 1;
4318         }
4319     }
4320
4321   return 0;
4322 }
4323
4324 /* Return true if there's a moribund breakpoint at PC.  */
4325
4326 int
4327 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4328 {
4329   struct bp_location *loc;
4330   int ix;
4331
4332   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4333     if (breakpoint_location_address_match (loc, aspace, pc))
4334       return 1;
4335
4336   return 0;
4337 }
4338
4339 /* Returns non-zero iff BL is inserted at PC, in address space
4340    ASPACE.  */
4341
4342 static int
4343 bp_location_inserted_here_p (struct bp_location *bl,
4344                              struct address_space *aspace, CORE_ADDR pc)
4345 {
4346   if (bl->inserted
4347       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4348                                    aspace, pc))
4349     {
4350       if (overlay_debugging
4351           && section_is_overlay (bl->section)
4352           && !section_is_mapped (bl->section))
4353         return 0;               /* unmapped overlay -- can't be a match */
4354       else
4355         return 1;
4356     }
4357   return 0;
4358 }
4359
4360 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4361
4362 int
4363 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4364 {
4365   struct bp_location **blp, **blp_tmp = NULL;
4366
4367   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4368     {
4369       struct bp_location *bl = *blp;
4370
4371       if (bl->loc_type != bp_loc_software_breakpoint
4372           && bl->loc_type != bp_loc_hardware_breakpoint)
4373         continue;
4374
4375       if (bp_location_inserted_here_p (bl, aspace, pc))
4376         return 1;
4377     }
4378   return 0;
4379 }
4380
4381 /* This function returns non-zero iff there is a software breakpoint
4382    inserted at PC.  */
4383
4384 int
4385 software_breakpoint_inserted_here_p (struct address_space *aspace,
4386                                      CORE_ADDR pc)
4387 {
4388   struct bp_location **blp, **blp_tmp = NULL;
4389
4390   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4391     {
4392       struct bp_location *bl = *blp;
4393
4394       if (bl->loc_type != bp_loc_software_breakpoint)
4395         continue;
4396
4397       if (bp_location_inserted_here_p (bl, aspace, pc))
4398         return 1;
4399     }
4400
4401   return 0;
4402 }
4403
4404 /* See breakpoint.h.  */
4405
4406 int
4407 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4408                                      CORE_ADDR pc)
4409 {
4410   struct bp_location **blp, **blp_tmp = NULL;
4411
4412   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4413     {
4414       struct bp_location *bl = *blp;
4415
4416       if (bl->loc_type != bp_loc_hardware_breakpoint)
4417         continue;
4418
4419       if (bp_location_inserted_here_p (bl, aspace, pc))
4420         return 1;
4421     }
4422
4423   return 0;
4424 }
4425
4426 int
4427 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4428                                        CORE_ADDR addr, ULONGEST len)
4429 {
4430   struct breakpoint *bpt;
4431
4432   ALL_BREAKPOINTS (bpt)
4433     {
4434       struct bp_location *loc;
4435
4436       if (bpt->type != bp_hardware_watchpoint
4437           && bpt->type != bp_access_watchpoint)
4438         continue;
4439
4440       if (!breakpoint_enabled (bpt))
4441         continue;
4442
4443       for (loc = bpt->loc; loc; loc = loc->next)
4444         if (loc->pspace->aspace == aspace && loc->inserted)
4445           {
4446             CORE_ADDR l, h;
4447
4448             /* Check for intersection.  */
4449             l = max (loc->address, addr);
4450             h = min (loc->address + loc->length, addr + len);
4451             if (l < h)
4452               return 1;
4453           }
4454     }
4455   return 0;
4456 }
4457 \f
4458
4459 /* bpstat stuff.  External routines' interfaces are documented
4460    in breakpoint.h.  */
4461
4462 int
4463 is_catchpoint (struct breakpoint *ep)
4464 {
4465   return (ep->type == bp_catchpoint);
4466 }
4467
4468 /* Frees any storage that is part of a bpstat.  Does not walk the
4469    'next' chain.  */
4470
4471 static void
4472 bpstat_free (bpstat bs)
4473 {
4474   if (bs->old_val != NULL)
4475     value_free (bs->old_val);
4476   decref_counted_command_line (&bs->commands);
4477   decref_bp_location (&bs->bp_location_at);
4478   xfree (bs);
4479 }
4480
4481 /* Clear a bpstat so that it says we are not at any breakpoint.
4482    Also free any storage that is part of a bpstat.  */
4483
4484 void
4485 bpstat_clear (bpstat *bsp)
4486 {
4487   bpstat p;
4488   bpstat q;
4489
4490   if (bsp == 0)
4491     return;
4492   p = *bsp;
4493   while (p != NULL)
4494     {
4495       q = p->next;
4496       bpstat_free (p);
4497       p = q;
4498     }
4499   *bsp = NULL;
4500 }
4501
4502 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4503    is part of the bpstat is copied as well.  */
4504
4505 bpstat
4506 bpstat_copy (bpstat bs)
4507 {
4508   bpstat p = NULL;
4509   bpstat tmp;
4510   bpstat retval = NULL;
4511
4512   if (bs == NULL)
4513     return bs;
4514
4515   for (; bs != NULL; bs = bs->next)
4516     {
4517       tmp = (bpstat) xmalloc (sizeof (*tmp));
4518       memcpy (tmp, bs, sizeof (*tmp));
4519       incref_counted_command_line (tmp->commands);
4520       incref_bp_location (tmp->bp_location_at);
4521       if (bs->old_val != NULL)
4522         {
4523           tmp->old_val = value_copy (bs->old_val);
4524           release_value (tmp->old_val);
4525         }
4526
4527       if (p == NULL)
4528         /* This is the first thing in the chain.  */
4529         retval = tmp;
4530       else
4531         p->next = tmp;
4532       p = tmp;
4533     }
4534   p->next = NULL;
4535   return retval;
4536 }
4537
4538 /* Find the bpstat associated with this breakpoint.  */
4539
4540 bpstat
4541 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4542 {
4543   if (bsp == NULL)
4544     return NULL;
4545
4546   for (; bsp != NULL; bsp = bsp->next)
4547     {
4548       if (bsp->breakpoint_at == breakpoint)
4549         return bsp;
4550     }
4551   return NULL;
4552 }
4553
4554 /* See breakpoint.h.  */
4555
4556 int
4557 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4558 {
4559   for (; bsp != NULL; bsp = bsp->next)
4560     {
4561       if (bsp->breakpoint_at == NULL)
4562         {
4563           /* A moribund location can never explain a signal other than
4564              GDB_SIGNAL_TRAP.  */
4565           if (sig == GDB_SIGNAL_TRAP)
4566             return 1;
4567         }
4568       else
4569         {
4570           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4571                                                         sig))
4572             return 1;
4573         }
4574     }
4575
4576   return 0;
4577 }
4578
4579 /* Put in *NUM the breakpoint number of the first breakpoint we are
4580    stopped at.  *BSP upon return is a bpstat which points to the
4581    remaining breakpoints stopped at (but which is not guaranteed to be
4582    good for anything but further calls to bpstat_num).
4583
4584    Return 0 if passed a bpstat which does not indicate any breakpoints.
4585    Return -1 if stopped at a breakpoint that has been deleted since
4586    we set it.
4587    Return 1 otherwise.  */
4588
4589 int
4590 bpstat_num (bpstat *bsp, int *num)
4591 {
4592   struct breakpoint *b;
4593
4594   if ((*bsp) == NULL)
4595     return 0;                   /* No more breakpoint values */
4596
4597   /* We assume we'll never have several bpstats that correspond to a
4598      single breakpoint -- otherwise, this function might return the
4599      same number more than once and this will look ugly.  */
4600   b = (*bsp)->breakpoint_at;
4601   *bsp = (*bsp)->next;
4602   if (b == NULL)
4603     return -1;                  /* breakpoint that's been deleted since */
4604
4605   *num = b->number;             /* We have its number */
4606   return 1;
4607 }
4608
4609 /* See breakpoint.h.  */
4610
4611 void
4612 bpstat_clear_actions (void)
4613 {
4614   struct thread_info *tp;
4615   bpstat bs;
4616
4617   if (ptid_equal (inferior_ptid, null_ptid))
4618     return;
4619
4620   tp = find_thread_ptid (inferior_ptid);
4621   if (tp == NULL)
4622     return;
4623
4624   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4625     {
4626       decref_counted_command_line (&bs->commands);
4627
4628       if (bs->old_val != NULL)
4629         {
4630           value_free (bs->old_val);
4631           bs->old_val = NULL;
4632         }
4633     }
4634 }
4635
4636 /* Called when a command is about to proceed the inferior.  */
4637
4638 static void
4639 breakpoint_about_to_proceed (void)
4640 {
4641   if (!ptid_equal (inferior_ptid, null_ptid))
4642     {
4643       struct thread_info *tp = inferior_thread ();
4644
4645       /* Allow inferior function calls in breakpoint commands to not
4646          interrupt the command list.  When the call finishes
4647          successfully, the inferior will be standing at the same
4648          breakpoint as if nothing happened.  */
4649       if (tp->control.in_infcall)
4650         return;
4651     }
4652
4653   breakpoint_proceeded = 1;
4654 }
4655
4656 /* Stub for cleaning up our state if we error-out of a breakpoint
4657    command.  */
4658 static void
4659 cleanup_executing_breakpoints (void *ignore)
4660 {
4661   executing_breakpoint_commands = 0;
4662 }
4663
4664 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4665    or its equivalent.  */
4666
4667 static int
4668 command_line_is_silent (struct command_line *cmd)
4669 {
4670   return cmd && (strcmp ("silent", cmd->line) == 0);
4671 }
4672
4673 /* Execute all the commands associated with all the breakpoints at
4674    this location.  Any of these commands could cause the process to
4675    proceed beyond this point, etc.  We look out for such changes by
4676    checking the global "breakpoint_proceeded" after each command.
4677
4678    Returns true if a breakpoint command resumed the inferior.  In that
4679    case, it is the caller's responsibility to recall it again with the
4680    bpstat of the current thread.  */
4681
4682 static int
4683 bpstat_do_actions_1 (bpstat *bsp)
4684 {
4685   bpstat bs;
4686   struct cleanup *old_chain;
4687   int again = 0;
4688
4689   /* Avoid endless recursion if a `source' command is contained
4690      in bs->commands.  */
4691   if (executing_breakpoint_commands)
4692     return 0;
4693
4694   executing_breakpoint_commands = 1;
4695   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4696
4697   prevent_dont_repeat ();
4698
4699   /* This pointer will iterate over the list of bpstat's.  */
4700   bs = *bsp;
4701
4702   breakpoint_proceeded = 0;
4703   for (; bs != NULL; bs = bs->next)
4704     {
4705       struct counted_command_line *ccmd;
4706       struct command_line *cmd;
4707       struct cleanup *this_cmd_tree_chain;
4708
4709       /* Take ownership of the BSP's command tree, if it has one.
4710
4711          The command tree could legitimately contain commands like
4712          'step' and 'next', which call clear_proceed_status, which
4713          frees stop_bpstat's command tree.  To make sure this doesn't
4714          free the tree we're executing out from under us, we need to
4715          take ownership of the tree ourselves.  Since a given bpstat's
4716          commands are only executed once, we don't need to copy it; we
4717          can clear the pointer in the bpstat, and make sure we free
4718          the tree when we're done.  */
4719       ccmd = bs->commands;
4720       bs->commands = NULL;
4721       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4722       cmd = ccmd ? ccmd->commands : NULL;
4723       if (command_line_is_silent (cmd))
4724         {
4725           /* The action has been already done by bpstat_stop_status.  */
4726           cmd = cmd->next;
4727         }
4728
4729       while (cmd != NULL)
4730         {
4731           execute_control_command (cmd);
4732
4733           if (breakpoint_proceeded)
4734             break;
4735           else
4736             cmd = cmd->next;
4737         }
4738
4739       /* We can free this command tree now.  */
4740       do_cleanups (this_cmd_tree_chain);
4741
4742       if (breakpoint_proceeded)
4743         {
4744           if (current_ui->async)
4745             /* If we are in async mode, then the target might be still
4746                running, not stopped at any breakpoint, so nothing for
4747                us to do here -- just return to the event loop.  */
4748             ;
4749           else
4750             /* In sync mode, when execute_control_command returns
4751                we're already standing on the next breakpoint.
4752                Breakpoint commands for that stop were not run, since
4753                execute_command does not run breakpoint commands --
4754                only command_line_handler does, but that one is not
4755                involved in execution of breakpoint commands.  So, we
4756                can now execute breakpoint commands.  It should be
4757                noted that making execute_command do bpstat actions is
4758                not an option -- in this case we'll have recursive
4759                invocation of bpstat for each breakpoint with a
4760                command, and can easily blow up GDB stack.  Instead, we
4761                return true, which will trigger the caller to recall us
4762                with the new stop_bpstat.  */
4763             again = 1;
4764           break;
4765         }
4766     }
4767   do_cleanups (old_chain);
4768   return again;
4769 }
4770
4771 void
4772 bpstat_do_actions (void)
4773 {
4774   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4775
4776   /* Do any commands attached to breakpoint we are stopped at.  */
4777   while (!ptid_equal (inferior_ptid, null_ptid)
4778          && target_has_execution
4779          && !is_exited (inferior_ptid)
4780          && !is_executing (inferior_ptid))
4781     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4782        and only return when it is stopped at the next breakpoint, we
4783        keep doing breakpoint actions until it returns false to
4784        indicate the inferior was not resumed.  */
4785     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4786       break;
4787
4788   discard_cleanups (cleanup_if_error);
4789 }
4790
4791 /* Print out the (old or new) value associated with a watchpoint.  */
4792
4793 static void
4794 watchpoint_value_print (struct value *val, struct ui_file *stream)
4795 {
4796   if (val == NULL)
4797     fprintf_unfiltered (stream, _("<unreadable>"));
4798   else
4799     {
4800       struct value_print_options opts;
4801       get_user_print_options (&opts);
4802       value_print (val, stream, &opts);
4803     }
4804 }
4805
4806 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4807    debugging multiple threads.  */
4808
4809 void
4810 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4811 {
4812   if (ui_out_is_mi_like_p (uiout))
4813     return;
4814
4815   ui_out_text (uiout, "\n");
4816
4817   if (show_thread_that_caused_stop ())
4818     {
4819       const char *name;
4820       struct thread_info *thr = inferior_thread ();
4821
4822       ui_out_text (uiout, "Thread ");
4823       ui_out_field_fmt (uiout, "thread-id", "%s", print_thread_id (thr));
4824
4825       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4826       if (name != NULL)
4827         {
4828           ui_out_text (uiout, " \"");
4829           ui_out_field_fmt (uiout, "name", "%s", name);
4830           ui_out_text (uiout, "\"");
4831         }
4832
4833       ui_out_text (uiout, " hit ");
4834     }
4835 }
4836
4837 /* Generic routine for printing messages indicating why we
4838    stopped.  The behavior of this function depends on the value
4839    'print_it' in the bpstat structure.  Under some circumstances we
4840    may decide not to print anything here and delegate the task to
4841    normal_stop().  */
4842
4843 static enum print_stop_action
4844 print_bp_stop_message (bpstat bs)
4845 {
4846   switch (bs->print_it)
4847     {
4848     case print_it_noop:
4849       /* Nothing should be printed for this bpstat entry.  */
4850       return PRINT_UNKNOWN;
4851       break;
4852
4853     case print_it_done:
4854       /* We still want to print the frame, but we already printed the
4855          relevant messages.  */
4856       return PRINT_SRC_AND_LOC;
4857       break;
4858
4859     case print_it_normal:
4860       {
4861         struct breakpoint *b = bs->breakpoint_at;
4862
4863         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4864            which has since been deleted.  */
4865         if (b == NULL)
4866           return PRINT_UNKNOWN;
4867
4868         /* Normal case.  Call the breakpoint's print_it method.  */
4869         return b->ops->print_it (bs);
4870       }
4871       break;
4872
4873     default:
4874       internal_error (__FILE__, __LINE__,
4875                       _("print_bp_stop_message: unrecognized enum value"));
4876       break;
4877     }
4878 }
4879
4880 /* A helper function that prints a shared library stopped event.  */
4881
4882 static void
4883 print_solib_event (int is_catchpoint)
4884 {
4885   int any_deleted
4886     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4887   int any_added
4888     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4889
4890   if (!is_catchpoint)
4891     {
4892       if (any_added || any_deleted)
4893         ui_out_text (current_uiout,
4894                      _("Stopped due to shared library event:\n"));
4895       else
4896         ui_out_text (current_uiout,
4897                      _("Stopped due to shared library event (no "
4898                        "libraries added or removed)\n"));
4899     }
4900
4901   if (ui_out_is_mi_like_p (current_uiout))
4902     ui_out_field_string (current_uiout, "reason",
4903                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4904
4905   if (any_deleted)
4906     {
4907       struct cleanup *cleanup;
4908       char *name;
4909       int ix;
4910
4911       ui_out_text (current_uiout, _("  Inferior unloaded "));
4912       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4913                                                     "removed");
4914       for (ix = 0;
4915            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4916                         ix, name);
4917            ++ix)
4918         {
4919           if (ix > 0)
4920             ui_out_text (current_uiout, "    ");
4921           ui_out_field_string (current_uiout, "library", name);
4922           ui_out_text (current_uiout, "\n");
4923         }
4924
4925       do_cleanups (cleanup);
4926     }
4927
4928   if (any_added)
4929     {
4930       struct so_list *iter;
4931       int ix;
4932       struct cleanup *cleanup;
4933
4934       ui_out_text (current_uiout, _("  Inferior loaded "));
4935       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4936                                                     "added");
4937       for (ix = 0;
4938            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4939                         ix, iter);
4940            ++ix)
4941         {
4942           if (ix > 0)
4943             ui_out_text (current_uiout, "    ");
4944           ui_out_field_string (current_uiout, "library", iter->so_name);
4945           ui_out_text (current_uiout, "\n");
4946         }
4947
4948       do_cleanups (cleanup);
4949     }
4950 }
4951
4952 /* Print a message indicating what happened.  This is called from
4953    normal_stop().  The input to this routine is the head of the bpstat
4954    list - a list of the eventpoints that caused this stop.  KIND is
4955    the target_waitkind for the stopping event.  This
4956    routine calls the generic print routine for printing a message
4957    about reasons for stopping.  This will print (for example) the
4958    "Breakpoint n," part of the output.  The return value of this
4959    routine is one of:
4960
4961    PRINT_UNKNOWN: Means we printed nothing.
4962    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4963    code to print the location.  An example is 
4964    "Breakpoint 1, " which should be followed by
4965    the location.
4966    PRINT_SRC_ONLY: Means we printed something, but there is no need
4967    to also print the location part of the message.
4968    An example is the catch/throw messages, which
4969    don't require a location appended to the end.
4970    PRINT_NOTHING: We have done some printing and we don't need any 
4971    further info to be printed.  */
4972
4973 enum print_stop_action
4974 bpstat_print (bpstat bs, int kind)
4975 {
4976   enum print_stop_action val;
4977
4978   /* Maybe another breakpoint in the chain caused us to stop.
4979      (Currently all watchpoints go on the bpstat whether hit or not.
4980      That probably could (should) be changed, provided care is taken
4981      with respect to bpstat_explains_signal).  */
4982   for (; bs; bs = bs->next)
4983     {
4984       val = print_bp_stop_message (bs);
4985       if (val == PRINT_SRC_ONLY 
4986           || val == PRINT_SRC_AND_LOC 
4987           || val == PRINT_NOTHING)
4988         return val;
4989     }
4990
4991   /* If we had hit a shared library event breakpoint,
4992      print_bp_stop_message would print out this message.  If we hit an
4993      OS-level shared library event, do the same thing.  */
4994   if (kind == TARGET_WAITKIND_LOADED)
4995     {
4996       print_solib_event (0);
4997       return PRINT_NOTHING;
4998     }
4999
5000   /* We reached the end of the chain, or we got a null BS to start
5001      with and nothing was printed.  */
5002   return PRINT_UNKNOWN;
5003 }
5004
5005 /* Evaluate the expression EXP and return 1 if value is zero.
5006    This returns the inverse of the condition because it is called
5007    from catch_errors which returns 0 if an exception happened, and if an
5008    exception happens we want execution to stop.
5009    The argument is a "struct expression *" that has been cast to a
5010    "void *" to make it pass through catch_errors.  */
5011
5012 static int
5013 breakpoint_cond_eval (void *exp)
5014 {
5015   struct value *mark = value_mark ();
5016   int i = !value_true (evaluate_expression ((struct expression *) exp));
5017
5018   value_free_to_mark (mark);
5019   return i;
5020 }
5021
5022 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
5023
5024 static bpstat
5025 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
5026 {
5027   bpstat bs;
5028
5029   bs = (bpstat) xmalloc (sizeof (*bs));
5030   bs->next = NULL;
5031   **bs_link_pointer = bs;
5032   *bs_link_pointer = &bs->next;
5033   bs->breakpoint_at = bl->owner;
5034   bs->bp_location_at = bl;
5035   incref_bp_location (bl);
5036   /* If the condition is false, etc., don't do the commands.  */
5037   bs->commands = NULL;
5038   bs->old_val = NULL;
5039   bs->print_it = print_it_normal;
5040   return bs;
5041 }
5042 \f
5043 /* The target has stopped with waitstatus WS.  Check if any hardware
5044    watchpoints have triggered, according to the target.  */
5045
5046 int
5047 watchpoints_triggered (struct target_waitstatus *ws)
5048 {
5049   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
5050   CORE_ADDR addr;
5051   struct breakpoint *b;
5052
5053   if (!stopped_by_watchpoint)
5054     {
5055       /* We were not stopped by a watchpoint.  Mark all watchpoints
5056          as not triggered.  */
5057       ALL_BREAKPOINTS (b)
5058         if (is_hardware_watchpoint (b))
5059           {
5060             struct watchpoint *w = (struct watchpoint *) b;
5061
5062             w->watchpoint_triggered = watch_triggered_no;
5063           }
5064
5065       return 0;
5066     }
5067
5068   if (!target_stopped_data_address (&current_target, &addr))
5069     {
5070       /* We were stopped by a watchpoint, but we don't know where.
5071          Mark all watchpoints as unknown.  */
5072       ALL_BREAKPOINTS (b)
5073         if (is_hardware_watchpoint (b))
5074           {
5075             struct watchpoint *w = (struct watchpoint *) b;
5076
5077             w->watchpoint_triggered = watch_triggered_unknown;
5078           }
5079
5080       return 1;
5081     }
5082
5083   /* The target could report the data address.  Mark watchpoints
5084      affected by this data address as triggered, and all others as not
5085      triggered.  */
5086
5087   ALL_BREAKPOINTS (b)
5088     if (is_hardware_watchpoint (b))
5089       {
5090         struct watchpoint *w = (struct watchpoint *) b;
5091         struct bp_location *loc;
5092
5093         w->watchpoint_triggered = watch_triggered_no;
5094         for (loc = b->loc; loc; loc = loc->next)
5095           {
5096             if (is_masked_watchpoint (b))
5097               {
5098                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5099                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5100
5101                 if (newaddr == start)
5102                   {
5103                     w->watchpoint_triggered = watch_triggered_yes;
5104                     break;
5105                   }
5106               }
5107             /* Exact match not required.  Within range is sufficient.  */
5108             else if (target_watchpoint_addr_within_range (&current_target,
5109                                                          addr, loc->address,
5110                                                          loc->length))
5111               {
5112                 w->watchpoint_triggered = watch_triggered_yes;
5113                 break;
5114               }
5115           }
5116       }
5117
5118   return 1;
5119 }
5120
5121 /* Possible return values for watchpoint_check (this can't be an enum
5122    because of check_errors).  */
5123 /* The watchpoint has been deleted.  */
5124 #define WP_DELETED 1
5125 /* The value has changed.  */
5126 #define WP_VALUE_CHANGED 2
5127 /* The value has not changed.  */
5128 #define WP_VALUE_NOT_CHANGED 3
5129 /* Ignore this watchpoint, no matter if the value changed or not.  */
5130 #define WP_IGNORE 4
5131
5132 #define BP_TEMPFLAG 1
5133 #define BP_HARDWAREFLAG 2
5134
5135 /* Evaluate watchpoint condition expression and check if its value
5136    changed.
5137
5138    P should be a pointer to struct bpstat, but is defined as a void *
5139    in order for this function to be usable with catch_errors.  */
5140
5141 static int
5142 watchpoint_check (void *p)
5143 {
5144   bpstat bs = (bpstat) p;
5145   struct watchpoint *b;
5146   struct frame_info *fr;
5147   int within_current_scope;
5148
5149   /* BS is built from an existing struct breakpoint.  */
5150   gdb_assert (bs->breakpoint_at != NULL);
5151   b = (struct watchpoint *) bs->breakpoint_at;
5152
5153   /* If this is a local watchpoint, we only want to check if the
5154      watchpoint frame is in scope if the current thread is the thread
5155      that was used to create the watchpoint.  */
5156   if (!watchpoint_in_thread_scope (b))
5157     return WP_IGNORE;
5158
5159   if (b->exp_valid_block == NULL)
5160     within_current_scope = 1;
5161   else
5162     {
5163       struct frame_info *frame = get_current_frame ();
5164       struct gdbarch *frame_arch = get_frame_arch (frame);
5165       CORE_ADDR frame_pc = get_frame_pc (frame);
5166
5167       /* stack_frame_destroyed_p() returns a non-zero value if we're
5168          still in the function but the stack frame has already been
5169          invalidated.  Since we can't rely on the values of local
5170          variables after the stack has been destroyed, we are treating
5171          the watchpoint in that state as `not changed' without further
5172          checking.  Don't mark watchpoints as changed if the current
5173          frame is in an epilogue - even if they are in some other
5174          frame, our view of the stack is likely to be wrong and
5175          frame_find_by_id could error out.  */
5176       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5177         return WP_IGNORE;
5178
5179       fr = frame_find_by_id (b->watchpoint_frame);
5180       within_current_scope = (fr != NULL);
5181
5182       /* If we've gotten confused in the unwinder, we might have
5183          returned a frame that can't describe this variable.  */
5184       if (within_current_scope)
5185         {
5186           struct symbol *function;
5187
5188           function = get_frame_function (fr);
5189           if (function == NULL
5190               || !contained_in (b->exp_valid_block,
5191                                 SYMBOL_BLOCK_VALUE (function)))
5192             within_current_scope = 0;
5193         }
5194
5195       if (within_current_scope)
5196         /* If we end up stopping, the current frame will get selected
5197            in normal_stop.  So this call to select_frame won't affect
5198            the user.  */
5199         select_frame (fr);
5200     }
5201
5202   if (within_current_scope)
5203     {
5204       /* We use value_{,free_to_}mark because it could be a *long*
5205          time before we return to the command level and call
5206          free_all_values.  We can't call free_all_values because we
5207          might be in the middle of evaluating a function call.  */
5208
5209       int pc = 0;
5210       struct value *mark;
5211       struct value *new_val;
5212
5213       if (is_masked_watchpoint (&b->base))
5214         /* Since we don't know the exact trigger address (from
5215            stopped_data_address), just tell the user we've triggered
5216            a mask watchpoint.  */
5217         return WP_VALUE_CHANGED;
5218
5219       mark = value_mark ();
5220       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5221
5222       if (b->val_bitsize != 0)
5223         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5224
5225       /* We use value_equal_contents instead of value_equal because
5226          the latter coerces an array to a pointer, thus comparing just
5227          the address of the array instead of its contents.  This is
5228          not what we want.  */
5229       if ((b->val != NULL) != (new_val != NULL)
5230           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5231         {
5232           if (new_val != NULL)
5233             {
5234               release_value (new_val);
5235               value_free_to_mark (mark);
5236             }
5237           bs->old_val = b->val;
5238           b->val = new_val;
5239           b->val_valid = 1;
5240           return WP_VALUE_CHANGED;
5241         }
5242       else
5243         {
5244           /* Nothing changed.  */
5245           value_free_to_mark (mark);
5246           return WP_VALUE_NOT_CHANGED;
5247         }
5248     }
5249   else
5250     {
5251       struct switch_thru_all_uis state;
5252
5253       /* This seems like the only logical thing to do because
5254          if we temporarily ignored the watchpoint, then when
5255          we reenter the block in which it is valid it contains
5256          garbage (in the case of a function, it may have two
5257          garbage values, one before and one after the prologue).
5258          So we can't even detect the first assignment to it and
5259          watch after that (since the garbage may or may not equal
5260          the first value assigned).  */
5261       /* We print all the stop information in
5262          breakpoint_ops->print_it, but in this case, by the time we
5263          call breakpoint_ops->print_it this bp will be deleted
5264          already.  So we have no choice but print the information
5265          here.  */
5266
5267       SWITCH_THRU_ALL_UIS (state)
5268         {
5269           struct ui_out *uiout = current_uiout;
5270
5271           if (ui_out_is_mi_like_p (uiout))
5272             ui_out_field_string
5273               (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5274           ui_out_text (uiout, "\nWatchpoint ");
5275           ui_out_field_int (uiout, "wpnum", b->base.number);
5276           ui_out_text (uiout,
5277                        " deleted because the program has left the block in\n"
5278                        "which its expression is valid.\n");
5279         }
5280
5281       /* Make sure the watchpoint's commands aren't executed.  */
5282       decref_counted_command_line (&b->base.commands);
5283       watchpoint_del_at_next_stop (b);
5284
5285       return WP_DELETED;
5286     }
5287 }
5288
5289 /* Return true if it looks like target has stopped due to hitting
5290    breakpoint location BL.  This function does not check if we should
5291    stop, only if BL explains the stop.  */
5292
5293 static int
5294 bpstat_check_location (const struct bp_location *bl,
5295                        struct address_space *aspace, CORE_ADDR bp_addr,
5296                        const struct target_waitstatus *ws)
5297 {
5298   struct breakpoint *b = bl->owner;
5299
5300   /* BL is from an existing breakpoint.  */
5301   gdb_assert (b != NULL);
5302
5303   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5304 }
5305
5306 /* Determine if the watched values have actually changed, and we
5307    should stop.  If not, set BS->stop to 0.  */
5308
5309 static void
5310 bpstat_check_watchpoint (bpstat bs)
5311 {
5312   const struct bp_location *bl;
5313   struct watchpoint *b;
5314
5315   /* BS is built for existing struct breakpoint.  */
5316   bl = bs->bp_location_at;
5317   gdb_assert (bl != NULL);
5318   b = (struct watchpoint *) bs->breakpoint_at;
5319   gdb_assert (b != NULL);
5320
5321     {
5322       int must_check_value = 0;
5323       
5324       if (b->base.type == bp_watchpoint)
5325         /* For a software watchpoint, we must always check the
5326            watched value.  */
5327         must_check_value = 1;
5328       else if (b->watchpoint_triggered == watch_triggered_yes)
5329         /* We have a hardware watchpoint (read, write, or access)
5330            and the target earlier reported an address watched by
5331            this watchpoint.  */
5332         must_check_value = 1;
5333       else if (b->watchpoint_triggered == watch_triggered_unknown
5334                && b->base.type == bp_hardware_watchpoint)
5335         /* We were stopped by a hardware watchpoint, but the target could
5336            not report the data address.  We must check the watchpoint's
5337            value.  Access and read watchpoints are out of luck; without
5338            a data address, we can't figure it out.  */
5339         must_check_value = 1;
5340
5341       if (must_check_value)
5342         {
5343           char *message
5344             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5345                           b->base.number);
5346           struct cleanup *cleanups = make_cleanup (xfree, message);
5347           int e = catch_errors (watchpoint_check, bs, message,
5348                                 RETURN_MASK_ALL);
5349           do_cleanups (cleanups);
5350           switch (e)
5351             {
5352             case WP_DELETED:
5353               /* We've already printed what needs to be printed.  */
5354               bs->print_it = print_it_done;
5355               /* Stop.  */
5356               break;
5357             case WP_IGNORE:
5358               bs->print_it = print_it_noop;
5359               bs->stop = 0;
5360               break;
5361             case WP_VALUE_CHANGED:
5362               if (b->base.type == bp_read_watchpoint)
5363                 {
5364                   /* There are two cases to consider here:
5365
5366                      1. We're watching the triggered memory for reads.
5367                      In that case, trust the target, and always report
5368                      the watchpoint hit to the user.  Even though
5369                      reads don't cause value changes, the value may
5370                      have changed since the last time it was read, and
5371                      since we're not trapping writes, we will not see
5372                      those, and as such we should ignore our notion of
5373                      old value.
5374
5375                      2. We're watching the triggered memory for both
5376                      reads and writes.  There are two ways this may
5377                      happen:
5378
5379                      2.1. This is a target that can't break on data
5380                      reads only, but can break on accesses (reads or
5381                      writes), such as e.g., x86.  We detect this case
5382                      at the time we try to insert read watchpoints.
5383
5384                      2.2. Otherwise, the target supports read
5385                      watchpoints, but, the user set an access or write
5386                      watchpoint watching the same memory as this read
5387                      watchpoint.
5388
5389                      If we're watching memory writes as well as reads,
5390                      ignore watchpoint hits when we find that the
5391                      value hasn't changed, as reads don't cause
5392                      changes.  This still gives false positives when
5393                      the program writes the same value to memory as
5394                      what there was already in memory (we will confuse
5395                      it for a read), but it's much better than
5396                      nothing.  */
5397
5398                   int other_write_watchpoint = 0;
5399
5400                   if (bl->watchpoint_type == hw_read)
5401                     {
5402                       struct breakpoint *other_b;
5403
5404                       ALL_BREAKPOINTS (other_b)
5405                         if (other_b->type == bp_hardware_watchpoint
5406                             || other_b->type == bp_access_watchpoint)
5407                           {
5408                             struct watchpoint *other_w =
5409                               (struct watchpoint *) other_b;
5410
5411                             if (other_w->watchpoint_triggered
5412                                 == watch_triggered_yes)
5413                               {
5414                                 other_write_watchpoint = 1;
5415                                 break;
5416                               }
5417                           }
5418                     }
5419
5420                   if (other_write_watchpoint
5421                       || bl->watchpoint_type == hw_access)
5422                     {
5423                       /* We're watching the same memory for writes,
5424                          and the value changed since the last time we
5425                          updated it, so this trap must be for a write.
5426                          Ignore it.  */
5427                       bs->print_it = print_it_noop;
5428                       bs->stop = 0;
5429                     }
5430                 }
5431               break;
5432             case WP_VALUE_NOT_CHANGED:
5433               if (b->base.type == bp_hardware_watchpoint
5434                   || b->base.type == bp_watchpoint)
5435                 {
5436                   /* Don't stop: write watchpoints shouldn't fire if
5437                      the value hasn't changed.  */
5438                   bs->print_it = print_it_noop;
5439                   bs->stop = 0;
5440                 }
5441               /* Stop.  */
5442               break;
5443             default:
5444               /* Can't happen.  */
5445             case 0:
5446               /* Error from catch_errors.  */
5447               {
5448                 struct switch_thru_all_uis state;
5449
5450                 SWITCH_THRU_ALL_UIS (state)
5451                   {
5452                     printf_filtered (_("Watchpoint %d deleted.\n"),
5453                                      b->base.number);
5454                   }
5455                 watchpoint_del_at_next_stop (b);
5456                 /* We've already printed what needs to be printed.  */
5457                 bs->print_it = print_it_done;
5458               }
5459               break;
5460             }
5461         }
5462       else      /* must_check_value == 0 */
5463         {
5464           /* This is a case where some watchpoint(s) triggered, but
5465              not at the address of this watchpoint, or else no
5466              watchpoint triggered after all.  So don't print
5467              anything for this watchpoint.  */
5468           bs->print_it = print_it_noop;
5469           bs->stop = 0;
5470         }
5471     }
5472 }
5473
5474 /* For breakpoints that are currently marked as telling gdb to stop,
5475    check conditions (condition proper, frame, thread and ignore count)
5476    of breakpoint referred to by BS.  If we should not stop for this
5477    breakpoint, set BS->stop to 0.  */
5478
5479 static void
5480 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5481 {
5482   const struct bp_location *bl;
5483   struct breakpoint *b;
5484   int value_is_zero = 0;
5485   struct expression *cond;
5486
5487   gdb_assert (bs->stop);
5488
5489   /* BS is built for existing struct breakpoint.  */
5490   bl = bs->bp_location_at;
5491   gdb_assert (bl != NULL);
5492   b = bs->breakpoint_at;
5493   gdb_assert (b != NULL);
5494
5495   /* Even if the target evaluated the condition on its end and notified GDB, we
5496      need to do so again since GDB does not know if we stopped due to a
5497      breakpoint or a single step breakpoint.  */
5498
5499   if (frame_id_p (b->frame_id)
5500       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5501     {
5502       bs->stop = 0;
5503       return;
5504     }
5505
5506   /* If this is a thread/task-specific breakpoint, don't waste cpu
5507      evaluating the condition if this isn't the specified
5508      thread/task.  */
5509   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5510       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5511
5512     {
5513       bs->stop = 0;
5514       return;
5515     }
5516
5517   /* Evaluate extension language breakpoints that have a "stop" method
5518      implemented.  */
5519   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5520
5521   if (is_watchpoint (b))
5522     {
5523       struct watchpoint *w = (struct watchpoint *) b;
5524
5525       cond = w->cond_exp;
5526     }
5527   else
5528     cond = bl->cond;
5529
5530   if (cond && b->disposition != disp_del_at_next_stop)
5531     {
5532       int within_current_scope = 1;
5533       struct watchpoint * w;
5534
5535       /* We use value_mark and value_free_to_mark because it could
5536          be a long time before we return to the command level and
5537          call free_all_values.  We can't call free_all_values
5538          because we might be in the middle of evaluating a
5539          function call.  */
5540       struct value *mark = value_mark ();
5541
5542       if (is_watchpoint (b))
5543         w = (struct watchpoint *) b;
5544       else
5545         w = NULL;
5546
5547       /* Need to select the frame, with all that implies so that
5548          the conditions will have the right context.  Because we
5549          use the frame, we will not see an inlined function's
5550          variables when we arrive at a breakpoint at the start
5551          of the inlined function; the current frame will be the
5552          call site.  */
5553       if (w == NULL || w->cond_exp_valid_block == NULL)
5554         select_frame (get_current_frame ());
5555       else
5556         {
5557           struct frame_info *frame;
5558
5559           /* For local watchpoint expressions, which particular
5560              instance of a local is being watched matters, so we
5561              keep track of the frame to evaluate the expression
5562              in.  To evaluate the condition however, it doesn't
5563              really matter which instantiation of the function
5564              where the condition makes sense triggers the
5565              watchpoint.  This allows an expression like "watch
5566              global if q > 10" set in `func', catch writes to
5567              global on all threads that call `func', or catch
5568              writes on all recursive calls of `func' by a single
5569              thread.  We simply always evaluate the condition in
5570              the innermost frame that's executing where it makes
5571              sense to evaluate the condition.  It seems
5572              intuitive.  */
5573           frame = block_innermost_frame (w->cond_exp_valid_block);
5574           if (frame != NULL)
5575             select_frame (frame);
5576           else
5577             within_current_scope = 0;
5578         }
5579       if (within_current_scope)
5580         value_is_zero
5581           = catch_errors (breakpoint_cond_eval, cond,
5582                           "Error in testing breakpoint condition:\n",
5583                           RETURN_MASK_ALL);
5584       else
5585         {
5586           warning (_("Watchpoint condition cannot be tested "
5587                      "in the current scope"));
5588           /* If we failed to set the right context for this
5589              watchpoint, unconditionally report it.  */
5590           value_is_zero = 0;
5591         }
5592       /* FIXME-someday, should give breakpoint #.  */
5593       value_free_to_mark (mark);
5594     }
5595
5596   if (cond && value_is_zero)
5597     {
5598       bs->stop = 0;
5599     }
5600   else if (b->ignore_count > 0)
5601     {
5602       b->ignore_count--;
5603       bs->stop = 0;
5604       /* Increase the hit count even though we don't stop.  */
5605       ++(b->hit_count);
5606       observer_notify_breakpoint_modified (b);
5607     }   
5608 }
5609
5610 /* Returns true if we need to track moribund locations of LOC's type
5611    on the current target.  */
5612
5613 static int
5614 need_moribund_for_location_type (struct bp_location *loc)
5615 {
5616   return ((loc->loc_type == bp_loc_software_breakpoint
5617            && !target_supports_stopped_by_sw_breakpoint ())
5618           || (loc->loc_type == bp_loc_hardware_breakpoint
5619               && !target_supports_stopped_by_hw_breakpoint ()));
5620 }
5621
5622
5623 /* Get a bpstat associated with having just stopped at address
5624    BP_ADDR in thread PTID.
5625
5626    Determine whether we stopped at a breakpoint, etc, or whether we
5627    don't understand this stop.  Result is a chain of bpstat's such
5628    that:
5629
5630    if we don't understand the stop, the result is a null pointer.
5631
5632    if we understand why we stopped, the result is not null.
5633
5634    Each element of the chain refers to a particular breakpoint or
5635    watchpoint at which we have stopped.  (We may have stopped for
5636    several reasons concurrently.)
5637
5638    Each element of the chain has valid next, breakpoint_at,
5639    commands, FIXME??? fields.  */
5640
5641 bpstat
5642 bpstat_stop_status (struct address_space *aspace,
5643                     CORE_ADDR bp_addr, ptid_t ptid,
5644                     const struct target_waitstatus *ws)
5645 {
5646   struct breakpoint *b = NULL;
5647   struct bp_location *bl;
5648   struct bp_location *loc;
5649   /* First item of allocated bpstat's.  */
5650   bpstat bs_head = NULL, *bs_link = &bs_head;
5651   /* Pointer to the last thing in the chain currently.  */
5652   bpstat bs;
5653   int ix;
5654   int need_remove_insert;
5655   int removed_any;
5656
5657   /* First, build the bpstat chain with locations that explain a
5658      target stop, while being careful to not set the target running,
5659      as that may invalidate locations (in particular watchpoint
5660      locations are recreated).  Resuming will happen here with
5661      breakpoint conditions or watchpoint expressions that include
5662      inferior function calls.  */
5663
5664   ALL_BREAKPOINTS (b)
5665     {
5666       if (!breakpoint_enabled (b))
5667         continue;
5668
5669       for (bl = b->loc; bl != NULL; bl = bl->next)
5670         {
5671           /* For hardware watchpoints, we look only at the first
5672              location.  The watchpoint_check function will work on the
5673              entire expression, not the individual locations.  For
5674              read watchpoints, the watchpoints_triggered function has
5675              checked all locations already.  */
5676           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5677             break;
5678
5679           if (!bl->enabled || bl->shlib_disabled)
5680             continue;
5681
5682           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5683             continue;
5684
5685           /* Come here if it's a watchpoint, or if the break address
5686              matches.  */
5687
5688           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5689                                                    explain stop.  */
5690
5691           /* Assume we stop.  Should we find a watchpoint that is not
5692              actually triggered, or if the condition of the breakpoint
5693              evaluates as false, we'll reset 'stop' to 0.  */
5694           bs->stop = 1;
5695           bs->print = 1;
5696
5697           /* If this is a scope breakpoint, mark the associated
5698              watchpoint as triggered so that we will handle the
5699              out-of-scope event.  We'll get to the watchpoint next
5700              iteration.  */
5701           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5702             {
5703               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5704
5705               w->watchpoint_triggered = watch_triggered_yes;
5706             }
5707         }
5708     }
5709
5710   /* Check if a moribund breakpoint explains the stop.  */
5711   if (!target_supports_stopped_by_sw_breakpoint ()
5712       || !target_supports_stopped_by_hw_breakpoint ())
5713     {
5714       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5715         {
5716           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5717               && need_moribund_for_location_type (loc))
5718             {
5719               bs = bpstat_alloc (loc, &bs_link);
5720               /* For hits of moribund locations, we should just proceed.  */
5721               bs->stop = 0;
5722               bs->print = 0;
5723               bs->print_it = print_it_noop;
5724             }
5725         }
5726     }
5727
5728   /* A bit of special processing for shlib breakpoints.  We need to
5729      process solib loading here, so that the lists of loaded and
5730      unloaded libraries are correct before we handle "catch load" and
5731      "catch unload".  */
5732   for (bs = bs_head; bs != NULL; bs = bs->next)
5733     {
5734       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5735         {
5736           handle_solib_event ();
5737           break;
5738         }
5739     }
5740
5741   /* Now go through the locations that caused the target to stop, and
5742      check whether we're interested in reporting this stop to higher
5743      layers, or whether we should resume the target transparently.  */
5744
5745   removed_any = 0;
5746
5747   for (bs = bs_head; bs != NULL; bs = bs->next)
5748     {
5749       if (!bs->stop)
5750         continue;
5751
5752       b = bs->breakpoint_at;
5753       b->ops->check_status (bs);
5754       if (bs->stop)
5755         {
5756           bpstat_check_breakpoint_conditions (bs, ptid);
5757
5758           if (bs->stop)
5759             {
5760               ++(b->hit_count);
5761               observer_notify_breakpoint_modified (b);
5762
5763               /* We will stop here.  */
5764               if (b->disposition == disp_disable)
5765                 {
5766                   --(b->enable_count);
5767                   if (b->enable_count <= 0)
5768                     b->enable_state = bp_disabled;
5769                   removed_any = 1;
5770                 }
5771               if (b->silent)
5772                 bs->print = 0;
5773               bs->commands = b->commands;
5774               incref_counted_command_line (bs->commands);
5775               if (command_line_is_silent (bs->commands
5776                                           ? bs->commands->commands : NULL))
5777                 bs->print = 0;
5778
5779               b->ops->after_condition_true (bs);
5780             }
5781
5782         }
5783
5784       /* Print nothing for this entry if we don't stop or don't
5785          print.  */
5786       if (!bs->stop || !bs->print)
5787         bs->print_it = print_it_noop;
5788     }
5789
5790   /* If we aren't stopping, the value of some hardware watchpoint may
5791      not have changed, but the intermediate memory locations we are
5792      watching may have.  Don't bother if we're stopping; this will get
5793      done later.  */
5794   need_remove_insert = 0;
5795   if (! bpstat_causes_stop (bs_head))
5796     for (bs = bs_head; bs != NULL; bs = bs->next)
5797       if (!bs->stop
5798           && bs->breakpoint_at
5799           && is_hardware_watchpoint (bs->breakpoint_at))
5800         {
5801           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5802
5803           update_watchpoint (w, 0 /* don't reparse.  */);
5804           need_remove_insert = 1;
5805         }
5806
5807   if (need_remove_insert)
5808     update_global_location_list (UGLL_MAY_INSERT);
5809   else if (removed_any)
5810     update_global_location_list (UGLL_DONT_INSERT);
5811
5812   return bs_head;
5813 }
5814
5815 static void
5816 handle_jit_event (void)
5817 {
5818   struct frame_info *frame;
5819   struct gdbarch *gdbarch;
5820
5821   if (debug_infrun)
5822     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5823
5824   /* Switch terminal for any messages produced by
5825      breakpoint_re_set.  */
5826   target_terminal_ours_for_output ();
5827
5828   frame = get_current_frame ();
5829   gdbarch = get_frame_arch (frame);
5830
5831   jit_event_handler (gdbarch);
5832
5833   target_terminal_inferior ();
5834 }
5835
5836 /* Prepare WHAT final decision for infrun.  */
5837
5838 /* Decide what infrun needs to do with this bpstat.  */
5839
5840 struct bpstat_what
5841 bpstat_what (bpstat bs_head)
5842 {
5843   struct bpstat_what retval;
5844   bpstat bs;
5845
5846   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5847   retval.call_dummy = STOP_NONE;
5848   retval.is_longjmp = 0;
5849
5850   for (bs = bs_head; bs != NULL; bs = bs->next)
5851     {
5852       /* Extract this BS's action.  After processing each BS, we check
5853          if its action overrides all we've seem so far.  */
5854       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5855       enum bptype bptype;
5856
5857       if (bs->breakpoint_at == NULL)
5858         {
5859           /* I suspect this can happen if it was a momentary
5860              breakpoint which has since been deleted.  */
5861           bptype = bp_none;
5862         }
5863       else
5864         bptype = bs->breakpoint_at->type;
5865
5866       switch (bptype)
5867         {
5868         case bp_none:
5869           break;
5870         case bp_breakpoint:
5871         case bp_hardware_breakpoint:
5872         case bp_single_step:
5873         case bp_until:
5874         case bp_finish:
5875         case bp_shlib_event:
5876           if (bs->stop)
5877             {
5878               if (bs->print)
5879                 this_action = BPSTAT_WHAT_STOP_NOISY;
5880               else
5881                 this_action = BPSTAT_WHAT_STOP_SILENT;
5882             }
5883           else
5884             this_action = BPSTAT_WHAT_SINGLE;
5885           break;
5886         case bp_watchpoint:
5887         case bp_hardware_watchpoint:
5888         case bp_read_watchpoint:
5889         case bp_access_watchpoint:
5890           if (bs->stop)
5891             {
5892               if (bs->print)
5893                 this_action = BPSTAT_WHAT_STOP_NOISY;
5894               else
5895                 this_action = BPSTAT_WHAT_STOP_SILENT;
5896             }
5897           else
5898             {
5899               /* There was a watchpoint, but we're not stopping.
5900                  This requires no further action.  */
5901             }
5902           break;
5903         case bp_longjmp:
5904         case bp_longjmp_call_dummy:
5905         case bp_exception:
5906           if (bs->stop)
5907             {
5908               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5909               retval.is_longjmp = bptype != bp_exception;
5910             }
5911           else
5912             this_action = BPSTAT_WHAT_SINGLE;
5913           break;
5914         case bp_longjmp_resume:
5915         case bp_exception_resume:
5916           if (bs->stop)
5917             {
5918               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5919               retval.is_longjmp = bptype == bp_longjmp_resume;
5920             }
5921           else
5922             this_action = BPSTAT_WHAT_SINGLE;
5923           break;
5924         case bp_step_resume:
5925           if (bs->stop)
5926             this_action = BPSTAT_WHAT_STEP_RESUME;
5927           else
5928             {
5929               /* It is for the wrong frame.  */
5930               this_action = BPSTAT_WHAT_SINGLE;
5931             }
5932           break;
5933         case bp_hp_step_resume:
5934           if (bs->stop)
5935             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5936           else
5937             {
5938               /* It is for the wrong frame.  */
5939               this_action = BPSTAT_WHAT_SINGLE;
5940             }
5941           break;
5942         case bp_watchpoint_scope:
5943         case bp_thread_event:
5944         case bp_overlay_event:
5945         case bp_longjmp_master:
5946         case bp_std_terminate_master:
5947         case bp_exception_master:
5948           this_action = BPSTAT_WHAT_SINGLE;
5949           break;
5950         case bp_catchpoint:
5951           if (bs->stop)
5952             {
5953               if (bs->print)
5954                 this_action = BPSTAT_WHAT_STOP_NOISY;
5955               else
5956                 this_action = BPSTAT_WHAT_STOP_SILENT;
5957             }
5958           else
5959             {
5960               /* There was a catchpoint, but we're not stopping.
5961                  This requires no further action.  */
5962             }
5963           break;
5964         case bp_jit_event:
5965           this_action = BPSTAT_WHAT_SINGLE;
5966           break;
5967         case bp_call_dummy:
5968           /* Make sure the action is stop (silent or noisy),
5969              so infrun.c pops the dummy frame.  */
5970           retval.call_dummy = STOP_STACK_DUMMY;
5971           this_action = BPSTAT_WHAT_STOP_SILENT;
5972           break;
5973         case bp_std_terminate:
5974           /* Make sure the action is stop (silent or noisy),
5975              so infrun.c pops the dummy frame.  */
5976           retval.call_dummy = STOP_STD_TERMINATE;
5977           this_action = BPSTAT_WHAT_STOP_SILENT;
5978           break;
5979         case bp_tracepoint:
5980         case bp_fast_tracepoint:
5981         case bp_static_tracepoint:
5982           /* Tracepoint hits should not be reported back to GDB, and
5983              if one got through somehow, it should have been filtered
5984              out already.  */
5985           internal_error (__FILE__, __LINE__,
5986                           _("bpstat_what: tracepoint encountered"));
5987           break;
5988         case bp_gnu_ifunc_resolver:
5989           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5990           this_action = BPSTAT_WHAT_SINGLE;
5991           break;
5992         case bp_gnu_ifunc_resolver_return:
5993           /* The breakpoint will be removed, execution will restart from the
5994              PC of the former breakpoint.  */
5995           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5996           break;
5997
5998         case bp_dprintf:
5999           if (bs->stop)
6000             this_action = BPSTAT_WHAT_STOP_SILENT;
6001           else
6002             this_action = BPSTAT_WHAT_SINGLE;
6003           break;
6004
6005         default:
6006           internal_error (__FILE__, __LINE__,
6007                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
6008         }
6009
6010       retval.main_action = max (retval.main_action, this_action);
6011     }
6012
6013   return retval;
6014 }
6015
6016 void
6017 bpstat_run_callbacks (bpstat bs_head)
6018 {
6019   bpstat bs;
6020
6021   for (bs = bs_head; bs != NULL; bs = bs->next)
6022     {
6023       struct breakpoint *b = bs->breakpoint_at;
6024
6025       if (b == NULL)
6026         continue;
6027       switch (b->type)
6028         {
6029         case bp_jit_event:
6030           handle_jit_event ();
6031           break;
6032         case bp_gnu_ifunc_resolver:
6033           gnu_ifunc_resolver_stop (b);
6034           break;
6035         case bp_gnu_ifunc_resolver_return:
6036           gnu_ifunc_resolver_return_stop (b);
6037           break;
6038         }
6039     }
6040 }
6041
6042 /* Nonzero if we should step constantly (e.g. watchpoints on machines
6043    without hardware support).  This isn't related to a specific bpstat,
6044    just to things like whether watchpoints are set.  */
6045
6046 int
6047 bpstat_should_step (void)
6048 {
6049   struct breakpoint *b;
6050
6051   ALL_BREAKPOINTS (b)
6052     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6053       return 1;
6054   return 0;
6055 }
6056
6057 int
6058 bpstat_causes_stop (bpstat bs)
6059 {
6060   for (; bs != NULL; bs = bs->next)
6061     if (bs->stop)
6062       return 1;
6063
6064   return 0;
6065 }
6066
6067 \f
6068
6069 /* Compute a string of spaces suitable to indent the next line
6070    so it starts at the position corresponding to the table column
6071    named COL_NAME in the currently active table of UIOUT.  */
6072
6073 static char *
6074 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6075 {
6076   static char wrap_indent[80];
6077   int i, total_width, width, align;
6078   char *text;
6079
6080   total_width = 0;
6081   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
6082     {
6083       if (strcmp (text, col_name) == 0)
6084         {
6085           gdb_assert (total_width < sizeof wrap_indent);
6086           memset (wrap_indent, ' ', total_width);
6087           wrap_indent[total_width] = 0;
6088
6089           return wrap_indent;
6090         }
6091
6092       total_width += width + 1;
6093     }
6094
6095   return NULL;
6096 }
6097
6098 /* Determine if the locations of this breakpoint will have their conditions
6099    evaluated by the target, host or a mix of both.  Returns the following:
6100
6101     "host": Host evals condition.
6102     "host or target": Host or Target evals condition.
6103     "target": Target evals condition.
6104 */
6105
6106 static const char *
6107 bp_condition_evaluator (struct breakpoint *b)
6108 {
6109   struct bp_location *bl;
6110   char host_evals = 0;
6111   char target_evals = 0;
6112
6113   if (!b)
6114     return NULL;
6115
6116   if (!is_breakpoint (b))
6117     return NULL;
6118
6119   if (gdb_evaluates_breakpoint_condition_p ()
6120       || !target_supports_evaluation_of_breakpoint_conditions ())
6121     return condition_evaluation_host;
6122
6123   for (bl = b->loc; bl; bl = bl->next)
6124     {
6125       if (bl->cond_bytecode)
6126         target_evals++;
6127       else
6128         host_evals++;
6129     }
6130
6131   if (host_evals && target_evals)
6132     return condition_evaluation_both;
6133   else if (target_evals)
6134     return condition_evaluation_target;
6135   else
6136     return condition_evaluation_host;
6137 }
6138
6139 /* Determine the breakpoint location's condition evaluator.  This is
6140    similar to bp_condition_evaluator, but for locations.  */
6141
6142 static const char *
6143 bp_location_condition_evaluator (struct bp_location *bl)
6144 {
6145   if (bl && !is_breakpoint (bl->owner))
6146     return NULL;
6147
6148   if (gdb_evaluates_breakpoint_condition_p ()
6149       || !target_supports_evaluation_of_breakpoint_conditions ())
6150     return condition_evaluation_host;
6151
6152   if (bl && bl->cond_bytecode)
6153     return condition_evaluation_target;
6154   else
6155     return condition_evaluation_host;
6156 }
6157
6158 /* Print the LOC location out of the list of B->LOC locations.  */
6159
6160 static void
6161 print_breakpoint_location (struct breakpoint *b,
6162                            struct bp_location *loc)
6163 {
6164   struct ui_out *uiout = current_uiout;
6165   struct cleanup *old_chain = save_current_program_space ();
6166
6167   if (loc != NULL && loc->shlib_disabled)
6168     loc = NULL;
6169
6170   if (loc != NULL)
6171     set_current_program_space (loc->pspace);
6172
6173   if (b->display_canonical)
6174     ui_out_field_string (uiout, "what",
6175                          event_location_to_string (b->location));
6176   else if (loc && loc->symtab)
6177     {
6178       struct symbol *sym 
6179         = find_pc_sect_function (loc->address, loc->section);
6180       if (sym)
6181         {
6182           ui_out_text (uiout, "in ");
6183           ui_out_field_string (uiout, "func",
6184                                SYMBOL_PRINT_NAME (sym));
6185           ui_out_text (uiout, " ");
6186           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6187           ui_out_text (uiout, "at ");
6188         }
6189       ui_out_field_string (uiout, "file",
6190                            symtab_to_filename_for_display (loc->symtab));
6191       ui_out_text (uiout, ":");
6192
6193       if (ui_out_is_mi_like_p (uiout))
6194         ui_out_field_string (uiout, "fullname",
6195                              symtab_to_fullname (loc->symtab));
6196       
6197       ui_out_field_int (uiout, "line", loc->line_number);
6198     }
6199   else if (loc)
6200     {
6201       struct ui_file *stb = mem_fileopen ();
6202       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6203
6204       print_address_symbolic (loc->gdbarch, loc->address, stb,
6205                               demangle, "");
6206       ui_out_field_stream (uiout, "at", stb);
6207
6208       do_cleanups (stb_chain);
6209     }
6210   else
6211     {
6212       ui_out_field_string (uiout, "pending",
6213                            event_location_to_string (b->location));
6214       /* If extra_string is available, it could be holding a condition
6215          or dprintf arguments.  In either case, make sure it is printed,
6216          too, but only for non-MI streams.  */
6217       if (!ui_out_is_mi_like_p (uiout) && b->extra_string != NULL)
6218         {
6219           if (b->type == bp_dprintf)
6220             ui_out_text (uiout, ",");
6221           else
6222             ui_out_text (uiout, " ");
6223           ui_out_text (uiout, b->extra_string);
6224         }
6225     }
6226
6227   if (loc && is_breakpoint (b)
6228       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6229       && bp_condition_evaluator (b) == condition_evaluation_both)
6230     {
6231       ui_out_text (uiout, " (");
6232       ui_out_field_string (uiout, "evaluated-by",
6233                            bp_location_condition_evaluator (loc));
6234       ui_out_text (uiout, ")");
6235     }
6236
6237   do_cleanups (old_chain);
6238 }
6239
6240 static const char *
6241 bptype_string (enum bptype type)
6242 {
6243   struct ep_type_description
6244     {
6245       enum bptype type;
6246       char *description;
6247     };
6248   static struct ep_type_description bptypes[] =
6249   {
6250     {bp_none, "?deleted?"},
6251     {bp_breakpoint, "breakpoint"},
6252     {bp_hardware_breakpoint, "hw breakpoint"},
6253     {bp_single_step, "sw single-step"},
6254     {bp_until, "until"},
6255     {bp_finish, "finish"},
6256     {bp_watchpoint, "watchpoint"},
6257     {bp_hardware_watchpoint, "hw watchpoint"},
6258     {bp_read_watchpoint, "read watchpoint"},
6259     {bp_access_watchpoint, "acc watchpoint"},
6260     {bp_longjmp, "longjmp"},
6261     {bp_longjmp_resume, "longjmp resume"},
6262     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6263     {bp_exception, "exception"},
6264     {bp_exception_resume, "exception resume"},
6265     {bp_step_resume, "step resume"},
6266     {bp_hp_step_resume, "high-priority step resume"},
6267     {bp_watchpoint_scope, "watchpoint scope"},
6268     {bp_call_dummy, "call dummy"},
6269     {bp_std_terminate, "std::terminate"},
6270     {bp_shlib_event, "shlib events"},
6271     {bp_thread_event, "thread events"},
6272     {bp_overlay_event, "overlay events"},
6273     {bp_longjmp_master, "longjmp master"},
6274     {bp_std_terminate_master, "std::terminate master"},
6275     {bp_exception_master, "exception master"},
6276     {bp_catchpoint, "catchpoint"},
6277     {bp_tracepoint, "tracepoint"},
6278     {bp_fast_tracepoint, "fast tracepoint"},
6279     {bp_static_tracepoint, "static tracepoint"},
6280     {bp_dprintf, "dprintf"},
6281     {bp_jit_event, "jit events"},
6282     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6283     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6284   };
6285
6286   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6287       || ((int) type != bptypes[(int) type].type))
6288     internal_error (__FILE__, __LINE__,
6289                     _("bptypes table does not describe type #%d."),
6290                     (int) type);
6291
6292   return bptypes[(int) type].description;
6293 }
6294
6295 /* For MI, output a field named 'thread-groups' with a list as the value.
6296    For CLI, prefix the list with the string 'inf'. */
6297
6298 static void
6299 output_thread_groups (struct ui_out *uiout,
6300                       const char *field_name,
6301                       VEC(int) *inf_num,
6302                       int mi_only)
6303 {
6304   struct cleanup *back_to;
6305   int is_mi = ui_out_is_mi_like_p (uiout);
6306   int inf;
6307   int i;
6308
6309   /* For backward compatibility, don't display inferiors in CLI unless
6310      there are several.  Always display them for MI. */
6311   if (!is_mi && mi_only)
6312     return;
6313
6314   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6315
6316   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6317     {
6318       if (is_mi)
6319         {
6320           char mi_group[10];
6321
6322           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6323           ui_out_field_string (uiout, NULL, mi_group);
6324         }
6325       else
6326         {
6327           if (i == 0)
6328             ui_out_text (uiout, " inf ");
6329           else
6330             ui_out_text (uiout, ", ");
6331         
6332           ui_out_text (uiout, plongest (inf));
6333         }
6334     }
6335
6336   do_cleanups (back_to);
6337 }
6338
6339 /* Print B to gdb_stdout.  */
6340
6341 static void
6342 print_one_breakpoint_location (struct breakpoint *b,
6343                                struct bp_location *loc,
6344                                int loc_number,
6345                                struct bp_location **last_loc,
6346                                int allflag)
6347 {
6348   struct command_line *l;
6349   static char bpenables[] = "nynny";
6350
6351   struct ui_out *uiout = current_uiout;
6352   int header_of_multiple = 0;
6353   int part_of_multiple = (loc != NULL);
6354   struct value_print_options opts;
6355
6356   get_user_print_options (&opts);
6357
6358   gdb_assert (!loc || loc_number != 0);
6359   /* See comment in print_one_breakpoint concerning treatment of
6360      breakpoints with single disabled location.  */
6361   if (loc == NULL 
6362       && (b->loc != NULL 
6363           && (b->loc->next != NULL || !b->loc->enabled)))
6364     header_of_multiple = 1;
6365   if (loc == NULL)
6366     loc = b->loc;
6367
6368   annotate_record ();
6369
6370   /* 1 */
6371   annotate_field (0);
6372   if (part_of_multiple)
6373     {
6374       char *formatted;
6375       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6376       ui_out_field_string (uiout, "number", formatted);
6377       xfree (formatted);
6378     }
6379   else
6380     {
6381       ui_out_field_int (uiout, "number", b->number);
6382     }
6383
6384   /* 2 */
6385   annotate_field (1);
6386   if (part_of_multiple)
6387     ui_out_field_skip (uiout, "type");
6388   else
6389     ui_out_field_string (uiout, "type", bptype_string (b->type));
6390
6391   /* 3 */
6392   annotate_field (2);
6393   if (part_of_multiple)
6394     ui_out_field_skip (uiout, "disp");
6395   else
6396     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6397
6398
6399   /* 4 */
6400   annotate_field (3);
6401   if (part_of_multiple)
6402     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6403   else
6404     ui_out_field_fmt (uiout, "enabled", "%c", 
6405                       bpenables[(int) b->enable_state]);
6406   ui_out_spaces (uiout, 2);
6407
6408   
6409   /* 5 and 6 */
6410   if (b->ops != NULL && b->ops->print_one != NULL)
6411     {
6412       /* Although the print_one can possibly print all locations,
6413          calling it here is not likely to get any nice result.  So,
6414          make sure there's just one location.  */
6415       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6416       b->ops->print_one (b, last_loc);
6417     }
6418   else
6419     switch (b->type)
6420       {
6421       case bp_none:
6422         internal_error (__FILE__, __LINE__,
6423                         _("print_one_breakpoint: bp_none encountered\n"));
6424         break;
6425
6426       case bp_watchpoint:
6427       case bp_hardware_watchpoint:
6428       case bp_read_watchpoint:
6429       case bp_access_watchpoint:
6430         {
6431           struct watchpoint *w = (struct watchpoint *) b;
6432
6433           /* Field 4, the address, is omitted (which makes the columns
6434              not line up too nicely with the headers, but the effect
6435              is relatively readable).  */
6436           if (opts.addressprint)
6437             ui_out_field_skip (uiout, "addr");
6438           annotate_field (5);
6439           ui_out_field_string (uiout, "what", w->exp_string);
6440         }
6441         break;
6442
6443       case bp_breakpoint:
6444       case bp_hardware_breakpoint:
6445       case bp_single_step:
6446       case bp_until:
6447       case bp_finish:
6448       case bp_longjmp:
6449       case bp_longjmp_resume:
6450       case bp_longjmp_call_dummy:
6451       case bp_exception:
6452       case bp_exception_resume:
6453       case bp_step_resume:
6454       case bp_hp_step_resume:
6455       case bp_watchpoint_scope:
6456       case bp_call_dummy:
6457       case bp_std_terminate:
6458       case bp_shlib_event:
6459       case bp_thread_event:
6460       case bp_overlay_event:
6461       case bp_longjmp_master:
6462       case bp_std_terminate_master:
6463       case bp_exception_master:
6464       case bp_tracepoint:
6465       case bp_fast_tracepoint:
6466       case bp_static_tracepoint:
6467       case bp_dprintf:
6468       case bp_jit_event:
6469       case bp_gnu_ifunc_resolver:
6470       case bp_gnu_ifunc_resolver_return:
6471         if (opts.addressprint)
6472           {
6473             annotate_field (4);
6474             if (header_of_multiple)
6475               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6476             else if (b->loc == NULL || loc->shlib_disabled)
6477               ui_out_field_string (uiout, "addr", "<PENDING>");
6478             else
6479               ui_out_field_core_addr (uiout, "addr",
6480                                       loc->gdbarch, loc->address);
6481           }
6482         annotate_field (5);
6483         if (!header_of_multiple)
6484           print_breakpoint_location (b, loc);
6485         if (b->loc)
6486           *last_loc = b->loc;
6487         break;
6488       }
6489
6490
6491   if (loc != NULL && !header_of_multiple)
6492     {
6493       struct inferior *inf;
6494       VEC(int) *inf_num = NULL;
6495       int mi_only = 1;
6496
6497       ALL_INFERIORS (inf)
6498         {
6499           if (inf->pspace == loc->pspace)
6500             VEC_safe_push (int, inf_num, inf->num);
6501         }
6502
6503         /* For backward compatibility, don't display inferiors in CLI unless
6504            there are several.  Always display for MI. */
6505         if (allflag
6506             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6507                 && (number_of_program_spaces () > 1
6508                     || number_of_inferiors () > 1)
6509                 /* LOC is for existing B, it cannot be in
6510                    moribund_locations and thus having NULL OWNER.  */
6511                 && loc->owner->type != bp_catchpoint))
6512         mi_only = 0;
6513       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6514       VEC_free (int, inf_num);
6515     }
6516
6517   if (!part_of_multiple)
6518     {
6519       if (b->thread != -1)
6520         {
6521           /* FIXME: This seems to be redundant and lost here; see the
6522              "stop only in" line a little further down.  */
6523           ui_out_text (uiout, " thread ");
6524           ui_out_field_int (uiout, "thread", b->thread);
6525         }
6526       else if (b->task != 0)
6527         {
6528           ui_out_text (uiout, " task ");
6529           ui_out_field_int (uiout, "task", b->task);
6530         }
6531     }
6532
6533   ui_out_text (uiout, "\n");
6534
6535   if (!part_of_multiple)
6536     b->ops->print_one_detail (b, uiout);
6537
6538   if (part_of_multiple && frame_id_p (b->frame_id))
6539     {
6540       annotate_field (6);
6541       ui_out_text (uiout, "\tstop only in stack frame at ");
6542       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6543          the frame ID.  */
6544       ui_out_field_core_addr (uiout, "frame",
6545                               b->gdbarch, b->frame_id.stack_addr);
6546       ui_out_text (uiout, "\n");
6547     }
6548   
6549   if (!part_of_multiple && b->cond_string)
6550     {
6551       annotate_field (7);
6552       if (is_tracepoint (b))
6553         ui_out_text (uiout, "\ttrace only if ");
6554       else
6555         ui_out_text (uiout, "\tstop only if ");
6556       ui_out_field_string (uiout, "cond", b->cond_string);
6557
6558       /* Print whether the target is doing the breakpoint's condition
6559          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6560       if (is_breakpoint (b)
6561           && breakpoint_condition_evaluation_mode ()
6562           == condition_evaluation_target)
6563         {
6564           ui_out_text (uiout, " (");
6565           ui_out_field_string (uiout, "evaluated-by",
6566                                bp_condition_evaluator (b));
6567           ui_out_text (uiout, " evals)");
6568         }
6569       ui_out_text (uiout, "\n");
6570     }
6571
6572   if (!part_of_multiple && b->thread != -1)
6573     {
6574       /* FIXME should make an annotation for this.  */
6575       ui_out_text (uiout, "\tstop only in thread ");
6576       if (ui_out_is_mi_like_p (uiout))
6577         ui_out_field_int (uiout, "thread", b->thread);
6578       else
6579         {
6580           struct thread_info *thr = find_thread_global_id (b->thread);
6581
6582           ui_out_field_string (uiout, "thread", print_thread_id (thr));
6583         }
6584       ui_out_text (uiout, "\n");
6585     }
6586   
6587   if (!part_of_multiple)
6588     {
6589       if (b->hit_count)
6590         {
6591           /* FIXME should make an annotation for this.  */
6592           if (is_catchpoint (b))
6593             ui_out_text (uiout, "\tcatchpoint");
6594           else if (is_tracepoint (b))
6595             ui_out_text (uiout, "\ttracepoint");
6596           else
6597             ui_out_text (uiout, "\tbreakpoint");
6598           ui_out_text (uiout, " already hit ");
6599           ui_out_field_int (uiout, "times", b->hit_count);
6600           if (b->hit_count == 1)
6601             ui_out_text (uiout, " time\n");
6602           else
6603             ui_out_text (uiout, " times\n");
6604         }
6605       else
6606         {
6607           /* Output the count also if it is zero, but only if this is mi.  */
6608           if (ui_out_is_mi_like_p (uiout))
6609             ui_out_field_int (uiout, "times", b->hit_count);
6610         }
6611     }
6612
6613   if (!part_of_multiple && b->ignore_count)
6614     {
6615       annotate_field (8);
6616       ui_out_text (uiout, "\tignore next ");
6617       ui_out_field_int (uiout, "ignore", b->ignore_count);
6618       ui_out_text (uiout, " hits\n");
6619     }
6620
6621   /* Note that an enable count of 1 corresponds to "enable once"
6622      behavior, which is reported by the combination of enablement and
6623      disposition, so we don't need to mention it here.  */
6624   if (!part_of_multiple && b->enable_count > 1)
6625     {
6626       annotate_field (8);
6627       ui_out_text (uiout, "\tdisable after ");
6628       /* Tweak the wording to clarify that ignore and enable counts
6629          are distinct, and have additive effect.  */
6630       if (b->ignore_count)
6631         ui_out_text (uiout, "additional ");
6632       else
6633         ui_out_text (uiout, "next ");
6634       ui_out_field_int (uiout, "enable", b->enable_count);
6635       ui_out_text (uiout, " hits\n");
6636     }
6637
6638   if (!part_of_multiple && is_tracepoint (b))
6639     {
6640       struct tracepoint *tp = (struct tracepoint *) b;
6641
6642       if (tp->traceframe_usage)
6643         {
6644           ui_out_text (uiout, "\ttrace buffer usage ");
6645           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6646           ui_out_text (uiout, " bytes\n");
6647         }
6648     }
6649
6650   l = b->commands ? b->commands->commands : NULL;
6651   if (!part_of_multiple && l)
6652     {
6653       struct cleanup *script_chain;
6654
6655       annotate_field (9);
6656       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6657       print_command_lines (uiout, l, 4);
6658       do_cleanups (script_chain);
6659     }
6660
6661   if (is_tracepoint (b))
6662     {
6663       struct tracepoint *t = (struct tracepoint *) b;
6664
6665       if (!part_of_multiple && t->pass_count)
6666         {
6667           annotate_field (10);
6668           ui_out_text (uiout, "\tpass count ");
6669           ui_out_field_int (uiout, "pass", t->pass_count);
6670           ui_out_text (uiout, " \n");
6671         }
6672
6673       /* Don't display it when tracepoint or tracepoint location is
6674          pending.   */
6675       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6676         {
6677           annotate_field (11);
6678
6679           if (ui_out_is_mi_like_p (uiout))
6680             ui_out_field_string (uiout, "installed",
6681                                  loc->inserted ? "y" : "n");
6682           else
6683             {
6684               if (loc->inserted)
6685                 ui_out_text (uiout, "\t");
6686               else
6687                 ui_out_text (uiout, "\tnot ");
6688               ui_out_text (uiout, "installed on target\n");
6689             }
6690         }
6691     }
6692
6693   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6694     {
6695       if (is_watchpoint (b))
6696         {
6697           struct watchpoint *w = (struct watchpoint *) b;
6698
6699           ui_out_field_string (uiout, "original-location", w->exp_string);
6700         }
6701       else if (b->location != NULL
6702                && event_location_to_string (b->location) != NULL)
6703         ui_out_field_string (uiout, "original-location",
6704                              event_location_to_string (b->location));
6705     }
6706 }
6707
6708 static void
6709 print_one_breakpoint (struct breakpoint *b,
6710                       struct bp_location **last_loc, 
6711                       int allflag)
6712 {
6713   struct cleanup *bkpt_chain;
6714   struct ui_out *uiout = current_uiout;
6715
6716   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6717
6718   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6719   do_cleanups (bkpt_chain);
6720
6721   /* If this breakpoint has custom print function,
6722      it's already printed.  Otherwise, print individual
6723      locations, if any.  */
6724   if (b->ops == NULL || b->ops->print_one == NULL)
6725     {
6726       /* If breakpoint has a single location that is disabled, we
6727          print it as if it had several locations, since otherwise it's
6728          hard to represent "breakpoint enabled, location disabled"
6729          situation.
6730
6731          Note that while hardware watchpoints have several locations
6732          internally, that's not a property exposed to user.  */
6733       if (b->loc 
6734           && !is_hardware_watchpoint (b)
6735           && (b->loc->next || !b->loc->enabled))
6736         {
6737           struct bp_location *loc;
6738           int n = 1;
6739
6740           for (loc = b->loc; loc; loc = loc->next, ++n)
6741             {
6742               struct cleanup *inner2 =
6743                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6744               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6745               do_cleanups (inner2);
6746             }
6747         }
6748     }
6749 }
6750
6751 static int
6752 breakpoint_address_bits (struct breakpoint *b)
6753 {
6754   int print_address_bits = 0;
6755   struct bp_location *loc;
6756
6757   /* Software watchpoints that aren't watching memory don't have an
6758      address to print.  */
6759   if (is_no_memory_software_watchpoint (b))
6760     return 0;
6761
6762   for (loc = b->loc; loc; loc = loc->next)
6763     {
6764       int addr_bit;
6765
6766       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6767       if (addr_bit > print_address_bits)
6768         print_address_bits = addr_bit;
6769     }
6770
6771   return print_address_bits;
6772 }
6773
6774 struct captured_breakpoint_query_args
6775   {
6776     int bnum;
6777   };
6778
6779 static int
6780 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6781 {
6782   struct captured_breakpoint_query_args *args
6783     = (struct captured_breakpoint_query_args *) data;
6784   struct breakpoint *b;
6785   struct bp_location *dummy_loc = NULL;
6786
6787   ALL_BREAKPOINTS (b)
6788     {
6789       if (args->bnum == b->number)
6790         {
6791           print_one_breakpoint (b, &dummy_loc, 0);
6792           return GDB_RC_OK;
6793         }
6794     }
6795   return GDB_RC_NONE;
6796 }
6797
6798 enum gdb_rc
6799 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6800                       char **error_message)
6801 {
6802   struct captured_breakpoint_query_args args;
6803
6804   args.bnum = bnum;
6805   /* For the moment we don't trust print_one_breakpoint() to not throw
6806      an error.  */
6807   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6808                                  error_message, RETURN_MASK_ALL) < 0)
6809     return GDB_RC_FAIL;
6810   else
6811     return GDB_RC_OK;
6812 }
6813
6814 /* Return true if this breakpoint was set by the user, false if it is
6815    internal or momentary.  */
6816
6817 int
6818 user_breakpoint_p (struct breakpoint *b)
6819 {
6820   return b->number > 0;
6821 }
6822
6823 /* See breakpoint.h.  */
6824
6825 int
6826 pending_breakpoint_p (struct breakpoint *b)
6827 {
6828   return b->loc == NULL;
6829 }
6830
6831 /* Print information on user settable breakpoint (watchpoint, etc)
6832    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6833    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6834    FILTER is non-NULL, call it on each breakpoint and only include the
6835    ones for which it returns non-zero.  Return the total number of
6836    breakpoints listed.  */
6837
6838 static int
6839 breakpoint_1 (char *args, int allflag, 
6840               int (*filter) (const struct breakpoint *))
6841 {
6842   struct breakpoint *b;
6843   struct bp_location *last_loc = NULL;
6844   int nr_printable_breakpoints;
6845   struct cleanup *bkpttbl_chain;
6846   struct value_print_options opts;
6847   int print_address_bits = 0;
6848   int print_type_col_width = 14;
6849   struct ui_out *uiout = current_uiout;
6850
6851   get_user_print_options (&opts);
6852
6853   /* Compute the number of rows in the table, as well as the size
6854      required for address fields.  */
6855   nr_printable_breakpoints = 0;
6856   ALL_BREAKPOINTS (b)
6857     {
6858       /* If we have a filter, only list the breakpoints it accepts.  */
6859       if (filter && !filter (b))
6860         continue;
6861
6862       /* If we have an "args" string, it is a list of breakpoints to 
6863          accept.  Skip the others.  */
6864       if (args != NULL && *args != '\0')
6865         {
6866           if (allflag && parse_and_eval_long (args) != b->number)
6867             continue;
6868           if (!allflag && !number_is_in_list (args, b->number))
6869             continue;
6870         }
6871
6872       if (allflag || user_breakpoint_p (b))
6873         {
6874           int addr_bit, type_len;
6875
6876           addr_bit = breakpoint_address_bits (b);
6877           if (addr_bit > print_address_bits)
6878             print_address_bits = addr_bit;
6879
6880           type_len = strlen (bptype_string (b->type));
6881           if (type_len > print_type_col_width)
6882             print_type_col_width = type_len;
6883
6884           nr_printable_breakpoints++;
6885         }
6886     }
6887
6888   if (opts.addressprint)
6889     bkpttbl_chain 
6890       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6891                                              nr_printable_breakpoints,
6892                                              "BreakpointTable");
6893   else
6894     bkpttbl_chain 
6895       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6896                                              nr_printable_breakpoints,
6897                                              "BreakpointTable");
6898
6899   if (nr_printable_breakpoints > 0)
6900     annotate_breakpoints_headers ();
6901   if (nr_printable_breakpoints > 0)
6902     annotate_field (0);
6903   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6904   if (nr_printable_breakpoints > 0)
6905     annotate_field (1);
6906   ui_out_table_header (uiout, print_type_col_width, ui_left,
6907                        "type", "Type");                         /* 2 */
6908   if (nr_printable_breakpoints > 0)
6909     annotate_field (2);
6910   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6911   if (nr_printable_breakpoints > 0)
6912     annotate_field (3);
6913   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6914   if (opts.addressprint)
6915     {
6916       if (nr_printable_breakpoints > 0)
6917         annotate_field (4);
6918       if (print_address_bits <= 32)
6919         ui_out_table_header (uiout, 10, ui_left, 
6920                              "addr", "Address");                /* 5 */
6921       else
6922         ui_out_table_header (uiout, 18, ui_left, 
6923                              "addr", "Address");                /* 5 */
6924     }
6925   if (nr_printable_breakpoints > 0)
6926     annotate_field (5);
6927   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6928   ui_out_table_body (uiout);
6929   if (nr_printable_breakpoints > 0)
6930     annotate_breakpoints_table ();
6931
6932   ALL_BREAKPOINTS (b)
6933     {
6934       QUIT;
6935       /* If we have a filter, only list the breakpoints it accepts.  */
6936       if (filter && !filter (b))
6937         continue;
6938
6939       /* If we have an "args" string, it is a list of breakpoints to 
6940          accept.  Skip the others.  */
6941
6942       if (args != NULL && *args != '\0')
6943         {
6944           if (allflag)  /* maintenance info breakpoint */
6945             {
6946               if (parse_and_eval_long (args) != b->number)
6947                 continue;
6948             }
6949           else          /* all others */
6950             {
6951               if (!number_is_in_list (args, b->number))
6952                 continue;
6953             }
6954         }
6955       /* We only print out user settable breakpoints unless the
6956          allflag is set.  */
6957       if (allflag || user_breakpoint_p (b))
6958         print_one_breakpoint (b, &last_loc, allflag);
6959     }
6960
6961   do_cleanups (bkpttbl_chain);
6962
6963   if (nr_printable_breakpoints == 0)
6964     {
6965       /* If there's a filter, let the caller decide how to report
6966          empty list.  */
6967       if (!filter)
6968         {
6969           if (args == NULL || *args == '\0')
6970             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6971           else
6972             ui_out_message (uiout, 0, 
6973                             "No breakpoint or watchpoint matching '%s'.\n",
6974                             args);
6975         }
6976     }
6977   else
6978     {
6979       if (last_loc && !server_command)
6980         set_next_address (last_loc->gdbarch, last_loc->address);
6981     }
6982
6983   /* FIXME?  Should this be moved up so that it is only called when
6984      there have been breakpoints? */
6985   annotate_breakpoints_table_end ();
6986
6987   return nr_printable_breakpoints;
6988 }
6989
6990 /* Display the value of default-collect in a way that is generally
6991    compatible with the breakpoint list.  */
6992
6993 static void
6994 default_collect_info (void)
6995 {
6996   struct ui_out *uiout = current_uiout;
6997
6998   /* If it has no value (which is frequently the case), say nothing; a
6999      message like "No default-collect." gets in user's face when it's
7000      not wanted.  */
7001   if (!*default_collect)
7002     return;
7003
7004   /* The following phrase lines up nicely with per-tracepoint collect
7005      actions.  */
7006   ui_out_text (uiout, "default collect ");
7007   ui_out_field_string (uiout, "default-collect", default_collect);
7008   ui_out_text (uiout, " \n");
7009 }
7010   
7011 static void
7012 breakpoints_info (char *args, int from_tty)
7013 {
7014   breakpoint_1 (args, 0, NULL);
7015
7016   default_collect_info ();
7017 }
7018
7019 static void
7020 watchpoints_info (char *args, int from_tty)
7021 {
7022   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
7023   struct ui_out *uiout = current_uiout;
7024
7025   if (num_printed == 0)
7026     {
7027       if (args == NULL || *args == '\0')
7028         ui_out_message (uiout, 0, "No watchpoints.\n");
7029       else
7030         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
7031     }
7032 }
7033
7034 static void
7035 maintenance_info_breakpoints (char *args, int from_tty)
7036 {
7037   breakpoint_1 (args, 1, NULL);
7038
7039   default_collect_info ();
7040 }
7041
7042 static int
7043 breakpoint_has_pc (struct breakpoint *b,
7044                    struct program_space *pspace,
7045                    CORE_ADDR pc, struct obj_section *section)
7046 {
7047   struct bp_location *bl = b->loc;
7048
7049   for (; bl; bl = bl->next)
7050     {
7051       if (bl->pspace == pspace
7052           && bl->address == pc
7053           && (!overlay_debugging || bl->section == section))
7054         return 1;         
7055     }
7056   return 0;
7057 }
7058
7059 /* Print a message describing any user-breakpoints set at PC.  This
7060    concerns with logical breakpoints, so we match program spaces, not
7061    address spaces.  */
7062
7063 static void
7064 describe_other_breakpoints (struct gdbarch *gdbarch,
7065                             struct program_space *pspace, CORE_ADDR pc,
7066                             struct obj_section *section, int thread)
7067 {
7068   int others = 0;
7069   struct breakpoint *b;
7070
7071   ALL_BREAKPOINTS (b)
7072     others += (user_breakpoint_p (b)
7073                && breakpoint_has_pc (b, pspace, pc, section));
7074   if (others > 0)
7075     {
7076       if (others == 1)
7077         printf_filtered (_("Note: breakpoint "));
7078       else /* if (others == ???) */
7079         printf_filtered (_("Note: breakpoints "));
7080       ALL_BREAKPOINTS (b)
7081         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7082           {
7083             others--;
7084             printf_filtered ("%d", b->number);
7085             if (b->thread == -1 && thread != -1)
7086               printf_filtered (" (all threads)");
7087             else if (b->thread != -1)
7088               printf_filtered (" (thread %d)", b->thread);
7089             printf_filtered ("%s%s ",
7090                              ((b->enable_state == bp_disabled
7091                                || b->enable_state == bp_call_disabled)
7092                               ? " (disabled)"
7093                               : ""),
7094                              (others > 1) ? "," 
7095                              : ((others == 1) ? " and" : ""));
7096           }
7097       printf_filtered (_("also set at pc "));
7098       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
7099       printf_filtered (".\n");
7100     }
7101 }
7102 \f
7103
7104 /* Return true iff it is meaningful to use the address member of
7105    BPT locations.  For some breakpoint types, the locations' address members
7106    are irrelevant and it makes no sense to attempt to compare them to other
7107    addresses (or use them for any other purpose either).
7108
7109    More specifically, each of the following breakpoint types will
7110    always have a zero valued location address and we don't want to mark
7111    breakpoints of any of these types to be a duplicate of an actual
7112    breakpoint location at address zero:
7113
7114       bp_watchpoint
7115       bp_catchpoint
7116
7117 */
7118
7119 static int
7120 breakpoint_address_is_meaningful (struct breakpoint *bpt)
7121 {
7122   enum bptype type = bpt->type;
7123
7124   return (type != bp_watchpoint && type != bp_catchpoint);
7125 }
7126
7127 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7128    true if LOC1 and LOC2 represent the same watchpoint location.  */
7129
7130 static int
7131 watchpoint_locations_match (struct bp_location *loc1, 
7132                             struct bp_location *loc2)
7133 {
7134   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7135   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7136
7137   /* Both of them must exist.  */
7138   gdb_assert (w1 != NULL);
7139   gdb_assert (w2 != NULL);
7140
7141   /* If the target can evaluate the condition expression in hardware,
7142      then we we need to insert both watchpoints even if they are at
7143      the same place.  Otherwise the watchpoint will only trigger when
7144      the condition of whichever watchpoint was inserted evaluates to
7145      true, not giving a chance for GDB to check the condition of the
7146      other watchpoint.  */
7147   if ((w1->cond_exp
7148        && target_can_accel_watchpoint_condition (loc1->address, 
7149                                                  loc1->length,
7150                                                  loc1->watchpoint_type,
7151                                                  w1->cond_exp))
7152       || (w2->cond_exp
7153           && target_can_accel_watchpoint_condition (loc2->address, 
7154                                                     loc2->length,
7155                                                     loc2->watchpoint_type,
7156                                                     w2->cond_exp)))
7157     return 0;
7158
7159   /* Note that this checks the owner's type, not the location's.  In
7160      case the target does not support read watchpoints, but does
7161      support access watchpoints, we'll have bp_read_watchpoint
7162      watchpoints with hw_access locations.  Those should be considered
7163      duplicates of hw_read locations.  The hw_read locations will
7164      become hw_access locations later.  */
7165   return (loc1->owner->type == loc2->owner->type
7166           && loc1->pspace->aspace == loc2->pspace->aspace
7167           && loc1->address == loc2->address
7168           && loc1->length == loc2->length);
7169 }
7170
7171 /* See breakpoint.h.  */
7172
7173 int
7174 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7175                           struct address_space *aspace2, CORE_ADDR addr2)
7176 {
7177   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7178            || aspace1 == aspace2)
7179           && addr1 == addr2);
7180 }
7181
7182 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7183    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7184    matches ASPACE2.  On targets that have global breakpoints, the address
7185    space doesn't really matter.  */
7186
7187 static int
7188 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7189                                 int len1, struct address_space *aspace2,
7190                                 CORE_ADDR addr2)
7191 {
7192   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7193            || aspace1 == aspace2)
7194           && addr2 >= addr1 && addr2 < addr1 + len1);
7195 }
7196
7197 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7198    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7199    matches the breakpoint's address space.  On targets that have global
7200    breakpoints, the address space doesn't really matter.  */
7201
7202 static int
7203 breakpoint_location_address_match (struct bp_location *bl,
7204                                    struct address_space *aspace,
7205                                    CORE_ADDR addr)
7206 {
7207   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7208                                     aspace, addr)
7209           || (bl->length
7210               && breakpoint_address_match_range (bl->pspace->aspace,
7211                                                  bl->address, bl->length,
7212                                                  aspace, addr)));
7213 }
7214
7215 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7216    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7217    match happens only if ASPACE matches the breakpoint's address
7218    space.  On targets that have global breakpoints, the address space
7219    doesn't really matter.  */
7220
7221 static int
7222 breakpoint_location_address_range_overlap (struct bp_location *bl,
7223                                            struct address_space *aspace,
7224                                            CORE_ADDR addr, int len)
7225 {
7226   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7227       || bl->pspace->aspace == aspace)
7228     {
7229       int bl_len = bl->length != 0 ? bl->length : 1;
7230
7231       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7232         return 1;
7233     }
7234   return 0;
7235 }
7236
7237 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7238    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7239    true, otherwise returns false.  */
7240
7241 static int
7242 tracepoint_locations_match (struct bp_location *loc1,
7243                             struct bp_location *loc2)
7244 {
7245   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7246     /* Since tracepoint locations are never duplicated with others', tracepoint
7247        locations at the same address of different tracepoints are regarded as
7248        different locations.  */
7249     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7250   else
7251     return 0;
7252 }
7253
7254 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7255    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7256    represent the same location.  */
7257
7258 static int
7259 breakpoint_locations_match (struct bp_location *loc1, 
7260                             struct bp_location *loc2)
7261 {
7262   int hw_point1, hw_point2;
7263
7264   /* Both of them must not be in moribund_locations.  */
7265   gdb_assert (loc1->owner != NULL);
7266   gdb_assert (loc2->owner != NULL);
7267
7268   hw_point1 = is_hardware_watchpoint (loc1->owner);
7269   hw_point2 = is_hardware_watchpoint (loc2->owner);
7270
7271   if (hw_point1 != hw_point2)
7272     return 0;
7273   else if (hw_point1)
7274     return watchpoint_locations_match (loc1, loc2);
7275   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7276     return tracepoint_locations_match (loc1, loc2);
7277   else
7278     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7279     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7280                                      loc2->pspace->aspace, loc2->address)
7281             && loc1->length == loc2->length);
7282 }
7283
7284 static void
7285 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7286                                int bnum, int have_bnum)
7287 {
7288   /* The longest string possibly returned by hex_string_custom
7289      is 50 chars.  These must be at least that big for safety.  */
7290   char astr1[64];
7291   char astr2[64];
7292
7293   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7294   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7295   if (have_bnum)
7296     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7297              bnum, astr1, astr2);
7298   else
7299     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7300 }
7301
7302 /* Adjust a breakpoint's address to account for architectural
7303    constraints on breakpoint placement.  Return the adjusted address.
7304    Note: Very few targets require this kind of adjustment.  For most
7305    targets, this function is simply the identity function.  */
7306
7307 static CORE_ADDR
7308 adjust_breakpoint_address (struct gdbarch *gdbarch,
7309                            CORE_ADDR bpaddr, enum bptype bptype)
7310 {
7311   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7312     {
7313       /* Very few targets need any kind of breakpoint adjustment.  */
7314       return bpaddr;
7315     }
7316   else if (bptype == bp_watchpoint
7317            || bptype == bp_hardware_watchpoint
7318            || bptype == bp_read_watchpoint
7319            || bptype == bp_access_watchpoint
7320            || bptype == bp_catchpoint)
7321     {
7322       /* Watchpoints and the various bp_catch_* eventpoints should not
7323          have their addresses modified.  */
7324       return bpaddr;
7325     }
7326   else if (bptype == bp_single_step)
7327     {
7328       /* Single-step breakpoints should not have their addresses
7329          modified.  If there's any architectural constrain that
7330          applies to this address, then it should have already been
7331          taken into account when the breakpoint was created in the
7332          first place.  If we didn't do this, stepping through e.g.,
7333          Thumb-2 IT blocks would break.  */
7334       return bpaddr;
7335     }
7336   else
7337     {
7338       CORE_ADDR adjusted_bpaddr;
7339
7340       /* Some targets have architectural constraints on the placement
7341          of breakpoint instructions.  Obtain the adjusted address.  */
7342       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7343
7344       /* An adjusted breakpoint address can significantly alter
7345          a user's expectations.  Print a warning if an adjustment
7346          is required.  */
7347       if (adjusted_bpaddr != bpaddr)
7348         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7349
7350       return adjusted_bpaddr;
7351     }
7352 }
7353
7354 void
7355 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7356                   struct breakpoint *owner)
7357 {
7358   memset (loc, 0, sizeof (*loc));
7359
7360   gdb_assert (ops != NULL);
7361
7362   loc->ops = ops;
7363   loc->owner = owner;
7364   loc->cond = NULL;
7365   loc->cond_bytecode = NULL;
7366   loc->shlib_disabled = 0;
7367   loc->enabled = 1;
7368
7369   switch (owner->type)
7370     {
7371     case bp_breakpoint:
7372     case bp_single_step:
7373     case bp_until:
7374     case bp_finish:
7375     case bp_longjmp:
7376     case bp_longjmp_resume:
7377     case bp_longjmp_call_dummy:
7378     case bp_exception:
7379     case bp_exception_resume:
7380     case bp_step_resume:
7381     case bp_hp_step_resume:
7382     case bp_watchpoint_scope:
7383     case bp_call_dummy:
7384     case bp_std_terminate:
7385     case bp_shlib_event:
7386     case bp_thread_event:
7387     case bp_overlay_event:
7388     case bp_jit_event:
7389     case bp_longjmp_master:
7390     case bp_std_terminate_master:
7391     case bp_exception_master:
7392     case bp_gnu_ifunc_resolver:
7393     case bp_gnu_ifunc_resolver_return:
7394     case bp_dprintf:
7395       loc->loc_type = bp_loc_software_breakpoint;
7396       mark_breakpoint_location_modified (loc);
7397       break;
7398     case bp_hardware_breakpoint:
7399       loc->loc_type = bp_loc_hardware_breakpoint;
7400       mark_breakpoint_location_modified (loc);
7401       break;
7402     case bp_hardware_watchpoint:
7403     case bp_read_watchpoint:
7404     case bp_access_watchpoint:
7405       loc->loc_type = bp_loc_hardware_watchpoint;
7406       break;
7407     case bp_watchpoint:
7408     case bp_catchpoint:
7409     case bp_tracepoint:
7410     case bp_fast_tracepoint:
7411     case bp_static_tracepoint:
7412       loc->loc_type = bp_loc_other;
7413       break;
7414     default:
7415       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7416     }
7417
7418   loc->refc = 1;
7419 }
7420
7421 /* Allocate a struct bp_location.  */
7422
7423 static struct bp_location *
7424 allocate_bp_location (struct breakpoint *bpt)
7425 {
7426   return bpt->ops->allocate_location (bpt);
7427 }
7428
7429 static void
7430 free_bp_location (struct bp_location *loc)
7431 {
7432   loc->ops->dtor (loc);
7433   xfree (loc);
7434 }
7435
7436 /* Increment reference count.  */
7437
7438 static void
7439 incref_bp_location (struct bp_location *bl)
7440 {
7441   ++bl->refc;
7442 }
7443
7444 /* Decrement reference count.  If the reference count reaches 0,
7445    destroy the bp_location.  Sets *BLP to NULL.  */
7446
7447 static void
7448 decref_bp_location (struct bp_location **blp)
7449 {
7450   gdb_assert ((*blp)->refc > 0);
7451
7452   if (--(*blp)->refc == 0)
7453     free_bp_location (*blp);
7454   *blp = NULL;
7455 }
7456
7457 /* Add breakpoint B at the end of the global breakpoint chain.  */
7458
7459 static void
7460 add_to_breakpoint_chain (struct breakpoint *b)
7461 {
7462   struct breakpoint *b1;
7463
7464   /* Add this breakpoint to the end of the chain so that a list of
7465      breakpoints will come out in order of increasing numbers.  */
7466
7467   b1 = breakpoint_chain;
7468   if (b1 == 0)
7469     breakpoint_chain = b;
7470   else
7471     {
7472       while (b1->next)
7473         b1 = b1->next;
7474       b1->next = b;
7475     }
7476 }
7477
7478 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7479
7480 static void
7481 init_raw_breakpoint_without_location (struct breakpoint *b,
7482                                       struct gdbarch *gdbarch,
7483                                       enum bptype bptype,
7484                                       const struct breakpoint_ops *ops)
7485 {
7486   memset (b, 0, sizeof (*b));
7487
7488   gdb_assert (ops != NULL);
7489
7490   b->ops = ops;
7491   b->type = bptype;
7492   b->gdbarch = gdbarch;
7493   b->language = current_language->la_language;
7494   b->input_radix = input_radix;
7495   b->thread = -1;
7496   b->enable_state = bp_enabled;
7497   b->next = 0;
7498   b->silent = 0;
7499   b->ignore_count = 0;
7500   b->commands = NULL;
7501   b->frame_id = null_frame_id;
7502   b->condition_not_parsed = 0;
7503   b->py_bp_object = NULL;
7504   b->related_breakpoint = b;
7505   b->location = NULL;
7506 }
7507
7508 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7509    that has type BPTYPE and has no locations as yet.  */
7510
7511 static struct breakpoint *
7512 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7513                                      enum bptype bptype,
7514                                      const struct breakpoint_ops *ops)
7515 {
7516   struct breakpoint *b = XNEW (struct breakpoint);
7517
7518   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7519   add_to_breakpoint_chain (b);
7520   return b;
7521 }
7522
7523 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7524    resolutions should be made as the user specified the location explicitly
7525    enough.  */
7526
7527 static void
7528 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7529 {
7530   gdb_assert (loc->owner != NULL);
7531
7532   if (loc->owner->type == bp_breakpoint
7533       || loc->owner->type == bp_hardware_breakpoint
7534       || is_tracepoint (loc->owner))
7535     {
7536       int is_gnu_ifunc;
7537       const char *function_name;
7538       CORE_ADDR func_addr;
7539
7540       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7541                                           &func_addr, NULL, &is_gnu_ifunc);
7542
7543       if (is_gnu_ifunc && !explicit_loc)
7544         {
7545           struct breakpoint *b = loc->owner;
7546
7547           gdb_assert (loc->pspace == current_program_space);
7548           if (gnu_ifunc_resolve_name (function_name,
7549                                       &loc->requested_address))
7550             {
7551               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7552               loc->address = adjust_breakpoint_address (loc->gdbarch,
7553                                                         loc->requested_address,
7554                                                         b->type);
7555             }
7556           else if (b->type == bp_breakpoint && b->loc == loc
7557                    && loc->next == NULL && b->related_breakpoint == b)
7558             {
7559               /* Create only the whole new breakpoint of this type but do not
7560                  mess more complicated breakpoints with multiple locations.  */
7561               b->type = bp_gnu_ifunc_resolver;
7562               /* Remember the resolver's address for use by the return
7563                  breakpoint.  */
7564               loc->related_address = func_addr;
7565             }
7566         }
7567
7568       if (function_name)
7569         loc->function_name = xstrdup (function_name);
7570     }
7571 }
7572
7573 /* Attempt to determine architecture of location identified by SAL.  */
7574 struct gdbarch *
7575 get_sal_arch (struct symtab_and_line sal)
7576 {
7577   if (sal.section)
7578     return get_objfile_arch (sal.section->objfile);
7579   if (sal.symtab)
7580     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7581
7582   return NULL;
7583 }
7584
7585 /* Low level routine for partially initializing a breakpoint of type
7586    BPTYPE.  The newly created breakpoint's address, section, source
7587    file name, and line number are provided by SAL.
7588
7589    It is expected that the caller will complete the initialization of
7590    the newly created breakpoint struct as well as output any status
7591    information regarding the creation of a new breakpoint.  */
7592
7593 static void
7594 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7595                      struct symtab_and_line sal, enum bptype bptype,
7596                      const struct breakpoint_ops *ops)
7597 {
7598   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7599
7600   add_location_to_breakpoint (b, &sal);
7601
7602   if (bptype != bp_catchpoint)
7603     gdb_assert (sal.pspace != NULL);
7604
7605   /* Store the program space that was used to set the breakpoint,
7606      except for ordinary breakpoints, which are independent of the
7607      program space.  */
7608   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7609     b->pspace = sal.pspace;
7610 }
7611
7612 /* set_raw_breakpoint is a low level routine for allocating and
7613    partially initializing a breakpoint of type BPTYPE.  The newly
7614    created breakpoint's address, section, source file name, and line
7615    number are provided by SAL.  The newly created and partially
7616    initialized breakpoint is added to the breakpoint chain and
7617    is also returned as the value of this function.
7618
7619    It is expected that the caller will complete the initialization of
7620    the newly created breakpoint struct as well as output any status
7621    information regarding the creation of a new breakpoint.  In
7622    particular, set_raw_breakpoint does NOT set the breakpoint
7623    number!  Care should be taken to not allow an error to occur
7624    prior to completing the initialization of the breakpoint.  If this
7625    should happen, a bogus breakpoint will be left on the chain.  */
7626
7627 struct breakpoint *
7628 set_raw_breakpoint (struct gdbarch *gdbarch,
7629                     struct symtab_and_line sal, enum bptype bptype,
7630                     const struct breakpoint_ops *ops)
7631 {
7632   struct breakpoint *b = XNEW (struct breakpoint);
7633
7634   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7635   add_to_breakpoint_chain (b);
7636   return b;
7637 }
7638
7639 /* Call this routine when stepping and nexting to enable a breakpoint
7640    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7641    initiated the operation.  */
7642
7643 void
7644 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7645 {
7646   struct breakpoint *b, *b_tmp;
7647   int thread = tp->global_num;
7648
7649   /* To avoid having to rescan all objfile symbols at every step,
7650      we maintain a list of continually-inserted but always disabled
7651      longjmp "master" breakpoints.  Here, we simply create momentary
7652      clones of those and enable them for the requested thread.  */
7653   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7654     if (b->pspace == current_program_space
7655         && (b->type == bp_longjmp_master
7656             || b->type == bp_exception_master))
7657       {
7658         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7659         struct breakpoint *clone;
7660
7661         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7662            after their removal.  */
7663         clone = momentary_breakpoint_from_master (b, type,
7664                                                   &longjmp_breakpoint_ops, 1);
7665         clone->thread = thread;
7666       }
7667
7668   tp->initiating_frame = frame;
7669 }
7670
7671 /* Delete all longjmp breakpoints from THREAD.  */
7672 void
7673 delete_longjmp_breakpoint (int thread)
7674 {
7675   struct breakpoint *b, *b_tmp;
7676
7677   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7678     if (b->type == bp_longjmp || b->type == bp_exception)
7679       {
7680         if (b->thread == thread)
7681           delete_breakpoint (b);
7682       }
7683 }
7684
7685 void
7686 delete_longjmp_breakpoint_at_next_stop (int thread)
7687 {
7688   struct breakpoint *b, *b_tmp;
7689
7690   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7691     if (b->type == bp_longjmp || b->type == bp_exception)
7692       {
7693         if (b->thread == thread)
7694           b->disposition = disp_del_at_next_stop;
7695       }
7696 }
7697
7698 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7699    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7700    pointer to any of them.  Return NULL if this system cannot place longjmp
7701    breakpoints.  */
7702
7703 struct breakpoint *
7704 set_longjmp_breakpoint_for_call_dummy (void)
7705 {
7706   struct breakpoint *b, *retval = NULL;
7707
7708   ALL_BREAKPOINTS (b)
7709     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7710       {
7711         struct breakpoint *new_b;
7712
7713         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7714                                                   &momentary_breakpoint_ops,
7715                                                   1);
7716         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7717
7718         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7719
7720         gdb_assert (new_b->related_breakpoint == new_b);
7721         if (retval == NULL)
7722           retval = new_b;
7723         new_b->related_breakpoint = retval;
7724         while (retval->related_breakpoint != new_b->related_breakpoint)
7725           retval = retval->related_breakpoint;
7726         retval->related_breakpoint = new_b;
7727       }
7728
7729   return retval;
7730 }
7731
7732 /* Verify all existing dummy frames and their associated breakpoints for
7733    TP.  Remove those which can no longer be found in the current frame
7734    stack.
7735
7736    You should call this function only at places where it is safe to currently
7737    unwind the whole stack.  Failed stack unwind would discard live dummy
7738    frames.  */
7739
7740 void
7741 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7742 {
7743   struct breakpoint *b, *b_tmp;
7744
7745   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7746     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7747       {
7748         struct breakpoint *dummy_b = b->related_breakpoint;
7749
7750         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7751           dummy_b = dummy_b->related_breakpoint;
7752         if (dummy_b->type != bp_call_dummy
7753             || frame_find_by_id (dummy_b->frame_id) != NULL)
7754           continue;
7755         
7756         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7757
7758         while (b->related_breakpoint != b)
7759           {
7760             if (b_tmp == b->related_breakpoint)
7761               b_tmp = b->related_breakpoint->next;
7762             delete_breakpoint (b->related_breakpoint);
7763           }
7764         delete_breakpoint (b);
7765       }
7766 }
7767
7768 void
7769 enable_overlay_breakpoints (void)
7770 {
7771   struct breakpoint *b;
7772
7773   ALL_BREAKPOINTS (b)
7774     if (b->type == bp_overlay_event)
7775     {
7776       b->enable_state = bp_enabled;
7777       update_global_location_list (UGLL_MAY_INSERT);
7778       overlay_events_enabled = 1;
7779     }
7780 }
7781
7782 void
7783 disable_overlay_breakpoints (void)
7784 {
7785   struct breakpoint *b;
7786
7787   ALL_BREAKPOINTS (b)
7788     if (b->type == bp_overlay_event)
7789     {
7790       b->enable_state = bp_disabled;
7791       update_global_location_list (UGLL_DONT_INSERT);
7792       overlay_events_enabled = 0;
7793     }
7794 }
7795
7796 /* Set an active std::terminate breakpoint for each std::terminate
7797    master breakpoint.  */
7798 void
7799 set_std_terminate_breakpoint (void)
7800 {
7801   struct breakpoint *b, *b_tmp;
7802
7803   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7804     if (b->pspace == current_program_space
7805         && b->type == bp_std_terminate_master)
7806       {
7807         momentary_breakpoint_from_master (b, bp_std_terminate,
7808                                           &momentary_breakpoint_ops, 1);
7809       }
7810 }
7811
7812 /* Delete all the std::terminate breakpoints.  */
7813 void
7814 delete_std_terminate_breakpoint (void)
7815 {
7816   struct breakpoint *b, *b_tmp;
7817
7818   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7819     if (b->type == bp_std_terminate)
7820       delete_breakpoint (b);
7821 }
7822
7823 struct breakpoint *
7824 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7825 {
7826   struct breakpoint *b;
7827
7828   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7829                                   &internal_breakpoint_ops);
7830
7831   b->enable_state = bp_enabled;
7832   /* location has to be used or breakpoint_re_set will delete me.  */
7833   b->location = new_address_location (b->loc->address, NULL, 0);
7834
7835   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7836
7837   return b;
7838 }
7839
7840 struct lang_and_radix
7841   {
7842     enum language lang;
7843     int radix;
7844   };
7845
7846 /* Create a breakpoint for JIT code registration and unregistration.  */
7847
7848 struct breakpoint *
7849 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7850 {
7851   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7852                                      &internal_breakpoint_ops);
7853 }
7854
7855 /* Remove JIT code registration and unregistration breakpoint(s).  */
7856
7857 void
7858 remove_jit_event_breakpoints (void)
7859 {
7860   struct breakpoint *b, *b_tmp;
7861
7862   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7863     if (b->type == bp_jit_event
7864         && b->loc->pspace == current_program_space)
7865       delete_breakpoint (b);
7866 }
7867
7868 void
7869 remove_solib_event_breakpoints (void)
7870 {
7871   struct breakpoint *b, *b_tmp;
7872
7873   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7874     if (b->type == bp_shlib_event
7875         && b->loc->pspace == current_program_space)
7876       delete_breakpoint (b);
7877 }
7878
7879 /* See breakpoint.h.  */
7880
7881 void
7882 remove_solib_event_breakpoints_at_next_stop (void)
7883 {
7884   struct breakpoint *b, *b_tmp;
7885
7886   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7887     if (b->type == bp_shlib_event
7888         && b->loc->pspace == current_program_space)
7889       b->disposition = disp_del_at_next_stop;
7890 }
7891
7892 /* Helper for create_solib_event_breakpoint /
7893    create_and_insert_solib_event_breakpoint.  Allows specifying which
7894    INSERT_MODE to pass through to update_global_location_list.  */
7895
7896 static struct breakpoint *
7897 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7898                                  enum ugll_insert_mode insert_mode)
7899 {
7900   struct breakpoint *b;
7901
7902   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7903                                   &internal_breakpoint_ops);
7904   update_global_location_list_nothrow (insert_mode);
7905   return b;
7906 }
7907
7908 struct breakpoint *
7909 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7910 {
7911   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7912 }
7913
7914 /* See breakpoint.h.  */
7915
7916 struct breakpoint *
7917 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7918 {
7919   struct breakpoint *b;
7920
7921   /* Explicitly tell update_global_location_list to insert
7922      locations.  */
7923   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7924   if (!b->loc->inserted)
7925     {
7926       delete_breakpoint (b);
7927       return NULL;
7928     }
7929   return b;
7930 }
7931
7932 /* Disable any breakpoints that are on code in shared libraries.  Only
7933    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7934
7935 void
7936 disable_breakpoints_in_shlibs (void)
7937 {
7938   struct bp_location *loc, **locp_tmp;
7939
7940   ALL_BP_LOCATIONS (loc, locp_tmp)
7941   {
7942     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7943     struct breakpoint *b = loc->owner;
7944
7945     /* We apply the check to all breakpoints, including disabled for
7946        those with loc->duplicate set.  This is so that when breakpoint
7947        becomes enabled, or the duplicate is removed, gdb will try to
7948        insert all breakpoints.  If we don't set shlib_disabled here,
7949        we'll try to insert those breakpoints and fail.  */
7950     if (((b->type == bp_breakpoint)
7951          || (b->type == bp_jit_event)
7952          || (b->type == bp_hardware_breakpoint)
7953          || (is_tracepoint (b)))
7954         && loc->pspace == current_program_space
7955         && !loc->shlib_disabled
7956         && solib_name_from_address (loc->pspace, loc->address)
7957         )
7958       {
7959         loc->shlib_disabled = 1;
7960       }
7961   }
7962 }
7963
7964 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7965    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7966    disabled ones can just stay disabled.  */
7967
7968 static void
7969 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7970 {
7971   struct bp_location *loc, **locp_tmp;
7972   int disabled_shlib_breaks = 0;
7973
7974   /* SunOS a.out shared libraries are always mapped, so do not
7975      disable breakpoints; they will only be reported as unloaded
7976      through clear_solib when GDB discards its shared library
7977      list.  See clear_solib for more information.  */
7978   if (exec_bfd != NULL
7979       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7980     return;
7981
7982   ALL_BP_LOCATIONS (loc, locp_tmp)
7983   {
7984     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7985     struct breakpoint *b = loc->owner;
7986
7987     if (solib->pspace == loc->pspace
7988         && !loc->shlib_disabled
7989         && (((b->type == bp_breakpoint
7990               || b->type == bp_jit_event
7991               || b->type == bp_hardware_breakpoint)
7992              && (loc->loc_type == bp_loc_hardware_breakpoint
7993                  || loc->loc_type == bp_loc_software_breakpoint))
7994             || is_tracepoint (b))
7995         && solib_contains_address_p (solib, loc->address))
7996       {
7997         loc->shlib_disabled = 1;
7998         /* At this point, we cannot rely on remove_breakpoint
7999            succeeding so we must mark the breakpoint as not inserted
8000            to prevent future errors occurring in remove_breakpoints.  */
8001         loc->inserted = 0;
8002
8003         /* This may cause duplicate notifications for the same breakpoint.  */
8004         observer_notify_breakpoint_modified (b);
8005
8006         if (!disabled_shlib_breaks)
8007           {
8008             target_terminal_ours_for_output ();
8009             warning (_("Temporarily disabling breakpoints "
8010                        "for unloaded shared library \"%s\""),
8011                      solib->so_name);
8012           }
8013         disabled_shlib_breaks = 1;
8014       }
8015   }
8016 }
8017
8018 /* Disable any breakpoints and tracepoints in OBJFILE upon
8019    notification of free_objfile.  Only apply to enabled breakpoints,
8020    disabled ones can just stay disabled.  */
8021
8022 static void
8023 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
8024 {
8025   struct breakpoint *b;
8026
8027   if (objfile == NULL)
8028     return;
8029
8030   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
8031      managed by the user with add-symbol-file/remove-symbol-file.
8032      Similarly to how breakpoints in shared libraries are handled in
8033      response to "nosharedlibrary", mark breakpoints in such modules
8034      shlib_disabled so they end up uninserted on the next global
8035      location list update.  Shared libraries not loaded by the user
8036      aren't handled here -- they're already handled in
8037      disable_breakpoints_in_unloaded_shlib, called by solib.c's
8038      solib_unloaded observer.  We skip objfiles that are not
8039      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
8040      main objfile).  */
8041   if ((objfile->flags & OBJF_SHARED) == 0
8042       || (objfile->flags & OBJF_USERLOADED) == 0)
8043     return;
8044
8045   ALL_BREAKPOINTS (b)
8046     {
8047       struct bp_location *loc;
8048       int bp_modified = 0;
8049
8050       if (!is_breakpoint (b) && !is_tracepoint (b))
8051         continue;
8052
8053       for (loc = b->loc; loc != NULL; loc = loc->next)
8054         {
8055           CORE_ADDR loc_addr = loc->address;
8056
8057           if (loc->loc_type != bp_loc_hardware_breakpoint
8058               && loc->loc_type != bp_loc_software_breakpoint)
8059             continue;
8060
8061           if (loc->shlib_disabled != 0)
8062             continue;
8063
8064           if (objfile->pspace != loc->pspace)
8065             continue;
8066
8067           if (loc->loc_type != bp_loc_hardware_breakpoint
8068               && loc->loc_type != bp_loc_software_breakpoint)
8069             continue;
8070
8071           if (is_addr_in_objfile (loc_addr, objfile))
8072             {
8073               loc->shlib_disabled = 1;
8074               /* At this point, we don't know whether the object was
8075                  unmapped from the inferior or not, so leave the
8076                  inserted flag alone.  We'll handle failure to
8077                  uninsert quietly, in case the object was indeed
8078                  unmapped.  */
8079
8080               mark_breakpoint_location_modified (loc);
8081
8082               bp_modified = 1;
8083             }
8084         }
8085
8086       if (bp_modified)
8087         observer_notify_breakpoint_modified (b);
8088     }
8089 }
8090
8091 /* FORK & VFORK catchpoints.  */
8092
8093 /* An instance of this type is used to represent a fork or vfork
8094    catchpoint.  It includes a "struct breakpoint" as a kind of base
8095    class; users downcast to "struct breakpoint *" when needed.  A
8096    breakpoint is really of this type iff its ops pointer points to
8097    CATCH_FORK_BREAKPOINT_OPS.  */
8098
8099 struct fork_catchpoint
8100 {
8101   /* The base class.  */
8102   struct breakpoint base;
8103
8104   /* Process id of a child process whose forking triggered this
8105      catchpoint.  This field is only valid immediately after this
8106      catchpoint has triggered.  */
8107   ptid_t forked_inferior_pid;
8108 };
8109
8110 /* Implement the "insert" breakpoint_ops method for fork
8111    catchpoints.  */
8112
8113 static int
8114 insert_catch_fork (struct bp_location *bl)
8115 {
8116   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
8117 }
8118
8119 /* Implement the "remove" breakpoint_ops method for fork
8120    catchpoints.  */
8121
8122 static int
8123 remove_catch_fork (struct bp_location *bl)
8124 {
8125   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
8126 }
8127
8128 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
8129    catchpoints.  */
8130
8131 static int
8132 breakpoint_hit_catch_fork (const struct bp_location *bl,
8133                            struct address_space *aspace, CORE_ADDR bp_addr,
8134                            const struct target_waitstatus *ws)
8135 {
8136   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8137
8138   if (ws->kind != TARGET_WAITKIND_FORKED)
8139     return 0;
8140
8141   c->forked_inferior_pid = ws->value.related_pid;
8142   return 1;
8143 }
8144
8145 /* Implement the "print_it" breakpoint_ops method for fork
8146    catchpoints.  */
8147
8148 static enum print_stop_action
8149 print_it_catch_fork (bpstat bs)
8150 {
8151   struct ui_out *uiout = current_uiout;
8152   struct breakpoint *b = bs->breakpoint_at;
8153   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8154
8155   annotate_catchpoint (b->number);
8156   maybe_print_thread_hit_breakpoint (uiout);
8157   if (b->disposition == disp_del)
8158     ui_out_text (uiout, "Temporary catchpoint ");
8159   else
8160     ui_out_text (uiout, "Catchpoint ");
8161   if (ui_out_is_mi_like_p (uiout))
8162     {
8163       ui_out_field_string (uiout, "reason",
8164                            async_reason_lookup (EXEC_ASYNC_FORK));
8165       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8166     }
8167   ui_out_field_int (uiout, "bkptno", b->number);
8168   ui_out_text (uiout, " (forked process ");
8169   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8170   ui_out_text (uiout, "), ");
8171   return PRINT_SRC_AND_LOC;
8172 }
8173
8174 /* Implement the "print_one" breakpoint_ops method for fork
8175    catchpoints.  */
8176
8177 static void
8178 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8179 {
8180   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8181   struct value_print_options opts;
8182   struct ui_out *uiout = current_uiout;
8183
8184   get_user_print_options (&opts);
8185
8186   /* Field 4, the address, is omitted (which makes the columns not
8187      line up too nicely with the headers, but the effect is relatively
8188      readable).  */
8189   if (opts.addressprint)
8190     ui_out_field_skip (uiout, "addr");
8191   annotate_field (5);
8192   ui_out_text (uiout, "fork");
8193   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8194     {
8195       ui_out_text (uiout, ", process ");
8196       ui_out_field_int (uiout, "what",
8197                         ptid_get_pid (c->forked_inferior_pid));
8198       ui_out_spaces (uiout, 1);
8199     }
8200
8201   if (ui_out_is_mi_like_p (uiout))
8202     ui_out_field_string (uiout, "catch-type", "fork");
8203 }
8204
8205 /* Implement the "print_mention" breakpoint_ops method for fork
8206    catchpoints.  */
8207
8208 static void
8209 print_mention_catch_fork (struct breakpoint *b)
8210 {
8211   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8212 }
8213
8214 /* Implement the "print_recreate" breakpoint_ops method for fork
8215    catchpoints.  */
8216
8217 static void
8218 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8219 {
8220   fprintf_unfiltered (fp, "catch fork");
8221   print_recreate_thread (b, fp);
8222 }
8223
8224 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8225
8226 static struct breakpoint_ops catch_fork_breakpoint_ops;
8227
8228 /* Implement the "insert" breakpoint_ops method for vfork
8229    catchpoints.  */
8230
8231 static int
8232 insert_catch_vfork (struct bp_location *bl)
8233 {
8234   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8235 }
8236
8237 /* Implement the "remove" breakpoint_ops method for vfork
8238    catchpoints.  */
8239
8240 static int
8241 remove_catch_vfork (struct bp_location *bl)
8242 {
8243   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8244 }
8245
8246 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8247    catchpoints.  */
8248
8249 static int
8250 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8251                             struct address_space *aspace, CORE_ADDR bp_addr,
8252                             const struct target_waitstatus *ws)
8253 {
8254   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8255
8256   if (ws->kind != TARGET_WAITKIND_VFORKED)
8257     return 0;
8258
8259   c->forked_inferior_pid = ws->value.related_pid;
8260   return 1;
8261 }
8262
8263 /* Implement the "print_it" breakpoint_ops method for vfork
8264    catchpoints.  */
8265
8266 static enum print_stop_action
8267 print_it_catch_vfork (bpstat bs)
8268 {
8269   struct ui_out *uiout = current_uiout;
8270   struct breakpoint *b = bs->breakpoint_at;
8271   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8272
8273   annotate_catchpoint (b->number);
8274   maybe_print_thread_hit_breakpoint (uiout);
8275   if (b->disposition == disp_del)
8276     ui_out_text (uiout, "Temporary catchpoint ");
8277   else
8278     ui_out_text (uiout, "Catchpoint ");
8279   if (ui_out_is_mi_like_p (uiout))
8280     {
8281       ui_out_field_string (uiout, "reason",
8282                            async_reason_lookup (EXEC_ASYNC_VFORK));
8283       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8284     }
8285   ui_out_field_int (uiout, "bkptno", b->number);
8286   ui_out_text (uiout, " (vforked process ");
8287   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8288   ui_out_text (uiout, "), ");
8289   return PRINT_SRC_AND_LOC;
8290 }
8291
8292 /* Implement the "print_one" breakpoint_ops method for vfork
8293    catchpoints.  */
8294
8295 static void
8296 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8297 {
8298   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8299   struct value_print_options opts;
8300   struct ui_out *uiout = current_uiout;
8301
8302   get_user_print_options (&opts);
8303   /* Field 4, the address, is omitted (which makes the columns not
8304      line up too nicely with the headers, but the effect is relatively
8305      readable).  */
8306   if (opts.addressprint)
8307     ui_out_field_skip (uiout, "addr");
8308   annotate_field (5);
8309   ui_out_text (uiout, "vfork");
8310   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8311     {
8312       ui_out_text (uiout, ", process ");
8313       ui_out_field_int (uiout, "what",
8314                         ptid_get_pid (c->forked_inferior_pid));
8315       ui_out_spaces (uiout, 1);
8316     }
8317
8318   if (ui_out_is_mi_like_p (uiout))
8319     ui_out_field_string (uiout, "catch-type", "vfork");
8320 }
8321
8322 /* Implement the "print_mention" breakpoint_ops method for vfork
8323    catchpoints.  */
8324
8325 static void
8326 print_mention_catch_vfork (struct breakpoint *b)
8327 {
8328   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8329 }
8330
8331 /* Implement the "print_recreate" breakpoint_ops method for vfork
8332    catchpoints.  */
8333
8334 static void
8335 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8336 {
8337   fprintf_unfiltered (fp, "catch vfork");
8338   print_recreate_thread (b, fp);
8339 }
8340
8341 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8342
8343 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8344
8345 /* An instance of this type is used to represent an solib catchpoint.
8346    It includes a "struct breakpoint" as a kind of base class; users
8347    downcast to "struct breakpoint *" when needed.  A breakpoint is
8348    really of this type iff its ops pointer points to
8349    CATCH_SOLIB_BREAKPOINT_OPS.  */
8350
8351 struct solib_catchpoint
8352 {
8353   /* The base class.  */
8354   struct breakpoint base;
8355
8356   /* True for "catch load", false for "catch unload".  */
8357   unsigned char is_load;
8358
8359   /* Regular expression to match, if any.  COMPILED is only valid when
8360      REGEX is non-NULL.  */
8361   char *regex;
8362   regex_t compiled;
8363 };
8364
8365 static void
8366 dtor_catch_solib (struct breakpoint *b)
8367 {
8368   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8369
8370   if (self->regex)
8371     regfree (&self->compiled);
8372   xfree (self->regex);
8373
8374   base_breakpoint_ops.dtor (b);
8375 }
8376
8377 static int
8378 insert_catch_solib (struct bp_location *ignore)
8379 {
8380   return 0;
8381 }
8382
8383 static int
8384 remove_catch_solib (struct bp_location *ignore)
8385 {
8386   return 0;
8387 }
8388
8389 static int
8390 breakpoint_hit_catch_solib (const struct bp_location *bl,
8391                             struct address_space *aspace,
8392                             CORE_ADDR bp_addr,
8393                             const struct target_waitstatus *ws)
8394 {
8395   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8396   struct breakpoint *other;
8397
8398   if (ws->kind == TARGET_WAITKIND_LOADED)
8399     return 1;
8400
8401   ALL_BREAKPOINTS (other)
8402   {
8403     struct bp_location *other_bl;
8404
8405     if (other == bl->owner)
8406       continue;
8407
8408     if (other->type != bp_shlib_event)
8409       continue;
8410
8411     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8412       continue;
8413
8414     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8415       {
8416         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8417           return 1;
8418       }
8419   }
8420
8421   return 0;
8422 }
8423
8424 static void
8425 check_status_catch_solib (struct bpstats *bs)
8426 {
8427   struct solib_catchpoint *self
8428     = (struct solib_catchpoint *) bs->breakpoint_at;
8429   int ix;
8430
8431   if (self->is_load)
8432     {
8433       struct so_list *iter;
8434
8435       for (ix = 0;
8436            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8437                         ix, iter);
8438            ++ix)
8439         {
8440           if (!self->regex
8441               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8442             return;
8443         }
8444     }
8445   else
8446     {
8447       char *iter;
8448
8449       for (ix = 0;
8450            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8451                         ix, iter);
8452            ++ix)
8453         {
8454           if (!self->regex
8455               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8456             return;
8457         }
8458     }
8459
8460   bs->stop = 0;
8461   bs->print_it = print_it_noop;
8462 }
8463
8464 static enum print_stop_action
8465 print_it_catch_solib (bpstat bs)
8466 {
8467   struct breakpoint *b = bs->breakpoint_at;
8468   struct ui_out *uiout = current_uiout;
8469
8470   annotate_catchpoint (b->number);
8471   maybe_print_thread_hit_breakpoint (uiout);
8472   if (b->disposition == disp_del)
8473     ui_out_text (uiout, "Temporary catchpoint ");
8474   else
8475     ui_out_text (uiout, "Catchpoint ");
8476   ui_out_field_int (uiout, "bkptno", b->number);
8477   ui_out_text (uiout, "\n");
8478   if (ui_out_is_mi_like_p (uiout))
8479     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8480   print_solib_event (1);
8481   return PRINT_SRC_AND_LOC;
8482 }
8483
8484 static void
8485 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8486 {
8487   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8488   struct value_print_options opts;
8489   struct ui_out *uiout = current_uiout;
8490   char *msg;
8491
8492   get_user_print_options (&opts);
8493   /* Field 4, the address, is omitted (which makes the columns not
8494      line up too nicely with the headers, but the effect is relatively
8495      readable).  */
8496   if (opts.addressprint)
8497     {
8498       annotate_field (4);
8499       ui_out_field_skip (uiout, "addr");
8500     }
8501
8502   annotate_field (5);
8503   if (self->is_load)
8504     {
8505       if (self->regex)
8506         msg = xstrprintf (_("load of library matching %s"), self->regex);
8507       else
8508         msg = xstrdup (_("load of library"));
8509     }
8510   else
8511     {
8512       if (self->regex)
8513         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8514       else
8515         msg = xstrdup (_("unload of library"));
8516     }
8517   ui_out_field_string (uiout, "what", msg);
8518   xfree (msg);
8519
8520   if (ui_out_is_mi_like_p (uiout))
8521     ui_out_field_string (uiout, "catch-type",
8522                          self->is_load ? "load" : "unload");
8523 }
8524
8525 static void
8526 print_mention_catch_solib (struct breakpoint *b)
8527 {
8528   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8529
8530   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8531                    self->is_load ? "load" : "unload");
8532 }
8533
8534 static void
8535 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8536 {
8537   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8538
8539   fprintf_unfiltered (fp, "%s %s",
8540                       b->disposition == disp_del ? "tcatch" : "catch",
8541                       self->is_load ? "load" : "unload");
8542   if (self->regex)
8543     fprintf_unfiltered (fp, " %s", self->regex);
8544   fprintf_unfiltered (fp, "\n");
8545 }
8546
8547 static struct breakpoint_ops catch_solib_breakpoint_ops;
8548
8549 /* Shared helper function (MI and CLI) for creating and installing
8550    a shared object event catchpoint.  If IS_LOAD is non-zero then
8551    the events to be caught are load events, otherwise they are
8552    unload events.  If IS_TEMP is non-zero the catchpoint is a
8553    temporary one.  If ENABLED is non-zero the catchpoint is
8554    created in an enabled state.  */
8555
8556 void
8557 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8558 {
8559   struct solib_catchpoint *c;
8560   struct gdbarch *gdbarch = get_current_arch ();
8561   struct cleanup *cleanup;
8562
8563   if (!arg)
8564     arg = "";
8565   arg = skip_spaces (arg);
8566
8567   c = XCNEW (struct solib_catchpoint);
8568   cleanup = make_cleanup (xfree, c);
8569
8570   if (*arg != '\0')
8571     {
8572       int errcode;
8573
8574       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8575       if (errcode != 0)
8576         {
8577           char *err = get_regcomp_error (errcode, &c->compiled);
8578
8579           make_cleanup (xfree, err);
8580           error (_("Invalid regexp (%s): %s"), err, arg);
8581         }
8582       c->regex = xstrdup (arg);
8583     }
8584
8585   c->is_load = is_load;
8586   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8587                    &catch_solib_breakpoint_ops);
8588
8589   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8590
8591   discard_cleanups (cleanup);
8592   install_breakpoint (0, &c->base, 1);
8593 }
8594
8595 /* A helper function that does all the work for "catch load" and
8596    "catch unload".  */
8597
8598 static void
8599 catch_load_or_unload (char *arg, int from_tty, int is_load,
8600                       struct cmd_list_element *command)
8601 {
8602   int tempflag;
8603   const int enabled = 1;
8604
8605   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8606
8607   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8608 }
8609
8610 static void
8611 catch_load_command_1 (char *arg, int from_tty,
8612                       struct cmd_list_element *command)
8613 {
8614   catch_load_or_unload (arg, from_tty, 1, command);
8615 }
8616
8617 static void
8618 catch_unload_command_1 (char *arg, int from_tty,
8619                         struct cmd_list_element *command)
8620 {
8621   catch_load_or_unload (arg, from_tty, 0, command);
8622 }
8623
8624 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8625    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8626    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8627    the breakpoint_ops structure associated to the catchpoint.  */
8628
8629 void
8630 init_catchpoint (struct breakpoint *b,
8631                  struct gdbarch *gdbarch, int tempflag,
8632                  char *cond_string,
8633                  const struct breakpoint_ops *ops)
8634 {
8635   struct symtab_and_line sal;
8636
8637   init_sal (&sal);
8638   sal.pspace = current_program_space;
8639
8640   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8641
8642   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8643   b->disposition = tempflag ? disp_del : disp_donttouch;
8644 }
8645
8646 void
8647 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8648 {
8649   add_to_breakpoint_chain (b);
8650   set_breakpoint_number (internal, b);
8651   if (is_tracepoint (b))
8652     set_tracepoint_count (breakpoint_count);
8653   if (!internal)
8654     mention (b);
8655   observer_notify_breakpoint_created (b);
8656
8657   if (update_gll)
8658     update_global_location_list (UGLL_MAY_INSERT);
8659 }
8660
8661 static void
8662 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8663                                     int tempflag, char *cond_string,
8664                                     const struct breakpoint_ops *ops)
8665 {
8666   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8667
8668   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8669
8670   c->forked_inferior_pid = null_ptid;
8671
8672   install_breakpoint (0, &c->base, 1);
8673 }
8674
8675 /* Exec catchpoints.  */
8676
8677 /* An instance of this type is used to represent an exec catchpoint.
8678    It includes a "struct breakpoint" as a kind of base class; users
8679    downcast to "struct breakpoint *" when needed.  A breakpoint is
8680    really of this type iff its ops pointer points to
8681    CATCH_EXEC_BREAKPOINT_OPS.  */
8682
8683 struct exec_catchpoint
8684 {
8685   /* The base class.  */
8686   struct breakpoint base;
8687
8688   /* Filename of a program whose exec triggered this catchpoint.
8689      This field is only valid immediately after this catchpoint has
8690      triggered.  */
8691   char *exec_pathname;
8692 };
8693
8694 /* Implement the "dtor" breakpoint_ops method for exec
8695    catchpoints.  */
8696
8697 static void
8698 dtor_catch_exec (struct breakpoint *b)
8699 {
8700   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8701
8702   xfree (c->exec_pathname);
8703
8704   base_breakpoint_ops.dtor (b);
8705 }
8706
8707 static int
8708 insert_catch_exec (struct bp_location *bl)
8709 {
8710   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8711 }
8712
8713 static int
8714 remove_catch_exec (struct bp_location *bl)
8715 {
8716   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8717 }
8718
8719 static int
8720 breakpoint_hit_catch_exec (const struct bp_location *bl,
8721                            struct address_space *aspace, CORE_ADDR bp_addr,
8722                            const struct target_waitstatus *ws)
8723 {
8724   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8725
8726   if (ws->kind != TARGET_WAITKIND_EXECD)
8727     return 0;
8728
8729   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8730   return 1;
8731 }
8732
8733 static enum print_stop_action
8734 print_it_catch_exec (bpstat bs)
8735 {
8736   struct ui_out *uiout = current_uiout;
8737   struct breakpoint *b = bs->breakpoint_at;
8738   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8739
8740   annotate_catchpoint (b->number);
8741   maybe_print_thread_hit_breakpoint (uiout);
8742   if (b->disposition == disp_del)
8743     ui_out_text (uiout, "Temporary catchpoint ");
8744   else
8745     ui_out_text (uiout, "Catchpoint ");
8746   if (ui_out_is_mi_like_p (uiout))
8747     {
8748       ui_out_field_string (uiout, "reason",
8749                            async_reason_lookup (EXEC_ASYNC_EXEC));
8750       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8751     }
8752   ui_out_field_int (uiout, "bkptno", b->number);
8753   ui_out_text (uiout, " (exec'd ");
8754   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8755   ui_out_text (uiout, "), ");
8756
8757   return PRINT_SRC_AND_LOC;
8758 }
8759
8760 static void
8761 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8762 {
8763   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8764   struct value_print_options opts;
8765   struct ui_out *uiout = current_uiout;
8766
8767   get_user_print_options (&opts);
8768
8769   /* Field 4, the address, is omitted (which makes the columns
8770      not line up too nicely with the headers, but the effect
8771      is relatively readable).  */
8772   if (opts.addressprint)
8773     ui_out_field_skip (uiout, "addr");
8774   annotate_field (5);
8775   ui_out_text (uiout, "exec");
8776   if (c->exec_pathname != NULL)
8777     {
8778       ui_out_text (uiout, ", program \"");
8779       ui_out_field_string (uiout, "what", c->exec_pathname);
8780       ui_out_text (uiout, "\" ");
8781     }
8782
8783   if (ui_out_is_mi_like_p (uiout))
8784     ui_out_field_string (uiout, "catch-type", "exec");
8785 }
8786
8787 static void
8788 print_mention_catch_exec (struct breakpoint *b)
8789 {
8790   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8791 }
8792
8793 /* Implement the "print_recreate" breakpoint_ops method for exec
8794    catchpoints.  */
8795
8796 static void
8797 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8798 {
8799   fprintf_unfiltered (fp, "catch exec");
8800   print_recreate_thread (b, fp);
8801 }
8802
8803 static struct breakpoint_ops catch_exec_breakpoint_ops;
8804
8805 static int
8806 hw_breakpoint_used_count (void)
8807 {
8808   int i = 0;
8809   struct breakpoint *b;
8810   struct bp_location *bl;
8811
8812   ALL_BREAKPOINTS (b)
8813   {
8814     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8815       for (bl = b->loc; bl; bl = bl->next)
8816         {
8817           /* Special types of hardware breakpoints may use more than
8818              one register.  */
8819           i += b->ops->resources_needed (bl);
8820         }
8821   }
8822
8823   return i;
8824 }
8825
8826 /* Returns the resources B would use if it were a hardware
8827    watchpoint.  */
8828
8829 static int
8830 hw_watchpoint_use_count (struct breakpoint *b)
8831 {
8832   int i = 0;
8833   struct bp_location *bl;
8834
8835   if (!breakpoint_enabled (b))
8836     return 0;
8837
8838   for (bl = b->loc; bl; bl = bl->next)
8839     {
8840       /* Special types of hardware watchpoints may use more than
8841          one register.  */
8842       i += b->ops->resources_needed (bl);
8843     }
8844
8845   return i;
8846 }
8847
8848 /* Returns the sum the used resources of all hardware watchpoints of
8849    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8850    the sum of the used resources of all hardware watchpoints of other
8851    types _not_ TYPE.  */
8852
8853 static int
8854 hw_watchpoint_used_count_others (struct breakpoint *except,
8855                                  enum bptype type, int *other_type_used)
8856 {
8857   int i = 0;
8858   struct breakpoint *b;
8859
8860   *other_type_used = 0;
8861   ALL_BREAKPOINTS (b)
8862     {
8863       if (b == except)
8864         continue;
8865       if (!breakpoint_enabled (b))
8866         continue;
8867
8868       if (b->type == type)
8869         i += hw_watchpoint_use_count (b);
8870       else if (is_hardware_watchpoint (b))
8871         *other_type_used = 1;
8872     }
8873
8874   return i;
8875 }
8876
8877 void
8878 disable_watchpoints_before_interactive_call_start (void)
8879 {
8880   struct breakpoint *b;
8881
8882   ALL_BREAKPOINTS (b)
8883   {
8884     if (is_watchpoint (b) && breakpoint_enabled (b))
8885       {
8886         b->enable_state = bp_call_disabled;
8887         update_global_location_list (UGLL_DONT_INSERT);
8888       }
8889   }
8890 }
8891
8892 void
8893 enable_watchpoints_after_interactive_call_stop (void)
8894 {
8895   struct breakpoint *b;
8896
8897   ALL_BREAKPOINTS (b)
8898   {
8899     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8900       {
8901         b->enable_state = bp_enabled;
8902         update_global_location_list (UGLL_MAY_INSERT);
8903       }
8904   }
8905 }
8906
8907 void
8908 disable_breakpoints_before_startup (void)
8909 {
8910   current_program_space->executing_startup = 1;
8911   update_global_location_list (UGLL_DONT_INSERT);
8912 }
8913
8914 void
8915 enable_breakpoints_after_startup (void)
8916 {
8917   current_program_space->executing_startup = 0;
8918   breakpoint_re_set ();
8919 }
8920
8921 /* Create a new single-step breakpoint for thread THREAD, with no
8922    locations.  */
8923
8924 static struct breakpoint *
8925 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8926 {
8927   struct breakpoint *b = XNEW (struct breakpoint);
8928
8929   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8930                                         &momentary_breakpoint_ops);
8931
8932   b->disposition = disp_donttouch;
8933   b->frame_id = null_frame_id;
8934
8935   b->thread = thread;
8936   gdb_assert (b->thread != 0);
8937
8938   add_to_breakpoint_chain (b);
8939
8940   return b;
8941 }
8942
8943 /* Set a momentary breakpoint of type TYPE at address specified by
8944    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8945    frame.  */
8946
8947 struct breakpoint *
8948 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8949                           struct frame_id frame_id, enum bptype type)
8950 {
8951   struct breakpoint *b;
8952
8953   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8954      tail-called one.  */
8955   gdb_assert (!frame_id_artificial_p (frame_id));
8956
8957   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8958   b->enable_state = bp_enabled;
8959   b->disposition = disp_donttouch;
8960   b->frame_id = frame_id;
8961
8962   /* If we're debugging a multi-threaded program, then we want
8963      momentary breakpoints to be active in only a single thread of
8964      control.  */
8965   if (in_thread_list (inferior_ptid))
8966     b->thread = ptid_to_global_thread_id (inferior_ptid);
8967
8968   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8969
8970   return b;
8971 }
8972
8973 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8974    The new breakpoint will have type TYPE, use OPS as its
8975    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8976
8977 static struct breakpoint *
8978 momentary_breakpoint_from_master (struct breakpoint *orig,
8979                                   enum bptype type,
8980                                   const struct breakpoint_ops *ops,
8981                                   int loc_enabled)
8982 {
8983   struct breakpoint *copy;
8984
8985   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8986   copy->loc = allocate_bp_location (copy);
8987   set_breakpoint_location_function (copy->loc, 1);
8988
8989   copy->loc->gdbarch = orig->loc->gdbarch;
8990   copy->loc->requested_address = orig->loc->requested_address;
8991   copy->loc->address = orig->loc->address;
8992   copy->loc->section = orig->loc->section;
8993   copy->loc->pspace = orig->loc->pspace;
8994   copy->loc->probe = orig->loc->probe;
8995   copy->loc->line_number = orig->loc->line_number;
8996   copy->loc->symtab = orig->loc->symtab;
8997   copy->loc->enabled = loc_enabled;
8998   copy->frame_id = orig->frame_id;
8999   copy->thread = orig->thread;
9000   copy->pspace = orig->pspace;
9001
9002   copy->enable_state = bp_enabled;
9003   copy->disposition = disp_donttouch;
9004   copy->number = internal_breakpoint_number--;
9005
9006   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9007   return copy;
9008 }
9009
9010 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9011    ORIG is NULL.  */
9012
9013 struct breakpoint *
9014 clone_momentary_breakpoint (struct breakpoint *orig)
9015 {
9016   /* If there's nothing to clone, then return nothing.  */
9017   if (orig == NULL)
9018     return NULL;
9019
9020   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9021 }
9022
9023 struct breakpoint *
9024 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9025                                 enum bptype type)
9026 {
9027   struct symtab_and_line sal;
9028
9029   sal = find_pc_line (pc, 0);
9030   sal.pc = pc;
9031   sal.section = find_pc_overlay (pc);
9032   sal.explicit_pc = 1;
9033
9034   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9035 }
9036 \f
9037
9038 /* Tell the user we have just set a breakpoint B.  */
9039
9040 static void
9041 mention (struct breakpoint *b)
9042 {
9043   b->ops->print_mention (b);
9044   if (ui_out_is_mi_like_p (current_uiout))
9045     return;
9046   printf_filtered ("\n");
9047 }
9048 \f
9049
9050 static int bp_loc_is_permanent (struct bp_location *loc);
9051
9052 static struct bp_location *
9053 add_location_to_breakpoint (struct breakpoint *b,
9054                             const struct symtab_and_line *sal)
9055 {
9056   struct bp_location *loc, **tmp;
9057   CORE_ADDR adjusted_address;
9058   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9059
9060   if (loc_gdbarch == NULL)
9061     loc_gdbarch = b->gdbarch;
9062
9063   /* Adjust the breakpoint's address prior to allocating a location.
9064      Once we call allocate_bp_location(), that mostly uninitialized
9065      location will be placed on the location chain.  Adjustment of the
9066      breakpoint may cause target_read_memory() to be called and we do
9067      not want its scan of the location chain to find a breakpoint and
9068      location that's only been partially initialized.  */
9069   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9070                                                 sal->pc, b->type);
9071
9072   /* Sort the locations by their ADDRESS.  */
9073   loc = allocate_bp_location (b);
9074   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9075        tmp = &((*tmp)->next))
9076     ;
9077   loc->next = *tmp;
9078   *tmp = loc;
9079
9080   loc->requested_address = sal->pc;
9081   loc->address = adjusted_address;
9082   loc->pspace = sal->pspace;
9083   loc->probe.probe = sal->probe;
9084   loc->probe.objfile = sal->objfile;
9085   gdb_assert (loc->pspace != NULL);
9086   loc->section = sal->section;
9087   loc->gdbarch = loc_gdbarch;
9088   loc->line_number = sal->line;
9089   loc->symtab = sal->symtab;
9090
9091   set_breakpoint_location_function (loc,
9092                                     sal->explicit_pc || sal->explicit_line);
9093
9094   /* While by definition, permanent breakpoints are already present in the
9095      code, we don't mark the location as inserted.  Normally one would expect
9096      that GDB could rely on that breakpoint instruction to stop the program,
9097      thus removing the need to insert its own breakpoint, except that executing
9098      the breakpoint instruction can kill the target instead of reporting a
9099      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
9100      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
9101      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
9102      breakpoint be inserted normally results in QEMU knowing about the GDB
9103      breakpoint, and thus trap before the breakpoint instruction is executed.
9104      (If GDB later needs to continue execution past the permanent breakpoint,
9105      it manually increments the PC, thus avoiding executing the breakpoint
9106      instruction.)  */
9107   if (bp_loc_is_permanent (loc))
9108     loc->permanent = 1;
9109
9110   return loc;
9111 }
9112 \f
9113
9114 /* See breakpoint.h.  */
9115
9116 int
9117 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9118 {
9119   int len;
9120   CORE_ADDR addr;
9121   const gdb_byte *bpoint;
9122   gdb_byte *target_mem;
9123   struct cleanup *cleanup;
9124   int retval = 0;
9125
9126   addr = address;
9127   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9128
9129   /* Software breakpoints unsupported?  */
9130   if (bpoint == NULL)
9131     return 0;
9132
9133   target_mem = (gdb_byte *) alloca (len);
9134
9135   /* Enable the automatic memory restoration from breakpoints while
9136      we read the memory.  Otherwise we could say about our temporary
9137      breakpoints they are permanent.  */
9138   cleanup = make_show_memory_breakpoints_cleanup (0);
9139
9140   if (target_read_memory (address, target_mem, len) == 0
9141       && memcmp (target_mem, bpoint, len) == 0)
9142     retval = 1;
9143
9144   do_cleanups (cleanup);
9145
9146   return retval;
9147 }
9148
9149 /* Return 1 if LOC is pointing to a permanent breakpoint,
9150    return 0 otherwise.  */
9151
9152 static int
9153 bp_loc_is_permanent (struct bp_location *loc)
9154 {
9155   struct cleanup *cleanup;
9156   int retval;
9157
9158   gdb_assert (loc != NULL);
9159
9160   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9161      attempt to read from the addresses the locations of these breakpoint types
9162      point to.  program_breakpoint_here_p, below, will attempt to read
9163      memory.  */
9164   if (!breakpoint_address_is_meaningful (loc->owner))
9165     return 0;
9166
9167   cleanup = save_current_space_and_thread ();
9168   switch_to_program_space_and_thread (loc->pspace);
9169
9170   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9171
9172   do_cleanups (cleanup);
9173
9174   return retval;
9175 }
9176
9177 /* Build a command list for the dprintf corresponding to the current
9178    settings of the dprintf style options.  */
9179
9180 static void
9181 update_dprintf_command_list (struct breakpoint *b)
9182 {
9183   char *dprintf_args = b->extra_string;
9184   char *printf_line = NULL;
9185
9186   if (!dprintf_args)
9187     return;
9188
9189   dprintf_args = skip_spaces (dprintf_args);
9190
9191   /* Allow a comma, as it may have terminated a location, but don't
9192      insist on it.  */
9193   if (*dprintf_args == ',')
9194     ++dprintf_args;
9195   dprintf_args = skip_spaces (dprintf_args);
9196
9197   if (*dprintf_args != '"')
9198     error (_("Bad format string, missing '\"'."));
9199
9200   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9201     printf_line = xstrprintf ("printf %s", dprintf_args);
9202   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9203     {
9204       if (!dprintf_function)
9205         error (_("No function supplied for dprintf call"));
9206
9207       if (dprintf_channel && strlen (dprintf_channel) > 0)
9208         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9209                                   dprintf_function,
9210                                   dprintf_channel,
9211                                   dprintf_args);
9212       else
9213         printf_line = xstrprintf ("call (void) %s (%s)",
9214                                   dprintf_function,
9215                                   dprintf_args);
9216     }
9217   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9218     {
9219       if (target_can_run_breakpoint_commands ())
9220         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9221       else
9222         {
9223           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9224           printf_line = xstrprintf ("printf %s", dprintf_args);
9225         }
9226     }
9227   else
9228     internal_error (__FILE__, __LINE__,
9229                     _("Invalid dprintf style."));
9230
9231   gdb_assert (printf_line != NULL);
9232   /* Manufacture a printf sequence.  */
9233   {
9234     struct command_line *printf_cmd_line = XNEW (struct command_line);
9235
9236     printf_cmd_line->control_type = simple_control;
9237     printf_cmd_line->body_count = 0;
9238     printf_cmd_line->body_list = NULL;
9239     printf_cmd_line->next = NULL;
9240     printf_cmd_line->line = printf_line;
9241
9242     breakpoint_set_commands (b, printf_cmd_line);
9243   }
9244 }
9245
9246 /* Update all dprintf commands, making their command lists reflect
9247    current style settings.  */
9248
9249 static void
9250 update_dprintf_commands (char *args, int from_tty,
9251                          struct cmd_list_element *c)
9252 {
9253   struct breakpoint *b;
9254
9255   ALL_BREAKPOINTS (b)
9256     {
9257       if (b->type == bp_dprintf)
9258         update_dprintf_command_list (b);
9259     }
9260 }
9261
9262 /* Create a breakpoint with SAL as location.  Use LOCATION
9263    as a description of the location, and COND_STRING
9264    as condition expression.  If LOCATION is NULL then create an
9265    "address location" from the address in the SAL.  */
9266
9267 static void
9268 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9269                      struct symtabs_and_lines sals,
9270                      struct event_location *location,
9271                      char *filter, char *cond_string,
9272                      char *extra_string,
9273                      enum bptype type, enum bpdisp disposition,
9274                      int thread, int task, int ignore_count,
9275                      const struct breakpoint_ops *ops, int from_tty,
9276                      int enabled, int internal, unsigned flags,
9277                      int display_canonical)
9278 {
9279   int i;
9280
9281   if (type == bp_hardware_breakpoint)
9282     {
9283       int target_resources_ok;
9284
9285       i = hw_breakpoint_used_count ();
9286       target_resources_ok =
9287         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9288                                             i + 1, 0);
9289       if (target_resources_ok == 0)
9290         error (_("No hardware breakpoint support in the target."));
9291       else if (target_resources_ok < 0)
9292         error (_("Hardware breakpoints used exceeds limit."));
9293     }
9294
9295   gdb_assert (sals.nelts > 0);
9296
9297   for (i = 0; i < sals.nelts; ++i)
9298     {
9299       struct symtab_and_line sal = sals.sals[i];
9300       struct bp_location *loc;
9301
9302       if (from_tty)
9303         {
9304           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9305           if (!loc_gdbarch)
9306             loc_gdbarch = gdbarch;
9307
9308           describe_other_breakpoints (loc_gdbarch,
9309                                       sal.pspace, sal.pc, sal.section, thread);
9310         }
9311
9312       if (i == 0)
9313         {
9314           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9315           b->thread = thread;
9316           b->task = task;
9317
9318           b->cond_string = cond_string;
9319           b->extra_string = extra_string;
9320           b->ignore_count = ignore_count;
9321           b->enable_state = enabled ? bp_enabled : bp_disabled;
9322           b->disposition = disposition;
9323
9324           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9325             b->loc->inserted = 1;
9326
9327           if (type == bp_static_tracepoint)
9328             {
9329               struct tracepoint *t = (struct tracepoint *) b;
9330               struct static_tracepoint_marker marker;
9331
9332               if (strace_marker_p (b))
9333                 {
9334                   /* We already know the marker exists, otherwise, we
9335                      wouldn't see a sal for it.  */
9336                   const char *p = &event_location_to_string (b->location)[3];
9337                   const char *endp;
9338                   char *marker_str;
9339
9340                   p = skip_spaces_const (p);
9341
9342                   endp = skip_to_space_const (p);
9343
9344                   marker_str = savestring (p, endp - p);
9345                   t->static_trace_marker_id = marker_str;
9346
9347                   printf_filtered (_("Probed static tracepoint "
9348                                      "marker \"%s\"\n"),
9349                                    t->static_trace_marker_id);
9350                 }
9351               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9352                 {
9353                   t->static_trace_marker_id = xstrdup (marker.str_id);
9354                   release_static_tracepoint_marker (&marker);
9355
9356                   printf_filtered (_("Probed static tracepoint "
9357                                      "marker \"%s\"\n"),
9358                                    t->static_trace_marker_id);
9359                 }
9360               else
9361                 warning (_("Couldn't determine the static "
9362                            "tracepoint marker to probe"));
9363             }
9364
9365           loc = b->loc;
9366         }
9367       else
9368         {
9369           loc = add_location_to_breakpoint (b, &sal);
9370           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9371             loc->inserted = 1;
9372         }
9373
9374       if (b->cond_string)
9375         {
9376           const char *arg = b->cond_string;
9377
9378           loc->cond = parse_exp_1 (&arg, loc->address,
9379                                    block_for_pc (loc->address), 0);
9380           if (*arg)
9381               error (_("Garbage '%s' follows condition"), arg);
9382         }
9383
9384       /* Dynamic printf requires and uses additional arguments on the
9385          command line, otherwise it's an error.  */
9386       if (type == bp_dprintf)
9387         {
9388           if (b->extra_string)
9389             update_dprintf_command_list (b);
9390           else
9391             error (_("Format string required"));
9392         }
9393       else if (b->extra_string)
9394         error (_("Garbage '%s' at end of command"), b->extra_string);
9395     }
9396
9397   b->display_canonical = display_canonical;
9398   if (location != NULL)
9399     b->location = location;
9400   else
9401     {
9402       const char *addr_string = NULL;
9403       int addr_string_len = 0;
9404
9405       if (location != NULL)
9406         addr_string = event_location_to_string (location);
9407       if (addr_string != NULL)
9408         addr_string_len = strlen (addr_string);
9409
9410       b->location = new_address_location (b->loc->address,
9411                                           addr_string, addr_string_len);
9412     }
9413   b->filter = filter;
9414 }
9415
9416 static void
9417 create_breakpoint_sal (struct gdbarch *gdbarch,
9418                        struct symtabs_and_lines sals,
9419                        struct event_location *location,
9420                        char *filter, char *cond_string,
9421                        char *extra_string,
9422                        enum bptype type, enum bpdisp disposition,
9423                        int thread, int task, int ignore_count,
9424                        const struct breakpoint_ops *ops, int from_tty,
9425                        int enabled, int internal, unsigned flags,
9426                        int display_canonical)
9427 {
9428   struct breakpoint *b;
9429   struct cleanup *old_chain;
9430
9431   if (is_tracepoint_type (type))
9432     {
9433       struct tracepoint *t;
9434
9435       t = XCNEW (struct tracepoint);
9436       b = &t->base;
9437     }
9438   else
9439     b = XNEW (struct breakpoint);
9440
9441   old_chain = make_cleanup (xfree, b);
9442
9443   init_breakpoint_sal (b, gdbarch,
9444                        sals, location,
9445                        filter, cond_string, extra_string,
9446                        type, disposition,
9447                        thread, task, ignore_count,
9448                        ops, from_tty,
9449                        enabled, internal, flags,
9450                        display_canonical);
9451   discard_cleanups (old_chain);
9452
9453   install_breakpoint (internal, b, 0);
9454 }
9455
9456 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9457    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9458    value.  COND_STRING, if not NULL, specified the condition to be
9459    used for all breakpoints.  Essentially the only case where
9460    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9461    function.  In that case, it's still not possible to specify
9462    separate conditions for different overloaded functions, so
9463    we take just a single condition string.
9464    
9465    NOTE: If the function succeeds, the caller is expected to cleanup
9466    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9467    array contents).  If the function fails (error() is called), the
9468    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9469    COND and SALS arrays and each of those arrays contents.  */
9470
9471 static void
9472 create_breakpoints_sal (struct gdbarch *gdbarch,
9473                         struct linespec_result *canonical,
9474                         char *cond_string, char *extra_string,
9475                         enum bptype type, enum bpdisp disposition,
9476                         int thread, int task, int ignore_count,
9477                         const struct breakpoint_ops *ops, int from_tty,
9478                         int enabled, int internal, unsigned flags)
9479 {
9480   int i;
9481   struct linespec_sals *lsal;
9482
9483   if (canonical->pre_expanded)
9484     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9485
9486   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9487     {
9488       /* Note that 'location' can be NULL in the case of a plain
9489          'break', without arguments.  */
9490       struct event_location *location
9491         = (canonical->location != NULL
9492            ? copy_event_location (canonical->location) : NULL);
9493       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9494       struct cleanup *inner = make_cleanup_delete_event_location (location);
9495
9496       make_cleanup (xfree, filter_string);
9497       create_breakpoint_sal (gdbarch, lsal->sals,
9498                              location,
9499                              filter_string,
9500                              cond_string, extra_string,
9501                              type, disposition,
9502                              thread, task, ignore_count, ops,
9503                              from_tty, enabled, internal, flags,
9504                              canonical->special_display);
9505       discard_cleanups (inner);
9506     }
9507 }
9508
9509 /* Parse LOCATION which is assumed to be a SAL specification possibly
9510    followed by conditionals.  On return, SALS contains an array of SAL
9511    addresses found.  LOCATION points to the end of the SAL (for
9512    linespec locations).
9513
9514    The array and the line spec strings are allocated on the heap, it is
9515    the caller's responsibility to free them.  */
9516
9517 static void
9518 parse_breakpoint_sals (const struct event_location *location,
9519                        struct linespec_result *canonical)
9520 {
9521   struct symtab_and_line cursal;
9522
9523   if (event_location_type (location) == LINESPEC_LOCATION)
9524     {
9525       const char *address = get_linespec_location (location);
9526
9527       if (address == NULL)
9528         {
9529           /* The last displayed codepoint, if it's valid, is our default
9530              breakpoint address.  */
9531           if (last_displayed_sal_is_valid ())
9532             {
9533               struct linespec_sals lsal;
9534               struct symtab_and_line sal;
9535               CORE_ADDR pc;
9536
9537               init_sal (&sal);          /* Initialize to zeroes.  */
9538               lsal.sals.sals = XNEW (struct symtab_and_line);
9539
9540               /* Set sal's pspace, pc, symtab, and line to the values
9541                  corresponding to the last call to print_frame_info.
9542                  Be sure to reinitialize LINE with NOTCURRENT == 0
9543                  as the breakpoint line number is inappropriate otherwise.
9544                  find_pc_line would adjust PC, re-set it back.  */
9545               get_last_displayed_sal (&sal);
9546               pc = sal.pc;
9547               sal = find_pc_line (pc, 0);
9548
9549               /* "break" without arguments is equivalent to "break *PC"
9550                  where PC is the last displayed codepoint's address.  So
9551                  make sure to set sal.explicit_pc to prevent GDB from
9552                  trying to expand the list of sals to include all other
9553                  instances with the same symtab and line.  */
9554               sal.pc = pc;
9555               sal.explicit_pc = 1;
9556
9557               lsal.sals.sals[0] = sal;
9558               lsal.sals.nelts = 1;
9559               lsal.canonical = NULL;
9560
9561               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9562               return;
9563             }
9564           else
9565             error (_("No default breakpoint address now."));
9566         }
9567     }
9568
9569   /* Force almost all breakpoints to be in terms of the
9570      current_source_symtab (which is decode_line_1's default).
9571      This should produce the results we want almost all of the
9572      time while leaving default_breakpoint_* alone.
9573
9574      ObjC: However, don't match an Objective-C method name which
9575      may have a '+' or '-' succeeded by a '['.  */
9576   cursal = get_current_source_symtab_and_line ();
9577   if (last_displayed_sal_is_valid ())
9578     {
9579       const char *address = NULL;
9580
9581       if (event_location_type (location) == LINESPEC_LOCATION)
9582         address = get_linespec_location (location);
9583
9584       if (!cursal.symtab
9585           || (address != NULL
9586               && strchr ("+-", address[0]) != NULL
9587               && address[1] != '['))
9588         {
9589           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9590                             get_last_displayed_symtab (),
9591                             get_last_displayed_line (),
9592                             canonical, NULL, NULL);
9593           return;
9594         }
9595     }
9596
9597   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9598                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9599 }
9600
9601
9602 /* Convert each SAL into a real PC.  Verify that the PC can be
9603    inserted as a breakpoint.  If it can't throw an error.  */
9604
9605 static void
9606 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9607 {    
9608   int i;
9609
9610   for (i = 0; i < sals->nelts; i++)
9611     resolve_sal_pc (&sals->sals[i]);
9612 }
9613
9614 /* Fast tracepoints may have restrictions on valid locations.  For
9615    instance, a fast tracepoint using a jump instead of a trap will
9616    likely have to overwrite more bytes than a trap would, and so can
9617    only be placed where the instruction is longer than the jump, or a
9618    multi-instruction sequence does not have a jump into the middle of
9619    it, etc.  */
9620
9621 static void
9622 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9623                             struct symtabs_and_lines *sals)
9624 {
9625   int i, rslt;
9626   struct symtab_and_line *sal;
9627   char *msg;
9628   struct cleanup *old_chain;
9629
9630   for (i = 0; i < sals->nelts; i++)
9631     {
9632       struct gdbarch *sarch;
9633
9634       sal = &sals->sals[i];
9635
9636       sarch = get_sal_arch (*sal);
9637       /* We fall back to GDBARCH if there is no architecture
9638          associated with SAL.  */
9639       if (sarch == NULL)
9640         sarch = gdbarch;
9641       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9642       old_chain = make_cleanup (xfree, msg);
9643
9644       if (!rslt)
9645         error (_("May not have a fast tracepoint at 0x%s%s"),
9646                paddress (sarch, sal->pc), (msg ? msg : ""));
9647
9648       do_cleanups (old_chain);
9649     }
9650 }
9651
9652 /* Given TOK, a string specification of condition and thread, as
9653    accepted by the 'break' command, extract the condition
9654    string and thread number and set *COND_STRING and *THREAD.
9655    PC identifies the context at which the condition should be parsed.
9656    If no condition is found, *COND_STRING is set to NULL.
9657    If no thread is found, *THREAD is set to -1.  */
9658
9659 static void
9660 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9661                            char **cond_string, int *thread, int *task,
9662                            char **rest)
9663 {
9664   *cond_string = NULL;
9665   *thread = -1;
9666   *task = 0;
9667   *rest = NULL;
9668
9669   while (tok && *tok)
9670     {
9671       const char *end_tok;
9672       int toklen;
9673       const char *cond_start = NULL;
9674       const char *cond_end = NULL;
9675
9676       tok = skip_spaces_const (tok);
9677
9678       if ((*tok == '"' || *tok == ',') && rest)
9679         {
9680           *rest = savestring (tok, strlen (tok));
9681           return;
9682         }
9683
9684       end_tok = skip_to_space_const (tok);
9685
9686       toklen = end_tok - tok;
9687
9688       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9689         {
9690           struct expression *expr;
9691
9692           tok = cond_start = end_tok + 1;
9693           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9694           xfree (expr);
9695           cond_end = tok;
9696           *cond_string = savestring (cond_start, cond_end - cond_start);
9697         }
9698       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9699         {
9700           const char *tmptok;
9701           struct thread_info *thr;
9702
9703           tok = end_tok + 1;
9704           thr = parse_thread_id (tok, &tmptok);
9705           if (tok == tmptok)
9706             error (_("Junk after thread keyword."));
9707           *thread = thr->global_num;
9708           tok = tmptok;
9709         }
9710       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9711         {
9712           char *tmptok;
9713
9714           tok = end_tok + 1;
9715           *task = strtol (tok, &tmptok, 0);
9716           if (tok == tmptok)
9717             error (_("Junk after task keyword."));
9718           if (!valid_task_id (*task))
9719             error (_("Unknown task %d."), *task);
9720           tok = tmptok;
9721         }
9722       else if (rest)
9723         {
9724           *rest = savestring (tok, strlen (tok));
9725           return;
9726         }
9727       else
9728         error (_("Junk at end of arguments."));
9729     }
9730 }
9731
9732 /* Decode a static tracepoint marker spec.  */
9733
9734 static struct symtabs_and_lines
9735 decode_static_tracepoint_spec (const char **arg_p)
9736 {
9737   VEC(static_tracepoint_marker_p) *markers = NULL;
9738   struct symtabs_and_lines sals;
9739   struct cleanup *old_chain;
9740   const char *p = &(*arg_p)[3];
9741   const char *endp;
9742   char *marker_str;
9743   int i;
9744
9745   p = skip_spaces_const (p);
9746
9747   endp = skip_to_space_const (p);
9748
9749   marker_str = savestring (p, endp - p);
9750   old_chain = make_cleanup (xfree, marker_str);
9751
9752   markers = target_static_tracepoint_markers_by_strid (marker_str);
9753   if (VEC_empty(static_tracepoint_marker_p, markers))
9754     error (_("No known static tracepoint marker named %s"), marker_str);
9755
9756   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9757   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9758
9759   for (i = 0; i < sals.nelts; i++)
9760     {
9761       struct static_tracepoint_marker *marker;
9762
9763       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9764
9765       init_sal (&sals.sals[i]);
9766
9767       sals.sals[i] = find_pc_line (marker->address, 0);
9768       sals.sals[i].pc = marker->address;
9769
9770       release_static_tracepoint_marker (marker);
9771     }
9772
9773   do_cleanups (old_chain);
9774
9775   *arg_p = endp;
9776   return sals;
9777 }
9778
9779 /* See breakpoint.h.  */
9780
9781 int
9782 create_breakpoint (struct gdbarch *gdbarch,
9783                    const struct event_location *location, char *cond_string,
9784                    int thread, char *extra_string,
9785                    int parse_extra,
9786                    int tempflag, enum bptype type_wanted,
9787                    int ignore_count,
9788                    enum auto_boolean pending_break_support,
9789                    const struct breakpoint_ops *ops,
9790                    int from_tty, int enabled, int internal,
9791                    unsigned flags)
9792 {
9793   struct linespec_result canonical;
9794   struct cleanup *old_chain;
9795   struct cleanup *bkpt_chain = NULL;
9796   int pending = 0;
9797   int task = 0;
9798   int prev_bkpt_count = breakpoint_count;
9799
9800   gdb_assert (ops != NULL);
9801
9802   /* If extra_string isn't useful, set it to NULL.  */
9803   if (extra_string != NULL && *extra_string == '\0')
9804     extra_string = NULL;
9805
9806   init_linespec_result (&canonical);
9807
9808   TRY
9809     {
9810       ops->create_sals_from_location (location, &canonical, type_wanted);
9811     }
9812   CATCH (e, RETURN_MASK_ERROR)
9813     {
9814       /* If caller is interested in rc value from parse, set
9815          value.  */
9816       if (e.error == NOT_FOUND_ERROR)
9817         {
9818           /* If pending breakpoint support is turned off, throw
9819              error.  */
9820
9821           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9822             throw_exception (e);
9823
9824           exception_print (gdb_stderr, e);
9825
9826           /* If pending breakpoint support is auto query and the user
9827              selects no, then simply return the error code.  */
9828           if (pending_break_support == AUTO_BOOLEAN_AUTO
9829               && !nquery (_("Make %s pending on future shared library load? "),
9830                           bptype_string (type_wanted)))
9831             return 0;
9832
9833           /* At this point, either the user was queried about setting
9834              a pending breakpoint and selected yes, or pending
9835              breakpoint behavior is on and thus a pending breakpoint
9836              is defaulted on behalf of the user.  */
9837           pending = 1;
9838         }
9839       else
9840         throw_exception (e);
9841     }
9842   END_CATCH
9843
9844   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9845     return 0;
9846
9847   /* Create a chain of things that always need to be cleaned up.  */
9848   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9849
9850   /* ----------------------------- SNIP -----------------------------
9851      Anything added to the cleanup chain beyond this point is assumed
9852      to be part of a breakpoint.  If the breakpoint create succeeds
9853      then the memory is not reclaimed.  */
9854   bkpt_chain = make_cleanup (null_cleanup, 0);
9855
9856   /* Resolve all line numbers to PC's and verify that the addresses
9857      are ok for the target.  */
9858   if (!pending)
9859     {
9860       int ix;
9861       struct linespec_sals *iter;
9862
9863       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9864         breakpoint_sals_to_pc (&iter->sals);
9865     }
9866
9867   /* Fast tracepoints may have additional restrictions on location.  */
9868   if (!pending && type_wanted == bp_fast_tracepoint)
9869     {
9870       int ix;
9871       struct linespec_sals *iter;
9872
9873       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9874         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9875     }
9876
9877   /* Verify that condition can be parsed, before setting any
9878      breakpoints.  Allocate a separate condition expression for each
9879      breakpoint.  */
9880   if (!pending)
9881     {
9882       if (parse_extra)
9883         {
9884           char *rest;
9885           struct linespec_sals *lsal;
9886
9887           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9888
9889           /* Here we only parse 'arg' to separate condition
9890              from thread number, so parsing in context of first
9891              sal is OK.  When setting the breakpoint we'll
9892              re-parse it in context of each sal.  */
9893
9894           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9895                                      &cond_string, &thread, &task, &rest);
9896           if (cond_string)
9897             make_cleanup (xfree, cond_string);
9898           if (rest)
9899             make_cleanup (xfree, rest);
9900           if (rest)
9901             extra_string = rest;
9902           else
9903             extra_string = NULL;
9904         }
9905       else
9906         {
9907           if (type_wanted != bp_dprintf
9908               && extra_string != NULL && *extra_string != '\0')
9909                 error (_("Garbage '%s' at end of location"), extra_string);
9910
9911           /* Create a private copy of condition string.  */
9912           if (cond_string)
9913             {
9914               cond_string = xstrdup (cond_string);
9915               make_cleanup (xfree, cond_string);
9916             }
9917           /* Create a private copy of any extra string.  */
9918           if (extra_string)
9919             {
9920               extra_string = xstrdup (extra_string);
9921               make_cleanup (xfree, extra_string);
9922             }
9923         }
9924
9925       ops->create_breakpoints_sal (gdbarch, &canonical,
9926                                    cond_string, extra_string, type_wanted,
9927                                    tempflag ? disp_del : disp_donttouch,
9928                                    thread, task, ignore_count, ops,
9929                                    from_tty, enabled, internal, flags);
9930     }
9931   else
9932     {
9933       struct breakpoint *b;
9934
9935       if (is_tracepoint_type (type_wanted))
9936         {
9937           struct tracepoint *t;
9938
9939           t = XCNEW (struct tracepoint);
9940           b = &t->base;
9941         }
9942       else
9943         b = XNEW (struct breakpoint);
9944
9945       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9946       b->location = copy_event_location (location);
9947
9948       if (parse_extra)
9949         b->cond_string = NULL;
9950       else
9951         {
9952           /* Create a private copy of condition string.  */
9953           if (cond_string)
9954             {
9955               cond_string = xstrdup (cond_string);
9956               make_cleanup (xfree, cond_string);
9957             }
9958           b->cond_string = cond_string;
9959           b->thread = thread;
9960         }
9961
9962       /* Create a private copy of any extra string.  */
9963       if (extra_string != NULL)
9964         {
9965           extra_string = xstrdup (extra_string);
9966           make_cleanup (xfree, extra_string);
9967         }
9968       b->extra_string = extra_string;
9969       b->ignore_count = ignore_count;
9970       b->disposition = tempflag ? disp_del : disp_donttouch;
9971       b->condition_not_parsed = 1;
9972       b->enable_state = enabled ? bp_enabled : bp_disabled;
9973       if ((type_wanted != bp_breakpoint
9974            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9975         b->pspace = current_program_space;
9976
9977       install_breakpoint (internal, b, 0);
9978     }
9979   
9980   if (VEC_length (linespec_sals, canonical.sals) > 1)
9981     {
9982       warning (_("Multiple breakpoints were set.\nUse the "
9983                  "\"delete\" command to delete unwanted breakpoints."));
9984       prev_breakpoint_count = prev_bkpt_count;
9985     }
9986
9987   /* That's it.  Discard the cleanups for data inserted into the
9988      breakpoint.  */
9989   discard_cleanups (bkpt_chain);
9990   /* But cleanup everything else.  */
9991   do_cleanups (old_chain);
9992
9993   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9994   update_global_location_list (UGLL_MAY_INSERT);
9995
9996   return 1;
9997 }
9998
9999 /* Set a breakpoint.
10000    ARG is a string describing breakpoint address,
10001    condition, and thread.
10002    FLAG specifies if a breakpoint is hardware on,
10003    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10004    and BP_TEMPFLAG.  */
10005
10006 static void
10007 break_command_1 (char *arg, int flag, int from_tty)
10008 {
10009   int tempflag = flag & BP_TEMPFLAG;
10010   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10011                              ? bp_hardware_breakpoint
10012                              : bp_breakpoint);
10013   struct breakpoint_ops *ops;
10014   struct event_location *location;
10015   struct cleanup *cleanup;
10016
10017   location = string_to_event_location (&arg, current_language);
10018   cleanup = make_cleanup_delete_event_location (location);
10019
10020   /* Matching breakpoints on probes.  */
10021   if (location != NULL
10022       && event_location_type (location) == PROBE_LOCATION)
10023     ops = &bkpt_probe_breakpoint_ops;
10024   else
10025     ops = &bkpt_breakpoint_ops;
10026
10027   create_breakpoint (get_current_arch (),
10028                      location,
10029                      NULL, 0, arg, 1 /* parse arg */,
10030                      tempflag, type_wanted,
10031                      0 /* Ignore count */,
10032                      pending_break_support,
10033                      ops,
10034                      from_tty,
10035                      1 /* enabled */,
10036                      0 /* internal */,
10037                      0);
10038   do_cleanups (cleanup);
10039 }
10040
10041 /* Helper function for break_command_1 and disassemble_command.  */
10042
10043 void
10044 resolve_sal_pc (struct symtab_and_line *sal)
10045 {
10046   CORE_ADDR pc;
10047
10048   if (sal->pc == 0 && sal->symtab != NULL)
10049     {
10050       if (!find_line_pc (sal->symtab, sal->line, &pc))
10051         error (_("No line %d in file \"%s\"."),
10052                sal->line, symtab_to_filename_for_display (sal->symtab));
10053       sal->pc = pc;
10054
10055       /* If this SAL corresponds to a breakpoint inserted using a line
10056          number, then skip the function prologue if necessary.  */
10057       if (sal->explicit_line)
10058         skip_prologue_sal (sal);
10059     }
10060
10061   if (sal->section == 0 && sal->symtab != NULL)
10062     {
10063       const struct blockvector *bv;
10064       const struct block *b;
10065       struct symbol *sym;
10066
10067       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
10068                                     SYMTAB_COMPUNIT (sal->symtab));
10069       if (bv != NULL)
10070         {
10071           sym = block_linkage_function (b);
10072           if (sym != NULL)
10073             {
10074               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
10075               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
10076                                                  sym);
10077             }
10078           else
10079             {
10080               /* It really is worthwhile to have the section, so we'll
10081                  just have to look harder. This case can be executed
10082                  if we have line numbers but no functions (as can
10083                  happen in assembly source).  */
10084
10085               struct bound_minimal_symbol msym;
10086               struct cleanup *old_chain = save_current_space_and_thread ();
10087
10088               switch_to_program_space_and_thread (sal->pspace);
10089
10090               msym = lookup_minimal_symbol_by_pc (sal->pc);
10091               if (msym.minsym)
10092                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10093
10094               do_cleanups (old_chain);
10095             }
10096         }
10097     }
10098 }
10099
10100 void
10101 break_command (char *arg, int from_tty)
10102 {
10103   break_command_1 (arg, 0, from_tty);
10104 }
10105
10106 void
10107 tbreak_command (char *arg, int from_tty)
10108 {
10109   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10110 }
10111
10112 static void
10113 hbreak_command (char *arg, int from_tty)
10114 {
10115   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10116 }
10117
10118 static void
10119 thbreak_command (char *arg, int from_tty)
10120 {
10121   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10122 }
10123
10124 static void
10125 stop_command (char *arg, int from_tty)
10126 {
10127   printf_filtered (_("Specify the type of breakpoint to set.\n\
10128 Usage: stop in <function | address>\n\
10129        stop at <line>\n"));
10130 }
10131
10132 static void
10133 stopin_command (char *arg, int from_tty)
10134 {
10135   int badInput = 0;
10136
10137   if (arg == (char *) NULL)
10138     badInput = 1;
10139   else if (*arg != '*')
10140     {
10141       char *argptr = arg;
10142       int hasColon = 0;
10143
10144       /* Look for a ':'.  If this is a line number specification, then
10145          say it is bad, otherwise, it should be an address or
10146          function/method name.  */
10147       while (*argptr && !hasColon)
10148         {
10149           hasColon = (*argptr == ':');
10150           argptr++;
10151         }
10152
10153       if (hasColon)
10154         badInput = (*argptr != ':');    /* Not a class::method */
10155       else
10156         badInput = isdigit (*arg);      /* a simple line number */
10157     }
10158
10159   if (badInput)
10160     printf_filtered (_("Usage: stop in <function | address>\n"));
10161   else
10162     break_command_1 (arg, 0, from_tty);
10163 }
10164
10165 static void
10166 stopat_command (char *arg, int from_tty)
10167 {
10168   int badInput = 0;
10169
10170   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10171     badInput = 1;
10172   else
10173     {
10174       char *argptr = arg;
10175       int hasColon = 0;
10176
10177       /* Look for a ':'.  If there is a '::' then get out, otherwise
10178          it is probably a line number.  */
10179       while (*argptr && !hasColon)
10180         {
10181           hasColon = (*argptr == ':');
10182           argptr++;
10183         }
10184
10185       if (hasColon)
10186         badInput = (*argptr == ':');    /* we have class::method */
10187       else
10188         badInput = !isdigit (*arg);     /* not a line number */
10189     }
10190
10191   if (badInput)
10192     printf_filtered (_("Usage: stop at <line>\n"));
10193   else
10194     break_command_1 (arg, 0, from_tty);
10195 }
10196
10197 /* The dynamic printf command is mostly like a regular breakpoint, but
10198    with a prewired command list consisting of a single output command,
10199    built from extra arguments supplied on the dprintf command
10200    line.  */
10201
10202 static void
10203 dprintf_command (char *arg, int from_tty)
10204 {
10205   struct event_location *location;
10206   struct cleanup *cleanup;
10207
10208   location = string_to_event_location (&arg, current_language);
10209   cleanup = make_cleanup_delete_event_location (location);
10210
10211   /* If non-NULL, ARG should have been advanced past the location;
10212      the next character must be ','.  */
10213   if (arg != NULL)
10214     {
10215       if (arg[0] != ',' || arg[1] == '\0')
10216         error (_("Format string required"));
10217       else
10218         {
10219           /* Skip the comma.  */
10220           ++arg;
10221         }
10222     }
10223
10224   create_breakpoint (get_current_arch (),
10225                      location,
10226                      NULL, 0, arg, 1 /* parse arg */,
10227                      0, bp_dprintf,
10228                      0 /* Ignore count */,
10229                      pending_break_support,
10230                      &dprintf_breakpoint_ops,
10231                      from_tty,
10232                      1 /* enabled */,
10233                      0 /* internal */,
10234                      0);
10235   do_cleanups (cleanup);
10236 }
10237
10238 static void
10239 agent_printf_command (char *arg, int from_tty)
10240 {
10241   error (_("May only run agent-printf on the target"));
10242 }
10243
10244 /* Implement the "breakpoint_hit" breakpoint_ops method for
10245    ranged breakpoints.  */
10246
10247 static int
10248 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10249                                   struct address_space *aspace,
10250                                   CORE_ADDR bp_addr,
10251                                   const struct target_waitstatus *ws)
10252 {
10253   if (ws->kind != TARGET_WAITKIND_STOPPED
10254       || ws->value.sig != GDB_SIGNAL_TRAP)
10255     return 0;
10256
10257   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10258                                          bl->length, aspace, bp_addr);
10259 }
10260
10261 /* Implement the "resources_needed" breakpoint_ops method for
10262    ranged breakpoints.  */
10263
10264 static int
10265 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10266 {
10267   return target_ranged_break_num_registers ();
10268 }
10269
10270 /* Implement the "print_it" breakpoint_ops method for
10271    ranged breakpoints.  */
10272
10273 static enum print_stop_action
10274 print_it_ranged_breakpoint (bpstat bs)
10275 {
10276   struct breakpoint *b = bs->breakpoint_at;
10277   struct bp_location *bl = b->loc;
10278   struct ui_out *uiout = current_uiout;
10279
10280   gdb_assert (b->type == bp_hardware_breakpoint);
10281
10282   /* Ranged breakpoints have only one location.  */
10283   gdb_assert (bl && bl->next == NULL);
10284
10285   annotate_breakpoint (b->number);
10286
10287   maybe_print_thread_hit_breakpoint (uiout);
10288
10289   if (b->disposition == disp_del)
10290     ui_out_text (uiout, "Temporary ranged breakpoint ");
10291   else
10292     ui_out_text (uiout, "Ranged breakpoint ");
10293   if (ui_out_is_mi_like_p (uiout))
10294     {
10295       ui_out_field_string (uiout, "reason",
10296                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10297       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10298     }
10299   ui_out_field_int (uiout, "bkptno", b->number);
10300   ui_out_text (uiout, ", ");
10301
10302   return PRINT_SRC_AND_LOC;
10303 }
10304
10305 /* Implement the "print_one" breakpoint_ops method for
10306    ranged breakpoints.  */
10307
10308 static void
10309 print_one_ranged_breakpoint (struct breakpoint *b,
10310                              struct bp_location **last_loc)
10311 {
10312   struct bp_location *bl = b->loc;
10313   struct value_print_options opts;
10314   struct ui_out *uiout = current_uiout;
10315
10316   /* Ranged breakpoints have only one location.  */
10317   gdb_assert (bl && bl->next == NULL);
10318
10319   get_user_print_options (&opts);
10320
10321   if (opts.addressprint)
10322     /* We don't print the address range here, it will be printed later
10323        by print_one_detail_ranged_breakpoint.  */
10324     ui_out_field_skip (uiout, "addr");
10325   annotate_field (5);
10326   print_breakpoint_location (b, bl);
10327   *last_loc = bl;
10328 }
10329
10330 /* Implement the "print_one_detail" breakpoint_ops method for
10331    ranged breakpoints.  */
10332
10333 static void
10334 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10335                                     struct ui_out *uiout)
10336 {
10337   CORE_ADDR address_start, address_end;
10338   struct bp_location *bl = b->loc;
10339   struct ui_file *stb = mem_fileopen ();
10340   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10341
10342   gdb_assert (bl);
10343
10344   address_start = bl->address;
10345   address_end = address_start + bl->length - 1;
10346
10347   ui_out_text (uiout, "\taddress range: ");
10348   fprintf_unfiltered (stb, "[%s, %s]",
10349                       print_core_address (bl->gdbarch, address_start),
10350                       print_core_address (bl->gdbarch, address_end));
10351   ui_out_field_stream (uiout, "addr", stb);
10352   ui_out_text (uiout, "\n");
10353
10354   do_cleanups (cleanup);
10355 }
10356
10357 /* Implement the "print_mention" breakpoint_ops method for
10358    ranged breakpoints.  */
10359
10360 static void
10361 print_mention_ranged_breakpoint (struct breakpoint *b)
10362 {
10363   struct bp_location *bl = b->loc;
10364   struct ui_out *uiout = current_uiout;
10365
10366   gdb_assert (bl);
10367   gdb_assert (b->type == bp_hardware_breakpoint);
10368
10369   if (ui_out_is_mi_like_p (uiout))
10370     return;
10371
10372   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10373                    b->number, paddress (bl->gdbarch, bl->address),
10374                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10375 }
10376
10377 /* Implement the "print_recreate" breakpoint_ops method for
10378    ranged breakpoints.  */
10379
10380 static void
10381 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10382 {
10383   fprintf_unfiltered (fp, "break-range %s, %s",
10384                       event_location_to_string (b->location),
10385                       event_location_to_string (b->location_range_end));
10386   print_recreate_thread (b, fp);
10387 }
10388
10389 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10390
10391 static struct breakpoint_ops ranged_breakpoint_ops;
10392
10393 /* Find the address where the end of the breakpoint range should be
10394    placed, given the SAL of the end of the range.  This is so that if
10395    the user provides a line number, the end of the range is set to the
10396    last instruction of the given line.  */
10397
10398 static CORE_ADDR
10399 find_breakpoint_range_end (struct symtab_and_line sal)
10400 {
10401   CORE_ADDR end;
10402
10403   /* If the user provided a PC value, use it.  Otherwise,
10404      find the address of the end of the given location.  */
10405   if (sal.explicit_pc)
10406     end = sal.pc;
10407   else
10408     {
10409       int ret;
10410       CORE_ADDR start;
10411
10412       ret = find_line_pc_range (sal, &start, &end);
10413       if (!ret)
10414         error (_("Could not find location of the end of the range."));
10415
10416       /* find_line_pc_range returns the start of the next line.  */
10417       end--;
10418     }
10419
10420   return end;
10421 }
10422
10423 /* Implement the "break-range" CLI command.  */
10424
10425 static void
10426 break_range_command (char *arg, int from_tty)
10427 {
10428   char *arg_start, *addr_string_start;
10429   struct linespec_result canonical_start, canonical_end;
10430   int bp_count, can_use_bp, length;
10431   CORE_ADDR end;
10432   struct breakpoint *b;
10433   struct symtab_and_line sal_start, sal_end;
10434   struct cleanup *cleanup_bkpt;
10435   struct linespec_sals *lsal_start, *lsal_end;
10436   struct event_location *start_location, *end_location;
10437
10438   /* We don't support software ranged breakpoints.  */
10439   if (target_ranged_break_num_registers () < 0)
10440     error (_("This target does not support hardware ranged breakpoints."));
10441
10442   bp_count = hw_breakpoint_used_count ();
10443   bp_count += target_ranged_break_num_registers ();
10444   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10445                                                    bp_count, 0);
10446   if (can_use_bp < 0)
10447     error (_("Hardware breakpoints used exceeds limit."));
10448
10449   arg = skip_spaces (arg);
10450   if (arg == NULL || arg[0] == '\0')
10451     error(_("No address range specified."));
10452
10453   init_linespec_result (&canonical_start);
10454
10455   arg_start = arg;
10456   start_location = string_to_event_location (&arg, current_language);
10457   cleanup_bkpt = make_cleanup_delete_event_location (start_location);
10458   parse_breakpoint_sals (start_location, &canonical_start);
10459   make_cleanup_destroy_linespec_result (&canonical_start);
10460
10461   if (arg[0] != ',')
10462     error (_("Too few arguments."));
10463   else if (VEC_empty (linespec_sals, canonical_start.sals))
10464     error (_("Could not find location of the beginning of the range."));
10465
10466   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10467
10468   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10469       || lsal_start->sals.nelts != 1)
10470     error (_("Cannot create a ranged breakpoint with multiple locations."));
10471
10472   sal_start = lsal_start->sals.sals[0];
10473   addr_string_start = savestring (arg_start, arg - arg_start);
10474   make_cleanup (xfree, addr_string_start);
10475
10476   arg++;        /* Skip the comma.  */
10477   arg = skip_spaces (arg);
10478
10479   /* Parse the end location.  */
10480
10481   init_linespec_result (&canonical_end);
10482   arg_start = arg;
10483
10484   /* We call decode_line_full directly here instead of using
10485      parse_breakpoint_sals because we need to specify the start location's
10486      symtab and line as the default symtab and line for the end of the
10487      range.  This makes it possible to have ranges like "foo.c:27, +14",
10488      where +14 means 14 lines from the start location.  */
10489   end_location = string_to_event_location (&arg, current_language);
10490   make_cleanup_delete_event_location (end_location);
10491   decode_line_full (end_location, DECODE_LINE_FUNFIRSTLINE, NULL,
10492                     sal_start.symtab, sal_start.line,
10493                     &canonical_end, NULL, NULL);
10494
10495   make_cleanup_destroy_linespec_result (&canonical_end);
10496
10497   if (VEC_empty (linespec_sals, canonical_end.sals))
10498     error (_("Could not find location of the end of the range."));
10499
10500   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10501   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10502       || lsal_end->sals.nelts != 1)
10503     error (_("Cannot create a ranged breakpoint with multiple locations."));
10504
10505   sal_end = lsal_end->sals.sals[0];
10506
10507   end = find_breakpoint_range_end (sal_end);
10508   if (sal_start.pc > end)
10509     error (_("Invalid address range, end precedes start."));
10510
10511   length = end - sal_start.pc + 1;
10512   if (length < 0)
10513     /* Length overflowed.  */
10514     error (_("Address range too large."));
10515   else if (length == 1)
10516     {
10517       /* This range is simple enough to be handled by
10518          the `hbreak' command.  */
10519       hbreak_command (addr_string_start, 1);
10520
10521       do_cleanups (cleanup_bkpt);
10522
10523       return;
10524     }
10525
10526   /* Now set up the breakpoint.  */
10527   b = set_raw_breakpoint (get_current_arch (), sal_start,
10528                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10529   set_breakpoint_count (breakpoint_count + 1);
10530   b->number = breakpoint_count;
10531   b->disposition = disp_donttouch;
10532   b->location = copy_event_location (start_location);
10533   b->location_range_end = copy_event_location (end_location);
10534   b->loc->length = length;
10535
10536   do_cleanups (cleanup_bkpt);
10537
10538   mention (b);
10539   observer_notify_breakpoint_created (b);
10540   update_global_location_list (UGLL_MAY_INSERT);
10541 }
10542
10543 /*  Return non-zero if EXP is verified as constant.  Returned zero
10544     means EXP is variable.  Also the constant detection may fail for
10545     some constant expressions and in such case still falsely return
10546     zero.  */
10547
10548 static int
10549 watchpoint_exp_is_const (const struct expression *exp)
10550 {
10551   int i = exp->nelts;
10552
10553   while (i > 0)
10554     {
10555       int oplenp, argsp;
10556
10557       /* We are only interested in the descriptor of each element.  */
10558       operator_length (exp, i, &oplenp, &argsp);
10559       i -= oplenp;
10560
10561       switch (exp->elts[i].opcode)
10562         {
10563         case BINOP_ADD:
10564         case BINOP_SUB:
10565         case BINOP_MUL:
10566         case BINOP_DIV:
10567         case BINOP_REM:
10568         case BINOP_MOD:
10569         case BINOP_LSH:
10570         case BINOP_RSH:
10571         case BINOP_LOGICAL_AND:
10572         case BINOP_LOGICAL_OR:
10573         case BINOP_BITWISE_AND:
10574         case BINOP_BITWISE_IOR:
10575         case BINOP_BITWISE_XOR:
10576         case BINOP_EQUAL:
10577         case BINOP_NOTEQUAL:
10578         case BINOP_LESS:
10579         case BINOP_GTR:
10580         case BINOP_LEQ:
10581         case BINOP_GEQ:
10582         case BINOP_REPEAT:
10583         case BINOP_COMMA:
10584         case BINOP_EXP:
10585         case BINOP_MIN:
10586         case BINOP_MAX:
10587         case BINOP_INTDIV:
10588         case BINOP_CONCAT:
10589         case TERNOP_COND:
10590         case TERNOP_SLICE:
10591
10592         case OP_LONG:
10593         case OP_DOUBLE:
10594         case OP_DECFLOAT:
10595         case OP_LAST:
10596         case OP_COMPLEX:
10597         case OP_STRING:
10598         case OP_ARRAY:
10599         case OP_TYPE:
10600         case OP_TYPEOF:
10601         case OP_DECLTYPE:
10602         case OP_TYPEID:
10603         case OP_NAME:
10604         case OP_OBJC_NSSTRING:
10605
10606         case UNOP_NEG:
10607         case UNOP_LOGICAL_NOT:
10608         case UNOP_COMPLEMENT:
10609         case UNOP_ADDR:
10610         case UNOP_HIGH:
10611         case UNOP_CAST:
10612
10613         case UNOP_CAST_TYPE:
10614         case UNOP_REINTERPRET_CAST:
10615         case UNOP_DYNAMIC_CAST:
10616           /* Unary, binary and ternary operators: We have to check
10617              their operands.  If they are constant, then so is the
10618              result of that operation.  For instance, if A and B are
10619              determined to be constants, then so is "A + B".
10620
10621              UNOP_IND is one exception to the rule above, because the
10622              value of *ADDR is not necessarily a constant, even when
10623              ADDR is.  */
10624           break;
10625
10626         case OP_VAR_VALUE:
10627           /* Check whether the associated symbol is a constant.
10628
10629              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10630              possible that a buggy compiler could mark a variable as
10631              constant even when it is not, and TYPE_CONST would return
10632              true in this case, while SYMBOL_CLASS wouldn't.
10633
10634              We also have to check for function symbols because they
10635              are always constant.  */
10636           {
10637             struct symbol *s = exp->elts[i + 2].symbol;
10638
10639             if (SYMBOL_CLASS (s) != LOC_BLOCK
10640                 && SYMBOL_CLASS (s) != LOC_CONST
10641                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10642               return 0;
10643             break;
10644           }
10645
10646         /* The default action is to return 0 because we are using
10647            the optimistic approach here: If we don't know something,
10648            then it is not a constant.  */
10649         default:
10650           return 0;
10651         }
10652     }
10653
10654   return 1;
10655 }
10656
10657 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10658
10659 static void
10660 dtor_watchpoint (struct breakpoint *self)
10661 {
10662   struct watchpoint *w = (struct watchpoint *) self;
10663
10664   xfree (w->cond_exp);
10665   xfree (w->exp);
10666   xfree (w->exp_string);
10667   xfree (w->exp_string_reparse);
10668   value_free (w->val);
10669
10670   base_breakpoint_ops.dtor (self);
10671 }
10672
10673 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10674
10675 static void
10676 re_set_watchpoint (struct breakpoint *b)
10677 {
10678   struct watchpoint *w = (struct watchpoint *) b;
10679
10680   /* Watchpoint can be either on expression using entirely global
10681      variables, or it can be on local variables.
10682
10683      Watchpoints of the first kind are never auto-deleted, and even
10684      persist across program restarts.  Since they can use variables
10685      from shared libraries, we need to reparse expression as libraries
10686      are loaded and unloaded.
10687
10688      Watchpoints on local variables can also change meaning as result
10689      of solib event.  For example, if a watchpoint uses both a local
10690      and a global variables in expression, it's a local watchpoint,
10691      but unloading of a shared library will make the expression
10692      invalid.  This is not a very common use case, but we still
10693      re-evaluate expression, to avoid surprises to the user.
10694
10695      Note that for local watchpoints, we re-evaluate it only if
10696      watchpoints frame id is still valid.  If it's not, it means the
10697      watchpoint is out of scope and will be deleted soon.  In fact,
10698      I'm not sure we'll ever be called in this case.
10699
10700      If a local watchpoint's frame id is still valid, then
10701      w->exp_valid_block is likewise valid, and we can safely use it.
10702
10703      Don't do anything about disabled watchpoints, since they will be
10704      reevaluated again when enabled.  */
10705   update_watchpoint (w, 1 /* reparse */);
10706 }
10707
10708 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10709
10710 static int
10711 insert_watchpoint (struct bp_location *bl)
10712 {
10713   struct watchpoint *w = (struct watchpoint *) bl->owner;
10714   int length = w->exact ? 1 : bl->length;
10715
10716   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10717                                    w->cond_exp);
10718 }
10719
10720 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10721
10722 static int
10723 remove_watchpoint (struct bp_location *bl)
10724 {
10725   struct watchpoint *w = (struct watchpoint *) bl->owner;
10726   int length = w->exact ? 1 : bl->length;
10727
10728   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10729                                    w->cond_exp);
10730 }
10731
10732 static int
10733 breakpoint_hit_watchpoint (const struct bp_location *bl,
10734                            struct address_space *aspace, CORE_ADDR bp_addr,
10735                            const struct target_waitstatus *ws)
10736 {
10737   struct breakpoint *b = bl->owner;
10738   struct watchpoint *w = (struct watchpoint *) b;
10739
10740   /* Continuable hardware watchpoints are treated as non-existent if the
10741      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10742      some data address).  Otherwise gdb won't stop on a break instruction
10743      in the code (not from a breakpoint) when a hardware watchpoint has
10744      been defined.  Also skip watchpoints which we know did not trigger
10745      (did not match the data address).  */
10746   if (is_hardware_watchpoint (b)
10747       && w->watchpoint_triggered == watch_triggered_no)
10748     return 0;
10749
10750   return 1;
10751 }
10752
10753 static void
10754 check_status_watchpoint (bpstat bs)
10755 {
10756   gdb_assert (is_watchpoint (bs->breakpoint_at));
10757
10758   bpstat_check_watchpoint (bs);
10759 }
10760
10761 /* Implement the "resources_needed" breakpoint_ops method for
10762    hardware watchpoints.  */
10763
10764 static int
10765 resources_needed_watchpoint (const struct bp_location *bl)
10766 {
10767   struct watchpoint *w = (struct watchpoint *) bl->owner;
10768   int length = w->exact? 1 : bl->length;
10769
10770   return target_region_ok_for_hw_watchpoint (bl->address, length);
10771 }
10772
10773 /* Implement the "works_in_software_mode" breakpoint_ops method for
10774    hardware watchpoints.  */
10775
10776 static int
10777 works_in_software_mode_watchpoint (const struct breakpoint *b)
10778 {
10779   /* Read and access watchpoints only work with hardware support.  */
10780   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10781 }
10782
10783 static enum print_stop_action
10784 print_it_watchpoint (bpstat bs)
10785 {
10786   struct cleanup *old_chain;
10787   struct breakpoint *b;
10788   struct ui_file *stb;
10789   enum print_stop_action result;
10790   struct watchpoint *w;
10791   struct ui_out *uiout = current_uiout;
10792
10793   gdb_assert (bs->bp_location_at != NULL);
10794
10795   b = bs->breakpoint_at;
10796   w = (struct watchpoint *) b;
10797
10798   stb = mem_fileopen ();
10799   old_chain = make_cleanup_ui_file_delete (stb);
10800
10801   annotate_watchpoint (b->number);
10802   maybe_print_thread_hit_breakpoint (uiout);
10803
10804   switch (b->type)
10805     {
10806     case bp_watchpoint:
10807     case bp_hardware_watchpoint:
10808       if (ui_out_is_mi_like_p (uiout))
10809         ui_out_field_string
10810           (uiout, "reason",
10811            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10812       mention (b);
10813       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10814       ui_out_text (uiout, "\nOld value = ");
10815       watchpoint_value_print (bs->old_val, stb);
10816       ui_out_field_stream (uiout, "old", stb);
10817       ui_out_text (uiout, "\nNew value = ");
10818       watchpoint_value_print (w->val, stb);
10819       ui_out_field_stream (uiout, "new", stb);
10820       ui_out_text (uiout, "\n");
10821       /* More than one watchpoint may have been triggered.  */
10822       result = PRINT_UNKNOWN;
10823       break;
10824
10825     case bp_read_watchpoint:
10826       if (ui_out_is_mi_like_p (uiout))
10827         ui_out_field_string
10828           (uiout, "reason",
10829            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10830       mention (b);
10831       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10832       ui_out_text (uiout, "\nValue = ");
10833       watchpoint_value_print (w->val, stb);
10834       ui_out_field_stream (uiout, "value", stb);
10835       ui_out_text (uiout, "\n");
10836       result = PRINT_UNKNOWN;
10837       break;
10838
10839     case bp_access_watchpoint:
10840       if (bs->old_val != NULL)
10841         {
10842           if (ui_out_is_mi_like_p (uiout))
10843             ui_out_field_string
10844               (uiout, "reason",
10845                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10846           mention (b);
10847           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10848           ui_out_text (uiout, "\nOld value = ");
10849           watchpoint_value_print (bs->old_val, stb);
10850           ui_out_field_stream (uiout, "old", stb);
10851           ui_out_text (uiout, "\nNew value = ");
10852         }
10853       else
10854         {
10855           mention (b);
10856           if (ui_out_is_mi_like_p (uiout))
10857             ui_out_field_string
10858               (uiout, "reason",
10859                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10860           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10861           ui_out_text (uiout, "\nValue = ");
10862         }
10863       watchpoint_value_print (w->val, stb);
10864       ui_out_field_stream (uiout, "new", stb);
10865       ui_out_text (uiout, "\n");
10866       result = PRINT_UNKNOWN;
10867       break;
10868     default:
10869       result = PRINT_UNKNOWN;
10870     }
10871
10872   do_cleanups (old_chain);
10873   return result;
10874 }
10875
10876 /* Implement the "print_mention" breakpoint_ops method for hardware
10877    watchpoints.  */
10878
10879 static void
10880 print_mention_watchpoint (struct breakpoint *b)
10881 {
10882   struct cleanup *ui_out_chain;
10883   struct watchpoint *w = (struct watchpoint *) b;
10884   struct ui_out *uiout = current_uiout;
10885
10886   switch (b->type)
10887     {
10888     case bp_watchpoint:
10889       ui_out_text (uiout, "Watchpoint ");
10890       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10891       break;
10892     case bp_hardware_watchpoint:
10893       ui_out_text (uiout, "Hardware watchpoint ");
10894       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10895       break;
10896     case bp_read_watchpoint:
10897       ui_out_text (uiout, "Hardware read watchpoint ");
10898       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10899       break;
10900     case bp_access_watchpoint:
10901       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10902       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10903       break;
10904     default:
10905       internal_error (__FILE__, __LINE__,
10906                       _("Invalid hardware watchpoint type."));
10907     }
10908
10909   ui_out_field_int (uiout, "number", b->number);
10910   ui_out_text (uiout, ": ");
10911   ui_out_field_string (uiout, "exp", w->exp_string);
10912   do_cleanups (ui_out_chain);
10913 }
10914
10915 /* Implement the "print_recreate" breakpoint_ops method for
10916    watchpoints.  */
10917
10918 static void
10919 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10920 {
10921   struct watchpoint *w = (struct watchpoint *) b;
10922
10923   switch (b->type)
10924     {
10925     case bp_watchpoint:
10926     case bp_hardware_watchpoint:
10927       fprintf_unfiltered (fp, "watch");
10928       break;
10929     case bp_read_watchpoint:
10930       fprintf_unfiltered (fp, "rwatch");
10931       break;
10932     case bp_access_watchpoint:
10933       fprintf_unfiltered (fp, "awatch");
10934       break;
10935     default:
10936       internal_error (__FILE__, __LINE__,
10937                       _("Invalid watchpoint type."));
10938     }
10939
10940   fprintf_unfiltered (fp, " %s", w->exp_string);
10941   print_recreate_thread (b, fp);
10942 }
10943
10944 /* Implement the "explains_signal" breakpoint_ops method for
10945    watchpoints.  */
10946
10947 static int
10948 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10949 {
10950   /* A software watchpoint cannot cause a signal other than
10951      GDB_SIGNAL_TRAP.  */
10952   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10953     return 0;
10954
10955   return 1;
10956 }
10957
10958 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10959
10960 static struct breakpoint_ops watchpoint_breakpoint_ops;
10961
10962 /* Implement the "insert" breakpoint_ops method for
10963    masked hardware watchpoints.  */
10964
10965 static int
10966 insert_masked_watchpoint (struct bp_location *bl)
10967 {
10968   struct watchpoint *w = (struct watchpoint *) bl->owner;
10969
10970   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10971                                         bl->watchpoint_type);
10972 }
10973
10974 /* Implement the "remove" breakpoint_ops method for
10975    masked hardware watchpoints.  */
10976
10977 static int
10978 remove_masked_watchpoint (struct bp_location *bl)
10979 {
10980   struct watchpoint *w = (struct watchpoint *) bl->owner;
10981
10982   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10983                                         bl->watchpoint_type);
10984 }
10985
10986 /* Implement the "resources_needed" breakpoint_ops method for
10987    masked hardware watchpoints.  */
10988
10989 static int
10990 resources_needed_masked_watchpoint (const struct bp_location *bl)
10991 {
10992   struct watchpoint *w = (struct watchpoint *) bl->owner;
10993
10994   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10995 }
10996
10997 /* Implement the "works_in_software_mode" breakpoint_ops method for
10998    masked hardware watchpoints.  */
10999
11000 static int
11001 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11002 {
11003   return 0;
11004 }
11005
11006 /* Implement the "print_it" breakpoint_ops method for
11007    masked hardware watchpoints.  */
11008
11009 static enum print_stop_action
11010 print_it_masked_watchpoint (bpstat bs)
11011 {
11012   struct breakpoint *b = bs->breakpoint_at;
11013   struct ui_out *uiout = current_uiout;
11014
11015   /* Masked watchpoints have only one location.  */
11016   gdb_assert (b->loc && b->loc->next == NULL);
11017
11018   annotate_watchpoint (b->number);
11019   maybe_print_thread_hit_breakpoint (uiout);
11020
11021   switch (b->type)
11022     {
11023     case bp_hardware_watchpoint:
11024       if (ui_out_is_mi_like_p (uiout))
11025         ui_out_field_string
11026           (uiout, "reason",
11027            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11028       break;
11029
11030     case bp_read_watchpoint:
11031       if (ui_out_is_mi_like_p (uiout))
11032         ui_out_field_string
11033           (uiout, "reason",
11034            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11035       break;
11036
11037     case bp_access_watchpoint:
11038       if (ui_out_is_mi_like_p (uiout))
11039         ui_out_field_string
11040           (uiout, "reason",
11041            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11042       break;
11043     default:
11044       internal_error (__FILE__, __LINE__,
11045                       _("Invalid hardware watchpoint type."));
11046     }
11047
11048   mention (b);
11049   ui_out_text (uiout, _("\n\
11050 Check the underlying instruction at PC for the memory\n\
11051 address and value which triggered this watchpoint.\n"));
11052   ui_out_text (uiout, "\n");
11053
11054   /* More than one watchpoint may have been triggered.  */
11055   return PRINT_UNKNOWN;
11056 }
11057
11058 /* Implement the "print_one_detail" breakpoint_ops method for
11059    masked hardware watchpoints.  */
11060
11061 static void
11062 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11063                                     struct ui_out *uiout)
11064 {
11065   struct watchpoint *w = (struct watchpoint *) b;
11066
11067   /* Masked watchpoints have only one location.  */
11068   gdb_assert (b->loc && b->loc->next == NULL);
11069
11070   ui_out_text (uiout, "\tmask ");
11071   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11072   ui_out_text (uiout, "\n");
11073 }
11074
11075 /* Implement the "print_mention" breakpoint_ops method for
11076    masked hardware watchpoints.  */
11077
11078 static void
11079 print_mention_masked_watchpoint (struct breakpoint *b)
11080 {
11081   struct watchpoint *w = (struct watchpoint *) b;
11082   struct ui_out *uiout = current_uiout;
11083   struct cleanup *ui_out_chain;
11084
11085   switch (b->type)
11086     {
11087     case bp_hardware_watchpoint:
11088       ui_out_text (uiout, "Masked hardware watchpoint ");
11089       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11090       break;
11091     case bp_read_watchpoint:
11092       ui_out_text (uiout, "Masked hardware read watchpoint ");
11093       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11094       break;
11095     case bp_access_watchpoint:
11096       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11097       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11098       break;
11099     default:
11100       internal_error (__FILE__, __LINE__,
11101                       _("Invalid hardware watchpoint type."));
11102     }
11103
11104   ui_out_field_int (uiout, "number", b->number);
11105   ui_out_text (uiout, ": ");
11106   ui_out_field_string (uiout, "exp", w->exp_string);
11107   do_cleanups (ui_out_chain);
11108 }
11109
11110 /* Implement the "print_recreate" breakpoint_ops method for
11111    masked hardware watchpoints.  */
11112
11113 static void
11114 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11115 {
11116   struct watchpoint *w = (struct watchpoint *) b;
11117   char tmp[40];
11118
11119   switch (b->type)
11120     {
11121     case bp_hardware_watchpoint:
11122       fprintf_unfiltered (fp, "watch");
11123       break;
11124     case bp_read_watchpoint:
11125       fprintf_unfiltered (fp, "rwatch");
11126       break;
11127     case bp_access_watchpoint:
11128       fprintf_unfiltered (fp, "awatch");
11129       break;
11130     default:
11131       internal_error (__FILE__, __LINE__,
11132                       _("Invalid hardware watchpoint type."));
11133     }
11134
11135   sprintf_vma (tmp, w->hw_wp_mask);
11136   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11137   print_recreate_thread (b, fp);
11138 }
11139
11140 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11141
11142 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11143
11144 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11145
11146 static int
11147 is_masked_watchpoint (const struct breakpoint *b)
11148 {
11149   return b->ops == &masked_watchpoint_breakpoint_ops;
11150 }
11151
11152 /* accessflag:  hw_write:  watch write, 
11153                 hw_read:   watch read, 
11154                 hw_access: watch access (read or write) */
11155 static void
11156 watch_command_1 (const char *arg, int accessflag, int from_tty,
11157                  int just_location, int internal)
11158 {
11159   struct breakpoint *b, *scope_breakpoint = NULL;
11160   struct expression *exp;
11161   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11162   struct value *val, *mark, *result;
11163   int saved_bitpos = 0, saved_bitsize = 0;
11164   struct frame_info *frame;
11165   const char *exp_start = NULL;
11166   const char *exp_end = NULL;
11167   const char *tok, *end_tok;
11168   int toklen = -1;
11169   const char *cond_start = NULL;
11170   const char *cond_end = NULL;
11171   enum bptype bp_type;
11172   int thread = -1;
11173   int pc = 0;
11174   /* Flag to indicate whether we are going to use masks for
11175      the hardware watchpoint.  */
11176   int use_mask = 0;
11177   CORE_ADDR mask = 0;
11178   struct watchpoint *w;
11179   char *expression;
11180   struct cleanup *back_to;
11181
11182   /* Make sure that we actually have parameters to parse.  */
11183   if (arg != NULL && arg[0] != '\0')
11184     {
11185       const char *value_start;
11186
11187       exp_end = arg + strlen (arg);
11188
11189       /* Look for "parameter value" pairs at the end
11190          of the arguments string.  */
11191       for (tok = exp_end - 1; tok > arg; tok--)
11192         {
11193           /* Skip whitespace at the end of the argument list.  */
11194           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11195             tok--;
11196
11197           /* Find the beginning of the last token.
11198              This is the value of the parameter.  */
11199           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11200             tok--;
11201           value_start = tok + 1;
11202
11203           /* Skip whitespace.  */
11204           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11205             tok--;
11206
11207           end_tok = tok;
11208
11209           /* Find the beginning of the second to last token.
11210              This is the parameter itself.  */
11211           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11212             tok--;
11213           tok++;
11214           toklen = end_tok - tok + 1;
11215
11216           if (toklen == 6 && startswith (tok, "thread"))
11217             {
11218               struct thread_info *thr;
11219               /* At this point we've found a "thread" token, which means
11220                  the user is trying to set a watchpoint that triggers
11221                  only in a specific thread.  */
11222               const char *endp;
11223
11224               if (thread != -1)
11225                 error(_("You can specify only one thread."));
11226
11227               /* Extract the thread ID from the next token.  */
11228               thr = parse_thread_id (value_start, &endp);
11229
11230               /* Check if the user provided a valid thread ID.  */
11231               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11232                 invalid_thread_id_error (value_start);
11233
11234               thread = thr->global_num;
11235             }
11236           else if (toklen == 4 && startswith (tok, "mask"))
11237             {
11238               /* We've found a "mask" token, which means the user wants to
11239                  create a hardware watchpoint that is going to have the mask
11240                  facility.  */
11241               struct value *mask_value, *mark;
11242
11243               if (use_mask)
11244                 error(_("You can specify only one mask."));
11245
11246               use_mask = just_location = 1;
11247
11248               mark = value_mark ();
11249               mask_value = parse_to_comma_and_eval (&value_start);
11250               mask = value_as_address (mask_value);
11251               value_free_to_mark (mark);
11252             }
11253           else
11254             /* We didn't recognize what we found.  We should stop here.  */
11255             break;
11256
11257           /* Truncate the string and get rid of the "parameter value" pair before
11258              the arguments string is parsed by the parse_exp_1 function.  */
11259           exp_end = tok;
11260         }
11261     }
11262   else
11263     exp_end = arg;
11264
11265   /* Parse the rest of the arguments.  From here on out, everything
11266      is in terms of a newly allocated string instead of the original
11267      ARG.  */
11268   innermost_block = NULL;
11269   expression = savestring (arg, exp_end - arg);
11270   back_to = make_cleanup (xfree, expression);
11271   exp_start = arg = expression;
11272   exp = parse_exp_1 (&arg, 0, 0, 0);
11273   exp_end = arg;
11274   /* Remove trailing whitespace from the expression before saving it.
11275      This makes the eventual display of the expression string a bit
11276      prettier.  */
11277   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11278     --exp_end;
11279
11280   /* Checking if the expression is not constant.  */
11281   if (watchpoint_exp_is_const (exp))
11282     {
11283       int len;
11284
11285       len = exp_end - exp_start;
11286       while (len > 0 && isspace (exp_start[len - 1]))
11287         len--;
11288       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11289     }
11290
11291   exp_valid_block = innermost_block;
11292   mark = value_mark ();
11293   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11294
11295   if (val != NULL && just_location)
11296     {
11297       saved_bitpos = value_bitpos (val);
11298       saved_bitsize = value_bitsize (val);
11299     }
11300
11301   if (just_location)
11302     {
11303       int ret;
11304
11305       exp_valid_block = NULL;
11306       val = value_addr (result);
11307       release_value (val);
11308       value_free_to_mark (mark);
11309
11310       if (use_mask)
11311         {
11312           ret = target_masked_watch_num_registers (value_as_address (val),
11313                                                    mask);
11314           if (ret == -1)
11315             error (_("This target does not support masked watchpoints."));
11316           else if (ret == -2)
11317             error (_("Invalid mask or memory region."));
11318         }
11319     }
11320   else if (val != NULL)
11321     release_value (val);
11322
11323   tok = skip_spaces_const (arg);
11324   end_tok = skip_to_space_const (tok);
11325
11326   toklen = end_tok - tok;
11327   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11328     {
11329       struct expression *cond;
11330
11331       innermost_block = NULL;
11332       tok = cond_start = end_tok + 1;
11333       cond = parse_exp_1 (&tok, 0, 0, 0);
11334
11335       /* The watchpoint expression may not be local, but the condition
11336          may still be.  E.g.: `watch global if local > 0'.  */
11337       cond_exp_valid_block = innermost_block;
11338
11339       xfree (cond);
11340       cond_end = tok;
11341     }
11342   if (*tok)
11343     error (_("Junk at end of command."));
11344
11345   frame = block_innermost_frame (exp_valid_block);
11346
11347   /* If the expression is "local", then set up a "watchpoint scope"
11348      breakpoint at the point where we've left the scope of the watchpoint
11349      expression.  Create the scope breakpoint before the watchpoint, so
11350      that we will encounter it first in bpstat_stop_status.  */
11351   if (exp_valid_block && frame)
11352     {
11353       if (frame_id_p (frame_unwind_caller_id (frame)))
11354         {
11355           scope_breakpoint
11356             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11357                                           frame_unwind_caller_pc (frame),
11358                                           bp_watchpoint_scope,
11359                                           &momentary_breakpoint_ops);
11360
11361           scope_breakpoint->enable_state = bp_enabled;
11362
11363           /* Automatically delete the breakpoint when it hits.  */
11364           scope_breakpoint->disposition = disp_del;
11365
11366           /* Only break in the proper frame (help with recursion).  */
11367           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11368
11369           /* Set the address at which we will stop.  */
11370           scope_breakpoint->loc->gdbarch
11371             = frame_unwind_caller_arch (frame);
11372           scope_breakpoint->loc->requested_address
11373             = frame_unwind_caller_pc (frame);
11374           scope_breakpoint->loc->address
11375             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11376                                          scope_breakpoint->loc->requested_address,
11377                                          scope_breakpoint->type);
11378         }
11379     }
11380
11381   /* Now set up the breakpoint.  We create all watchpoints as hardware
11382      watchpoints here even if hardware watchpoints are turned off, a call
11383      to update_watchpoint later in this function will cause the type to
11384      drop back to bp_watchpoint (software watchpoint) if required.  */
11385
11386   if (accessflag == hw_read)
11387     bp_type = bp_read_watchpoint;
11388   else if (accessflag == hw_access)
11389     bp_type = bp_access_watchpoint;
11390   else
11391     bp_type = bp_hardware_watchpoint;
11392
11393   w = XCNEW (struct watchpoint);
11394   b = &w->base;
11395   if (use_mask)
11396     init_raw_breakpoint_without_location (b, NULL, bp_type,
11397                                           &masked_watchpoint_breakpoint_ops);
11398   else
11399     init_raw_breakpoint_without_location (b, NULL, bp_type,
11400                                           &watchpoint_breakpoint_ops);
11401   b->thread = thread;
11402   b->disposition = disp_donttouch;
11403   b->pspace = current_program_space;
11404   w->exp = exp;
11405   w->exp_valid_block = exp_valid_block;
11406   w->cond_exp_valid_block = cond_exp_valid_block;
11407   if (just_location)
11408     {
11409       struct type *t = value_type (val);
11410       CORE_ADDR addr = value_as_address (val);
11411       char *name;
11412
11413       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11414       name = type_to_string (t);
11415
11416       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11417                                           core_addr_to_string (addr));
11418       xfree (name);
11419
11420       w->exp_string = xstrprintf ("-location %.*s",
11421                                   (int) (exp_end - exp_start), exp_start);
11422
11423       /* The above expression is in C.  */
11424       b->language = language_c;
11425     }
11426   else
11427     w->exp_string = savestring (exp_start, exp_end - exp_start);
11428
11429   if (use_mask)
11430     {
11431       w->hw_wp_mask = mask;
11432     }
11433   else
11434     {
11435       w->val = val;
11436       w->val_bitpos = saved_bitpos;
11437       w->val_bitsize = saved_bitsize;
11438       w->val_valid = 1;
11439     }
11440
11441   if (cond_start)
11442     b->cond_string = savestring (cond_start, cond_end - cond_start);
11443   else
11444     b->cond_string = 0;
11445
11446   if (frame)
11447     {
11448       w->watchpoint_frame = get_frame_id (frame);
11449       w->watchpoint_thread = inferior_ptid;
11450     }
11451   else
11452     {
11453       w->watchpoint_frame = null_frame_id;
11454       w->watchpoint_thread = null_ptid;
11455     }
11456
11457   if (scope_breakpoint != NULL)
11458     {
11459       /* The scope breakpoint is related to the watchpoint.  We will
11460          need to act on them together.  */
11461       b->related_breakpoint = scope_breakpoint;
11462       scope_breakpoint->related_breakpoint = b;
11463     }
11464
11465   if (!just_location)
11466     value_free_to_mark (mark);
11467
11468   TRY
11469     {
11470       /* Finally update the new watchpoint.  This creates the locations
11471          that should be inserted.  */
11472       update_watchpoint (w, 1);
11473     }
11474   CATCH (e, RETURN_MASK_ALL)
11475     {
11476       delete_breakpoint (b);
11477       throw_exception (e);
11478     }
11479   END_CATCH
11480
11481   install_breakpoint (internal, b, 1);
11482   do_cleanups (back_to);
11483 }
11484
11485 /* Return count of debug registers needed to watch the given expression.
11486    If the watchpoint cannot be handled in hardware return zero.  */
11487
11488 static int
11489 can_use_hardware_watchpoint (struct value *v)
11490 {
11491   int found_memory_cnt = 0;
11492   struct value *head = v;
11493
11494   /* Did the user specifically forbid us to use hardware watchpoints? */
11495   if (!can_use_hw_watchpoints)
11496     return 0;
11497
11498   /* Make sure that the value of the expression depends only upon
11499      memory contents, and values computed from them within GDB.  If we
11500      find any register references or function calls, we can't use a
11501      hardware watchpoint.
11502
11503      The idea here is that evaluating an expression generates a series
11504      of values, one holding the value of every subexpression.  (The
11505      expression a*b+c has five subexpressions: a, b, a*b, c, and
11506      a*b+c.)  GDB's values hold almost enough information to establish
11507      the criteria given above --- they identify memory lvalues,
11508      register lvalues, computed values, etcetera.  So we can evaluate
11509      the expression, and then scan the chain of values that leaves
11510      behind to decide whether we can detect any possible change to the
11511      expression's final value using only hardware watchpoints.
11512
11513      However, I don't think that the values returned by inferior
11514      function calls are special in any way.  So this function may not
11515      notice that an expression involving an inferior function call
11516      can't be watched with hardware watchpoints.  FIXME.  */
11517   for (; v; v = value_next (v))
11518     {
11519       if (VALUE_LVAL (v) == lval_memory)
11520         {
11521           if (v != head && value_lazy (v))
11522             /* A lazy memory lvalue in the chain is one that GDB never
11523                needed to fetch; we either just used its address (e.g.,
11524                `a' in `a.b') or we never needed it at all (e.g., `a'
11525                in `a,b').  This doesn't apply to HEAD; if that is
11526                lazy then it was not readable, but watch it anyway.  */
11527             ;
11528           else
11529             {
11530               /* Ahh, memory we actually used!  Check if we can cover
11531                  it with hardware watchpoints.  */
11532               struct type *vtype = check_typedef (value_type (v));
11533
11534               /* We only watch structs and arrays if user asked for it
11535                  explicitly, never if they just happen to appear in a
11536                  middle of some value chain.  */
11537               if (v == head
11538                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11539                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11540                 {
11541                   CORE_ADDR vaddr = value_address (v);
11542                   int len;
11543                   int num_regs;
11544
11545                   len = (target_exact_watchpoints
11546                          && is_scalar_type_recursive (vtype))?
11547                     1 : TYPE_LENGTH (value_type (v));
11548
11549                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11550                   if (!num_regs)
11551                     return 0;
11552                   else
11553                     found_memory_cnt += num_regs;
11554                 }
11555             }
11556         }
11557       else if (VALUE_LVAL (v) != not_lval
11558                && deprecated_value_modifiable (v) == 0)
11559         return 0;       /* These are values from the history (e.g., $1).  */
11560       else if (VALUE_LVAL (v) == lval_register)
11561         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11562     }
11563
11564   /* The expression itself looks suitable for using a hardware
11565      watchpoint, but give the target machine a chance to reject it.  */
11566   return found_memory_cnt;
11567 }
11568
11569 void
11570 watch_command_wrapper (char *arg, int from_tty, int internal)
11571 {
11572   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11573 }
11574
11575 /* A helper function that looks for the "-location" argument and then
11576    calls watch_command_1.  */
11577
11578 static void
11579 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11580 {
11581   int just_location = 0;
11582
11583   if (arg
11584       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11585           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11586     {
11587       arg = skip_spaces (arg);
11588       just_location = 1;
11589     }
11590
11591   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11592 }
11593
11594 static void
11595 watch_command (char *arg, int from_tty)
11596 {
11597   watch_maybe_just_location (arg, hw_write, from_tty);
11598 }
11599
11600 void
11601 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11602 {
11603   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11604 }
11605
11606 static void
11607 rwatch_command (char *arg, int from_tty)
11608 {
11609   watch_maybe_just_location (arg, hw_read, from_tty);
11610 }
11611
11612 void
11613 awatch_command_wrapper (char *arg, int from_tty, int internal)
11614 {
11615   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11616 }
11617
11618 static void
11619 awatch_command (char *arg, int from_tty)
11620 {
11621   watch_maybe_just_location (arg, hw_access, from_tty);
11622 }
11623 \f
11624
11625 /* Data for the FSM that manages the until(location)/advance commands
11626    in infcmd.c.  Here because it uses the mechanisms of
11627    breakpoints.  */
11628
11629 struct until_break_fsm
11630 {
11631   /* The base class.  */
11632   struct thread_fsm thread_fsm;
11633
11634   /* The thread that as current when the command was executed.  */
11635   int thread;
11636
11637   /* The breakpoint set at the destination location.  */
11638   struct breakpoint *location_breakpoint;
11639
11640   /* Breakpoint set at the return address in the caller frame.  May be
11641      NULL.  */
11642   struct breakpoint *caller_breakpoint;
11643 };
11644
11645 static void until_break_fsm_clean_up (struct thread_fsm *self,
11646                                       struct thread_info *thread);
11647 static int until_break_fsm_should_stop (struct thread_fsm *self,
11648                                         struct thread_info *thread);
11649 static enum async_reply_reason
11650   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11651
11652 /* until_break_fsm's vtable.  */
11653
11654 static struct thread_fsm_ops until_break_fsm_ops =
11655 {
11656   NULL, /* dtor */
11657   until_break_fsm_clean_up,
11658   until_break_fsm_should_stop,
11659   NULL, /* return_value */
11660   until_break_fsm_async_reply_reason,
11661 };
11662
11663 /* Allocate a new until_break_command_fsm.  */
11664
11665 static struct until_break_fsm *
11666 new_until_break_fsm (struct interp *cmd_interp, int thread,
11667                      struct breakpoint *location_breakpoint,
11668                      struct breakpoint *caller_breakpoint)
11669 {
11670   struct until_break_fsm *sm;
11671
11672   sm = XCNEW (struct until_break_fsm);
11673   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11674
11675   sm->thread = thread;
11676   sm->location_breakpoint = location_breakpoint;
11677   sm->caller_breakpoint = caller_breakpoint;
11678
11679   return sm;
11680 }
11681
11682 /* Implementation of the 'should_stop' FSM method for the
11683    until(location)/advance commands.  */
11684
11685 static int
11686 until_break_fsm_should_stop (struct thread_fsm *self,
11687                              struct thread_info *tp)
11688 {
11689   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11690
11691   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11692                               sm->location_breakpoint) != NULL
11693       || (sm->caller_breakpoint != NULL
11694           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11695                                      sm->caller_breakpoint) != NULL))
11696     thread_fsm_set_finished (self);
11697
11698   return 1;
11699 }
11700
11701 /* Implementation of the 'clean_up' FSM method for the
11702    until(location)/advance commands.  */
11703
11704 static void
11705 until_break_fsm_clean_up (struct thread_fsm *self,
11706                           struct thread_info *thread)
11707 {
11708   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11709
11710   /* Clean up our temporary breakpoints.  */
11711   if (sm->location_breakpoint != NULL)
11712     {
11713       delete_breakpoint (sm->location_breakpoint);
11714       sm->location_breakpoint = NULL;
11715     }
11716   if (sm->caller_breakpoint != NULL)
11717     {
11718       delete_breakpoint (sm->caller_breakpoint);
11719       sm->caller_breakpoint = NULL;
11720     }
11721   delete_longjmp_breakpoint (sm->thread);
11722 }
11723
11724 /* Implementation of the 'async_reply_reason' FSM method for the
11725    until(location)/advance commands.  */
11726
11727 static enum async_reply_reason
11728 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11729 {
11730   return EXEC_ASYNC_LOCATION_REACHED;
11731 }
11732
11733 void
11734 until_break_command (char *arg, int from_tty, int anywhere)
11735 {
11736   struct symtabs_and_lines sals;
11737   struct symtab_and_line sal;
11738   struct frame_info *frame;
11739   struct gdbarch *frame_gdbarch;
11740   struct frame_id stack_frame_id;
11741   struct frame_id caller_frame_id;
11742   struct breakpoint *location_breakpoint;
11743   struct breakpoint *caller_breakpoint = NULL;
11744   struct cleanup *old_chain, *cleanup;
11745   int thread;
11746   struct thread_info *tp;
11747   struct event_location *location;
11748   struct until_break_fsm *sm;
11749
11750   clear_proceed_status (0);
11751
11752   /* Set a breakpoint where the user wants it and at return from
11753      this function.  */
11754
11755   location = string_to_event_location (&arg, current_language);
11756   cleanup = make_cleanup_delete_event_location (location);
11757
11758   if (last_displayed_sal_is_valid ())
11759     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE, NULL,
11760                           get_last_displayed_symtab (),
11761                           get_last_displayed_line ());
11762   else
11763     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11764                           NULL, (struct symtab *) NULL, 0);
11765
11766   if (sals.nelts != 1)
11767     error (_("Couldn't get information on specified line."));
11768
11769   sal = sals.sals[0];
11770   xfree (sals.sals);    /* malloc'd, so freed.  */
11771
11772   if (*arg)
11773     error (_("Junk at end of arguments."));
11774
11775   resolve_sal_pc (&sal);
11776
11777   tp = inferior_thread ();
11778   thread = tp->global_num;
11779
11780   old_chain = make_cleanup (null_cleanup, NULL);
11781
11782   /* Note linespec handling above invalidates the frame chain.
11783      Installing a breakpoint also invalidates the frame chain (as it
11784      may need to switch threads), so do any frame handling before
11785      that.  */
11786
11787   frame = get_selected_frame (NULL);
11788   frame_gdbarch = get_frame_arch (frame);
11789   stack_frame_id = get_stack_frame_id (frame);
11790   caller_frame_id = frame_unwind_caller_id (frame);
11791
11792   /* Keep within the current frame, or in frames called by the current
11793      one.  */
11794
11795   if (frame_id_p (caller_frame_id))
11796     {
11797       struct symtab_and_line sal2;
11798       struct gdbarch *caller_gdbarch;
11799
11800       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11801       sal2.pc = frame_unwind_caller_pc (frame);
11802       caller_gdbarch = frame_unwind_caller_arch (frame);
11803       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11804                                                     sal2,
11805                                                     caller_frame_id,
11806                                                     bp_until);
11807       make_cleanup_delete_breakpoint (caller_breakpoint);
11808
11809       set_longjmp_breakpoint (tp, caller_frame_id);
11810       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11811     }
11812
11813   /* set_momentary_breakpoint could invalidate FRAME.  */
11814   frame = NULL;
11815
11816   if (anywhere)
11817     /* If the user told us to continue until a specified location,
11818        we don't specify a frame at which we need to stop.  */
11819     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11820                                                     null_frame_id, bp_until);
11821   else
11822     /* Otherwise, specify the selected frame, because we want to stop
11823        only at the very same frame.  */
11824     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11825                                                     stack_frame_id, bp_until);
11826   make_cleanup_delete_breakpoint (location_breakpoint);
11827
11828   sm = new_until_break_fsm (command_interp (), tp->global_num,
11829                             location_breakpoint, caller_breakpoint);
11830   tp->thread_fsm = &sm->thread_fsm;
11831
11832   discard_cleanups (old_chain);
11833
11834   proceed (-1, GDB_SIGNAL_DEFAULT);
11835
11836   do_cleanups (cleanup);
11837 }
11838
11839 /* This function attempts to parse an optional "if <cond>" clause
11840    from the arg string.  If one is not found, it returns NULL.
11841
11842    Else, it returns a pointer to the condition string.  (It does not
11843    attempt to evaluate the string against a particular block.)  And,
11844    it updates arg to point to the first character following the parsed
11845    if clause in the arg string.  */
11846
11847 char *
11848 ep_parse_optional_if_clause (char **arg)
11849 {
11850   char *cond_string;
11851
11852   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11853     return NULL;
11854
11855   /* Skip the "if" keyword.  */
11856   (*arg) += 2;
11857
11858   /* Skip any extra leading whitespace, and record the start of the
11859      condition string.  */
11860   *arg = skip_spaces (*arg);
11861   cond_string = *arg;
11862
11863   /* Assume that the condition occupies the remainder of the arg
11864      string.  */
11865   (*arg) += strlen (cond_string);
11866
11867   return cond_string;
11868 }
11869
11870 /* Commands to deal with catching events, such as signals, exceptions,
11871    process start/exit, etc.  */
11872
11873 typedef enum
11874 {
11875   catch_fork_temporary, catch_vfork_temporary,
11876   catch_fork_permanent, catch_vfork_permanent
11877 }
11878 catch_fork_kind;
11879
11880 static void
11881 catch_fork_command_1 (char *arg, int from_tty, 
11882                       struct cmd_list_element *command)
11883 {
11884   struct gdbarch *gdbarch = get_current_arch ();
11885   char *cond_string = NULL;
11886   catch_fork_kind fork_kind;
11887   int tempflag;
11888
11889   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11890   tempflag = (fork_kind == catch_fork_temporary
11891               || fork_kind == catch_vfork_temporary);
11892
11893   if (!arg)
11894     arg = "";
11895   arg = skip_spaces (arg);
11896
11897   /* The allowed syntax is:
11898      catch [v]fork
11899      catch [v]fork if <cond>
11900
11901      First, check if there's an if clause.  */
11902   cond_string = ep_parse_optional_if_clause (&arg);
11903
11904   if ((*arg != '\0') && !isspace (*arg))
11905     error (_("Junk at end of arguments."));
11906
11907   /* If this target supports it, create a fork or vfork catchpoint
11908      and enable reporting of such events.  */
11909   switch (fork_kind)
11910     {
11911     case catch_fork_temporary:
11912     case catch_fork_permanent:
11913       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11914                                           &catch_fork_breakpoint_ops);
11915       break;
11916     case catch_vfork_temporary:
11917     case catch_vfork_permanent:
11918       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11919                                           &catch_vfork_breakpoint_ops);
11920       break;
11921     default:
11922       error (_("unsupported or unknown fork kind; cannot catch it"));
11923       break;
11924     }
11925 }
11926
11927 static void
11928 catch_exec_command_1 (char *arg, int from_tty, 
11929                       struct cmd_list_element *command)
11930 {
11931   struct exec_catchpoint *c;
11932   struct gdbarch *gdbarch = get_current_arch ();
11933   int tempflag;
11934   char *cond_string = NULL;
11935
11936   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11937
11938   if (!arg)
11939     arg = "";
11940   arg = skip_spaces (arg);
11941
11942   /* The allowed syntax is:
11943      catch exec
11944      catch exec if <cond>
11945
11946      First, check if there's an if clause.  */
11947   cond_string = ep_parse_optional_if_clause (&arg);
11948
11949   if ((*arg != '\0') && !isspace (*arg))
11950     error (_("Junk at end of arguments."));
11951
11952   c = XNEW (struct exec_catchpoint);
11953   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11954                    &catch_exec_breakpoint_ops);
11955   c->exec_pathname = NULL;
11956
11957   install_breakpoint (0, &c->base, 1);
11958 }
11959
11960 void
11961 init_ada_exception_breakpoint (struct breakpoint *b,
11962                                struct gdbarch *gdbarch,
11963                                struct symtab_and_line sal,
11964                                char *addr_string,
11965                                const struct breakpoint_ops *ops,
11966                                int tempflag,
11967                                int enabled,
11968                                int from_tty)
11969 {
11970   if (from_tty)
11971     {
11972       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11973       if (!loc_gdbarch)
11974         loc_gdbarch = gdbarch;
11975
11976       describe_other_breakpoints (loc_gdbarch,
11977                                   sal.pspace, sal.pc, sal.section, -1);
11978       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11979          version for exception catchpoints, because two catchpoints
11980          used for different exception names will use the same address.
11981          In this case, a "breakpoint ... also set at..." warning is
11982          unproductive.  Besides, the warning phrasing is also a bit
11983          inappropriate, we should use the word catchpoint, and tell
11984          the user what type of catchpoint it is.  The above is good
11985          enough for now, though.  */
11986     }
11987
11988   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11989
11990   b->enable_state = enabled ? bp_enabled : bp_disabled;
11991   b->disposition = tempflag ? disp_del : disp_donttouch;
11992   b->location = string_to_event_location (&addr_string,
11993                                           language_def (language_ada));
11994   b->language = language_ada;
11995 }
11996
11997 static void
11998 catch_command (char *arg, int from_tty)
11999 {
12000   error (_("Catch requires an event name."));
12001 }
12002 \f
12003
12004 static void
12005 tcatch_command (char *arg, int from_tty)
12006 {
12007   error (_("Catch requires an event name."));
12008 }
12009
12010 /* A qsort comparison function that sorts breakpoints in order.  */
12011
12012 static int
12013 compare_breakpoints (const void *a, const void *b)
12014 {
12015   const breakpoint_p *ba = (const breakpoint_p *) a;
12016   uintptr_t ua = (uintptr_t) *ba;
12017   const breakpoint_p *bb = (const breakpoint_p *) b;
12018   uintptr_t ub = (uintptr_t) *bb;
12019
12020   if ((*ba)->number < (*bb)->number)
12021     return -1;
12022   else if ((*ba)->number > (*bb)->number)
12023     return 1;
12024
12025   /* Now sort by address, in case we see, e..g, two breakpoints with
12026      the number 0.  */
12027   if (ua < ub)
12028     return -1;
12029   return ua > ub ? 1 : 0;
12030 }
12031
12032 /* Delete breakpoints by address or line.  */
12033
12034 static void
12035 clear_command (char *arg, int from_tty)
12036 {
12037   struct breakpoint *b, *prev;
12038   VEC(breakpoint_p) *found = 0;
12039   int ix;
12040   int default_match;
12041   struct symtabs_and_lines sals;
12042   struct symtab_and_line sal;
12043   int i;
12044   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12045
12046   if (arg)
12047     {
12048       sals = decode_line_with_current_source (arg,
12049                                               (DECODE_LINE_FUNFIRSTLINE
12050                                                | DECODE_LINE_LIST_MODE));
12051       make_cleanup (xfree, sals.sals);
12052       default_match = 0;
12053     }
12054   else
12055     {
12056       sals.sals = XNEW (struct symtab_and_line);
12057       make_cleanup (xfree, sals.sals);
12058       init_sal (&sal);          /* Initialize to zeroes.  */
12059
12060       /* Set sal's line, symtab, pc, and pspace to the values
12061          corresponding to the last call to print_frame_info.  If the
12062          codepoint is not valid, this will set all the fields to 0.  */
12063       get_last_displayed_sal (&sal);
12064       if (sal.symtab == 0)
12065         error (_("No source file specified."));
12066
12067       sals.sals[0] = sal;
12068       sals.nelts = 1;
12069
12070       default_match = 1;
12071     }
12072
12073   /* We don't call resolve_sal_pc here.  That's not as bad as it
12074      seems, because all existing breakpoints typically have both
12075      file/line and pc set.  So, if clear is given file/line, we can
12076      match this to existing breakpoint without obtaining pc at all.
12077
12078      We only support clearing given the address explicitly 
12079      present in breakpoint table.  Say, we've set breakpoint 
12080      at file:line.  There were several PC values for that file:line,
12081      due to optimization, all in one block.
12082
12083      We've picked one PC value.  If "clear" is issued with another
12084      PC corresponding to the same file:line, the breakpoint won't
12085      be cleared.  We probably can still clear the breakpoint, but 
12086      since the other PC value is never presented to user, user
12087      can only find it by guessing, and it does not seem important
12088      to support that.  */
12089
12090   /* For each line spec given, delete bps which correspond to it.  Do
12091      it in two passes, solely to preserve the current behavior that
12092      from_tty is forced true if we delete more than one
12093      breakpoint.  */
12094
12095   found = NULL;
12096   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12097   for (i = 0; i < sals.nelts; i++)
12098     {
12099       const char *sal_fullname;
12100
12101       /* If exact pc given, clear bpts at that pc.
12102          If line given (pc == 0), clear all bpts on specified line.
12103          If defaulting, clear all bpts on default line
12104          or at default pc.
12105
12106          defaulting    sal.pc != 0    tests to do
12107
12108          0              1             pc
12109          1              1             pc _and_ line
12110          0              0             line
12111          1              0             <can't happen> */
12112
12113       sal = sals.sals[i];
12114       sal_fullname = (sal.symtab == NULL
12115                       ? NULL : symtab_to_fullname (sal.symtab));
12116
12117       /* Find all matching breakpoints and add them to 'found'.  */
12118       ALL_BREAKPOINTS (b)
12119         {
12120           int match = 0;
12121           /* Are we going to delete b?  */
12122           if (b->type != bp_none && !is_watchpoint (b))
12123             {
12124               struct bp_location *loc = b->loc;
12125               for (; loc; loc = loc->next)
12126                 {
12127                   /* If the user specified file:line, don't allow a PC
12128                      match.  This matches historical gdb behavior.  */
12129                   int pc_match = (!sal.explicit_line
12130                                   && sal.pc
12131                                   && (loc->pspace == sal.pspace)
12132                                   && (loc->address == sal.pc)
12133                                   && (!section_is_overlay (loc->section)
12134                                       || loc->section == sal.section));
12135                   int line_match = 0;
12136
12137                   if ((default_match || sal.explicit_line)
12138                       && loc->symtab != NULL
12139                       && sal_fullname != NULL
12140                       && sal.pspace == loc->pspace
12141                       && loc->line_number == sal.line
12142                       && filename_cmp (symtab_to_fullname (loc->symtab),
12143                                        sal_fullname) == 0)
12144                     line_match = 1;
12145
12146                   if (pc_match || line_match)
12147                     {
12148                       match = 1;
12149                       break;
12150                     }
12151                 }
12152             }
12153
12154           if (match)
12155             VEC_safe_push(breakpoint_p, found, b);
12156         }
12157     }
12158
12159   /* Now go thru the 'found' chain and delete them.  */
12160   if (VEC_empty(breakpoint_p, found))
12161     {
12162       if (arg)
12163         error (_("No breakpoint at %s."), arg);
12164       else
12165         error (_("No breakpoint at this line."));
12166     }
12167
12168   /* Remove duplicates from the vec.  */
12169   qsort (VEC_address (breakpoint_p, found),
12170          VEC_length (breakpoint_p, found),
12171          sizeof (breakpoint_p),
12172          compare_breakpoints);
12173   prev = VEC_index (breakpoint_p, found, 0);
12174   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12175     {
12176       if (b == prev)
12177         {
12178           VEC_ordered_remove (breakpoint_p, found, ix);
12179           --ix;
12180         }
12181     }
12182
12183   if (VEC_length(breakpoint_p, found) > 1)
12184     from_tty = 1;       /* Always report if deleted more than one.  */
12185   if (from_tty)
12186     {
12187       if (VEC_length(breakpoint_p, found) == 1)
12188         printf_unfiltered (_("Deleted breakpoint "));
12189       else
12190         printf_unfiltered (_("Deleted breakpoints "));
12191     }
12192
12193   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12194     {
12195       if (from_tty)
12196         printf_unfiltered ("%d ", b->number);
12197       delete_breakpoint (b);
12198     }
12199   if (from_tty)
12200     putchar_unfiltered ('\n');
12201
12202   do_cleanups (cleanups);
12203 }
12204 \f
12205 /* Delete breakpoint in BS if they are `delete' breakpoints and
12206    all breakpoints that are marked for deletion, whether hit or not.
12207    This is called after any breakpoint is hit, or after errors.  */
12208
12209 void
12210 breakpoint_auto_delete (bpstat bs)
12211 {
12212   struct breakpoint *b, *b_tmp;
12213
12214   for (; bs; bs = bs->next)
12215     if (bs->breakpoint_at
12216         && bs->breakpoint_at->disposition == disp_del
12217         && bs->stop)
12218       delete_breakpoint (bs->breakpoint_at);
12219
12220   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12221   {
12222     if (b->disposition == disp_del_at_next_stop)
12223       delete_breakpoint (b);
12224   }
12225 }
12226
12227 /* A comparison function for bp_location AP and BP being interfaced to
12228    qsort.  Sort elements primarily by their ADDRESS (no matter what
12229    does breakpoint_address_is_meaningful say for its OWNER),
12230    secondarily by ordering first permanent elements and
12231    terciarily just ensuring the array is sorted stable way despite
12232    qsort being an unstable algorithm.  */
12233
12234 static int
12235 bp_location_compare (const void *ap, const void *bp)
12236 {
12237   const struct bp_location *a = *(const struct bp_location **) ap;
12238   const struct bp_location *b = *(const struct bp_location **) bp;
12239
12240   if (a->address != b->address)
12241     return (a->address > b->address) - (a->address < b->address);
12242
12243   /* Sort locations at the same address by their pspace number, keeping
12244      locations of the same inferior (in a multi-inferior environment)
12245      grouped.  */
12246
12247   if (a->pspace->num != b->pspace->num)
12248     return ((a->pspace->num > b->pspace->num)
12249             - (a->pspace->num < b->pspace->num));
12250
12251   /* Sort permanent breakpoints first.  */
12252   if (a->permanent != b->permanent)
12253     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12254
12255   /* Make the internal GDB representation stable across GDB runs
12256      where A and B memory inside GDB can differ.  Breakpoint locations of
12257      the same type at the same address can be sorted in arbitrary order.  */
12258
12259   if (a->owner->number != b->owner->number)
12260     return ((a->owner->number > b->owner->number)
12261             - (a->owner->number < b->owner->number));
12262
12263   return (a > b) - (a < b);
12264 }
12265
12266 /* Set bp_location_placed_address_before_address_max and
12267    bp_location_shadow_len_after_address_max according to the current
12268    content of the bp_location array.  */
12269
12270 static void
12271 bp_location_target_extensions_update (void)
12272 {
12273   struct bp_location *bl, **blp_tmp;
12274
12275   bp_location_placed_address_before_address_max = 0;
12276   bp_location_shadow_len_after_address_max = 0;
12277
12278   ALL_BP_LOCATIONS (bl, blp_tmp)
12279     {
12280       CORE_ADDR start, end, addr;
12281
12282       if (!bp_location_has_shadow (bl))
12283         continue;
12284
12285       start = bl->target_info.placed_address;
12286       end = start + bl->target_info.shadow_len;
12287
12288       gdb_assert (bl->address >= start);
12289       addr = bl->address - start;
12290       if (addr > bp_location_placed_address_before_address_max)
12291         bp_location_placed_address_before_address_max = addr;
12292
12293       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12294
12295       gdb_assert (bl->address < end);
12296       addr = end - bl->address;
12297       if (addr > bp_location_shadow_len_after_address_max)
12298         bp_location_shadow_len_after_address_max = addr;
12299     }
12300 }
12301
12302 /* Download tracepoint locations if they haven't been.  */
12303
12304 static void
12305 download_tracepoint_locations (void)
12306 {
12307   struct breakpoint *b;
12308   struct cleanup *old_chain;
12309   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12310
12311   old_chain = save_current_space_and_thread ();
12312
12313   ALL_TRACEPOINTS (b)
12314     {
12315       struct bp_location *bl;
12316       struct tracepoint *t;
12317       int bp_location_downloaded = 0;
12318
12319       if ((b->type == bp_fast_tracepoint
12320            ? !may_insert_fast_tracepoints
12321            : !may_insert_tracepoints))
12322         continue;
12323
12324       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12325         {
12326           if (target_can_download_tracepoint ())
12327             can_download_tracepoint = TRIBOOL_TRUE;
12328           else
12329             can_download_tracepoint = TRIBOOL_FALSE;
12330         }
12331
12332       if (can_download_tracepoint == TRIBOOL_FALSE)
12333         break;
12334
12335       for (bl = b->loc; bl; bl = bl->next)
12336         {
12337           /* In tracepoint, locations are _never_ duplicated, so
12338              should_be_inserted is equivalent to
12339              unduplicated_should_be_inserted.  */
12340           if (!should_be_inserted (bl) || bl->inserted)
12341             continue;
12342
12343           switch_to_program_space_and_thread (bl->pspace);
12344
12345           target_download_tracepoint (bl);
12346
12347           bl->inserted = 1;
12348           bp_location_downloaded = 1;
12349         }
12350       t = (struct tracepoint *) b;
12351       t->number_on_target = b->number;
12352       if (bp_location_downloaded)
12353         observer_notify_breakpoint_modified (b);
12354     }
12355
12356   do_cleanups (old_chain);
12357 }
12358
12359 /* Swap the insertion/duplication state between two locations.  */
12360
12361 static void
12362 swap_insertion (struct bp_location *left, struct bp_location *right)
12363 {
12364   const int left_inserted = left->inserted;
12365   const int left_duplicate = left->duplicate;
12366   const int left_needs_update = left->needs_update;
12367   const struct bp_target_info left_target_info = left->target_info;
12368
12369   /* Locations of tracepoints can never be duplicated.  */
12370   if (is_tracepoint (left->owner))
12371     gdb_assert (!left->duplicate);
12372   if (is_tracepoint (right->owner))
12373     gdb_assert (!right->duplicate);
12374
12375   left->inserted = right->inserted;
12376   left->duplicate = right->duplicate;
12377   left->needs_update = right->needs_update;
12378   left->target_info = right->target_info;
12379   right->inserted = left_inserted;
12380   right->duplicate = left_duplicate;
12381   right->needs_update = left_needs_update;
12382   right->target_info = left_target_info;
12383 }
12384
12385 /* Force the re-insertion of the locations at ADDRESS.  This is called
12386    once a new/deleted/modified duplicate location is found and we are evaluating
12387    conditions on the target's side.  Such conditions need to be updated on
12388    the target.  */
12389
12390 static void
12391 force_breakpoint_reinsertion (struct bp_location *bl)
12392 {
12393   struct bp_location **locp = NULL, **loc2p;
12394   struct bp_location *loc;
12395   CORE_ADDR address = 0;
12396   int pspace_num;
12397
12398   address = bl->address;
12399   pspace_num = bl->pspace->num;
12400
12401   /* This is only meaningful if the target is
12402      evaluating conditions and if the user has
12403      opted for condition evaluation on the target's
12404      side.  */
12405   if (gdb_evaluates_breakpoint_condition_p ()
12406       || !target_supports_evaluation_of_breakpoint_conditions ())
12407     return;
12408
12409   /* Flag all breakpoint locations with this address and
12410      the same program space as the location
12411      as "its condition has changed".  We need to
12412      update the conditions on the target's side.  */
12413   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12414     {
12415       loc = *loc2p;
12416
12417       if (!is_breakpoint (loc->owner)
12418           || pspace_num != loc->pspace->num)
12419         continue;
12420
12421       /* Flag the location appropriately.  We use a different state to
12422          let everyone know that we already updated the set of locations
12423          with addr bl->address and program space bl->pspace.  This is so
12424          we don't have to keep calling these functions just to mark locations
12425          that have already been marked.  */
12426       loc->condition_changed = condition_updated;
12427
12428       /* Free the agent expression bytecode as well.  We will compute
12429          it later on.  */
12430       if (loc->cond_bytecode)
12431         {
12432           free_agent_expr (loc->cond_bytecode);
12433           loc->cond_bytecode = NULL;
12434         }
12435     }
12436 }
12437 /* Called whether new breakpoints are created, or existing breakpoints
12438    deleted, to update the global location list and recompute which
12439    locations are duplicate of which.
12440
12441    The INSERT_MODE flag determines whether locations may not, may, or
12442    shall be inserted now.  See 'enum ugll_insert_mode' for more
12443    info.  */
12444
12445 static void
12446 update_global_location_list (enum ugll_insert_mode insert_mode)
12447 {
12448   struct breakpoint *b;
12449   struct bp_location **locp, *loc;
12450   struct cleanup *cleanups;
12451   /* Last breakpoint location address that was marked for update.  */
12452   CORE_ADDR last_addr = 0;
12453   /* Last breakpoint location program space that was marked for update.  */
12454   int last_pspace_num = -1;
12455
12456   /* Used in the duplicates detection below.  When iterating over all
12457      bp_locations, points to the first bp_location of a given address.
12458      Breakpoints and watchpoints of different types are never
12459      duplicates of each other.  Keep one pointer for each type of
12460      breakpoint/watchpoint, so we only need to loop over all locations
12461      once.  */
12462   struct bp_location *bp_loc_first;  /* breakpoint */
12463   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12464   struct bp_location *awp_loc_first; /* access watchpoint */
12465   struct bp_location *rwp_loc_first; /* read watchpoint */
12466
12467   /* Saved former bp_location array which we compare against the newly
12468      built bp_location from the current state of ALL_BREAKPOINTS.  */
12469   struct bp_location **old_location, **old_locp;
12470   unsigned old_location_count;
12471
12472   old_location = bp_location;
12473   old_location_count = bp_location_count;
12474   bp_location = NULL;
12475   bp_location_count = 0;
12476   cleanups = make_cleanup (xfree, old_location);
12477
12478   ALL_BREAKPOINTS (b)
12479     for (loc = b->loc; loc; loc = loc->next)
12480       bp_location_count++;
12481
12482   bp_location = XNEWVEC (struct bp_location *, bp_location_count);
12483   locp = bp_location;
12484   ALL_BREAKPOINTS (b)
12485     for (loc = b->loc; loc; loc = loc->next)
12486       *locp++ = loc;
12487   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12488          bp_location_compare);
12489
12490   bp_location_target_extensions_update ();
12491
12492   /* Identify bp_location instances that are no longer present in the
12493      new list, and therefore should be freed.  Note that it's not
12494      necessary that those locations should be removed from inferior --
12495      if there's another location at the same address (previously
12496      marked as duplicate), we don't need to remove/insert the
12497      location.
12498      
12499      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12500      and former bp_location array state respectively.  */
12501
12502   locp = bp_location;
12503   for (old_locp = old_location; old_locp < old_location + old_location_count;
12504        old_locp++)
12505     {
12506       struct bp_location *old_loc = *old_locp;
12507       struct bp_location **loc2p;
12508
12509       /* Tells if 'old_loc' is found among the new locations.  If
12510          not, we have to free it.  */
12511       int found_object = 0;
12512       /* Tells if the location should remain inserted in the target.  */
12513       int keep_in_target = 0;
12514       int removed = 0;
12515
12516       /* Skip LOCP entries which will definitely never be needed.
12517          Stop either at or being the one matching OLD_LOC.  */
12518       while (locp < bp_location + bp_location_count
12519              && (*locp)->address < old_loc->address)
12520         locp++;
12521
12522       for (loc2p = locp;
12523            (loc2p < bp_location + bp_location_count
12524             && (*loc2p)->address == old_loc->address);
12525            loc2p++)
12526         {
12527           /* Check if this is a new/duplicated location or a duplicated
12528              location that had its condition modified.  If so, we want to send
12529              its condition to the target if evaluation of conditions is taking
12530              place there.  */
12531           if ((*loc2p)->condition_changed == condition_modified
12532               && (last_addr != old_loc->address
12533                   || last_pspace_num != old_loc->pspace->num))
12534             {
12535               force_breakpoint_reinsertion (*loc2p);
12536               last_pspace_num = old_loc->pspace->num;
12537             }
12538
12539           if (*loc2p == old_loc)
12540             found_object = 1;
12541         }
12542
12543       /* We have already handled this address, update it so that we don't
12544          have to go through updates again.  */
12545       last_addr = old_loc->address;
12546
12547       /* Target-side condition evaluation: Handle deleted locations.  */
12548       if (!found_object)
12549         force_breakpoint_reinsertion (old_loc);
12550
12551       /* If this location is no longer present, and inserted, look if
12552          there's maybe a new location at the same address.  If so,
12553          mark that one inserted, and don't remove this one.  This is
12554          needed so that we don't have a time window where a breakpoint
12555          at certain location is not inserted.  */
12556
12557       if (old_loc->inserted)
12558         {
12559           /* If the location is inserted now, we might have to remove
12560              it.  */
12561
12562           if (found_object && should_be_inserted (old_loc))
12563             {
12564               /* The location is still present in the location list,
12565                  and still should be inserted.  Don't do anything.  */
12566               keep_in_target = 1;
12567             }
12568           else
12569             {
12570               /* This location still exists, but it won't be kept in the
12571                  target since it may have been disabled.  We proceed to
12572                  remove its target-side condition.  */
12573
12574               /* The location is either no longer present, or got
12575                  disabled.  See if there's another location at the
12576                  same address, in which case we don't need to remove
12577                  this one from the target.  */
12578
12579               /* OLD_LOC comes from existing struct breakpoint.  */
12580               if (breakpoint_address_is_meaningful (old_loc->owner))
12581                 {
12582                   for (loc2p = locp;
12583                        (loc2p < bp_location + bp_location_count
12584                         && (*loc2p)->address == old_loc->address);
12585                        loc2p++)
12586                     {
12587                       struct bp_location *loc2 = *loc2p;
12588
12589                       if (breakpoint_locations_match (loc2, old_loc))
12590                         {
12591                           /* Read watchpoint locations are switched to
12592                              access watchpoints, if the former are not
12593                              supported, but the latter are.  */
12594                           if (is_hardware_watchpoint (old_loc->owner))
12595                             {
12596                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12597                               loc2->watchpoint_type = old_loc->watchpoint_type;
12598                             }
12599
12600                           /* loc2 is a duplicated location. We need to check
12601                              if it should be inserted in case it will be
12602                              unduplicated.  */
12603                           if (loc2 != old_loc
12604                               && unduplicated_should_be_inserted (loc2))
12605                             {
12606                               swap_insertion (old_loc, loc2);
12607                               keep_in_target = 1;
12608                               break;
12609                             }
12610                         }
12611                     }
12612                 }
12613             }
12614
12615           if (!keep_in_target)
12616             {
12617               if (remove_breakpoint (old_loc))
12618                 {
12619                   /* This is just about all we can do.  We could keep
12620                      this location on the global list, and try to
12621                      remove it next time, but there's no particular
12622                      reason why we will succeed next time.
12623                      
12624                      Note that at this point, old_loc->owner is still
12625                      valid, as delete_breakpoint frees the breakpoint
12626                      only after calling us.  */
12627                   printf_filtered (_("warning: Error removing "
12628                                      "breakpoint %d\n"), 
12629                                    old_loc->owner->number);
12630                 }
12631               removed = 1;
12632             }
12633         }
12634
12635       if (!found_object)
12636         {
12637           if (removed && target_is_non_stop_p ()
12638               && need_moribund_for_location_type (old_loc))
12639             {
12640               /* This location was removed from the target.  In
12641                  non-stop mode, a race condition is possible where
12642                  we've removed a breakpoint, but stop events for that
12643                  breakpoint are already queued and will arrive later.
12644                  We apply an heuristic to be able to distinguish such
12645                  SIGTRAPs from other random SIGTRAPs: we keep this
12646                  breakpoint location for a bit, and will retire it
12647                  after we see some number of events.  The theory here
12648                  is that reporting of events should, "on the average",
12649                  be fair, so after a while we'll see events from all
12650                  threads that have anything of interest, and no longer
12651                  need to keep this breakpoint location around.  We
12652                  don't hold locations forever so to reduce chances of
12653                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12654                  SIGTRAP.
12655
12656                  The heuristic failing can be disastrous on
12657                  decr_pc_after_break targets.
12658
12659                  On decr_pc_after_break targets, like e.g., x86-linux,
12660                  if we fail to recognize a late breakpoint SIGTRAP,
12661                  because events_till_retirement has reached 0 too
12662                  soon, we'll fail to do the PC adjustment, and report
12663                  a random SIGTRAP to the user.  When the user resumes
12664                  the inferior, it will most likely immediately crash
12665                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12666                  corrupted, because of being resumed e.g., in the
12667                  middle of a multi-byte instruction, or skipped a
12668                  one-byte instruction.  This was actually seen happen
12669                  on native x86-linux, and should be less rare on
12670                  targets that do not support new thread events, like
12671                  remote, due to the heuristic depending on
12672                  thread_count.
12673
12674                  Mistaking a random SIGTRAP for a breakpoint trap
12675                  causes similar symptoms (PC adjustment applied when
12676                  it shouldn't), but then again, playing with SIGTRAPs
12677                  behind the debugger's back is asking for trouble.
12678
12679                  Since hardware watchpoint traps are always
12680                  distinguishable from other traps, so we don't need to
12681                  apply keep hardware watchpoint moribund locations
12682                  around.  We simply always ignore hardware watchpoint
12683                  traps we can no longer explain.  */
12684
12685               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12686               old_loc->owner = NULL;
12687
12688               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12689             }
12690           else
12691             {
12692               old_loc->owner = NULL;
12693               decref_bp_location (&old_loc);
12694             }
12695         }
12696     }
12697
12698   /* Rescan breakpoints at the same address and section, marking the
12699      first one as "first" and any others as "duplicates".  This is so
12700      that the bpt instruction is only inserted once.  If we have a
12701      permanent breakpoint at the same place as BPT, make that one the
12702      official one, and the rest as duplicates.  Permanent breakpoints
12703      are sorted first for the same address.
12704
12705      Do the same for hardware watchpoints, but also considering the
12706      watchpoint's type (regular/access/read) and length.  */
12707
12708   bp_loc_first = NULL;
12709   wp_loc_first = NULL;
12710   awp_loc_first = NULL;
12711   rwp_loc_first = NULL;
12712   ALL_BP_LOCATIONS (loc, locp)
12713     {
12714       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12715          non-NULL.  */
12716       struct bp_location **loc_first_p;
12717       b = loc->owner;
12718
12719       if (!unduplicated_should_be_inserted (loc)
12720           || !breakpoint_address_is_meaningful (b)
12721           /* Don't detect duplicate for tracepoint locations because they are
12722            never duplicated.  See the comments in field `duplicate' of
12723            `struct bp_location'.  */
12724           || is_tracepoint (b))
12725         {
12726           /* Clear the condition modification flag.  */
12727           loc->condition_changed = condition_unchanged;
12728           continue;
12729         }
12730
12731       if (b->type == bp_hardware_watchpoint)
12732         loc_first_p = &wp_loc_first;
12733       else if (b->type == bp_read_watchpoint)
12734         loc_first_p = &rwp_loc_first;
12735       else if (b->type == bp_access_watchpoint)
12736         loc_first_p = &awp_loc_first;
12737       else
12738         loc_first_p = &bp_loc_first;
12739
12740       if (*loc_first_p == NULL
12741           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12742           || !breakpoint_locations_match (loc, *loc_first_p))
12743         {
12744           *loc_first_p = loc;
12745           loc->duplicate = 0;
12746
12747           if (is_breakpoint (loc->owner) && loc->condition_changed)
12748             {
12749               loc->needs_update = 1;
12750               /* Clear the condition modification flag.  */
12751               loc->condition_changed = condition_unchanged;
12752             }
12753           continue;
12754         }
12755
12756
12757       /* This and the above ensure the invariant that the first location
12758          is not duplicated, and is the inserted one.
12759          All following are marked as duplicated, and are not inserted.  */
12760       if (loc->inserted)
12761         swap_insertion (loc, *loc_first_p);
12762       loc->duplicate = 1;
12763
12764       /* Clear the condition modification flag.  */
12765       loc->condition_changed = condition_unchanged;
12766     }
12767
12768   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12769     {
12770       if (insert_mode != UGLL_DONT_INSERT)
12771         insert_breakpoint_locations ();
12772       else
12773         {
12774           /* Even though the caller told us to not insert new
12775              locations, we may still need to update conditions on the
12776              target's side of breakpoints that were already inserted
12777              if the target is evaluating breakpoint conditions.  We
12778              only update conditions for locations that are marked
12779              "needs_update".  */
12780           update_inserted_breakpoint_locations ();
12781         }
12782     }
12783
12784   if (insert_mode != UGLL_DONT_INSERT)
12785     download_tracepoint_locations ();
12786
12787   do_cleanups (cleanups);
12788 }
12789
12790 void
12791 breakpoint_retire_moribund (void)
12792 {
12793   struct bp_location *loc;
12794   int ix;
12795
12796   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12797     if (--(loc->events_till_retirement) == 0)
12798       {
12799         decref_bp_location (&loc);
12800         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12801         --ix;
12802       }
12803 }
12804
12805 static void
12806 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12807 {
12808
12809   TRY
12810     {
12811       update_global_location_list (insert_mode);
12812     }
12813   CATCH (e, RETURN_MASK_ERROR)
12814     {
12815     }
12816   END_CATCH
12817 }
12818
12819 /* Clear BKP from a BPS.  */
12820
12821 static void
12822 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12823 {
12824   bpstat bs;
12825
12826   for (bs = bps; bs; bs = bs->next)
12827     if (bs->breakpoint_at == bpt)
12828       {
12829         bs->breakpoint_at = NULL;
12830         bs->old_val = NULL;
12831         /* bs->commands will be freed later.  */
12832       }
12833 }
12834
12835 /* Callback for iterate_over_threads.  */
12836 static int
12837 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12838 {
12839   struct breakpoint *bpt = (struct breakpoint *) data;
12840
12841   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12842   return 0;
12843 }
12844
12845 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12846    callbacks.  */
12847
12848 static void
12849 say_where (struct breakpoint *b)
12850 {
12851   struct value_print_options opts;
12852
12853   get_user_print_options (&opts);
12854
12855   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12856      single string.  */
12857   if (b->loc == NULL)
12858     {
12859       /* For pending locations, the output differs slightly based
12860          on b->extra_string.  If this is non-NULL, it contains either
12861          a condition or dprintf arguments.  */
12862       if (b->extra_string == NULL)
12863         {
12864           printf_filtered (_(" (%s) pending."),
12865                            event_location_to_string (b->location));
12866         }
12867       else if (b->type == bp_dprintf)
12868         {
12869           printf_filtered (_(" (%s,%s) pending."),
12870                            event_location_to_string (b->location),
12871                            b->extra_string);
12872         }
12873       else
12874         {
12875           printf_filtered (_(" (%s %s) pending."),
12876                            event_location_to_string (b->location),
12877                            b->extra_string);
12878         }
12879     }
12880   else
12881     {
12882       if (opts.addressprint || b->loc->symtab == NULL)
12883         {
12884           printf_filtered (" at ");
12885           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12886                           gdb_stdout);
12887         }
12888       if (b->loc->symtab != NULL)
12889         {
12890           /* If there is a single location, we can print the location
12891              more nicely.  */
12892           if (b->loc->next == NULL)
12893             printf_filtered (": file %s, line %d.",
12894                              symtab_to_filename_for_display (b->loc->symtab),
12895                              b->loc->line_number);
12896           else
12897             /* This is not ideal, but each location may have a
12898                different file name, and this at least reflects the
12899                real situation somewhat.  */
12900             printf_filtered (": %s.",
12901                              event_location_to_string (b->location));
12902         }
12903
12904       if (b->loc->next)
12905         {
12906           struct bp_location *loc = b->loc;
12907           int n = 0;
12908           for (; loc; loc = loc->next)
12909             ++n;
12910           printf_filtered (" (%d locations)", n);
12911         }
12912     }
12913 }
12914
12915 /* Default bp_location_ops methods.  */
12916
12917 static void
12918 bp_location_dtor (struct bp_location *self)
12919 {
12920   xfree (self->cond);
12921   if (self->cond_bytecode)
12922     free_agent_expr (self->cond_bytecode);
12923   xfree (self->function_name);
12924
12925   VEC_free (agent_expr_p, self->target_info.conditions);
12926   VEC_free (agent_expr_p, self->target_info.tcommands);
12927 }
12928
12929 static const struct bp_location_ops bp_location_ops =
12930 {
12931   bp_location_dtor
12932 };
12933
12934 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12935    inherit from.  */
12936
12937 static void
12938 base_breakpoint_dtor (struct breakpoint *self)
12939 {
12940   decref_counted_command_line (&self->commands);
12941   xfree (self->cond_string);
12942   xfree (self->extra_string);
12943   xfree (self->filter);
12944   delete_event_location (self->location);
12945   delete_event_location (self->location_range_end);
12946 }
12947
12948 static struct bp_location *
12949 base_breakpoint_allocate_location (struct breakpoint *self)
12950 {
12951   struct bp_location *loc;
12952
12953   loc = XNEW (struct bp_location);
12954   init_bp_location (loc, &bp_location_ops, self);
12955   return loc;
12956 }
12957
12958 static void
12959 base_breakpoint_re_set (struct breakpoint *b)
12960 {
12961   /* Nothing to re-set. */
12962 }
12963
12964 #define internal_error_pure_virtual_called() \
12965   gdb_assert_not_reached ("pure virtual function called")
12966
12967 static int
12968 base_breakpoint_insert_location (struct bp_location *bl)
12969 {
12970   internal_error_pure_virtual_called ();
12971 }
12972
12973 static int
12974 base_breakpoint_remove_location (struct bp_location *bl)
12975 {
12976   internal_error_pure_virtual_called ();
12977 }
12978
12979 static int
12980 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12981                                 struct address_space *aspace,
12982                                 CORE_ADDR bp_addr,
12983                                 const struct target_waitstatus *ws)
12984 {
12985   internal_error_pure_virtual_called ();
12986 }
12987
12988 static void
12989 base_breakpoint_check_status (bpstat bs)
12990 {
12991   /* Always stop.   */
12992 }
12993
12994 /* A "works_in_software_mode" breakpoint_ops method that just internal
12995    errors.  */
12996
12997 static int
12998 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12999 {
13000   internal_error_pure_virtual_called ();
13001 }
13002
13003 /* A "resources_needed" breakpoint_ops method that just internal
13004    errors.  */
13005
13006 static int
13007 base_breakpoint_resources_needed (const struct bp_location *bl)
13008 {
13009   internal_error_pure_virtual_called ();
13010 }
13011
13012 static enum print_stop_action
13013 base_breakpoint_print_it (bpstat bs)
13014 {
13015   internal_error_pure_virtual_called ();
13016 }
13017
13018 static void
13019 base_breakpoint_print_one_detail (const struct breakpoint *self,
13020                                   struct ui_out *uiout)
13021 {
13022   /* nothing */
13023 }
13024
13025 static void
13026 base_breakpoint_print_mention (struct breakpoint *b)
13027 {
13028   internal_error_pure_virtual_called ();
13029 }
13030
13031 static void
13032 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13033 {
13034   internal_error_pure_virtual_called ();
13035 }
13036
13037 static void
13038 base_breakpoint_create_sals_from_location
13039   (const struct event_location *location,
13040    struct linespec_result *canonical,
13041    enum bptype type_wanted)
13042 {
13043   internal_error_pure_virtual_called ();
13044 }
13045
13046 static void
13047 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13048                                         struct linespec_result *c,
13049                                         char *cond_string,
13050                                         char *extra_string,
13051                                         enum bptype type_wanted,
13052                                         enum bpdisp disposition,
13053                                         int thread,
13054                                         int task, int ignore_count,
13055                                         const struct breakpoint_ops *o,
13056                                         int from_tty, int enabled,
13057                                         int internal, unsigned flags)
13058 {
13059   internal_error_pure_virtual_called ();
13060 }
13061
13062 static void
13063 base_breakpoint_decode_location (struct breakpoint *b,
13064                                  const struct event_location *location,
13065                                  struct program_space *search_pspace,
13066                                  struct symtabs_and_lines *sals)
13067 {
13068   internal_error_pure_virtual_called ();
13069 }
13070
13071 /* The default 'explains_signal' method.  */
13072
13073 static int
13074 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13075 {
13076   return 1;
13077 }
13078
13079 /* The default "after_condition_true" method.  */
13080
13081 static void
13082 base_breakpoint_after_condition_true (struct bpstats *bs)
13083 {
13084   /* Nothing to do.   */
13085 }
13086
13087 struct breakpoint_ops base_breakpoint_ops =
13088 {
13089   base_breakpoint_dtor,
13090   base_breakpoint_allocate_location,
13091   base_breakpoint_re_set,
13092   base_breakpoint_insert_location,
13093   base_breakpoint_remove_location,
13094   base_breakpoint_breakpoint_hit,
13095   base_breakpoint_check_status,
13096   base_breakpoint_resources_needed,
13097   base_breakpoint_works_in_software_mode,
13098   base_breakpoint_print_it,
13099   NULL,
13100   base_breakpoint_print_one_detail,
13101   base_breakpoint_print_mention,
13102   base_breakpoint_print_recreate,
13103   base_breakpoint_create_sals_from_location,
13104   base_breakpoint_create_breakpoints_sal,
13105   base_breakpoint_decode_location,
13106   base_breakpoint_explains_signal,
13107   base_breakpoint_after_condition_true,
13108 };
13109
13110 /* Default breakpoint_ops methods.  */
13111
13112 static void
13113 bkpt_re_set (struct breakpoint *b)
13114 {
13115   /* FIXME: is this still reachable?  */
13116   if (breakpoint_event_location_empty_p (b))
13117     {
13118       /* Anything without a location can't be re-set.  */
13119       delete_breakpoint (b);
13120       return;
13121     }
13122
13123   breakpoint_re_set_default (b);
13124 }
13125
13126 static int
13127 bkpt_insert_location (struct bp_location *bl)
13128 {
13129   if (bl->loc_type == bp_loc_hardware_breakpoint)
13130     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13131   else
13132     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13133 }
13134
13135 static int
13136 bkpt_remove_location (struct bp_location *bl)
13137 {
13138   if (bl->loc_type == bp_loc_hardware_breakpoint)
13139     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13140   else
13141     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13142 }
13143
13144 static int
13145 bkpt_breakpoint_hit (const struct bp_location *bl,
13146                      struct address_space *aspace, CORE_ADDR bp_addr,
13147                      const struct target_waitstatus *ws)
13148 {
13149   if (ws->kind != TARGET_WAITKIND_STOPPED
13150       || ws->value.sig != GDB_SIGNAL_TRAP)
13151     return 0;
13152
13153   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13154                                  aspace, bp_addr))
13155     return 0;
13156
13157   if (overlay_debugging         /* unmapped overlay section */
13158       && section_is_overlay (bl->section)
13159       && !section_is_mapped (bl->section))
13160     return 0;
13161
13162   return 1;
13163 }
13164
13165 static int
13166 dprintf_breakpoint_hit (const struct bp_location *bl,
13167                         struct address_space *aspace, CORE_ADDR bp_addr,
13168                         const struct target_waitstatus *ws)
13169 {
13170   if (dprintf_style == dprintf_style_agent
13171       && target_can_run_breakpoint_commands ())
13172     {
13173       /* An agent-style dprintf never causes a stop.  If we see a trap
13174          for this address it must be for a breakpoint that happens to
13175          be set at the same address.  */
13176       return 0;
13177     }
13178
13179   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13180 }
13181
13182 static int
13183 bkpt_resources_needed (const struct bp_location *bl)
13184 {
13185   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13186
13187   return 1;
13188 }
13189
13190 static enum print_stop_action
13191 bkpt_print_it (bpstat bs)
13192 {
13193   struct breakpoint *b;
13194   const struct bp_location *bl;
13195   int bp_temp;
13196   struct ui_out *uiout = current_uiout;
13197
13198   gdb_assert (bs->bp_location_at != NULL);
13199
13200   bl = bs->bp_location_at;
13201   b = bs->breakpoint_at;
13202
13203   bp_temp = b->disposition == disp_del;
13204   if (bl->address != bl->requested_address)
13205     breakpoint_adjustment_warning (bl->requested_address,
13206                                    bl->address,
13207                                    b->number, 1);
13208   annotate_breakpoint (b->number);
13209   maybe_print_thread_hit_breakpoint (uiout);
13210
13211   if (bp_temp)
13212     ui_out_text (uiout, "Temporary breakpoint ");
13213   else
13214     ui_out_text (uiout, "Breakpoint ");
13215   if (ui_out_is_mi_like_p (uiout))
13216     {
13217       ui_out_field_string (uiout, "reason",
13218                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13219       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13220     }
13221   ui_out_field_int (uiout, "bkptno", b->number);
13222   ui_out_text (uiout, ", ");
13223
13224   return PRINT_SRC_AND_LOC;
13225 }
13226
13227 static void
13228 bkpt_print_mention (struct breakpoint *b)
13229 {
13230   if (ui_out_is_mi_like_p (current_uiout))
13231     return;
13232
13233   switch (b->type)
13234     {
13235     case bp_breakpoint:
13236     case bp_gnu_ifunc_resolver:
13237       if (b->disposition == disp_del)
13238         printf_filtered (_("Temporary breakpoint"));
13239       else
13240         printf_filtered (_("Breakpoint"));
13241       printf_filtered (_(" %d"), b->number);
13242       if (b->type == bp_gnu_ifunc_resolver)
13243         printf_filtered (_(" at gnu-indirect-function resolver"));
13244       break;
13245     case bp_hardware_breakpoint:
13246       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13247       break;
13248     case bp_dprintf:
13249       printf_filtered (_("Dprintf %d"), b->number);
13250       break;
13251     }
13252
13253   say_where (b);
13254 }
13255
13256 static void
13257 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13258 {
13259   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13260     fprintf_unfiltered (fp, "tbreak");
13261   else if (tp->type == bp_breakpoint)
13262     fprintf_unfiltered (fp, "break");
13263   else if (tp->type == bp_hardware_breakpoint
13264            && tp->disposition == disp_del)
13265     fprintf_unfiltered (fp, "thbreak");
13266   else if (tp->type == bp_hardware_breakpoint)
13267     fprintf_unfiltered (fp, "hbreak");
13268   else
13269     internal_error (__FILE__, __LINE__,
13270                     _("unhandled breakpoint type %d"), (int) tp->type);
13271
13272   fprintf_unfiltered (fp, " %s",
13273                       event_location_to_string (tp->location));
13274
13275   /* Print out extra_string if this breakpoint is pending.  It might
13276      contain, for example, conditions that were set by the user.  */
13277   if (tp->loc == NULL && tp->extra_string != NULL)
13278     fprintf_unfiltered (fp, " %s", tp->extra_string);
13279
13280   print_recreate_thread (tp, fp);
13281 }
13282
13283 static void
13284 bkpt_create_sals_from_location (const struct event_location *location,
13285                                 struct linespec_result *canonical,
13286                                 enum bptype type_wanted)
13287 {
13288   create_sals_from_location_default (location, canonical, type_wanted);
13289 }
13290
13291 static void
13292 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13293                              struct linespec_result *canonical,
13294                              char *cond_string,
13295                              char *extra_string,
13296                              enum bptype type_wanted,
13297                              enum bpdisp disposition,
13298                              int thread,
13299                              int task, int ignore_count,
13300                              const struct breakpoint_ops *ops,
13301                              int from_tty, int enabled,
13302                              int internal, unsigned flags)
13303 {
13304   create_breakpoints_sal_default (gdbarch, canonical,
13305                                   cond_string, extra_string,
13306                                   type_wanted,
13307                                   disposition, thread, task,
13308                                   ignore_count, ops, from_tty,
13309                                   enabled, internal, flags);
13310 }
13311
13312 static void
13313 bkpt_decode_location (struct breakpoint *b,
13314                       const struct event_location *location,
13315                       struct program_space *search_pspace,
13316                       struct symtabs_and_lines *sals)
13317 {
13318   decode_location_default (b, location, search_pspace, sals);
13319 }
13320
13321 /* Virtual table for internal breakpoints.  */
13322
13323 static void
13324 internal_bkpt_re_set (struct breakpoint *b)
13325 {
13326   switch (b->type)
13327     {
13328       /* Delete overlay event and longjmp master breakpoints; they
13329          will be reset later by breakpoint_re_set.  */
13330     case bp_overlay_event:
13331     case bp_longjmp_master:
13332     case bp_std_terminate_master:
13333     case bp_exception_master:
13334       delete_breakpoint (b);
13335       break;
13336
13337       /* This breakpoint is special, it's set up when the inferior
13338          starts and we really don't want to touch it.  */
13339     case bp_shlib_event:
13340
13341       /* Like bp_shlib_event, this breakpoint type is special.  Once
13342          it is set up, we do not want to touch it.  */
13343     case bp_thread_event:
13344       break;
13345     }
13346 }
13347
13348 static void
13349 internal_bkpt_check_status (bpstat bs)
13350 {
13351   if (bs->breakpoint_at->type == bp_shlib_event)
13352     {
13353       /* If requested, stop when the dynamic linker notifies GDB of
13354          events.  This allows the user to get control and place
13355          breakpoints in initializer routines for dynamically loaded
13356          objects (among other things).  */
13357       bs->stop = stop_on_solib_events;
13358       bs->print = stop_on_solib_events;
13359     }
13360   else
13361     bs->stop = 0;
13362 }
13363
13364 static enum print_stop_action
13365 internal_bkpt_print_it (bpstat bs)
13366 {
13367   struct breakpoint *b;
13368
13369   b = bs->breakpoint_at;
13370
13371   switch (b->type)
13372     {
13373     case bp_shlib_event:
13374       /* Did we stop because the user set the stop_on_solib_events
13375          variable?  (If so, we report this as a generic, "Stopped due
13376          to shlib event" message.) */
13377       print_solib_event (0);
13378       break;
13379
13380     case bp_thread_event:
13381       /* Not sure how we will get here.
13382          GDB should not stop for these breakpoints.  */
13383       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13384       break;
13385
13386     case bp_overlay_event:
13387       /* By analogy with the thread event, GDB should not stop for these.  */
13388       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13389       break;
13390
13391     case bp_longjmp_master:
13392       /* These should never be enabled.  */
13393       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13394       break;
13395
13396     case bp_std_terminate_master:
13397       /* These should never be enabled.  */
13398       printf_filtered (_("std::terminate Master Breakpoint: "
13399                          "gdb should not stop!\n"));
13400       break;
13401
13402     case bp_exception_master:
13403       /* These should never be enabled.  */
13404       printf_filtered (_("Exception Master Breakpoint: "
13405                          "gdb should not stop!\n"));
13406       break;
13407     }
13408
13409   return PRINT_NOTHING;
13410 }
13411
13412 static void
13413 internal_bkpt_print_mention (struct breakpoint *b)
13414 {
13415   /* Nothing to mention.  These breakpoints are internal.  */
13416 }
13417
13418 /* Virtual table for momentary breakpoints  */
13419
13420 static void
13421 momentary_bkpt_re_set (struct breakpoint *b)
13422 {
13423   /* Keep temporary breakpoints, which can be encountered when we step
13424      over a dlopen call and solib_add is resetting the breakpoints.
13425      Otherwise these should have been blown away via the cleanup chain
13426      or by breakpoint_init_inferior when we rerun the executable.  */
13427 }
13428
13429 static void
13430 momentary_bkpt_check_status (bpstat bs)
13431 {
13432   /* Nothing.  The point of these breakpoints is causing a stop.  */
13433 }
13434
13435 static enum print_stop_action
13436 momentary_bkpt_print_it (bpstat bs)
13437 {
13438   return PRINT_UNKNOWN;
13439 }
13440
13441 static void
13442 momentary_bkpt_print_mention (struct breakpoint *b)
13443 {
13444   /* Nothing to mention.  These breakpoints are internal.  */
13445 }
13446
13447 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13448
13449    It gets cleared already on the removal of the first one of such placed
13450    breakpoints.  This is OK as they get all removed altogether.  */
13451
13452 static void
13453 longjmp_bkpt_dtor (struct breakpoint *self)
13454 {
13455   struct thread_info *tp = find_thread_global_id (self->thread);
13456
13457   if (tp)
13458     tp->initiating_frame = null_frame_id;
13459
13460   momentary_breakpoint_ops.dtor (self);
13461 }
13462
13463 /* Specific methods for probe breakpoints.  */
13464
13465 static int
13466 bkpt_probe_insert_location (struct bp_location *bl)
13467 {
13468   int v = bkpt_insert_location (bl);
13469
13470   if (v == 0)
13471     {
13472       /* The insertion was successful, now let's set the probe's semaphore
13473          if needed.  */
13474       if (bl->probe.probe->pops->set_semaphore != NULL)
13475         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13476                                               bl->probe.objfile,
13477                                               bl->gdbarch);
13478     }
13479
13480   return v;
13481 }
13482
13483 static int
13484 bkpt_probe_remove_location (struct bp_location *bl)
13485 {
13486   /* Let's clear the semaphore before removing the location.  */
13487   if (bl->probe.probe->pops->clear_semaphore != NULL)
13488     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13489                                             bl->probe.objfile,
13490                                             bl->gdbarch);
13491
13492   return bkpt_remove_location (bl);
13493 }
13494
13495 static void
13496 bkpt_probe_create_sals_from_location (const struct event_location *location,
13497                                       struct linespec_result *canonical,
13498                                       enum bptype type_wanted)
13499 {
13500   struct linespec_sals lsal;
13501
13502   lsal.sals = parse_probes (location, NULL, canonical);
13503   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13504   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13505 }
13506
13507 static void
13508 bkpt_probe_decode_location (struct breakpoint *b,
13509                             const struct event_location *location,
13510                             struct program_space *search_pspace,
13511                             struct symtabs_and_lines *sals)
13512 {
13513   *sals = parse_probes (location, search_pspace, NULL);
13514   if (!sals->sals)
13515     error (_("probe not found"));
13516 }
13517
13518 /* The breakpoint_ops structure to be used in tracepoints.  */
13519
13520 static void
13521 tracepoint_re_set (struct breakpoint *b)
13522 {
13523   breakpoint_re_set_default (b);
13524 }
13525
13526 static int
13527 tracepoint_breakpoint_hit (const struct bp_location *bl,
13528                            struct address_space *aspace, CORE_ADDR bp_addr,
13529                            const struct target_waitstatus *ws)
13530 {
13531   /* By definition, the inferior does not report stops at
13532      tracepoints.  */
13533   return 0;
13534 }
13535
13536 static void
13537 tracepoint_print_one_detail (const struct breakpoint *self,
13538                              struct ui_out *uiout)
13539 {
13540   struct tracepoint *tp = (struct tracepoint *) self;
13541   if (tp->static_trace_marker_id)
13542     {
13543       gdb_assert (self->type == bp_static_tracepoint);
13544
13545       ui_out_text (uiout, "\tmarker id is ");
13546       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13547                            tp->static_trace_marker_id);
13548       ui_out_text (uiout, "\n");
13549     }
13550 }
13551
13552 static void
13553 tracepoint_print_mention (struct breakpoint *b)
13554 {
13555   if (ui_out_is_mi_like_p (current_uiout))
13556     return;
13557
13558   switch (b->type)
13559     {
13560     case bp_tracepoint:
13561       printf_filtered (_("Tracepoint"));
13562       printf_filtered (_(" %d"), b->number);
13563       break;
13564     case bp_fast_tracepoint:
13565       printf_filtered (_("Fast tracepoint"));
13566       printf_filtered (_(" %d"), b->number);
13567       break;
13568     case bp_static_tracepoint:
13569       printf_filtered (_("Static tracepoint"));
13570       printf_filtered (_(" %d"), b->number);
13571       break;
13572     default:
13573       internal_error (__FILE__, __LINE__,
13574                       _("unhandled tracepoint type %d"), (int) b->type);
13575     }
13576
13577   say_where (b);
13578 }
13579
13580 static void
13581 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13582 {
13583   struct tracepoint *tp = (struct tracepoint *) self;
13584
13585   if (self->type == bp_fast_tracepoint)
13586     fprintf_unfiltered (fp, "ftrace");
13587   else if (self->type == bp_static_tracepoint)
13588     fprintf_unfiltered (fp, "strace");
13589   else if (self->type == bp_tracepoint)
13590     fprintf_unfiltered (fp, "trace");
13591   else
13592     internal_error (__FILE__, __LINE__,
13593                     _("unhandled tracepoint type %d"), (int) self->type);
13594
13595   fprintf_unfiltered (fp, " %s",
13596                       event_location_to_string (self->location));
13597   print_recreate_thread (self, fp);
13598
13599   if (tp->pass_count)
13600     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13601 }
13602
13603 static void
13604 tracepoint_create_sals_from_location (const struct event_location *location,
13605                                       struct linespec_result *canonical,
13606                                       enum bptype type_wanted)
13607 {
13608   create_sals_from_location_default (location, canonical, type_wanted);
13609 }
13610
13611 static void
13612 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13613                                    struct linespec_result *canonical,
13614                                    char *cond_string,
13615                                    char *extra_string,
13616                                    enum bptype type_wanted,
13617                                    enum bpdisp disposition,
13618                                    int thread,
13619                                    int task, int ignore_count,
13620                                    const struct breakpoint_ops *ops,
13621                                    int from_tty, int enabled,
13622                                    int internal, unsigned flags)
13623 {
13624   create_breakpoints_sal_default (gdbarch, canonical,
13625                                   cond_string, extra_string,
13626                                   type_wanted,
13627                                   disposition, thread, task,
13628                                   ignore_count, ops, from_tty,
13629                                   enabled, internal, flags);
13630 }
13631
13632 static void
13633 tracepoint_decode_location (struct breakpoint *b,
13634                             const struct event_location *location,
13635                             struct program_space *search_pspace,
13636                             struct symtabs_and_lines *sals)
13637 {
13638   decode_location_default (b, location, search_pspace, sals);
13639 }
13640
13641 struct breakpoint_ops tracepoint_breakpoint_ops;
13642
13643 /* The breakpoint_ops structure to be use on tracepoints placed in a
13644    static probe.  */
13645
13646 static void
13647 tracepoint_probe_create_sals_from_location
13648   (const struct event_location *location,
13649    struct linespec_result *canonical,
13650    enum bptype type_wanted)
13651 {
13652   /* We use the same method for breakpoint on probes.  */
13653   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13654 }
13655
13656 static void
13657 tracepoint_probe_decode_location (struct breakpoint *b,
13658                                   const struct event_location *location,
13659                                   struct program_space *search_pspace,
13660                                   struct symtabs_and_lines *sals)
13661 {
13662   /* We use the same method for breakpoint on probes.  */
13663   bkpt_probe_decode_location (b, location, search_pspace, sals);
13664 }
13665
13666 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13667
13668 /* Dprintf breakpoint_ops methods.  */
13669
13670 static void
13671 dprintf_re_set (struct breakpoint *b)
13672 {
13673   breakpoint_re_set_default (b);
13674
13675   /* extra_string should never be non-NULL for dprintf.  */
13676   gdb_assert (b->extra_string != NULL);
13677
13678   /* 1 - connect to target 1, that can run breakpoint commands.
13679      2 - create a dprintf, which resolves fine.
13680      3 - disconnect from target 1
13681      4 - connect to target 2, that can NOT run breakpoint commands.
13682
13683      After steps #3/#4, you'll want the dprintf command list to
13684      be updated, because target 1 and 2 may well return different
13685      answers for target_can_run_breakpoint_commands().
13686      Given absence of finer grained resetting, we get to do
13687      it all the time.  */
13688   if (b->extra_string != NULL)
13689     update_dprintf_command_list (b);
13690 }
13691
13692 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13693
13694 static void
13695 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13696 {
13697   fprintf_unfiltered (fp, "dprintf %s,%s",
13698                       event_location_to_string (tp->location),
13699                       tp->extra_string);
13700   print_recreate_thread (tp, fp);
13701 }
13702
13703 /* Implement the "after_condition_true" breakpoint_ops method for
13704    dprintf.
13705
13706    dprintf's are implemented with regular commands in their command
13707    list, but we run the commands here instead of before presenting the
13708    stop to the user, as dprintf's don't actually cause a stop.  This
13709    also makes it so that the commands of multiple dprintfs at the same
13710    address are all handled.  */
13711
13712 static void
13713 dprintf_after_condition_true (struct bpstats *bs)
13714 {
13715   struct cleanup *old_chain;
13716   struct bpstats tmp_bs = { NULL };
13717   struct bpstats *tmp_bs_p = &tmp_bs;
13718
13719   /* dprintf's never cause a stop.  This wasn't set in the
13720      check_status hook instead because that would make the dprintf's
13721      condition not be evaluated.  */
13722   bs->stop = 0;
13723
13724   /* Run the command list here.  Take ownership of it instead of
13725      copying.  We never want these commands to run later in
13726      bpstat_do_actions, if a breakpoint that causes a stop happens to
13727      be set at same address as this dprintf, or even if running the
13728      commands here throws.  */
13729   tmp_bs.commands = bs->commands;
13730   bs->commands = NULL;
13731   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13732
13733   bpstat_do_actions_1 (&tmp_bs_p);
13734
13735   /* 'tmp_bs.commands' will usually be NULL by now, but
13736      bpstat_do_actions_1 may return early without processing the whole
13737      list.  */
13738   do_cleanups (old_chain);
13739 }
13740
13741 /* The breakpoint_ops structure to be used on static tracepoints with
13742    markers (`-m').  */
13743
13744 static void
13745 strace_marker_create_sals_from_location (const struct event_location *location,
13746                                          struct linespec_result *canonical,
13747                                          enum bptype type_wanted)
13748 {
13749   struct linespec_sals lsal;
13750   const char *arg_start, *arg;
13751   char *str;
13752   struct cleanup *cleanup;
13753
13754   arg = arg_start = get_linespec_location (location);
13755   lsal.sals = decode_static_tracepoint_spec (&arg);
13756
13757   str = savestring (arg_start, arg - arg_start);
13758   cleanup = make_cleanup (xfree, str);
13759   canonical->location = new_linespec_location (&str);
13760   do_cleanups (cleanup);
13761
13762   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13763   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13764 }
13765
13766 static void
13767 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13768                                       struct linespec_result *canonical,
13769                                       char *cond_string,
13770                                       char *extra_string,
13771                                       enum bptype type_wanted,
13772                                       enum bpdisp disposition,
13773                                       int thread,
13774                                       int task, int ignore_count,
13775                                       const struct breakpoint_ops *ops,
13776                                       int from_tty, int enabled,
13777                                       int internal, unsigned flags)
13778 {
13779   int i;
13780   struct linespec_sals *lsal = VEC_index (linespec_sals,
13781                                           canonical->sals, 0);
13782
13783   /* If the user is creating a static tracepoint by marker id
13784      (strace -m MARKER_ID), then store the sals index, so that
13785      breakpoint_re_set can try to match up which of the newly
13786      found markers corresponds to this one, and, don't try to
13787      expand multiple locations for each sal, given than SALS
13788      already should contain all sals for MARKER_ID.  */
13789
13790   for (i = 0; i < lsal->sals.nelts; ++i)
13791     {
13792       struct symtabs_and_lines expanded;
13793       struct tracepoint *tp;
13794       struct cleanup *old_chain;
13795       struct event_location *location;
13796
13797       expanded.nelts = 1;
13798       expanded.sals = &lsal->sals.sals[i];
13799
13800       location = copy_event_location (canonical->location);
13801       old_chain = make_cleanup_delete_event_location (location);
13802
13803       tp = XCNEW (struct tracepoint);
13804       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13805                            location, NULL,
13806                            cond_string, extra_string,
13807                            type_wanted, disposition,
13808                            thread, task, ignore_count, ops,
13809                            from_tty, enabled, internal, flags,
13810                            canonical->special_display);
13811       /* Given that its possible to have multiple markers with
13812          the same string id, if the user is creating a static
13813          tracepoint by marker id ("strace -m MARKER_ID"), then
13814          store the sals index, so that breakpoint_re_set can
13815          try to match up which of the newly found markers
13816          corresponds to this one  */
13817       tp->static_trace_marker_id_idx = i;
13818
13819       install_breakpoint (internal, &tp->base, 0);
13820
13821       discard_cleanups (old_chain);
13822     }
13823 }
13824
13825 static void
13826 strace_marker_decode_location (struct breakpoint *b,
13827                                const struct event_location *location,
13828                                struct program_space *search_pspace,
13829                                struct symtabs_and_lines *sals)
13830 {
13831   struct tracepoint *tp = (struct tracepoint *) b;
13832   const char *s = get_linespec_location (location);
13833
13834   *sals = decode_static_tracepoint_spec (&s);
13835   if (sals->nelts > tp->static_trace_marker_id_idx)
13836     {
13837       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13838       sals->nelts = 1;
13839     }
13840   else
13841     error (_("marker %s not found"), tp->static_trace_marker_id);
13842 }
13843
13844 static struct breakpoint_ops strace_marker_breakpoint_ops;
13845
13846 static int
13847 strace_marker_p (struct breakpoint *b)
13848 {
13849   return b->ops == &strace_marker_breakpoint_ops;
13850 }
13851
13852 /* Delete a breakpoint and clean up all traces of it in the data
13853    structures.  */
13854
13855 void
13856 delete_breakpoint (struct breakpoint *bpt)
13857 {
13858   struct breakpoint *b;
13859
13860   gdb_assert (bpt != NULL);
13861
13862   /* Has this bp already been deleted?  This can happen because
13863      multiple lists can hold pointers to bp's.  bpstat lists are
13864      especial culprits.
13865
13866      One example of this happening is a watchpoint's scope bp.  When
13867      the scope bp triggers, we notice that the watchpoint is out of
13868      scope, and delete it.  We also delete its scope bp.  But the
13869      scope bp is marked "auto-deleting", and is already on a bpstat.
13870      That bpstat is then checked for auto-deleting bp's, which are
13871      deleted.
13872
13873      A real solution to this problem might involve reference counts in
13874      bp's, and/or giving them pointers back to their referencing
13875      bpstat's, and teaching delete_breakpoint to only free a bp's
13876      storage when no more references were extent.  A cheaper bandaid
13877      was chosen.  */
13878   if (bpt->type == bp_none)
13879     return;
13880
13881   /* At least avoid this stale reference until the reference counting
13882      of breakpoints gets resolved.  */
13883   if (bpt->related_breakpoint != bpt)
13884     {
13885       struct breakpoint *related;
13886       struct watchpoint *w;
13887
13888       if (bpt->type == bp_watchpoint_scope)
13889         w = (struct watchpoint *) bpt->related_breakpoint;
13890       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13891         w = (struct watchpoint *) bpt;
13892       else
13893         w = NULL;
13894       if (w != NULL)
13895         watchpoint_del_at_next_stop (w);
13896
13897       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13898       for (related = bpt; related->related_breakpoint != bpt;
13899            related = related->related_breakpoint);
13900       related->related_breakpoint = bpt->related_breakpoint;
13901       bpt->related_breakpoint = bpt;
13902     }
13903
13904   /* watch_command_1 creates a watchpoint but only sets its number if
13905      update_watchpoint succeeds in creating its bp_locations.  If there's
13906      a problem in that process, we'll be asked to delete the half-created
13907      watchpoint.  In that case, don't announce the deletion.  */
13908   if (bpt->number)
13909     observer_notify_breakpoint_deleted (bpt);
13910
13911   if (breakpoint_chain == bpt)
13912     breakpoint_chain = bpt->next;
13913
13914   ALL_BREAKPOINTS (b)
13915     if (b->next == bpt)
13916     {
13917       b->next = bpt->next;
13918       break;
13919     }
13920
13921   /* Be sure no bpstat's are pointing at the breakpoint after it's
13922      been freed.  */
13923   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13924      in all threads for now.  Note that we cannot just remove bpstats
13925      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13926      commands are associated with the bpstat; if we remove it here,
13927      then the later call to bpstat_do_actions (&stop_bpstat); in
13928      event-top.c won't do anything, and temporary breakpoints with
13929      commands won't work.  */
13930
13931   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13932
13933   /* Now that breakpoint is removed from breakpoint list, update the
13934      global location list.  This will remove locations that used to
13935      belong to this breakpoint.  Do this before freeing the breakpoint
13936      itself, since remove_breakpoint looks at location's owner.  It
13937      might be better design to have location completely
13938      self-contained, but it's not the case now.  */
13939   update_global_location_list (UGLL_DONT_INSERT);
13940
13941   bpt->ops->dtor (bpt);
13942   /* On the chance that someone will soon try again to delete this
13943      same bp, we mark it as deleted before freeing its storage.  */
13944   bpt->type = bp_none;
13945   xfree (bpt);
13946 }
13947
13948 static void
13949 do_delete_breakpoint_cleanup (void *b)
13950 {
13951   delete_breakpoint ((struct breakpoint *) b);
13952 }
13953
13954 struct cleanup *
13955 make_cleanup_delete_breakpoint (struct breakpoint *b)
13956 {
13957   return make_cleanup (do_delete_breakpoint_cleanup, b);
13958 }
13959
13960 /* Iterator function to call a user-provided callback function once
13961    for each of B and its related breakpoints.  */
13962
13963 static void
13964 iterate_over_related_breakpoints (struct breakpoint *b,
13965                                   void (*function) (struct breakpoint *,
13966                                                     void *),
13967                                   void *data)
13968 {
13969   struct breakpoint *related;
13970
13971   related = b;
13972   do
13973     {
13974       struct breakpoint *next;
13975
13976       /* FUNCTION may delete RELATED.  */
13977       next = related->related_breakpoint;
13978
13979       if (next == related)
13980         {
13981           /* RELATED is the last ring entry.  */
13982           function (related, data);
13983
13984           /* FUNCTION may have deleted it, so we'd never reach back to
13985              B.  There's nothing left to do anyway, so just break
13986              out.  */
13987           break;
13988         }
13989       else
13990         function (related, data);
13991
13992       related = next;
13993     }
13994   while (related != b);
13995 }
13996
13997 static void
13998 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13999 {
14000   delete_breakpoint (b);
14001 }
14002
14003 /* A callback for map_breakpoint_numbers that calls
14004    delete_breakpoint.  */
14005
14006 static void
14007 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14008 {
14009   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14010 }
14011
14012 void
14013 delete_command (char *arg, int from_tty)
14014 {
14015   struct breakpoint *b, *b_tmp;
14016
14017   dont_repeat ();
14018
14019   if (arg == 0)
14020     {
14021       int breaks_to_delete = 0;
14022
14023       /* Delete all breakpoints if no argument.  Do not delete
14024          internal breakpoints, these have to be deleted with an
14025          explicit breakpoint number argument.  */
14026       ALL_BREAKPOINTS (b)
14027         if (user_breakpoint_p (b))
14028           {
14029             breaks_to_delete = 1;
14030             break;
14031           }
14032
14033       /* Ask user only if there are some breakpoints to delete.  */
14034       if (!from_tty
14035           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14036         {
14037           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14038             if (user_breakpoint_p (b))
14039               delete_breakpoint (b);
14040         }
14041     }
14042   else
14043     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14044 }
14045
14046 /* Return true if all locations of B bound to PSPACE are pending.  If
14047    PSPACE is NULL, all locations of all program spaces are
14048    considered.  */
14049
14050 static int
14051 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
14052 {
14053   struct bp_location *loc;
14054
14055   for (loc = b->loc; loc != NULL; loc = loc->next)
14056     if ((pspace == NULL
14057          || loc->pspace == pspace)
14058         && !loc->shlib_disabled
14059         && !loc->pspace->executing_startup)
14060       return 0;
14061   return 1;
14062 }
14063
14064 /* Subroutine of update_breakpoint_locations to simplify it.
14065    Return non-zero if multiple fns in list LOC have the same name.
14066    Null names are ignored.  */
14067
14068 static int
14069 ambiguous_names_p (struct bp_location *loc)
14070 {
14071   struct bp_location *l;
14072   htab_t htab = htab_create_alloc (13, htab_hash_string,
14073                                    (int (*) (const void *, 
14074                                              const void *)) streq,
14075                                    NULL, xcalloc, xfree);
14076
14077   for (l = loc; l != NULL; l = l->next)
14078     {
14079       const char **slot;
14080       const char *name = l->function_name;
14081
14082       /* Allow for some names to be NULL, ignore them.  */
14083       if (name == NULL)
14084         continue;
14085
14086       slot = (const char **) htab_find_slot (htab, (const void *) name,
14087                                              INSERT);
14088       /* NOTE: We can assume slot != NULL here because xcalloc never
14089          returns NULL.  */
14090       if (*slot != NULL)
14091         {
14092           htab_delete (htab);
14093           return 1;
14094         }
14095       *slot = name;
14096     }
14097
14098   htab_delete (htab);
14099   return 0;
14100 }
14101
14102 /* When symbols change, it probably means the sources changed as well,
14103    and it might mean the static tracepoint markers are no longer at
14104    the same address or line numbers they used to be at last we
14105    checked.  Losing your static tracepoints whenever you rebuild is
14106    undesirable.  This function tries to resync/rematch gdb static
14107    tracepoints with the markers on the target, for static tracepoints
14108    that have not been set by marker id.  Static tracepoint that have
14109    been set by marker id are reset by marker id in breakpoint_re_set.
14110    The heuristic is:
14111
14112    1) For a tracepoint set at a specific address, look for a marker at
14113    the old PC.  If one is found there, assume to be the same marker.
14114    If the name / string id of the marker found is different from the
14115    previous known name, assume that means the user renamed the marker
14116    in the sources, and output a warning.
14117
14118    2) For a tracepoint set at a given line number, look for a marker
14119    at the new address of the old line number.  If one is found there,
14120    assume to be the same marker.  If the name / string id of the
14121    marker found is different from the previous known name, assume that
14122    means the user renamed the marker in the sources, and output a
14123    warning.
14124
14125    3) If a marker is no longer found at the same address or line, it
14126    may mean the marker no longer exists.  But it may also just mean
14127    the code changed a bit.  Maybe the user added a few lines of code
14128    that made the marker move up or down (in line number terms).  Ask
14129    the target for info about the marker with the string id as we knew
14130    it.  If found, update line number and address in the matching
14131    static tracepoint.  This will get confused if there's more than one
14132    marker with the same ID (possible in UST, although unadvised
14133    precisely because it confuses tools).  */
14134
14135 static struct symtab_and_line
14136 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14137 {
14138   struct tracepoint *tp = (struct tracepoint *) b;
14139   struct static_tracepoint_marker marker;
14140   CORE_ADDR pc;
14141
14142   pc = sal.pc;
14143   if (sal.line)
14144     find_line_pc (sal.symtab, sal.line, &pc);
14145
14146   if (target_static_tracepoint_marker_at (pc, &marker))
14147     {
14148       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14149         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14150                  b->number,
14151                  tp->static_trace_marker_id, marker.str_id);
14152
14153       xfree (tp->static_trace_marker_id);
14154       tp->static_trace_marker_id = xstrdup (marker.str_id);
14155       release_static_tracepoint_marker (&marker);
14156
14157       return sal;
14158     }
14159
14160   /* Old marker wasn't found on target at lineno.  Try looking it up
14161      by string ID.  */
14162   if (!sal.explicit_pc
14163       && sal.line != 0
14164       && sal.symtab != NULL
14165       && tp->static_trace_marker_id != NULL)
14166     {
14167       VEC(static_tracepoint_marker_p) *markers;
14168
14169       markers
14170         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14171
14172       if (!VEC_empty(static_tracepoint_marker_p, markers))
14173         {
14174           struct symtab_and_line sal2;
14175           struct symbol *sym;
14176           struct static_tracepoint_marker *tpmarker;
14177           struct ui_out *uiout = current_uiout;
14178           struct explicit_location explicit_loc;
14179
14180           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14181
14182           xfree (tp->static_trace_marker_id);
14183           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14184
14185           warning (_("marker for static tracepoint %d (%s) not "
14186                      "found at previous line number"),
14187                    b->number, tp->static_trace_marker_id);
14188
14189           init_sal (&sal2);
14190
14191           sal2.pc = tpmarker->address;
14192
14193           sal2 = find_pc_line (tpmarker->address, 0);
14194           sym = find_pc_sect_function (tpmarker->address, NULL);
14195           ui_out_text (uiout, "Now in ");
14196           if (sym)
14197             {
14198               ui_out_field_string (uiout, "func",
14199                                    SYMBOL_PRINT_NAME (sym));
14200               ui_out_text (uiout, " at ");
14201             }
14202           ui_out_field_string (uiout, "file",
14203                                symtab_to_filename_for_display (sal2.symtab));
14204           ui_out_text (uiout, ":");
14205
14206           if (ui_out_is_mi_like_p (uiout))
14207             {
14208               const char *fullname = symtab_to_fullname (sal2.symtab);
14209
14210               ui_out_field_string (uiout, "fullname", fullname);
14211             }
14212
14213           ui_out_field_int (uiout, "line", sal2.line);
14214           ui_out_text (uiout, "\n");
14215
14216           b->loc->line_number = sal2.line;
14217           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14218
14219           delete_event_location (b->location);
14220           initialize_explicit_location (&explicit_loc);
14221           explicit_loc.source_filename
14222             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14223           explicit_loc.line_offset.offset = b->loc->line_number;
14224           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14225           b->location = new_explicit_location (&explicit_loc);
14226
14227           /* Might be nice to check if function changed, and warn if
14228              so.  */
14229
14230           release_static_tracepoint_marker (tpmarker);
14231         }
14232     }
14233   return sal;
14234 }
14235
14236 /* Returns 1 iff locations A and B are sufficiently same that
14237    we don't need to report breakpoint as changed.  */
14238
14239 static int
14240 locations_are_equal (struct bp_location *a, struct bp_location *b)
14241 {
14242   while (a && b)
14243     {
14244       if (a->address != b->address)
14245         return 0;
14246
14247       if (a->shlib_disabled != b->shlib_disabled)
14248         return 0;
14249
14250       if (a->enabled != b->enabled)
14251         return 0;
14252
14253       a = a->next;
14254       b = b->next;
14255     }
14256
14257   if ((a == NULL) != (b == NULL))
14258     return 0;
14259
14260   return 1;
14261 }
14262
14263 /* Split all locations of B that are bound to PSPACE out of B's
14264    location list to a separate list and return that list's head.  If
14265    PSPACE is NULL, hoist out all locations of B.  */
14266
14267 static struct bp_location *
14268 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
14269 {
14270   struct bp_location head;
14271   struct bp_location *i = b->loc;
14272   struct bp_location **i_link = &b->loc;
14273   struct bp_location *hoisted = &head;
14274
14275   if (pspace == NULL)
14276     {
14277       i = b->loc;
14278       b->loc = NULL;
14279       return i;
14280     }
14281
14282   head.next = NULL;
14283
14284   while (i != NULL)
14285     {
14286       if (i->pspace == pspace)
14287         {
14288           *i_link = i->next;
14289           i->next = NULL;
14290           hoisted->next = i;
14291           hoisted = i;
14292         }
14293       else
14294         i_link = &i->next;
14295       i = *i_link;
14296     }
14297
14298   return head.next;
14299 }
14300
14301 /* Create new breakpoint locations for B (a hardware or software
14302    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
14303    zero, then B is a ranged breakpoint.  Only recreates locations for
14304    FILTER_PSPACE.  Locations of other program spaces are left
14305    untouched.  */
14306
14307 void
14308 update_breakpoint_locations (struct breakpoint *b,
14309                              struct program_space *filter_pspace,
14310                              struct symtabs_and_lines sals,
14311                              struct symtabs_and_lines sals_end)
14312 {
14313   int i;
14314   struct bp_location *existing_locations;
14315
14316   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14317     {
14318       /* Ranged breakpoints have only one start location and one end
14319          location.  */
14320       b->enable_state = bp_disabled;
14321       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14322                            "multiple locations found\n"),
14323                          b->number);
14324       return;
14325     }
14326
14327   /* If there's no new locations, and all existing locations are
14328      pending, don't do anything.  This optimizes the common case where
14329      all locations are in the same shared library, that was unloaded.
14330      We'd like to retain the location, so that when the library is
14331      loaded again, we don't loose the enabled/disabled status of the
14332      individual locations.  */
14333   if (all_locations_are_pending (b, filter_pspace) && sals.nelts == 0)
14334     return;
14335
14336   existing_locations = hoist_existing_locations (b, filter_pspace);
14337
14338   for (i = 0; i < sals.nelts; ++i)
14339     {
14340       struct bp_location *new_loc;
14341
14342       switch_to_program_space_and_thread (sals.sals[i].pspace);
14343
14344       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14345
14346       /* Reparse conditions, they might contain references to the
14347          old symtab.  */
14348       if (b->cond_string != NULL)
14349         {
14350           const char *s;
14351
14352           s = b->cond_string;
14353           TRY
14354             {
14355               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14356                                            block_for_pc (sals.sals[i].pc), 
14357                                            0);
14358             }
14359           CATCH (e, RETURN_MASK_ERROR)
14360             {
14361               warning (_("failed to reevaluate condition "
14362                          "for breakpoint %d: %s"), 
14363                        b->number, e.message);
14364               new_loc->enabled = 0;
14365             }
14366           END_CATCH
14367         }
14368
14369       if (sals_end.nelts)
14370         {
14371           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14372
14373           new_loc->length = end - sals.sals[0].pc + 1;
14374         }
14375     }
14376
14377   /* If possible, carry over 'disable' status from existing
14378      breakpoints.  */
14379   {
14380     struct bp_location *e = existing_locations;
14381     /* If there are multiple breakpoints with the same function name,
14382        e.g. for inline functions, comparing function names won't work.
14383        Instead compare pc addresses; this is just a heuristic as things
14384        may have moved, but in practice it gives the correct answer
14385        often enough until a better solution is found.  */
14386     int have_ambiguous_names = ambiguous_names_p (b->loc);
14387
14388     for (; e; e = e->next)
14389       {
14390         if (!e->enabled && e->function_name)
14391           {
14392             struct bp_location *l = b->loc;
14393             if (have_ambiguous_names)
14394               {
14395                 for (; l; l = l->next)
14396                   if (breakpoint_locations_match (e, l))
14397                     {
14398                       l->enabled = 0;
14399                       break;
14400                     }
14401               }
14402             else
14403               {
14404                 for (; l; l = l->next)
14405                   if (l->function_name
14406                       && strcmp (e->function_name, l->function_name) == 0)
14407                     {
14408                       l->enabled = 0;
14409                       break;
14410                     }
14411               }
14412           }
14413       }
14414   }
14415
14416   if (!locations_are_equal (existing_locations, b->loc))
14417     observer_notify_breakpoint_modified (b);
14418 }
14419
14420 /* Find the SaL locations corresponding to the given LOCATION.
14421    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14422
14423 static struct symtabs_and_lines
14424 location_to_sals (struct breakpoint *b, struct event_location *location,
14425                   struct program_space *search_pspace, int *found)
14426 {
14427   struct symtabs_and_lines sals = {0};
14428   struct gdb_exception exception = exception_none;
14429
14430   gdb_assert (b->ops != NULL);
14431
14432   TRY
14433     {
14434       b->ops->decode_location (b, location, search_pspace, &sals);
14435     }
14436   CATCH (e, RETURN_MASK_ERROR)
14437     {
14438       int not_found_and_ok = 0;
14439
14440       exception = e;
14441
14442       /* For pending breakpoints, it's expected that parsing will
14443          fail until the right shared library is loaded.  User has
14444          already told to create pending breakpoints and don't need
14445          extra messages.  If breakpoint is in bp_shlib_disabled
14446          state, then user already saw the message about that
14447          breakpoint being disabled, and don't want to see more
14448          errors.  */
14449       if (e.error == NOT_FOUND_ERROR
14450           && (b->condition_not_parsed
14451               || (b->loc != NULL
14452                   && search_pspace != NULL
14453                   && b->loc->pspace != search_pspace)
14454               || (b->loc && b->loc->shlib_disabled)
14455               || (b->loc && b->loc->pspace->executing_startup)
14456               || b->enable_state == bp_disabled))
14457         not_found_and_ok = 1;
14458
14459       if (!not_found_and_ok)
14460         {
14461           /* We surely don't want to warn about the same breakpoint
14462              10 times.  One solution, implemented here, is disable
14463              the breakpoint on error.  Another solution would be to
14464              have separate 'warning emitted' flag.  Since this
14465              happens only when a binary has changed, I don't know
14466              which approach is better.  */
14467           b->enable_state = bp_disabled;
14468           throw_exception (e);
14469         }
14470     }
14471   END_CATCH
14472
14473   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14474     {
14475       int i;
14476
14477       for (i = 0; i < sals.nelts; ++i)
14478         resolve_sal_pc (&sals.sals[i]);
14479       if (b->condition_not_parsed && b->extra_string != NULL)
14480         {
14481           char *cond_string, *extra_string;
14482           int thread, task;
14483
14484           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14485                                      &cond_string, &thread, &task,
14486                                      &extra_string);
14487           gdb_assert (b->cond_string == NULL);
14488           if (cond_string)
14489             b->cond_string = cond_string;
14490           b->thread = thread;
14491           b->task = task;
14492           if (extra_string)
14493             {
14494               xfree (b->extra_string);
14495               b->extra_string = extra_string;
14496             }
14497           b->condition_not_parsed = 0;
14498         }
14499
14500       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14501         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14502
14503       *found = 1;
14504     }
14505   else
14506     *found = 0;
14507
14508   return sals;
14509 }
14510
14511 /* The default re_set method, for typical hardware or software
14512    breakpoints.  Reevaluate the breakpoint and recreate its
14513    locations.  */
14514
14515 static void
14516 breakpoint_re_set_default (struct breakpoint *b)
14517 {
14518   int found;
14519   struct symtabs_and_lines sals, sals_end;
14520   struct symtabs_and_lines expanded = {0};
14521   struct symtabs_and_lines expanded_end = {0};
14522   struct program_space *filter_pspace = current_program_space;
14523
14524   sals = location_to_sals (b, b->location, filter_pspace, &found);
14525   if (found)
14526     {
14527       make_cleanup (xfree, sals.sals);
14528       expanded = sals;
14529     }
14530
14531   if (b->location_range_end != NULL)
14532     {
14533       sals_end = location_to_sals (b, b->location_range_end,
14534                                    filter_pspace, &found);
14535       if (found)
14536         {
14537           make_cleanup (xfree, sals_end.sals);
14538           expanded_end = sals_end;
14539         }
14540     }
14541
14542   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14543 }
14544
14545 /* Default method for creating SALs from an address string.  It basically
14546    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14547
14548 static void
14549 create_sals_from_location_default (const struct event_location *location,
14550                                    struct linespec_result *canonical,
14551                                    enum bptype type_wanted)
14552 {
14553   parse_breakpoint_sals (location, canonical);
14554 }
14555
14556 /* Call create_breakpoints_sal for the given arguments.  This is the default
14557    function for the `create_breakpoints_sal' method of
14558    breakpoint_ops.  */
14559
14560 static void
14561 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14562                                 struct linespec_result *canonical,
14563                                 char *cond_string,
14564                                 char *extra_string,
14565                                 enum bptype type_wanted,
14566                                 enum bpdisp disposition,
14567                                 int thread,
14568                                 int task, int ignore_count,
14569                                 const struct breakpoint_ops *ops,
14570                                 int from_tty, int enabled,
14571                                 int internal, unsigned flags)
14572 {
14573   create_breakpoints_sal (gdbarch, canonical, cond_string,
14574                           extra_string,
14575                           type_wanted, disposition,
14576                           thread, task, ignore_count, ops, from_tty,
14577                           enabled, internal, flags);
14578 }
14579
14580 /* Decode the line represented by S by calling decode_line_full.  This is the
14581    default function for the `decode_location' method of breakpoint_ops.  */
14582
14583 static void
14584 decode_location_default (struct breakpoint *b,
14585                          const struct event_location *location,
14586                          struct program_space *search_pspace,
14587                          struct symtabs_and_lines *sals)
14588 {
14589   struct linespec_result canonical;
14590
14591   init_linespec_result (&canonical);
14592   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14593                     (struct symtab *) NULL, 0,
14594                     &canonical, multiple_symbols_all,
14595                     b->filter);
14596
14597   /* We should get 0 or 1 resulting SALs.  */
14598   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14599
14600   if (VEC_length (linespec_sals, canonical.sals) > 0)
14601     {
14602       struct linespec_sals *lsal;
14603
14604       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14605       *sals = lsal->sals;
14606       /* Arrange it so the destructor does not free the
14607          contents.  */
14608       lsal->sals.sals = NULL;
14609     }
14610
14611   destroy_linespec_result (&canonical);
14612 }
14613
14614 /* Prepare the global context for a re-set of breakpoint B.  */
14615
14616 static struct cleanup *
14617 prepare_re_set_context (struct breakpoint *b)
14618 {
14619   input_radix = b->input_radix;
14620   set_language (b->language);
14621
14622   return make_cleanup (null_cleanup, NULL);
14623 }
14624
14625 /* Reset a breakpoint given it's struct breakpoint * BINT.
14626    The value we return ends up being the return value from catch_errors.
14627    Unused in this case.  */
14628
14629 static int
14630 breakpoint_re_set_one (void *bint)
14631 {
14632   /* Get past catch_errs.  */
14633   struct breakpoint *b = (struct breakpoint *) bint;
14634   struct cleanup *cleanups;
14635
14636   cleanups = prepare_re_set_context (b);
14637   b->ops->re_set (b);
14638   do_cleanups (cleanups);
14639   return 0;
14640 }
14641
14642 /* Re-set breakpoint locations for the current program space.
14643    Locations bound to other program spaces are left untouched.  */
14644
14645 void
14646 breakpoint_re_set (void)
14647 {
14648   struct breakpoint *b, *b_tmp;
14649   enum language save_language;
14650   int save_input_radix;
14651   struct cleanup *old_chain;
14652
14653   save_language = current_language->la_language;
14654   save_input_radix = input_radix;
14655   old_chain = save_current_space_and_thread ();
14656
14657   /* Note: we must not try to insert locations until after all
14658      breakpoints have been re-set.  Otherwise, e.g., when re-setting
14659      breakpoint 1, we'd insert the locations of breakpoint 2, which
14660      hadn't been re-set yet, and thus may have stale locations.  */
14661
14662   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14663   {
14664     /* Format possible error msg.  */
14665     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14666                                 b->number);
14667     struct cleanup *cleanups = make_cleanup (xfree, message);
14668     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14669     do_cleanups (cleanups);
14670   }
14671   set_language (save_language);
14672   input_radix = save_input_radix;
14673
14674   jit_breakpoint_re_set ();
14675
14676   do_cleanups (old_chain);
14677
14678   create_overlay_event_breakpoint ();
14679   create_longjmp_master_breakpoint ();
14680   create_std_terminate_master_breakpoint ();
14681   create_exception_master_breakpoint ();
14682
14683   /* Now we can insert.  */
14684   update_global_location_list (UGLL_MAY_INSERT);
14685 }
14686 \f
14687 /* Reset the thread number of this breakpoint:
14688
14689    - If the breakpoint is for all threads, leave it as-is.
14690    - Else, reset it to the current thread for inferior_ptid.  */
14691 void
14692 breakpoint_re_set_thread (struct breakpoint *b)
14693 {
14694   if (b->thread != -1)
14695     {
14696       if (in_thread_list (inferior_ptid))
14697         b->thread = ptid_to_global_thread_id (inferior_ptid);
14698
14699       /* We're being called after following a fork.  The new fork is
14700          selected as current, and unless this was a vfork will have a
14701          different program space from the original thread.  Reset that
14702          as well.  */
14703       b->loc->pspace = current_program_space;
14704     }
14705 }
14706
14707 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14708    If from_tty is nonzero, it prints a message to that effect,
14709    which ends with a period (no newline).  */
14710
14711 void
14712 set_ignore_count (int bptnum, int count, int from_tty)
14713 {
14714   struct breakpoint *b;
14715
14716   if (count < 0)
14717     count = 0;
14718
14719   ALL_BREAKPOINTS (b)
14720     if (b->number == bptnum)
14721     {
14722       if (is_tracepoint (b))
14723         {
14724           if (from_tty && count != 0)
14725             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14726                              bptnum);
14727           return;
14728         }
14729       
14730       b->ignore_count = count;
14731       if (from_tty)
14732         {
14733           if (count == 0)
14734             printf_filtered (_("Will stop next time "
14735                                "breakpoint %d is reached."),
14736                              bptnum);
14737           else if (count == 1)
14738             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14739                              bptnum);
14740           else
14741             printf_filtered (_("Will ignore next %d "
14742                                "crossings of breakpoint %d."),
14743                              count, bptnum);
14744         }
14745       observer_notify_breakpoint_modified (b);
14746       return;
14747     }
14748
14749   error (_("No breakpoint number %d."), bptnum);
14750 }
14751
14752 /* Command to set ignore-count of breakpoint N to COUNT.  */
14753
14754 static void
14755 ignore_command (char *args, int from_tty)
14756 {
14757   char *p = args;
14758   int num;
14759
14760   if (p == 0)
14761     error_no_arg (_("a breakpoint number"));
14762
14763   num = get_number (&p);
14764   if (num == 0)
14765     error (_("bad breakpoint number: '%s'"), args);
14766   if (*p == 0)
14767     error (_("Second argument (specified ignore-count) is missing."));
14768
14769   set_ignore_count (num,
14770                     longest_to_int (value_as_long (parse_and_eval (p))),
14771                     from_tty);
14772   if (from_tty)
14773     printf_filtered ("\n");
14774 }
14775 \f
14776 /* Call FUNCTION on each of the breakpoints
14777    whose numbers are given in ARGS.  */
14778
14779 static void
14780 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14781                                                       void *),
14782                         void *data)
14783 {
14784   int num;
14785   struct breakpoint *b, *tmp;
14786   int match;
14787   struct get_number_or_range_state state;
14788
14789   if (args == 0 || *args == '\0')
14790     error_no_arg (_("one or more breakpoint numbers"));
14791
14792   init_number_or_range (&state, args);
14793
14794   while (!state.finished)
14795     {
14796       const char *p = state.string;
14797
14798       match = 0;
14799
14800       num = get_number_or_range (&state);
14801       if (num == 0)
14802         {
14803           warning (_("bad breakpoint number at or near '%s'"), p);
14804         }
14805       else
14806         {
14807           ALL_BREAKPOINTS_SAFE (b, tmp)
14808             if (b->number == num)
14809               {
14810                 match = 1;
14811                 function (b, data);
14812                 break;
14813               }
14814           if (match == 0)
14815             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14816         }
14817     }
14818 }
14819
14820 static struct bp_location *
14821 find_location_by_number (char *number)
14822 {
14823   char *dot = strchr (number, '.');
14824   char *p1;
14825   int bp_num;
14826   int loc_num;
14827   struct breakpoint *b;
14828   struct bp_location *loc;  
14829
14830   *dot = '\0';
14831
14832   p1 = number;
14833   bp_num = get_number (&p1);
14834   if (bp_num == 0)
14835     error (_("Bad breakpoint number '%s'"), number);
14836
14837   ALL_BREAKPOINTS (b)
14838     if (b->number == bp_num)
14839       {
14840         break;
14841       }
14842
14843   if (!b || b->number != bp_num)
14844     error (_("Bad breakpoint number '%s'"), number);
14845   
14846   p1 = dot+1;
14847   loc_num = get_number (&p1);
14848   if (loc_num == 0)
14849     error (_("Bad breakpoint location number '%s'"), number);
14850
14851   --loc_num;
14852   loc = b->loc;
14853   for (;loc_num && loc; --loc_num, loc = loc->next)
14854     ;
14855   if (!loc)
14856     error (_("Bad breakpoint location number '%s'"), dot+1);
14857     
14858   return loc;  
14859 }
14860
14861
14862 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14863    If from_tty is nonzero, it prints a message to that effect,
14864    which ends with a period (no newline).  */
14865
14866 void
14867 disable_breakpoint (struct breakpoint *bpt)
14868 {
14869   /* Never disable a watchpoint scope breakpoint; we want to
14870      hit them when we leave scope so we can delete both the
14871      watchpoint and its scope breakpoint at that time.  */
14872   if (bpt->type == bp_watchpoint_scope)
14873     return;
14874
14875   bpt->enable_state = bp_disabled;
14876
14877   /* Mark breakpoint locations modified.  */
14878   mark_breakpoint_modified (bpt);
14879
14880   if (target_supports_enable_disable_tracepoint ()
14881       && current_trace_status ()->running && is_tracepoint (bpt))
14882     {
14883       struct bp_location *location;
14884      
14885       for (location = bpt->loc; location; location = location->next)
14886         target_disable_tracepoint (location);
14887     }
14888
14889   update_global_location_list (UGLL_DONT_INSERT);
14890
14891   observer_notify_breakpoint_modified (bpt);
14892 }
14893
14894 /* A callback for iterate_over_related_breakpoints.  */
14895
14896 static void
14897 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14898 {
14899   disable_breakpoint (b);
14900 }
14901
14902 /* A callback for map_breakpoint_numbers that calls
14903    disable_breakpoint.  */
14904
14905 static void
14906 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14907 {
14908   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14909 }
14910
14911 static void
14912 disable_command (char *args, int from_tty)
14913 {
14914   if (args == 0)
14915     {
14916       struct breakpoint *bpt;
14917
14918       ALL_BREAKPOINTS (bpt)
14919         if (user_breakpoint_p (bpt))
14920           disable_breakpoint (bpt);
14921     }
14922   else
14923     {
14924       char *num = extract_arg (&args);
14925
14926       while (num)
14927         {
14928           if (strchr (num, '.'))
14929             {
14930               struct bp_location *loc = find_location_by_number (num);
14931
14932               if (loc)
14933                 {
14934                   if (loc->enabled)
14935                     {
14936                       loc->enabled = 0;
14937                       mark_breakpoint_location_modified (loc);
14938                     }
14939                   if (target_supports_enable_disable_tracepoint ()
14940                       && current_trace_status ()->running && loc->owner
14941                       && is_tracepoint (loc->owner))
14942                     target_disable_tracepoint (loc);
14943                 }
14944               update_global_location_list (UGLL_DONT_INSERT);
14945             }
14946           else
14947             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14948           num = extract_arg (&args);
14949         }
14950     }
14951 }
14952
14953 static void
14954 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14955                         int count)
14956 {
14957   int target_resources_ok;
14958
14959   if (bpt->type == bp_hardware_breakpoint)
14960     {
14961       int i;
14962       i = hw_breakpoint_used_count ();
14963       target_resources_ok = 
14964         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14965                                             i + 1, 0);
14966       if (target_resources_ok == 0)
14967         error (_("No hardware breakpoint support in the target."));
14968       else if (target_resources_ok < 0)
14969         error (_("Hardware breakpoints used exceeds limit."));
14970     }
14971
14972   if (is_watchpoint (bpt))
14973     {
14974       /* Initialize it just to avoid a GCC false warning.  */
14975       enum enable_state orig_enable_state = bp_disabled;
14976
14977       TRY
14978         {
14979           struct watchpoint *w = (struct watchpoint *) bpt;
14980
14981           orig_enable_state = bpt->enable_state;
14982           bpt->enable_state = bp_enabled;
14983           update_watchpoint (w, 1 /* reparse */);
14984         }
14985       CATCH (e, RETURN_MASK_ALL)
14986         {
14987           bpt->enable_state = orig_enable_state;
14988           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14989                              bpt->number);
14990           return;
14991         }
14992       END_CATCH
14993     }
14994
14995   bpt->enable_state = bp_enabled;
14996
14997   /* Mark breakpoint locations modified.  */
14998   mark_breakpoint_modified (bpt);
14999
15000   if (target_supports_enable_disable_tracepoint ()
15001       && current_trace_status ()->running && is_tracepoint (bpt))
15002     {
15003       struct bp_location *location;
15004
15005       for (location = bpt->loc; location; location = location->next)
15006         target_enable_tracepoint (location);
15007     }
15008
15009   bpt->disposition = disposition;
15010   bpt->enable_count = count;
15011   update_global_location_list (UGLL_MAY_INSERT);
15012
15013   observer_notify_breakpoint_modified (bpt);
15014 }
15015
15016
15017 void
15018 enable_breakpoint (struct breakpoint *bpt)
15019 {
15020   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15021 }
15022
15023 static void
15024 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15025 {
15026   enable_breakpoint (bpt);
15027 }
15028
15029 /* A callback for map_breakpoint_numbers that calls
15030    enable_breakpoint.  */
15031
15032 static void
15033 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15034 {
15035   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15036 }
15037
15038 /* The enable command enables the specified breakpoints (or all defined
15039    breakpoints) so they once again become (or continue to be) effective
15040    in stopping the inferior.  */
15041
15042 static void
15043 enable_command (char *args, int from_tty)
15044 {
15045   if (args == 0)
15046     {
15047       struct breakpoint *bpt;
15048
15049       ALL_BREAKPOINTS (bpt)
15050         if (user_breakpoint_p (bpt))
15051           enable_breakpoint (bpt);
15052     }
15053   else
15054     {
15055       char *num = extract_arg (&args);
15056
15057       while (num)
15058         {
15059           if (strchr (num, '.'))
15060             {
15061               struct bp_location *loc = find_location_by_number (num);
15062
15063               if (loc)
15064                 {
15065                   if (!loc->enabled)
15066                     {
15067                       loc->enabled = 1;
15068                       mark_breakpoint_location_modified (loc);
15069                     }
15070                   if (target_supports_enable_disable_tracepoint ()
15071                       && current_trace_status ()->running && loc->owner
15072                       && is_tracepoint (loc->owner))
15073                     target_enable_tracepoint (loc);
15074                 }
15075               update_global_location_list (UGLL_MAY_INSERT);
15076             }
15077           else
15078             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15079           num = extract_arg (&args);
15080         }
15081     }
15082 }
15083
15084 /* This struct packages up disposition data for application to multiple
15085    breakpoints.  */
15086
15087 struct disp_data
15088 {
15089   enum bpdisp disp;
15090   int count;
15091 };
15092
15093 static void
15094 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15095 {
15096   struct disp_data disp_data = *(struct disp_data *) arg;
15097
15098   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15099 }
15100
15101 static void
15102 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15103 {
15104   struct disp_data disp = { disp_disable, 1 };
15105
15106   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15107 }
15108
15109 static void
15110 enable_once_command (char *args, int from_tty)
15111 {
15112   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15113 }
15114
15115 static void
15116 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15117 {
15118   struct disp_data disp = { disp_disable, *(int *) countptr };
15119
15120   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15121 }
15122
15123 static void
15124 enable_count_command (char *args, int from_tty)
15125 {
15126   int count;
15127
15128   if (args == NULL)
15129     error_no_arg (_("hit count"));
15130
15131   count = get_number (&args);
15132
15133   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15134 }
15135
15136 static void
15137 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15138 {
15139   struct disp_data disp = { disp_del, 1 };
15140
15141   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15142 }
15143
15144 static void
15145 enable_delete_command (char *args, int from_tty)
15146 {
15147   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15148 }
15149 \f
15150 static void
15151 set_breakpoint_cmd (char *args, int from_tty)
15152 {
15153 }
15154
15155 static void
15156 show_breakpoint_cmd (char *args, int from_tty)
15157 {
15158 }
15159
15160 /* Invalidate last known value of any hardware watchpoint if
15161    the memory which that value represents has been written to by
15162    GDB itself.  */
15163
15164 static void
15165 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15166                                       CORE_ADDR addr, ssize_t len,
15167                                       const bfd_byte *data)
15168 {
15169   struct breakpoint *bp;
15170
15171   ALL_BREAKPOINTS (bp)
15172     if (bp->enable_state == bp_enabled
15173         && bp->type == bp_hardware_watchpoint)
15174       {
15175         struct watchpoint *wp = (struct watchpoint *) bp;
15176
15177         if (wp->val_valid && wp->val)
15178           {
15179             struct bp_location *loc;
15180
15181             for (loc = bp->loc; loc != NULL; loc = loc->next)
15182               if (loc->loc_type == bp_loc_hardware_watchpoint
15183                   && loc->address + loc->length > addr
15184                   && addr + len > loc->address)
15185                 {
15186                   value_free (wp->val);
15187                   wp->val = NULL;
15188                   wp->val_valid = 0;
15189                 }
15190           }
15191       }
15192 }
15193
15194 /* Create and insert a breakpoint for software single step.  */
15195
15196 void
15197 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15198                                struct address_space *aspace, 
15199                                CORE_ADDR next_pc)
15200 {
15201   struct thread_info *tp = inferior_thread ();
15202   struct symtab_and_line sal;
15203   CORE_ADDR pc = next_pc;
15204
15205   if (tp->control.single_step_breakpoints == NULL)
15206     {
15207       tp->control.single_step_breakpoints
15208         = new_single_step_breakpoint (tp->global_num, gdbarch);
15209     }
15210
15211   sal = find_pc_line (pc, 0);
15212   sal.pc = pc;
15213   sal.section = find_pc_overlay (pc);
15214   sal.explicit_pc = 1;
15215   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15216
15217   update_global_location_list (UGLL_INSERT);
15218 }
15219
15220 /* See breakpoint.h.  */
15221
15222 int
15223 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15224                                        struct address_space *aspace,
15225                                        CORE_ADDR pc)
15226 {
15227   struct bp_location *loc;
15228
15229   for (loc = bp->loc; loc != NULL; loc = loc->next)
15230     if (loc->inserted
15231         && breakpoint_location_address_match (loc, aspace, pc))
15232       return 1;
15233
15234   return 0;
15235 }
15236
15237 /* Check whether a software single-step breakpoint is inserted at
15238    PC.  */
15239
15240 int
15241 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15242                                         CORE_ADDR pc)
15243 {
15244   struct breakpoint *bpt;
15245
15246   ALL_BREAKPOINTS (bpt)
15247     {
15248       if (bpt->type == bp_single_step
15249           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15250         return 1;
15251     }
15252   return 0;
15253 }
15254
15255 /* Tracepoint-specific operations.  */
15256
15257 /* Set tracepoint count to NUM.  */
15258 static void
15259 set_tracepoint_count (int num)
15260 {
15261   tracepoint_count = num;
15262   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15263 }
15264
15265 static void
15266 trace_command (char *arg, int from_tty)
15267 {
15268   struct breakpoint_ops *ops;
15269   struct event_location *location;
15270   struct cleanup *back_to;
15271
15272   location = string_to_event_location (&arg, current_language);
15273   back_to = make_cleanup_delete_event_location (location);
15274   if (location != NULL
15275       && event_location_type (location) == PROBE_LOCATION)
15276     ops = &tracepoint_probe_breakpoint_ops;
15277   else
15278     ops = &tracepoint_breakpoint_ops;
15279
15280   create_breakpoint (get_current_arch (),
15281                      location,
15282                      NULL, 0, arg, 1 /* parse arg */,
15283                      0 /* tempflag */,
15284                      bp_tracepoint /* type_wanted */,
15285                      0 /* Ignore count */,
15286                      pending_break_support,
15287                      ops,
15288                      from_tty,
15289                      1 /* enabled */,
15290                      0 /* internal */, 0);
15291   do_cleanups (back_to);
15292 }
15293
15294 static void
15295 ftrace_command (char *arg, int from_tty)
15296 {
15297   struct event_location *location;
15298   struct cleanup *back_to;
15299
15300   location = string_to_event_location (&arg, current_language);
15301   back_to = make_cleanup_delete_event_location (location);
15302   create_breakpoint (get_current_arch (),
15303                      location,
15304                      NULL, 0, arg, 1 /* parse arg */,
15305                      0 /* tempflag */,
15306                      bp_fast_tracepoint /* type_wanted */,
15307                      0 /* Ignore count */,
15308                      pending_break_support,
15309                      &tracepoint_breakpoint_ops,
15310                      from_tty,
15311                      1 /* enabled */,
15312                      0 /* internal */, 0);
15313   do_cleanups (back_to);
15314 }
15315
15316 /* strace command implementation.  Creates a static tracepoint.  */
15317
15318 static void
15319 strace_command (char *arg, int from_tty)
15320 {
15321   struct breakpoint_ops *ops;
15322   struct event_location *location;
15323   struct cleanup *back_to;
15324
15325   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15326      or with a normal static tracepoint.  */
15327   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15328     {
15329       ops = &strace_marker_breakpoint_ops;
15330       location = new_linespec_location (&arg);
15331     }
15332   else
15333     {
15334       ops = &tracepoint_breakpoint_ops;
15335       location = string_to_event_location (&arg, current_language);
15336     }
15337
15338   back_to = make_cleanup_delete_event_location (location);
15339   create_breakpoint (get_current_arch (),
15340                      location,
15341                      NULL, 0, arg, 1 /* parse arg */,
15342                      0 /* tempflag */,
15343                      bp_static_tracepoint /* type_wanted */,
15344                      0 /* Ignore count */,
15345                      pending_break_support,
15346                      ops,
15347                      from_tty,
15348                      1 /* enabled */,
15349                      0 /* internal */, 0);
15350   do_cleanups (back_to);
15351 }
15352
15353 /* Set up a fake reader function that gets command lines from a linked
15354    list that was acquired during tracepoint uploading.  */
15355
15356 static struct uploaded_tp *this_utp;
15357 static int next_cmd;
15358
15359 static char *
15360 read_uploaded_action (void)
15361 {
15362   char *rslt;
15363
15364   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15365
15366   next_cmd++;
15367
15368   return rslt;
15369 }
15370
15371 /* Given information about a tracepoint as recorded on a target (which
15372    can be either a live system or a trace file), attempt to create an
15373    equivalent GDB tracepoint.  This is not a reliable process, since
15374    the target does not necessarily have all the information used when
15375    the tracepoint was originally defined.  */
15376   
15377 struct tracepoint *
15378 create_tracepoint_from_upload (struct uploaded_tp *utp)
15379 {
15380   char *addr_str, small_buf[100];
15381   struct tracepoint *tp;
15382   struct event_location *location;
15383   struct cleanup *cleanup;
15384
15385   if (utp->at_string)
15386     addr_str = utp->at_string;
15387   else
15388     {
15389       /* In the absence of a source location, fall back to raw
15390          address.  Since there is no way to confirm that the address
15391          means the same thing as when the trace was started, warn the
15392          user.  */
15393       warning (_("Uploaded tracepoint %d has no "
15394                  "source location, using raw address"),
15395                utp->number);
15396       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15397       addr_str = small_buf;
15398     }
15399
15400   /* There's not much we can do with a sequence of bytecodes.  */
15401   if (utp->cond && !utp->cond_string)
15402     warning (_("Uploaded tracepoint %d condition "
15403                "has no source form, ignoring it"),
15404              utp->number);
15405
15406   location = string_to_event_location (&addr_str, current_language);
15407   cleanup = make_cleanup_delete_event_location (location);
15408   if (!create_breakpoint (get_current_arch (),
15409                           location,
15410                           utp->cond_string, -1, addr_str,
15411                           0 /* parse cond/thread */,
15412                           0 /* tempflag */,
15413                           utp->type /* type_wanted */,
15414                           0 /* Ignore count */,
15415                           pending_break_support,
15416                           &tracepoint_breakpoint_ops,
15417                           0 /* from_tty */,
15418                           utp->enabled /* enabled */,
15419                           0 /* internal */,
15420                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15421     {
15422       do_cleanups (cleanup);
15423       return NULL;
15424     }
15425
15426   do_cleanups (cleanup);
15427
15428   /* Get the tracepoint we just created.  */
15429   tp = get_tracepoint (tracepoint_count);
15430   gdb_assert (tp != NULL);
15431
15432   if (utp->pass > 0)
15433     {
15434       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15435                  tp->base.number);
15436
15437       trace_pass_command (small_buf, 0);
15438     }
15439
15440   /* If we have uploaded versions of the original commands, set up a
15441      special-purpose "reader" function and call the usual command line
15442      reader, then pass the result to the breakpoint command-setting
15443      function.  */
15444   if (!VEC_empty (char_ptr, utp->cmd_strings))
15445     {
15446       struct command_line *cmd_list;
15447
15448       this_utp = utp;
15449       next_cmd = 0;
15450
15451       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15452
15453       breakpoint_set_commands (&tp->base, cmd_list);
15454     }
15455   else if (!VEC_empty (char_ptr, utp->actions)
15456            || !VEC_empty (char_ptr, utp->step_actions))
15457     warning (_("Uploaded tracepoint %d actions "
15458                "have no source form, ignoring them"),
15459              utp->number);
15460
15461   /* Copy any status information that might be available.  */
15462   tp->base.hit_count = utp->hit_count;
15463   tp->traceframe_usage = utp->traceframe_usage;
15464
15465   return tp;
15466 }
15467   
15468 /* Print information on tracepoint number TPNUM_EXP, or all if
15469    omitted.  */
15470
15471 static void
15472 tracepoints_info (char *args, int from_tty)
15473 {
15474   struct ui_out *uiout = current_uiout;
15475   int num_printed;
15476
15477   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15478
15479   if (num_printed == 0)
15480     {
15481       if (args == NULL || *args == '\0')
15482         ui_out_message (uiout, 0, "No tracepoints.\n");
15483       else
15484         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15485     }
15486
15487   default_collect_info ();
15488 }
15489
15490 /* The 'enable trace' command enables tracepoints.
15491    Not supported by all targets.  */
15492 static void
15493 enable_trace_command (char *args, int from_tty)
15494 {
15495   enable_command (args, from_tty);
15496 }
15497
15498 /* The 'disable trace' command disables tracepoints.
15499    Not supported by all targets.  */
15500 static void
15501 disable_trace_command (char *args, int from_tty)
15502 {
15503   disable_command (args, from_tty);
15504 }
15505
15506 /* Remove a tracepoint (or all if no argument).  */
15507 static void
15508 delete_trace_command (char *arg, int from_tty)
15509 {
15510   struct breakpoint *b, *b_tmp;
15511
15512   dont_repeat ();
15513
15514   if (arg == 0)
15515     {
15516       int breaks_to_delete = 0;
15517
15518       /* Delete all breakpoints if no argument.
15519          Do not delete internal or call-dummy breakpoints, these
15520          have to be deleted with an explicit breakpoint number 
15521          argument.  */
15522       ALL_TRACEPOINTS (b)
15523         if (is_tracepoint (b) && user_breakpoint_p (b))
15524           {
15525             breaks_to_delete = 1;
15526             break;
15527           }
15528
15529       /* Ask user only if there are some breakpoints to delete.  */
15530       if (!from_tty
15531           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15532         {
15533           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15534             if (is_tracepoint (b) && user_breakpoint_p (b))
15535               delete_breakpoint (b);
15536         }
15537     }
15538   else
15539     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15540 }
15541
15542 /* Helper function for trace_pass_command.  */
15543
15544 static void
15545 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15546 {
15547   tp->pass_count = count;
15548   observer_notify_breakpoint_modified (&tp->base);
15549   if (from_tty)
15550     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15551                      tp->base.number, count);
15552 }
15553
15554 /* Set passcount for tracepoint.
15555
15556    First command argument is passcount, second is tracepoint number.
15557    If tracepoint number omitted, apply to most recently defined.
15558    Also accepts special argument "all".  */
15559
15560 static void
15561 trace_pass_command (char *args, int from_tty)
15562 {
15563   struct tracepoint *t1;
15564   unsigned int count;
15565
15566   if (args == 0 || *args == 0)
15567     error (_("passcount command requires an "
15568              "argument (count + optional TP num)"));
15569
15570   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15571
15572   args = skip_spaces (args);
15573   if (*args && strncasecmp (args, "all", 3) == 0)
15574     {
15575       struct breakpoint *b;
15576
15577       args += 3;                        /* Skip special argument "all".  */
15578       if (*args)
15579         error (_("Junk at end of arguments."));
15580
15581       ALL_TRACEPOINTS (b)
15582       {
15583         t1 = (struct tracepoint *) b;
15584         trace_pass_set_count (t1, count, from_tty);
15585       }
15586     }
15587   else if (*args == '\0')
15588     {
15589       t1 = get_tracepoint_by_number (&args, NULL);
15590       if (t1)
15591         trace_pass_set_count (t1, count, from_tty);
15592     }
15593   else
15594     {
15595       struct get_number_or_range_state state;
15596
15597       init_number_or_range (&state, args);
15598       while (!state.finished)
15599         {
15600           t1 = get_tracepoint_by_number (&args, &state);
15601           if (t1)
15602             trace_pass_set_count (t1, count, from_tty);
15603         }
15604     }
15605 }
15606
15607 struct tracepoint *
15608 get_tracepoint (int num)
15609 {
15610   struct breakpoint *t;
15611
15612   ALL_TRACEPOINTS (t)
15613     if (t->number == num)
15614       return (struct tracepoint *) t;
15615
15616   return NULL;
15617 }
15618
15619 /* Find the tracepoint with the given target-side number (which may be
15620    different from the tracepoint number after disconnecting and
15621    reconnecting).  */
15622
15623 struct tracepoint *
15624 get_tracepoint_by_number_on_target (int num)
15625 {
15626   struct breakpoint *b;
15627
15628   ALL_TRACEPOINTS (b)
15629     {
15630       struct tracepoint *t = (struct tracepoint *) b;
15631
15632       if (t->number_on_target == num)
15633         return t;
15634     }
15635
15636   return NULL;
15637 }
15638
15639 /* Utility: parse a tracepoint number and look it up in the list.
15640    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15641    If the argument is missing, the most recent tracepoint
15642    (tracepoint_count) is returned.  */
15643
15644 struct tracepoint *
15645 get_tracepoint_by_number (char **arg,
15646                           struct get_number_or_range_state *state)
15647 {
15648   struct breakpoint *t;
15649   int tpnum;
15650   char *instring = arg == NULL ? NULL : *arg;
15651
15652   if (state)
15653     {
15654       gdb_assert (!state->finished);
15655       tpnum = get_number_or_range (state);
15656     }
15657   else if (arg == NULL || *arg == NULL || ! **arg)
15658     tpnum = tracepoint_count;
15659   else
15660     tpnum = get_number (arg);
15661
15662   if (tpnum <= 0)
15663     {
15664       if (instring && *instring)
15665         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15666                          instring);
15667       else
15668         printf_filtered (_("No previous tracepoint\n"));
15669       return NULL;
15670     }
15671
15672   ALL_TRACEPOINTS (t)
15673     if (t->number == tpnum)
15674     {
15675       return (struct tracepoint *) t;
15676     }
15677
15678   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15679   return NULL;
15680 }
15681
15682 void
15683 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15684 {
15685   if (b->thread != -1)
15686     fprintf_unfiltered (fp, " thread %d", b->thread);
15687
15688   if (b->task != 0)
15689     fprintf_unfiltered (fp, " task %d", b->task);
15690
15691   fprintf_unfiltered (fp, "\n");
15692 }
15693
15694 /* Save information on user settable breakpoints (watchpoints, etc) to
15695    a new script file named FILENAME.  If FILTER is non-NULL, call it
15696    on each breakpoint and only include the ones for which it returns
15697    non-zero.  */
15698
15699 static void
15700 save_breakpoints (char *filename, int from_tty,
15701                   int (*filter) (const struct breakpoint *))
15702 {
15703   struct breakpoint *tp;
15704   int any = 0;
15705   struct cleanup *cleanup;
15706   struct ui_file *fp;
15707   int extra_trace_bits = 0;
15708
15709   if (filename == 0 || *filename == 0)
15710     error (_("Argument required (file name in which to save)"));
15711
15712   /* See if we have anything to save.  */
15713   ALL_BREAKPOINTS (tp)
15714   {
15715     /* Skip internal and momentary breakpoints.  */
15716     if (!user_breakpoint_p (tp))
15717       continue;
15718
15719     /* If we have a filter, only save the breakpoints it accepts.  */
15720     if (filter && !filter (tp))
15721       continue;
15722
15723     any = 1;
15724
15725     if (is_tracepoint (tp))
15726       {
15727         extra_trace_bits = 1;
15728
15729         /* We can stop searching.  */
15730         break;
15731       }
15732   }
15733
15734   if (!any)
15735     {
15736       warning (_("Nothing to save."));
15737       return;
15738     }
15739
15740   filename = tilde_expand (filename);
15741   cleanup = make_cleanup (xfree, filename);
15742   fp = gdb_fopen (filename, "w");
15743   if (!fp)
15744     error (_("Unable to open file '%s' for saving (%s)"),
15745            filename, safe_strerror (errno));
15746   make_cleanup_ui_file_delete (fp);
15747
15748   if (extra_trace_bits)
15749     save_trace_state_variables (fp);
15750
15751   ALL_BREAKPOINTS (tp)
15752   {
15753     /* Skip internal and momentary breakpoints.  */
15754     if (!user_breakpoint_p (tp))
15755       continue;
15756
15757     /* If we have a filter, only save the breakpoints it accepts.  */
15758     if (filter && !filter (tp))
15759       continue;
15760
15761     tp->ops->print_recreate (tp, fp);
15762
15763     /* Note, we can't rely on tp->number for anything, as we can't
15764        assume the recreated breakpoint numbers will match.  Use $bpnum
15765        instead.  */
15766
15767     if (tp->cond_string)
15768       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15769
15770     if (tp->ignore_count)
15771       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15772
15773     if (tp->type != bp_dprintf && tp->commands)
15774       {
15775         fprintf_unfiltered (fp, "  commands\n");
15776         
15777         ui_out_redirect (current_uiout, fp);
15778         TRY
15779           {
15780             print_command_lines (current_uiout, tp->commands->commands, 2);
15781           }
15782         CATCH (ex, RETURN_MASK_ALL)
15783           {
15784             ui_out_redirect (current_uiout, NULL);
15785             throw_exception (ex);
15786           }
15787         END_CATCH
15788
15789         ui_out_redirect (current_uiout, NULL);
15790         fprintf_unfiltered (fp, "  end\n");
15791       }
15792
15793     if (tp->enable_state == bp_disabled)
15794       fprintf_unfiltered (fp, "disable $bpnum\n");
15795
15796     /* If this is a multi-location breakpoint, check if the locations
15797        should be individually disabled.  Watchpoint locations are
15798        special, and not user visible.  */
15799     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15800       {
15801         struct bp_location *loc;
15802         int n = 1;
15803
15804         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15805           if (!loc->enabled)
15806             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15807       }
15808   }
15809
15810   if (extra_trace_bits && *default_collect)
15811     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15812
15813   if (from_tty)
15814     printf_filtered (_("Saved to file '%s'.\n"), filename);
15815   do_cleanups (cleanup);
15816 }
15817
15818 /* The `save breakpoints' command.  */
15819
15820 static void
15821 save_breakpoints_command (char *args, int from_tty)
15822 {
15823   save_breakpoints (args, from_tty, NULL);
15824 }
15825
15826 /* The `save tracepoints' command.  */
15827
15828 static void
15829 save_tracepoints_command (char *args, int from_tty)
15830 {
15831   save_breakpoints (args, from_tty, is_tracepoint);
15832 }
15833
15834 /* Create a vector of all tracepoints.  */
15835
15836 VEC(breakpoint_p) *
15837 all_tracepoints (void)
15838 {
15839   VEC(breakpoint_p) *tp_vec = 0;
15840   struct breakpoint *tp;
15841
15842   ALL_TRACEPOINTS (tp)
15843   {
15844     VEC_safe_push (breakpoint_p, tp_vec, tp);
15845   }
15846
15847   return tp_vec;
15848 }
15849
15850 \f
15851 /* This help string is used to consolidate all the help string for specifying
15852    locations used by several commands.  */
15853
15854 #define LOCATION_HELP_STRING \
15855 "Linespecs are colon-separated lists of location parameters, such as\n\
15856 source filename, function name, label name, and line number.\n\
15857 Example: To specify the start of a label named \"the_top\" in the\n\
15858 function \"fact\" in the file \"factorial.c\", use\n\
15859 \"factorial.c:fact:the_top\".\n\
15860 \n\
15861 Address locations begin with \"*\" and specify an exact address in the\n\
15862 program.  Example: To specify the fourth byte past the start function\n\
15863 \"main\", use \"*main + 4\".\n\
15864 \n\
15865 Explicit locations are similar to linespecs but use an option/argument\n\
15866 syntax to specify location parameters.\n\
15867 Example: To specify the start of the label named \"the_top\" in the\n\
15868 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15869 -function fact -label the_top\".\n"
15870
15871 /* This help string is used for the break, hbreak, tbreak and thbreak
15872    commands.  It is defined as a macro to prevent duplication.
15873    COMMAND should be a string constant containing the name of the
15874    command.  */
15875
15876 #define BREAK_ARGS_HELP(command) \
15877 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15878 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15879 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15880 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15881 `-probe-dtrace' (for a DTrace probe).\n\
15882 LOCATION may be a linespec, address, or explicit location as described\n\
15883 below.\n\
15884 \n\
15885 With no LOCATION, uses current execution address of the selected\n\
15886 stack frame.  This is useful for breaking on return to a stack frame.\n\
15887 \n\
15888 THREADNUM is the number from \"info threads\".\n\
15889 CONDITION is a boolean expression.\n\
15890 \n" LOCATION_HELP_STRING "\n\
15891 Multiple breakpoints at one place are permitted, and useful if their\n\
15892 conditions are different.\n\
15893 \n\
15894 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15895
15896 /* List of subcommands for "catch".  */
15897 static struct cmd_list_element *catch_cmdlist;
15898
15899 /* List of subcommands for "tcatch".  */
15900 static struct cmd_list_element *tcatch_cmdlist;
15901
15902 void
15903 add_catch_command (char *name, char *docstring,
15904                    cmd_sfunc_ftype *sfunc,
15905                    completer_ftype *completer,
15906                    void *user_data_catch,
15907                    void *user_data_tcatch)
15908 {
15909   struct cmd_list_element *command;
15910
15911   command = add_cmd (name, class_breakpoint, NULL, docstring,
15912                      &catch_cmdlist);
15913   set_cmd_sfunc (command, sfunc);
15914   set_cmd_context (command, user_data_catch);
15915   set_cmd_completer (command, completer);
15916
15917   command = add_cmd (name, class_breakpoint, NULL, docstring,
15918                      &tcatch_cmdlist);
15919   set_cmd_sfunc (command, sfunc);
15920   set_cmd_context (command, user_data_tcatch);
15921   set_cmd_completer (command, completer);
15922 }
15923
15924 static void
15925 save_command (char *arg, int from_tty)
15926 {
15927   printf_unfiltered (_("\"save\" must be followed by "
15928                        "the name of a save subcommand.\n"));
15929   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15930 }
15931
15932 struct breakpoint *
15933 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15934                           void *data)
15935 {
15936   struct breakpoint *b, *b_tmp;
15937
15938   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15939     {
15940       if ((*callback) (b, data))
15941         return b;
15942     }
15943
15944   return NULL;
15945 }
15946
15947 /* Zero if any of the breakpoint's locations could be a location where
15948    functions have been inlined, nonzero otherwise.  */
15949
15950 static int
15951 is_non_inline_function (struct breakpoint *b)
15952 {
15953   /* The shared library event breakpoint is set on the address of a
15954      non-inline function.  */
15955   if (b->type == bp_shlib_event)
15956     return 1;
15957
15958   return 0;
15959 }
15960
15961 /* Nonzero if the specified PC cannot be a location where functions
15962    have been inlined.  */
15963
15964 int
15965 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15966                            const struct target_waitstatus *ws)
15967 {
15968   struct breakpoint *b;
15969   struct bp_location *bl;
15970
15971   ALL_BREAKPOINTS (b)
15972     {
15973       if (!is_non_inline_function (b))
15974         continue;
15975
15976       for (bl = b->loc; bl != NULL; bl = bl->next)
15977         {
15978           if (!bl->shlib_disabled
15979               && bpstat_check_location (bl, aspace, pc, ws))
15980             return 1;
15981         }
15982     }
15983
15984   return 0;
15985 }
15986
15987 /* Remove any references to OBJFILE which is going to be freed.  */
15988
15989 void
15990 breakpoint_free_objfile (struct objfile *objfile)
15991 {
15992   struct bp_location **locp, *loc;
15993
15994   ALL_BP_LOCATIONS (loc, locp)
15995     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15996       loc->symtab = NULL;
15997 }
15998
15999 void
16000 initialize_breakpoint_ops (void)
16001 {
16002   static int initialized = 0;
16003
16004   struct breakpoint_ops *ops;
16005
16006   if (initialized)
16007     return;
16008   initialized = 1;
16009
16010   /* The breakpoint_ops structure to be inherit by all kinds of
16011      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16012      internal and momentary breakpoints, etc.).  */
16013   ops = &bkpt_base_breakpoint_ops;
16014   *ops = base_breakpoint_ops;
16015   ops->re_set = bkpt_re_set;
16016   ops->insert_location = bkpt_insert_location;
16017   ops->remove_location = bkpt_remove_location;
16018   ops->breakpoint_hit = bkpt_breakpoint_hit;
16019   ops->create_sals_from_location = bkpt_create_sals_from_location;
16020   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16021   ops->decode_location = bkpt_decode_location;
16022
16023   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16024   ops = &bkpt_breakpoint_ops;
16025   *ops = bkpt_base_breakpoint_ops;
16026   ops->re_set = bkpt_re_set;
16027   ops->resources_needed = bkpt_resources_needed;
16028   ops->print_it = bkpt_print_it;
16029   ops->print_mention = bkpt_print_mention;
16030   ops->print_recreate = bkpt_print_recreate;
16031
16032   /* Ranged breakpoints.  */
16033   ops = &ranged_breakpoint_ops;
16034   *ops = bkpt_breakpoint_ops;
16035   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16036   ops->resources_needed = resources_needed_ranged_breakpoint;
16037   ops->print_it = print_it_ranged_breakpoint;
16038   ops->print_one = print_one_ranged_breakpoint;
16039   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16040   ops->print_mention = print_mention_ranged_breakpoint;
16041   ops->print_recreate = print_recreate_ranged_breakpoint;
16042
16043   /* Internal breakpoints.  */
16044   ops = &internal_breakpoint_ops;
16045   *ops = bkpt_base_breakpoint_ops;
16046   ops->re_set = internal_bkpt_re_set;
16047   ops->check_status = internal_bkpt_check_status;
16048   ops->print_it = internal_bkpt_print_it;
16049   ops->print_mention = internal_bkpt_print_mention;
16050
16051   /* Momentary breakpoints.  */
16052   ops = &momentary_breakpoint_ops;
16053   *ops = bkpt_base_breakpoint_ops;
16054   ops->re_set = momentary_bkpt_re_set;
16055   ops->check_status = momentary_bkpt_check_status;
16056   ops->print_it = momentary_bkpt_print_it;
16057   ops->print_mention = momentary_bkpt_print_mention;
16058
16059   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16060   ops = &longjmp_breakpoint_ops;
16061   *ops = momentary_breakpoint_ops;
16062   ops->dtor = longjmp_bkpt_dtor;
16063
16064   /* Probe breakpoints.  */
16065   ops = &bkpt_probe_breakpoint_ops;
16066   *ops = bkpt_breakpoint_ops;
16067   ops->insert_location = bkpt_probe_insert_location;
16068   ops->remove_location = bkpt_probe_remove_location;
16069   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
16070   ops->decode_location = bkpt_probe_decode_location;
16071
16072   /* Watchpoints.  */
16073   ops = &watchpoint_breakpoint_ops;
16074   *ops = base_breakpoint_ops;
16075   ops->dtor = dtor_watchpoint;
16076   ops->re_set = re_set_watchpoint;
16077   ops->insert_location = insert_watchpoint;
16078   ops->remove_location = remove_watchpoint;
16079   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16080   ops->check_status = check_status_watchpoint;
16081   ops->resources_needed = resources_needed_watchpoint;
16082   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16083   ops->print_it = print_it_watchpoint;
16084   ops->print_mention = print_mention_watchpoint;
16085   ops->print_recreate = print_recreate_watchpoint;
16086   ops->explains_signal = explains_signal_watchpoint;
16087
16088   /* Masked watchpoints.  */
16089   ops = &masked_watchpoint_breakpoint_ops;
16090   *ops = watchpoint_breakpoint_ops;
16091   ops->insert_location = insert_masked_watchpoint;
16092   ops->remove_location = remove_masked_watchpoint;
16093   ops->resources_needed = resources_needed_masked_watchpoint;
16094   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16095   ops->print_it = print_it_masked_watchpoint;
16096   ops->print_one_detail = print_one_detail_masked_watchpoint;
16097   ops->print_mention = print_mention_masked_watchpoint;
16098   ops->print_recreate = print_recreate_masked_watchpoint;
16099
16100   /* Tracepoints.  */
16101   ops = &tracepoint_breakpoint_ops;
16102   *ops = base_breakpoint_ops;
16103   ops->re_set = tracepoint_re_set;
16104   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16105   ops->print_one_detail = tracepoint_print_one_detail;
16106   ops->print_mention = tracepoint_print_mention;
16107   ops->print_recreate = tracepoint_print_recreate;
16108   ops->create_sals_from_location = tracepoint_create_sals_from_location;
16109   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16110   ops->decode_location = tracepoint_decode_location;
16111
16112   /* Probe tracepoints.  */
16113   ops = &tracepoint_probe_breakpoint_ops;
16114   *ops = tracepoint_breakpoint_ops;
16115   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
16116   ops->decode_location = tracepoint_probe_decode_location;
16117
16118   /* Static tracepoints with marker (`-m').  */
16119   ops = &strace_marker_breakpoint_ops;
16120   *ops = tracepoint_breakpoint_ops;
16121   ops->create_sals_from_location = strace_marker_create_sals_from_location;
16122   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16123   ops->decode_location = strace_marker_decode_location;
16124
16125   /* Fork catchpoints.  */
16126   ops = &catch_fork_breakpoint_ops;
16127   *ops = base_breakpoint_ops;
16128   ops->insert_location = insert_catch_fork;
16129   ops->remove_location = remove_catch_fork;
16130   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16131   ops->print_it = print_it_catch_fork;
16132   ops->print_one = print_one_catch_fork;
16133   ops->print_mention = print_mention_catch_fork;
16134   ops->print_recreate = print_recreate_catch_fork;
16135
16136   /* Vfork catchpoints.  */
16137   ops = &catch_vfork_breakpoint_ops;
16138   *ops = base_breakpoint_ops;
16139   ops->insert_location = insert_catch_vfork;
16140   ops->remove_location = remove_catch_vfork;
16141   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16142   ops->print_it = print_it_catch_vfork;
16143   ops->print_one = print_one_catch_vfork;
16144   ops->print_mention = print_mention_catch_vfork;
16145   ops->print_recreate = print_recreate_catch_vfork;
16146
16147   /* Exec catchpoints.  */
16148   ops = &catch_exec_breakpoint_ops;
16149   *ops = base_breakpoint_ops;
16150   ops->dtor = dtor_catch_exec;
16151   ops->insert_location = insert_catch_exec;
16152   ops->remove_location = remove_catch_exec;
16153   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16154   ops->print_it = print_it_catch_exec;
16155   ops->print_one = print_one_catch_exec;
16156   ops->print_mention = print_mention_catch_exec;
16157   ops->print_recreate = print_recreate_catch_exec;
16158
16159   /* Solib-related catchpoints.  */
16160   ops = &catch_solib_breakpoint_ops;
16161   *ops = base_breakpoint_ops;
16162   ops->dtor = dtor_catch_solib;
16163   ops->insert_location = insert_catch_solib;
16164   ops->remove_location = remove_catch_solib;
16165   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16166   ops->check_status = check_status_catch_solib;
16167   ops->print_it = print_it_catch_solib;
16168   ops->print_one = print_one_catch_solib;
16169   ops->print_mention = print_mention_catch_solib;
16170   ops->print_recreate = print_recreate_catch_solib;
16171
16172   ops = &dprintf_breakpoint_ops;
16173   *ops = bkpt_base_breakpoint_ops;
16174   ops->re_set = dprintf_re_set;
16175   ops->resources_needed = bkpt_resources_needed;
16176   ops->print_it = bkpt_print_it;
16177   ops->print_mention = bkpt_print_mention;
16178   ops->print_recreate = dprintf_print_recreate;
16179   ops->after_condition_true = dprintf_after_condition_true;
16180   ops->breakpoint_hit = dprintf_breakpoint_hit;
16181 }
16182
16183 /* Chain containing all defined "enable breakpoint" subcommands.  */
16184
16185 static struct cmd_list_element *enablebreaklist = NULL;
16186
16187 void
16188 _initialize_breakpoint (void)
16189 {
16190   struct cmd_list_element *c;
16191
16192   initialize_breakpoint_ops ();
16193
16194   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16195   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16196   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16197
16198   breakpoint_objfile_key
16199     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16200
16201   breakpoint_chain = 0;
16202   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16203      before a breakpoint is set.  */
16204   breakpoint_count = 0;
16205
16206   tracepoint_count = 0;
16207
16208   add_com ("ignore", class_breakpoint, ignore_command, _("\
16209 Set ignore-count of breakpoint number N to COUNT.\n\
16210 Usage is `ignore N COUNT'."));
16211
16212   add_com ("commands", class_breakpoint, commands_command, _("\
16213 Set commands to be executed when a breakpoint is hit.\n\
16214 Give breakpoint number as argument after \"commands\".\n\
16215 With no argument, the targeted breakpoint is the last one set.\n\
16216 The commands themselves follow starting on the next line.\n\
16217 Type a line containing \"end\" to indicate the end of them.\n\
16218 Give \"silent\" as the first line to make the breakpoint silent;\n\
16219 then no output is printed when it is hit, except what the commands print."));
16220
16221   c = add_com ("condition", class_breakpoint, condition_command, _("\
16222 Specify breakpoint number N to break only if COND is true.\n\
16223 Usage is `condition N COND', where N is an integer and COND is an\n\
16224 expression to be evaluated whenever breakpoint N is reached."));
16225   set_cmd_completer (c, condition_completer);
16226
16227   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16228 Set a temporary breakpoint.\n\
16229 Like \"break\" except the breakpoint is only temporary,\n\
16230 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16231 by using \"enable delete\" on the breakpoint number.\n\
16232 \n"
16233 BREAK_ARGS_HELP ("tbreak")));
16234   set_cmd_completer (c, location_completer);
16235
16236   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16237 Set a hardware assisted breakpoint.\n\
16238 Like \"break\" except the breakpoint requires hardware support,\n\
16239 some target hardware may not have this support.\n\
16240 \n"
16241 BREAK_ARGS_HELP ("hbreak")));
16242   set_cmd_completer (c, location_completer);
16243
16244   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16245 Set a temporary hardware assisted breakpoint.\n\
16246 Like \"hbreak\" except the breakpoint is only temporary,\n\
16247 so it will be deleted when hit.\n\
16248 \n"
16249 BREAK_ARGS_HELP ("thbreak")));
16250   set_cmd_completer (c, location_completer);
16251
16252   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16253 Enable some breakpoints.\n\
16254 Give breakpoint numbers (separated by spaces) as arguments.\n\
16255 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16256 This is used to cancel the effect of the \"disable\" command.\n\
16257 With a subcommand you can enable temporarily."),
16258                   &enablelist, "enable ", 1, &cmdlist);
16259
16260   add_com_alias ("en", "enable", class_breakpoint, 1);
16261
16262   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16263 Enable some breakpoints.\n\
16264 Give breakpoint numbers (separated by spaces) as arguments.\n\
16265 This is used to cancel the effect of the \"disable\" command.\n\
16266 May be abbreviated to simply \"enable\".\n"),
16267                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16268
16269   add_cmd ("once", no_class, enable_once_command, _("\
16270 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16271 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16272            &enablebreaklist);
16273
16274   add_cmd ("delete", no_class, enable_delete_command, _("\
16275 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16276 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16277            &enablebreaklist);
16278
16279   add_cmd ("count", no_class, enable_count_command, _("\
16280 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16281 If a breakpoint is hit while enabled in this fashion,\n\
16282 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16283            &enablebreaklist);
16284
16285   add_cmd ("delete", no_class, enable_delete_command, _("\
16286 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16287 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16288            &enablelist);
16289
16290   add_cmd ("once", no_class, enable_once_command, _("\
16291 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16292 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16293            &enablelist);
16294
16295   add_cmd ("count", no_class, enable_count_command, _("\
16296 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16297 If a breakpoint is hit while enabled in this fashion,\n\
16298 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16299            &enablelist);
16300
16301   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16302 Disable some breakpoints.\n\
16303 Arguments are breakpoint numbers with spaces in between.\n\
16304 To disable all breakpoints, give no argument.\n\
16305 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16306                   &disablelist, "disable ", 1, &cmdlist);
16307   add_com_alias ("dis", "disable", class_breakpoint, 1);
16308   add_com_alias ("disa", "disable", class_breakpoint, 1);
16309
16310   add_cmd ("breakpoints", class_alias, disable_command, _("\
16311 Disable some breakpoints.\n\
16312 Arguments are breakpoint numbers with spaces in between.\n\
16313 To disable all breakpoints, give no argument.\n\
16314 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16315 This command may be abbreviated \"disable\"."),
16316            &disablelist);
16317
16318   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16319 Delete some breakpoints or auto-display expressions.\n\
16320 Arguments are breakpoint numbers with spaces in between.\n\
16321 To delete all breakpoints, give no argument.\n\
16322 \n\
16323 Also a prefix command for deletion of other GDB objects.\n\
16324 The \"unset\" command is also an alias for \"delete\"."),
16325                   &deletelist, "delete ", 1, &cmdlist);
16326   add_com_alias ("d", "delete", class_breakpoint, 1);
16327   add_com_alias ("del", "delete", class_breakpoint, 1);
16328
16329   add_cmd ("breakpoints", class_alias, delete_command, _("\
16330 Delete some breakpoints or auto-display expressions.\n\
16331 Arguments are breakpoint numbers with spaces in between.\n\
16332 To delete all breakpoints, give no argument.\n\
16333 This command may be abbreviated \"delete\"."),
16334            &deletelist);
16335
16336   add_com ("clear", class_breakpoint, clear_command, _("\
16337 Clear breakpoint at specified location.\n\
16338 Argument may be a linespec, explicit, or address location as described below.\n\
16339 \n\
16340 With no argument, clears all breakpoints in the line that the selected frame\n\
16341 is executing in.\n"
16342 "\n" LOCATION_HELP_STRING "\n\
16343 See also the \"delete\" command which clears breakpoints by number."));
16344   add_com_alias ("cl", "clear", class_breakpoint, 1);
16345
16346   c = add_com ("break", class_breakpoint, break_command, _("\
16347 Set breakpoint at specified location.\n"
16348 BREAK_ARGS_HELP ("break")));
16349   set_cmd_completer (c, location_completer);
16350
16351   add_com_alias ("b", "break", class_run, 1);
16352   add_com_alias ("br", "break", class_run, 1);
16353   add_com_alias ("bre", "break", class_run, 1);
16354   add_com_alias ("brea", "break", class_run, 1);
16355
16356   if (dbx_commands)
16357     {
16358       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16359 Break in function/address or break at a line in the current file."),
16360                              &stoplist, "stop ", 1, &cmdlist);
16361       add_cmd ("in", class_breakpoint, stopin_command,
16362                _("Break in function or address."), &stoplist);
16363       add_cmd ("at", class_breakpoint, stopat_command,
16364                _("Break at a line in the current file."), &stoplist);
16365       add_com ("status", class_info, breakpoints_info, _("\
16366 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16367 The \"Type\" column indicates one of:\n\
16368 \tbreakpoint     - normal breakpoint\n\
16369 \twatchpoint     - watchpoint\n\
16370 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16371 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16372 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16373 address and file/line number respectively.\n\
16374 \n\
16375 Convenience variable \"$_\" and default examine address for \"x\"\n\
16376 are set to the address of the last breakpoint listed unless the command\n\
16377 is prefixed with \"server \".\n\n\
16378 Convenience variable \"$bpnum\" contains the number of the last\n\
16379 breakpoint set."));
16380     }
16381
16382   add_info ("breakpoints", breakpoints_info, _("\
16383 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16384 The \"Type\" column indicates one of:\n\
16385 \tbreakpoint     - normal breakpoint\n\
16386 \twatchpoint     - watchpoint\n\
16387 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16388 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16389 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16390 address and file/line number respectively.\n\
16391 \n\
16392 Convenience variable \"$_\" and default examine address for \"x\"\n\
16393 are set to the address of the last breakpoint listed unless the command\n\
16394 is prefixed with \"server \".\n\n\
16395 Convenience variable \"$bpnum\" contains the number of the last\n\
16396 breakpoint set."));
16397
16398   add_info_alias ("b", "breakpoints", 1);
16399
16400   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16401 Status of all breakpoints, or breakpoint number NUMBER.\n\
16402 The \"Type\" column indicates one of:\n\
16403 \tbreakpoint     - normal breakpoint\n\
16404 \twatchpoint     - watchpoint\n\
16405 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16406 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16407 \tuntil          - internal breakpoint used by the \"until\" command\n\
16408 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16409 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16410 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16411 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16412 address and file/line number respectively.\n\
16413 \n\
16414 Convenience variable \"$_\" and default examine address for \"x\"\n\
16415 are set to the address of the last breakpoint listed unless the command\n\
16416 is prefixed with \"server \".\n\n\
16417 Convenience variable \"$bpnum\" contains the number of the last\n\
16418 breakpoint set."),
16419            &maintenanceinfolist);
16420
16421   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16422 Set catchpoints to catch events."),
16423                   &catch_cmdlist, "catch ",
16424                   0/*allow-unknown*/, &cmdlist);
16425
16426   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16427 Set temporary catchpoints to catch events."),
16428                   &tcatch_cmdlist, "tcatch ",
16429                   0/*allow-unknown*/, &cmdlist);
16430
16431   add_catch_command ("fork", _("Catch calls to fork."),
16432                      catch_fork_command_1,
16433                      NULL,
16434                      (void *) (uintptr_t) catch_fork_permanent,
16435                      (void *) (uintptr_t) catch_fork_temporary);
16436   add_catch_command ("vfork", _("Catch calls to vfork."),
16437                      catch_fork_command_1,
16438                      NULL,
16439                      (void *) (uintptr_t) catch_vfork_permanent,
16440                      (void *) (uintptr_t) catch_vfork_temporary);
16441   add_catch_command ("exec", _("Catch calls to exec."),
16442                      catch_exec_command_1,
16443                      NULL,
16444                      CATCH_PERMANENT,
16445                      CATCH_TEMPORARY);
16446   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16447 Usage: catch load [REGEX]\n\
16448 If REGEX is given, only stop for libraries matching the regular expression."),
16449                      catch_load_command_1,
16450                      NULL,
16451                      CATCH_PERMANENT,
16452                      CATCH_TEMPORARY);
16453   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16454 Usage: catch unload [REGEX]\n\
16455 If REGEX is given, only stop for libraries matching the regular expression."),
16456                      catch_unload_command_1,
16457                      NULL,
16458                      CATCH_PERMANENT,
16459                      CATCH_TEMPORARY);
16460
16461   c = add_com ("watch", class_breakpoint, watch_command, _("\
16462 Set a watchpoint for an expression.\n\
16463 Usage: watch [-l|-location] EXPRESSION\n\
16464 A watchpoint stops execution of your program whenever the value of\n\
16465 an expression changes.\n\
16466 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16467 the memory to which it refers."));
16468   set_cmd_completer (c, expression_completer);
16469
16470   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16471 Set a read watchpoint for an expression.\n\
16472 Usage: rwatch [-l|-location] EXPRESSION\n\
16473 A watchpoint stops execution of your program whenever the value of\n\
16474 an expression is read.\n\
16475 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16476 the memory to which it refers."));
16477   set_cmd_completer (c, expression_completer);
16478
16479   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16480 Set a watchpoint for an expression.\n\
16481 Usage: awatch [-l|-location] EXPRESSION\n\
16482 A watchpoint stops execution of your program whenever the value of\n\
16483 an expression is either read or written.\n\
16484 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16485 the memory to which it refers."));
16486   set_cmd_completer (c, expression_completer);
16487
16488   add_info ("watchpoints", watchpoints_info, _("\
16489 Status of specified watchpoints (all watchpoints if no argument)."));
16490
16491   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16492      respond to changes - contrary to the description.  */
16493   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16494                             &can_use_hw_watchpoints, _("\
16495 Set debugger's willingness to use watchpoint hardware."), _("\
16496 Show debugger's willingness to use watchpoint hardware."), _("\
16497 If zero, gdb will not use hardware for new watchpoints, even if\n\
16498 such is available.  (However, any hardware watchpoints that were\n\
16499 created before setting this to nonzero, will continue to use watchpoint\n\
16500 hardware.)"),
16501                             NULL,
16502                             show_can_use_hw_watchpoints,
16503                             &setlist, &showlist);
16504
16505   can_use_hw_watchpoints = 1;
16506
16507   /* Tracepoint manipulation commands.  */
16508
16509   c = add_com ("trace", class_breakpoint, trace_command, _("\
16510 Set a tracepoint at specified location.\n\
16511 \n"
16512 BREAK_ARGS_HELP ("trace") "\n\
16513 Do \"help tracepoints\" for info on other tracepoint commands."));
16514   set_cmd_completer (c, location_completer);
16515
16516   add_com_alias ("tp", "trace", class_alias, 0);
16517   add_com_alias ("tr", "trace", class_alias, 1);
16518   add_com_alias ("tra", "trace", class_alias, 1);
16519   add_com_alias ("trac", "trace", class_alias, 1);
16520
16521   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16522 Set a fast tracepoint at specified location.\n\
16523 \n"
16524 BREAK_ARGS_HELP ("ftrace") "\n\
16525 Do \"help tracepoints\" for info on other tracepoint commands."));
16526   set_cmd_completer (c, location_completer);
16527
16528   c = add_com ("strace", class_breakpoint, strace_command, _("\
16529 Set a static tracepoint at location or marker.\n\
16530 \n\
16531 strace [LOCATION] [if CONDITION]\n\
16532 LOCATION may be a linespec, explicit, or address location (described below) \n\
16533 or -m MARKER_ID.\n\n\
16534 If a marker id is specified, probe the marker with that name.  With\n\
16535 no LOCATION, uses current execution address of the selected stack frame.\n\
16536 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16537 This collects arbitrary user data passed in the probe point call to the\n\
16538 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16539 by printing the $_sdata variable like any other convenience variable.\n\
16540 \n\
16541 CONDITION is a boolean expression.\n\
16542 \n" LOCATION_HELP_STRING "\n\
16543 Multiple tracepoints at one place are permitted, and useful if their\n\
16544 conditions are different.\n\
16545 \n\
16546 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16547 Do \"help tracepoints\" for info on other tracepoint commands."));
16548   set_cmd_completer (c, location_completer);
16549
16550   add_info ("tracepoints", tracepoints_info, _("\
16551 Status of specified tracepoints (all tracepoints if no argument).\n\
16552 Convenience variable \"$tpnum\" contains the number of the\n\
16553 last tracepoint set."));
16554
16555   add_info_alias ("tp", "tracepoints", 1);
16556
16557   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16558 Delete specified tracepoints.\n\
16559 Arguments are tracepoint numbers, separated by spaces.\n\
16560 No argument means delete all tracepoints."),
16561            &deletelist);
16562   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16563
16564   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16565 Disable specified tracepoints.\n\
16566 Arguments are tracepoint numbers, separated by spaces.\n\
16567 No argument means disable all tracepoints."),
16568            &disablelist);
16569   deprecate_cmd (c, "disable");
16570
16571   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16572 Enable specified tracepoints.\n\
16573 Arguments are tracepoint numbers, separated by spaces.\n\
16574 No argument means enable all tracepoints."),
16575            &enablelist);
16576   deprecate_cmd (c, "enable");
16577
16578   add_com ("passcount", class_trace, trace_pass_command, _("\
16579 Set the passcount for a tracepoint.\n\
16580 The trace will end when the tracepoint has been passed 'count' times.\n\
16581 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16582 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16583
16584   add_prefix_cmd ("save", class_breakpoint, save_command,
16585                   _("Save breakpoint definitions as a script."),
16586                   &save_cmdlist, "save ",
16587                   0/*allow-unknown*/, &cmdlist);
16588
16589   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16590 Save current breakpoint definitions as a script.\n\
16591 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16592 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16593 session to restore them."),
16594                &save_cmdlist);
16595   set_cmd_completer (c, filename_completer);
16596
16597   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16598 Save current tracepoint definitions as a script.\n\
16599 Use the 'source' command in another debug session to restore them."),
16600                &save_cmdlist);
16601   set_cmd_completer (c, filename_completer);
16602
16603   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16604   deprecate_cmd (c, "save tracepoints");
16605
16606   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16607 Breakpoint specific settings\n\
16608 Configure various breakpoint-specific variables such as\n\
16609 pending breakpoint behavior"),
16610                   &breakpoint_set_cmdlist, "set breakpoint ",
16611                   0/*allow-unknown*/, &setlist);
16612   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16613 Breakpoint specific settings\n\
16614 Configure various breakpoint-specific variables such as\n\
16615 pending breakpoint behavior"),
16616                   &breakpoint_show_cmdlist, "show breakpoint ",
16617                   0/*allow-unknown*/, &showlist);
16618
16619   add_setshow_auto_boolean_cmd ("pending", no_class,
16620                                 &pending_break_support, _("\
16621 Set debugger's behavior regarding pending breakpoints."), _("\
16622 Show debugger's behavior regarding pending breakpoints."), _("\
16623 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16624 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16625 an error.  If auto, an unrecognized breakpoint location results in a\n\
16626 user-query to see if a pending breakpoint should be created."),
16627                                 NULL,
16628                                 show_pending_break_support,
16629                                 &breakpoint_set_cmdlist,
16630                                 &breakpoint_show_cmdlist);
16631
16632   pending_break_support = AUTO_BOOLEAN_AUTO;
16633
16634   add_setshow_boolean_cmd ("auto-hw", no_class,
16635                            &automatic_hardware_breakpoints, _("\
16636 Set automatic usage of hardware breakpoints."), _("\
16637 Show automatic usage of hardware breakpoints."), _("\
16638 If set, the debugger will automatically use hardware breakpoints for\n\
16639 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16640 a warning will be emitted for such breakpoints."),
16641                            NULL,
16642                            show_automatic_hardware_breakpoints,
16643                            &breakpoint_set_cmdlist,
16644                            &breakpoint_show_cmdlist);
16645
16646   add_setshow_boolean_cmd ("always-inserted", class_support,
16647                            &always_inserted_mode, _("\
16648 Set mode for inserting breakpoints."), _("\
16649 Show mode for inserting breakpoints."), _("\
16650 When this mode is on, breakpoints are inserted immediately as soon as\n\
16651 they're created, kept inserted even when execution stops, and removed\n\
16652 only when the user deletes them.  When this mode is off (the default),\n\
16653 breakpoints are inserted only when execution continues, and removed\n\
16654 when execution stops."),
16655                                 NULL,
16656                                 &show_always_inserted_mode,
16657                                 &breakpoint_set_cmdlist,
16658                                 &breakpoint_show_cmdlist);
16659
16660   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16661                         condition_evaluation_enums,
16662                         &condition_evaluation_mode_1, _("\
16663 Set mode of breakpoint condition evaluation."), _("\
16664 Show mode of breakpoint condition evaluation."), _("\
16665 When this is set to \"host\", breakpoint conditions will be\n\
16666 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16667 breakpoint conditions will be downloaded to the target (if the target\n\
16668 supports such feature) and conditions will be evaluated on the target's side.\n\
16669 If this is set to \"auto\" (default), this will be automatically set to\n\
16670 \"target\" if it supports condition evaluation, otherwise it will\n\
16671 be set to \"gdb\""),
16672                            &set_condition_evaluation_mode,
16673                            &show_condition_evaluation_mode,
16674                            &breakpoint_set_cmdlist,
16675                            &breakpoint_show_cmdlist);
16676
16677   add_com ("break-range", class_breakpoint, break_range_command, _("\
16678 Set a breakpoint for an address range.\n\
16679 break-range START-LOCATION, END-LOCATION\n\
16680 where START-LOCATION and END-LOCATION can be one of the following:\n\
16681   LINENUM, for that line in the current file,\n\
16682   FILE:LINENUM, for that line in that file,\n\
16683   +OFFSET, for that number of lines after the current line\n\
16684            or the start of the range\n\
16685   FUNCTION, for the first line in that function,\n\
16686   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16687   *ADDRESS, for the instruction at that address.\n\
16688 \n\
16689 The breakpoint will stop execution of the inferior whenever it executes\n\
16690 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16691 range (including START-LOCATION and END-LOCATION)."));
16692
16693   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16694 Set a dynamic printf at specified location.\n\
16695 dprintf location,format string,arg1,arg2,...\n\
16696 location may be a linespec, explicit, or address location.\n"
16697 "\n" LOCATION_HELP_STRING));
16698   set_cmd_completer (c, location_completer);
16699
16700   add_setshow_enum_cmd ("dprintf-style", class_support,
16701                         dprintf_style_enums, &dprintf_style, _("\
16702 Set the style of usage for dynamic printf."), _("\
16703 Show the style of usage for dynamic printf."), _("\
16704 This setting chooses how GDB will do a dynamic printf.\n\
16705 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16706 console, as with the \"printf\" command.\n\
16707 If the value is \"call\", the print is done by calling a function in your\n\
16708 program; by default printf(), but you can choose a different function or\n\
16709 output stream by setting dprintf-function and dprintf-channel."),
16710                         update_dprintf_commands, NULL,
16711                         &setlist, &showlist);
16712
16713   dprintf_function = xstrdup ("printf");
16714   add_setshow_string_cmd ("dprintf-function", class_support,
16715                           &dprintf_function, _("\
16716 Set the function to use for dynamic printf"), _("\
16717 Show the function to use for dynamic printf"), NULL,
16718                           update_dprintf_commands, NULL,
16719                           &setlist, &showlist);
16720
16721   dprintf_channel = xstrdup ("");
16722   add_setshow_string_cmd ("dprintf-channel", class_support,
16723                           &dprintf_channel, _("\
16724 Set the channel to use for dynamic printf"), _("\
16725 Show the channel to use for dynamic printf"), NULL,
16726                           update_dprintf_commands, NULL,
16727                           &setlist, &showlist);
16728
16729   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16730                            &disconnected_dprintf, _("\
16731 Set whether dprintf continues after GDB disconnects."), _("\
16732 Show whether dprintf continues after GDB disconnects."), _("\
16733 Use this to let dprintf commands continue to hit and produce output\n\
16734 even if GDB disconnects or detaches from the target."),
16735                            NULL,
16736                            NULL,
16737                            &setlist, &showlist);
16738
16739   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16740 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16741 (target agent only) This is useful for formatted output in user-defined commands."));
16742
16743   automatic_hardware_breakpoints = 1;
16744
16745   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16746   observer_attach_thread_exit (remove_threaded_breakpoints);
16747 }