Fix powerpc subis range
[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 typedef enum
198   {
199     mark_inserted,
200     mark_uninserted
201   }
202 insertion_state_t;
203
204 static int remove_breakpoint (struct bp_location *, insertion_state_t);
205 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
206
207 static enum print_stop_action print_bp_stop_message (bpstat bs);
208
209 static int watchpoint_check (void *);
210
211 static void maintenance_info_breakpoints (char *, int);
212
213 static int hw_breakpoint_used_count (void);
214
215 static int hw_watchpoint_use_count (struct breakpoint *);
216
217 static int hw_watchpoint_used_count_others (struct breakpoint *except,
218                                             enum bptype type,
219                                             int *other_type_used);
220
221 static void hbreak_command (char *, int);
222
223 static void thbreak_command (char *, int);
224
225 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
226                                     int count);
227
228 static void stop_command (char *arg, int from_tty);
229
230 static void stopin_command (char *arg, int from_tty);
231
232 static void stopat_command (char *arg, int from_tty);
233
234 static void tcatch_command (char *arg, int from_tty);
235
236 static void free_bp_location (struct bp_location *loc);
237 static void incref_bp_location (struct bp_location *loc);
238 static void decref_bp_location (struct bp_location **loc);
239
240 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
241
242 /* update_global_location_list's modes of operation wrt to whether to
243    insert locations now.  */
244 enum ugll_insert_mode
245 {
246   /* Don't insert any breakpoint locations into the inferior, only
247      remove already-inserted locations that no longer should be
248      inserted.  Functions that delete a breakpoint or breakpoints
249      should specify this mode, so that deleting a breakpoint doesn't
250      have the side effect of inserting the locations of other
251      breakpoints that are marked not-inserted, but should_be_inserted
252      returns true on them.
253
254      This behavior is useful is situations close to tear-down -- e.g.,
255      after an exec, while the target still has execution, but
256      breakpoint shadows of the previous executable image should *NOT*
257      be restored to the new image; or before detaching, where the
258      target still has execution and wants to delete breakpoints from
259      GDB's lists, and all breakpoints had already been removed from
260      the inferior.  */
261   UGLL_DONT_INSERT,
262
263   /* May insert breakpoints iff breakpoints_should_be_inserted_now
264      claims breakpoints should be inserted now.  */
265   UGLL_MAY_INSERT,
266
267   /* Insert locations now, irrespective of
268      breakpoints_should_be_inserted_now.  E.g., say all threads are
269      stopped right now, and the user did "continue".  We need to
270      insert breakpoints _before_ resuming the target, but
271      UGLL_MAY_INSERT wouldn't insert them, because
272      breakpoints_should_be_inserted_now returns false at that point,
273      as no thread is running yet.  */
274   UGLL_INSERT
275 };
276
277 static void update_global_location_list (enum ugll_insert_mode);
278
279 static void update_global_location_list_nothrow (enum ugll_insert_mode);
280
281 static int is_hardware_watchpoint (const struct breakpoint *bpt);
282
283 static void insert_breakpoint_locations (void);
284
285 static void tracepoints_info (char *, int);
286
287 static void delete_trace_command (char *, int);
288
289 static void enable_trace_command (char *, int);
290
291 static void disable_trace_command (char *, int);
292
293 static void trace_pass_command (char *, int);
294
295 static void set_tracepoint_count (int num);
296
297 static int is_masked_watchpoint (const struct breakpoint *b);
298
299 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
300
301 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
302    otherwise.  */
303
304 static int strace_marker_p (struct breakpoint *b);
305
306 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
307    that are implemented on top of software or hardware breakpoints
308    (user breakpoints, internal and momentary breakpoints, etc.).  */
309 static struct breakpoint_ops bkpt_base_breakpoint_ops;
310
311 /* Internal breakpoints class type.  */
312 static struct breakpoint_ops internal_breakpoint_ops;
313
314 /* Momentary breakpoints class type.  */
315 static struct breakpoint_ops momentary_breakpoint_ops;
316
317 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
318 static struct breakpoint_ops longjmp_breakpoint_ops;
319
320 /* The breakpoint_ops structure to be used in regular user created
321    breakpoints.  */
322 struct breakpoint_ops bkpt_breakpoint_ops;
323
324 /* Breakpoints set on probes.  */
325 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
326
327 /* Dynamic printf class type.  */
328 struct breakpoint_ops dprintf_breakpoint_ops;
329
330 /* The style in which to perform a dynamic printf.  This is a user
331    option because different output options have different tradeoffs;
332    if GDB does the printing, there is better error handling if there
333    is a problem with any of the arguments, but using an inferior
334    function lets you have special-purpose printers and sending of
335    output to the same place as compiled-in print functions.  */
336
337 static const char dprintf_style_gdb[] = "gdb";
338 static const char dprintf_style_call[] = "call";
339 static const char dprintf_style_agent[] = "agent";
340 static const char *const dprintf_style_enums[] = {
341   dprintf_style_gdb,
342   dprintf_style_call,
343   dprintf_style_agent,
344   NULL
345 };
346 static const char *dprintf_style = dprintf_style_gdb;
347
348 /* The function to use for dynamic printf if the preferred style is to
349    call into the inferior.  The value is simply a string that is
350    copied into the command, so it can be anything that GDB can
351    evaluate to a callable address, not necessarily a function name.  */
352
353 static char *dprintf_function = "";
354
355 /* The channel to use for dynamic printf if the preferred style is to
356    call into the inferior; if a nonempty string, it will be passed to
357    the call as the first argument, with the format string as the
358    second.  As with the dprintf function, this can be anything that
359    GDB knows how to evaluate, so in addition to common choices like
360    "stderr", this could be an app-specific expression like
361    "mystreams[curlogger]".  */
362
363 static char *dprintf_channel = "";
364
365 /* True if dprintf commands should continue to operate even if GDB
366    has disconnected.  */
367 static int disconnected_dprintf = 1;
368
369 /* A reference-counted struct command_line.  This lets multiple
370    breakpoints share a single command list.  */
371 struct counted_command_line
372 {
373   /* The reference count.  */
374   int refc;
375
376   /* The command list.  */
377   struct command_line *commands;
378 };
379
380 struct command_line *
381 breakpoint_commands (struct breakpoint *b)
382 {
383   return b->commands ? b->commands->commands : NULL;
384 }
385
386 /* Flag indicating that a command has proceeded the inferior past the
387    current breakpoint.  */
388
389 static int breakpoint_proceeded;
390
391 const char *
392 bpdisp_text (enum bpdisp disp)
393 {
394   /* NOTE: the following values are a part of MI protocol and
395      represent values of 'disp' field returned when inferior stops at
396      a breakpoint.  */
397   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
398
399   return bpdisps[(int) disp];
400 }
401
402 /* Prototypes for exported functions.  */
403 /* If FALSE, gdb will not use hardware support for watchpoints, even
404    if such is available.  */
405 static int can_use_hw_watchpoints;
406
407 static void
408 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
409                              struct cmd_list_element *c,
410                              const char *value)
411 {
412   fprintf_filtered (file,
413                     _("Debugger's willingness to use "
414                       "watchpoint hardware is %s.\n"),
415                     value);
416 }
417
418 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
419    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
420    for unrecognized breakpoint locations.
421    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
422 static enum auto_boolean pending_break_support;
423 static void
424 show_pending_break_support (struct ui_file *file, int from_tty,
425                             struct cmd_list_element *c,
426                             const char *value)
427 {
428   fprintf_filtered (file,
429                     _("Debugger's behavior regarding "
430                       "pending breakpoints is %s.\n"),
431                     value);
432 }
433
434 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
435    set with "break" but falling in read-only memory.
436    If 0, gdb will warn about such breakpoints, but won't automatically
437    use hardware breakpoints.  */
438 static int automatic_hardware_breakpoints;
439 static void
440 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
441                                      struct cmd_list_element *c,
442                                      const char *value)
443 {
444   fprintf_filtered (file,
445                     _("Automatic usage of hardware breakpoints is %s.\n"),
446                     value);
447 }
448
449 /* If on, GDB keeps breakpoints inserted even if the inferior is
450    stopped, and immediately inserts any new breakpoints as soon as
451    they're created.  If off (default), GDB keeps breakpoints off of
452    the target as long as possible.  That is, it delays inserting
453    breakpoints until the next resume, and removes them again when the
454    target fully stops.  This is a bit safer in case GDB crashes while
455    processing user input.  */
456 static int always_inserted_mode = 0;
457
458 static void
459 show_always_inserted_mode (struct ui_file *file, int from_tty,
460                      struct cmd_list_element *c, const char *value)
461 {
462   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
463                     value);
464 }
465
466 /* See breakpoint.h.  */
467
468 int
469 breakpoints_should_be_inserted_now (void)
470 {
471   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
472     {
473       /* If breakpoints are global, they should be inserted even if no
474          thread under gdb's control is running, or even if there are
475          no threads under GDB's control yet.  */
476       return 1;
477     }
478   else if (target_has_execution)
479     {
480       struct thread_info *tp;
481
482       if (always_inserted_mode)
483         {
484           /* The user wants breakpoints inserted even if all threads
485              are stopped.  */
486           return 1;
487         }
488
489       if (threads_are_executing ())
490         return 1;
491
492       /* Don't remove breakpoints yet if, even though all threads are
493          stopped, we still have events to process.  */
494       ALL_NON_EXITED_THREADS (tp)
495         if (tp->resumed
496             && tp->suspend.waitstatus_pending_p)
497           return 1;
498     }
499   return 0;
500 }
501
502 static const char condition_evaluation_both[] = "host or target";
503
504 /* Modes for breakpoint condition evaluation.  */
505 static const char condition_evaluation_auto[] = "auto";
506 static const char condition_evaluation_host[] = "host";
507 static const char condition_evaluation_target[] = "target";
508 static const char *const condition_evaluation_enums[] = {
509   condition_evaluation_auto,
510   condition_evaluation_host,
511   condition_evaluation_target,
512   NULL
513 };
514
515 /* Global that holds the current mode for breakpoint condition evaluation.  */
516 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
517
518 /* Global that we use to display information to the user (gets its value from
519    condition_evaluation_mode_1.  */
520 static const char *condition_evaluation_mode = condition_evaluation_auto;
521
522 /* Translate a condition evaluation mode MODE into either "host"
523    or "target".  This is used mostly to translate from "auto" to the
524    real setting that is being used.  It returns the translated
525    evaluation mode.  */
526
527 static const char *
528 translate_condition_evaluation_mode (const char *mode)
529 {
530   if (mode == condition_evaluation_auto)
531     {
532       if (target_supports_evaluation_of_breakpoint_conditions ())
533         return condition_evaluation_target;
534       else
535         return condition_evaluation_host;
536     }
537   else
538     return mode;
539 }
540
541 /* Discovers what condition_evaluation_auto translates to.  */
542
543 static const char *
544 breakpoint_condition_evaluation_mode (void)
545 {
546   return translate_condition_evaluation_mode (condition_evaluation_mode);
547 }
548
549 /* Return true if GDB should evaluate breakpoint conditions or false
550    otherwise.  */
551
552 static int
553 gdb_evaluates_breakpoint_condition_p (void)
554 {
555   const char *mode = breakpoint_condition_evaluation_mode ();
556
557   return (mode == condition_evaluation_host);
558 }
559
560 void _initialize_breakpoint (void);
561
562 /* Are we executing breakpoint commands?  */
563 static int executing_breakpoint_commands;
564
565 /* Are overlay event breakpoints enabled? */
566 static int overlay_events_enabled;
567
568 /* See description in breakpoint.h. */
569 int target_exact_watchpoints = 0;
570
571 /* Walk the following statement or block through all breakpoints.
572    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
573    current breakpoint.  */
574
575 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
576
577 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
578         for (B = breakpoint_chain;      \
579              B ? (TMP=B->next, 1): 0;   \
580              B = TMP)
581
582 /* Similar iterator for the low-level breakpoints.  SAFE variant is
583    not provided so update_global_location_list must not be called
584    while executing the block of ALL_BP_LOCATIONS.  */
585
586 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
587         for (BP_TMP = bp_location;                                      \
588              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
589              BP_TMP++)
590
591 /* Iterates through locations with address ADDRESS for the currently selected
592    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
593    to where the loop should start from.
594    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
595    appropriate location to start with.  */
596
597 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
598         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
599              BP_LOCP_TMP = BP_LOCP_START;                               \
600              BP_LOCP_START                                              \
601              && (BP_LOCP_TMP < bp_location + bp_location_count          \
602              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
603              BP_LOCP_TMP++)
604
605 /* Iterator for tracepoints only.  */
606
607 #define ALL_TRACEPOINTS(B)  \
608   for (B = breakpoint_chain; B; B = B->next)  \
609     if (is_tracepoint (B))
610
611 /* Chains of all breakpoints defined.  */
612
613 struct breakpoint *breakpoint_chain;
614
615 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
616
617 static struct bp_location **bp_location;
618
619 /* Number of elements of BP_LOCATION.  */
620
621 static unsigned bp_location_count;
622
623 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
624    ADDRESS for the current elements of BP_LOCATION which get a valid
625    result from bp_location_has_shadow.  You can use it for roughly
626    limiting the subrange of BP_LOCATION to scan for shadow bytes for
627    an address you need to read.  */
628
629 static CORE_ADDR bp_location_placed_address_before_address_max;
630
631 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
632    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
633    BP_LOCATION which get a valid result from bp_location_has_shadow.
634    You can use it for roughly limiting the subrange of BP_LOCATION to
635    scan for shadow bytes for an address you need to read.  */
636
637 static CORE_ADDR bp_location_shadow_len_after_address_max;
638
639 /* The locations that no longer correspond to any breakpoint, unlinked
640    from bp_location array, but for which a hit may still be reported
641    by a target.  */
642 VEC(bp_location_p) *moribund_locations = NULL;
643
644 /* Number of last breakpoint made.  */
645
646 static int breakpoint_count;
647
648 /* The value of `breakpoint_count' before the last command that
649    created breakpoints.  If the last (break-like) command created more
650    than one breakpoint, then the difference between BREAKPOINT_COUNT
651    and PREV_BREAKPOINT_COUNT is more than one.  */
652 static int prev_breakpoint_count;
653
654 /* Number of last tracepoint made.  */
655
656 static int tracepoint_count;
657
658 static struct cmd_list_element *breakpoint_set_cmdlist;
659 static struct cmd_list_element *breakpoint_show_cmdlist;
660 struct cmd_list_element *save_cmdlist;
661
662 /* See declaration at breakpoint.h.  */
663
664 struct breakpoint *
665 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
666                     void *user_data)
667 {
668   struct breakpoint *b = NULL;
669
670   ALL_BREAKPOINTS (b)
671     {
672       if (func (b, user_data) != 0)
673         break;
674     }
675
676   return b;
677 }
678
679 /* Return whether a breakpoint is an active enabled breakpoint.  */
680 static int
681 breakpoint_enabled (struct breakpoint *b)
682 {
683   return (b->enable_state == bp_enabled);
684 }
685
686 /* Set breakpoint count to NUM.  */
687
688 static void
689 set_breakpoint_count (int num)
690 {
691   prev_breakpoint_count = breakpoint_count;
692   breakpoint_count = num;
693   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
694 }
695
696 /* Used by `start_rbreak_breakpoints' below, to record the current
697    breakpoint count before "rbreak" creates any breakpoint.  */
698 static int rbreak_start_breakpoint_count;
699
700 /* Called at the start an "rbreak" command to record the first
701    breakpoint made.  */
702
703 void
704 start_rbreak_breakpoints (void)
705 {
706   rbreak_start_breakpoint_count = breakpoint_count;
707 }
708
709 /* Called at the end of an "rbreak" command to record the last
710    breakpoint made.  */
711
712 void
713 end_rbreak_breakpoints (void)
714 {
715   prev_breakpoint_count = rbreak_start_breakpoint_count;
716 }
717
718 /* Used in run_command to zero the hit count when a new run starts.  */
719
720 void
721 clear_breakpoint_hit_counts (void)
722 {
723   struct breakpoint *b;
724
725   ALL_BREAKPOINTS (b)
726     b->hit_count = 0;
727 }
728
729 /* Allocate a new counted_command_line with reference count of 1.
730    The new structure owns COMMANDS.  */
731
732 static struct counted_command_line *
733 alloc_counted_command_line (struct command_line *commands)
734 {
735   struct counted_command_line *result = XNEW (struct counted_command_line);
736
737   result->refc = 1;
738   result->commands = commands;
739
740   return result;
741 }
742
743 /* Increment reference count.  This does nothing if CMD is NULL.  */
744
745 static void
746 incref_counted_command_line (struct counted_command_line *cmd)
747 {
748   if (cmd)
749     ++cmd->refc;
750 }
751
752 /* Decrement reference count.  If the reference count reaches 0,
753    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
754    nothing if *CMDP is NULL.  */
755
756 static void
757 decref_counted_command_line (struct counted_command_line **cmdp)
758 {
759   if (*cmdp)
760     {
761       if (--(*cmdp)->refc == 0)
762         {
763           free_command_lines (&(*cmdp)->commands);
764           xfree (*cmdp);
765         }
766       *cmdp = NULL;
767     }
768 }
769
770 /* A cleanup function that calls decref_counted_command_line.  */
771
772 static void
773 do_cleanup_counted_command_line (void *arg)
774 {
775   decref_counted_command_line ((struct counted_command_line **) arg);
776 }
777
778 /* Create a cleanup that calls decref_counted_command_line on the
779    argument.  */
780
781 static struct cleanup *
782 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
783 {
784   return make_cleanup (do_cleanup_counted_command_line, cmdp);
785 }
786
787 \f
788 /* Return the breakpoint with the specified number, or NULL
789    if the number does not refer to an existing breakpoint.  */
790
791 struct breakpoint *
792 get_breakpoint (int num)
793 {
794   struct breakpoint *b;
795
796   ALL_BREAKPOINTS (b)
797     if (b->number == num)
798       return b;
799   
800   return NULL;
801 }
802
803 \f
804
805 /* Mark locations as "conditions have changed" in case the target supports
806    evaluating conditions on its side.  */
807
808 static void
809 mark_breakpoint_modified (struct breakpoint *b)
810 {
811   struct bp_location *loc;
812
813   /* This is only meaningful if the target is
814      evaluating conditions and if the user has
815      opted for condition evaluation on the target's
816      side.  */
817   if (gdb_evaluates_breakpoint_condition_p ()
818       || !target_supports_evaluation_of_breakpoint_conditions ())
819     return;
820
821   if (!is_breakpoint (b))
822     return;
823
824   for (loc = b->loc; loc; loc = loc->next)
825     loc->condition_changed = condition_modified;
826 }
827
828 /* Mark location as "conditions have changed" in case the target supports
829    evaluating conditions on its side.  */
830
831 static void
832 mark_breakpoint_location_modified (struct bp_location *loc)
833 {
834   /* This is only meaningful if the target is
835      evaluating conditions and if the user has
836      opted for condition evaluation on the target's
837      side.  */
838   if (gdb_evaluates_breakpoint_condition_p ()
839       || !target_supports_evaluation_of_breakpoint_conditions ())
840
841     return;
842
843   if (!is_breakpoint (loc->owner))
844     return;
845
846   loc->condition_changed = condition_modified;
847 }
848
849 /* Sets the condition-evaluation mode using the static global
850    condition_evaluation_mode.  */
851
852 static void
853 set_condition_evaluation_mode (char *args, int from_tty,
854                                struct cmd_list_element *c)
855 {
856   const char *old_mode, *new_mode;
857
858   if ((condition_evaluation_mode_1 == condition_evaluation_target)
859       && !target_supports_evaluation_of_breakpoint_conditions ())
860     {
861       condition_evaluation_mode_1 = condition_evaluation_mode;
862       warning (_("Target does not support breakpoint condition evaluation.\n"
863                  "Using host evaluation mode instead."));
864       return;
865     }
866
867   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
868   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
869
870   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
871      settings was "auto".  */
872   condition_evaluation_mode = condition_evaluation_mode_1;
873
874   /* Only update the mode if the user picked a different one.  */
875   if (new_mode != old_mode)
876     {
877       struct bp_location *loc, **loc_tmp;
878       /* If the user switched to a different evaluation mode, we
879          need to synch the changes with the target as follows:
880
881          "host" -> "target": Send all (valid) conditions to the target.
882          "target" -> "host": Remove all the conditions from the target.
883       */
884
885       if (new_mode == condition_evaluation_target)
886         {
887           /* Mark everything modified and synch conditions with the
888              target.  */
889           ALL_BP_LOCATIONS (loc, loc_tmp)
890             mark_breakpoint_location_modified (loc);
891         }
892       else
893         {
894           /* Manually mark non-duplicate locations to synch conditions
895              with the target.  We do this to remove all the conditions the
896              target knows about.  */
897           ALL_BP_LOCATIONS (loc, loc_tmp)
898             if (is_breakpoint (loc->owner) && loc->inserted)
899               loc->needs_update = 1;
900         }
901
902       /* Do the update.  */
903       update_global_location_list (UGLL_MAY_INSERT);
904     }
905
906   return;
907 }
908
909 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
910    what "auto" is translating to.  */
911
912 static void
913 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
914                                 struct cmd_list_element *c, const char *value)
915 {
916   if (condition_evaluation_mode == condition_evaluation_auto)
917     fprintf_filtered (file,
918                       _("Breakpoint condition evaluation "
919                         "mode is %s (currently %s).\n"),
920                       value,
921                       breakpoint_condition_evaluation_mode ());
922   else
923     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
924                       value);
925 }
926
927 /* A comparison function for bp_location AP and BP that is used by
928    bsearch.  This comparison function only cares about addresses, unlike
929    the more general bp_location_compare function.  */
930
931 static int
932 bp_location_compare_addrs (const void *ap, const void *bp)
933 {
934   const struct bp_location *a = *(const struct bp_location **) ap;
935   const struct bp_location *b = *(const struct bp_location **) bp;
936
937   if (a->address == b->address)
938     return 0;
939   else
940     return ((a->address > b->address) - (a->address < b->address));
941 }
942
943 /* Helper function to skip all bp_locations with addresses
944    less than ADDRESS.  It returns the first bp_location that
945    is greater than or equal to ADDRESS.  If none is found, just
946    return NULL.  */
947
948 static struct bp_location **
949 get_first_locp_gte_addr (CORE_ADDR address)
950 {
951   struct bp_location dummy_loc;
952   struct bp_location *dummy_locp = &dummy_loc;
953   struct bp_location **locp_found = NULL;
954
955   /* Initialize the dummy location's address field.  */
956   memset (&dummy_loc, 0, sizeof (struct bp_location));
957   dummy_loc.address = address;
958
959   /* Find a close match to the first location at ADDRESS.  */
960   locp_found = ((struct bp_location **)
961                 bsearch (&dummy_locp, bp_location, bp_location_count,
962                          sizeof (struct bp_location **),
963                          bp_location_compare_addrs));
964
965   /* Nothing was found, nothing left to do.  */
966   if (locp_found == NULL)
967     return NULL;
968
969   /* We may have found a location that is at ADDRESS but is not the first in the
970      location's list.  Go backwards (if possible) and locate the first one.  */
971   while ((locp_found - 1) >= bp_location
972          && (*(locp_found - 1))->address == address)
973     locp_found--;
974
975   return locp_found;
976 }
977
978 void
979 set_breakpoint_condition (struct breakpoint *b, const char *exp,
980                           int from_tty)
981 {
982   xfree (b->cond_string);
983   b->cond_string = NULL;
984
985   if (is_watchpoint (b))
986     {
987       struct watchpoint *w = (struct watchpoint *) b;
988
989       xfree (w->cond_exp);
990       w->cond_exp = NULL;
991     }
992   else
993     {
994       struct bp_location *loc;
995
996       for (loc = b->loc; loc; loc = loc->next)
997         {
998           xfree (loc->cond);
999           loc->cond = NULL;
1000
1001           /* No need to free the condition agent expression
1002              bytecode (if we have one).  We will handle this
1003              when we go through update_global_location_list.  */
1004         }
1005     }
1006
1007   if (*exp == 0)
1008     {
1009       if (from_tty)
1010         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1011     }
1012   else
1013     {
1014       const char *arg = exp;
1015
1016       /* I don't know if it matters whether this is the string the user
1017          typed in or the decompiled expression.  */
1018       b->cond_string = xstrdup (arg);
1019       b->condition_not_parsed = 0;
1020
1021       if (is_watchpoint (b))
1022         {
1023           struct watchpoint *w = (struct watchpoint *) b;
1024
1025           innermost_block = NULL;
1026           arg = exp;
1027           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1028           if (*arg)
1029             error (_("Junk at end of expression"));
1030           w->cond_exp_valid_block = innermost_block;
1031         }
1032       else
1033         {
1034           struct bp_location *loc;
1035
1036           for (loc = b->loc; loc; loc = loc->next)
1037             {
1038               arg = exp;
1039               loc->cond =
1040                 parse_exp_1 (&arg, loc->address,
1041                              block_for_pc (loc->address), 0);
1042               if (*arg)
1043                 error (_("Junk at end of expression"));
1044             }
1045         }
1046     }
1047   mark_breakpoint_modified (b);
1048
1049   observer_notify_breakpoint_modified (b);
1050 }
1051
1052 /* Completion for the "condition" command.  */
1053
1054 static VEC (char_ptr) *
1055 condition_completer (struct cmd_list_element *cmd,
1056                      const char *text, const char *word)
1057 {
1058   const char *space;
1059
1060   text = skip_spaces_const (text);
1061   space = skip_to_space_const (text);
1062   if (*space == '\0')
1063     {
1064       int len;
1065       struct breakpoint *b;
1066       VEC (char_ptr) *result = NULL;
1067
1068       if (text[0] == '$')
1069         {
1070           /* We don't support completion of history indices.  */
1071           if (isdigit (text[1]))
1072             return NULL;
1073           return complete_internalvar (&text[1]);
1074         }
1075
1076       /* We're completing the breakpoint number.  */
1077       len = strlen (text);
1078
1079       ALL_BREAKPOINTS (b)
1080         {
1081           char number[50];
1082
1083           xsnprintf (number, sizeof (number), "%d", b->number);
1084
1085           if (strncmp (number, text, len) == 0)
1086             VEC_safe_push (char_ptr, result, xstrdup (number));
1087         }
1088
1089       return result;
1090     }
1091
1092   /* We're completing the expression part.  */
1093   text = skip_spaces_const (space);
1094   return expression_completer (cmd, text, word);
1095 }
1096
1097 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1098
1099 static void
1100 condition_command (char *arg, int from_tty)
1101 {
1102   struct breakpoint *b;
1103   char *p;
1104   int bnum;
1105
1106   if (arg == 0)
1107     error_no_arg (_("breakpoint number"));
1108
1109   p = arg;
1110   bnum = get_number (&p);
1111   if (bnum == 0)
1112     error (_("Bad breakpoint argument: '%s'"), arg);
1113
1114   ALL_BREAKPOINTS (b)
1115     if (b->number == bnum)
1116       {
1117         /* Check if this breakpoint has a "stop" method implemented in an
1118            extension language.  This method and conditions entered into GDB
1119            from the CLI are mutually exclusive.  */
1120         const struct extension_language_defn *extlang
1121           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1122
1123         if (extlang != NULL)
1124           {
1125             error (_("Only one stop condition allowed.  There is currently"
1126                      " a %s stop condition defined for this breakpoint."),
1127                    ext_lang_capitalized_name (extlang));
1128           }
1129         set_breakpoint_condition (b, p, from_tty);
1130
1131         if (is_breakpoint (b))
1132           update_global_location_list (UGLL_MAY_INSERT);
1133
1134         return;
1135       }
1136
1137   error (_("No breakpoint number %d."), bnum);
1138 }
1139
1140 /* Check that COMMAND do not contain commands that are suitable
1141    only for tracepoints and not suitable for ordinary breakpoints.
1142    Throw if any such commands is found.  */
1143
1144 static void
1145 check_no_tracepoint_commands (struct command_line *commands)
1146 {
1147   struct command_line *c;
1148
1149   for (c = commands; c; c = c->next)
1150     {
1151       int i;
1152
1153       if (c->control_type == while_stepping_control)
1154         error (_("The 'while-stepping' command can "
1155                  "only be used for tracepoints"));
1156
1157       for (i = 0; i < c->body_count; ++i)
1158         check_no_tracepoint_commands ((c->body_list)[i]);
1159
1160       /* Not that command parsing removes leading whitespace and comment
1161          lines and also empty lines.  So, we only need to check for
1162          command directly.  */
1163       if (strstr (c->line, "collect ") == c->line)
1164         error (_("The 'collect' command can only be used for tracepoints"));
1165
1166       if (strstr (c->line, "teval ") == c->line)
1167         error (_("The 'teval' command can only be used for tracepoints"));
1168     }
1169 }
1170
1171 /* Encapsulate tests for different types of tracepoints.  */
1172
1173 static int
1174 is_tracepoint_type (enum bptype type)
1175 {
1176   return (type == bp_tracepoint
1177           || type == bp_fast_tracepoint
1178           || type == bp_static_tracepoint);
1179 }
1180
1181 int
1182 is_tracepoint (const struct breakpoint *b)
1183 {
1184   return is_tracepoint_type (b->type);
1185 }
1186
1187 /* A helper function that validates that COMMANDS are valid for a
1188    breakpoint.  This function will throw an exception if a problem is
1189    found.  */
1190
1191 static void
1192 validate_commands_for_breakpoint (struct breakpoint *b,
1193                                   struct command_line *commands)
1194 {
1195   if (is_tracepoint (b))
1196     {
1197       struct tracepoint *t = (struct tracepoint *) b;
1198       struct command_line *c;
1199       struct command_line *while_stepping = 0;
1200
1201       /* Reset the while-stepping step count.  The previous commands
1202          might have included a while-stepping action, while the new
1203          ones might not.  */
1204       t->step_count = 0;
1205
1206       /* We need to verify that each top-level element of commands is
1207          valid for tracepoints, that there's at most one
1208          while-stepping element, and that the while-stepping's body
1209          has valid tracing commands excluding nested while-stepping.
1210          We also need to validate the tracepoint action line in the
1211          context of the tracepoint --- validate_actionline actually
1212          has side effects, like setting the tracepoint's
1213          while-stepping STEP_COUNT, in addition to checking if the
1214          collect/teval actions parse and make sense in the
1215          tracepoint's context.  */
1216       for (c = commands; c; c = c->next)
1217         {
1218           if (c->control_type == while_stepping_control)
1219             {
1220               if (b->type == bp_fast_tracepoint)
1221                 error (_("The 'while-stepping' command "
1222                          "cannot be used for fast tracepoint"));
1223               else if (b->type == bp_static_tracepoint)
1224                 error (_("The 'while-stepping' command "
1225                          "cannot be used for static tracepoint"));
1226
1227               if (while_stepping)
1228                 error (_("The 'while-stepping' command "
1229                          "can be used only once"));
1230               else
1231                 while_stepping = c;
1232             }
1233
1234           validate_actionline (c->line, b);
1235         }
1236       if (while_stepping)
1237         {
1238           struct command_line *c2;
1239
1240           gdb_assert (while_stepping->body_count == 1);
1241           c2 = while_stepping->body_list[0];
1242           for (; c2; c2 = c2->next)
1243             {
1244               if (c2->control_type == while_stepping_control)
1245                 error (_("The 'while-stepping' command cannot be nested"));
1246             }
1247         }
1248     }
1249   else
1250     {
1251       check_no_tracepoint_commands (commands);
1252     }
1253 }
1254
1255 /* Return a vector of all the static tracepoints set at ADDR.  The
1256    caller is responsible for releasing the vector.  */
1257
1258 VEC(breakpoint_p) *
1259 static_tracepoints_here (CORE_ADDR addr)
1260 {
1261   struct breakpoint *b;
1262   VEC(breakpoint_p) *found = 0;
1263   struct bp_location *loc;
1264
1265   ALL_BREAKPOINTS (b)
1266     if (b->type == bp_static_tracepoint)
1267       {
1268         for (loc = b->loc; loc; loc = loc->next)
1269           if (loc->address == addr)
1270             VEC_safe_push(breakpoint_p, found, b);
1271       }
1272
1273   return found;
1274 }
1275
1276 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1277    validate that only allowed commands are included.  */
1278
1279 void
1280 breakpoint_set_commands (struct breakpoint *b, 
1281                          struct command_line *commands)
1282 {
1283   validate_commands_for_breakpoint (b, commands);
1284
1285   decref_counted_command_line (&b->commands);
1286   b->commands = alloc_counted_command_line (commands);
1287   observer_notify_breakpoint_modified (b);
1288 }
1289
1290 /* Set the internal `silent' flag on the breakpoint.  Note that this
1291    is not the same as the "silent" that may appear in the breakpoint's
1292    commands.  */
1293
1294 void
1295 breakpoint_set_silent (struct breakpoint *b, int silent)
1296 {
1297   int old_silent = b->silent;
1298
1299   b->silent = silent;
1300   if (old_silent != silent)
1301     observer_notify_breakpoint_modified (b);
1302 }
1303
1304 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1305    breakpoint work for any thread.  */
1306
1307 void
1308 breakpoint_set_thread (struct breakpoint *b, int thread)
1309 {
1310   int old_thread = b->thread;
1311
1312   b->thread = thread;
1313   if (old_thread != thread)
1314     observer_notify_breakpoint_modified (b);
1315 }
1316
1317 /* Set the task for this breakpoint.  If TASK is 0, make the
1318    breakpoint work for any task.  */
1319
1320 void
1321 breakpoint_set_task (struct breakpoint *b, int task)
1322 {
1323   int old_task = b->task;
1324
1325   b->task = task;
1326   if (old_task != task)
1327     observer_notify_breakpoint_modified (b);
1328 }
1329
1330 void
1331 check_tracepoint_command (char *line, void *closure)
1332 {
1333   struct breakpoint *b = (struct breakpoint *) closure;
1334
1335   validate_actionline (line, b);
1336 }
1337
1338 /* A structure used to pass information through
1339    map_breakpoint_numbers.  */
1340
1341 struct commands_info
1342 {
1343   /* True if the command was typed at a tty.  */
1344   int from_tty;
1345
1346   /* The breakpoint range spec.  */
1347   char *arg;
1348
1349   /* Non-NULL if the body of the commands are being read from this
1350      already-parsed command.  */
1351   struct command_line *control;
1352
1353   /* The command lines read from the user, or NULL if they have not
1354      yet been read.  */
1355   struct counted_command_line *cmd;
1356 };
1357
1358 /* A callback for map_breakpoint_numbers that sets the commands for
1359    commands_command.  */
1360
1361 static void
1362 do_map_commands_command (struct breakpoint *b, void *data)
1363 {
1364   struct commands_info *info = (struct commands_info *) data;
1365
1366   if (info->cmd == NULL)
1367     {
1368       struct command_line *l;
1369
1370       if (info->control != NULL)
1371         l = copy_command_lines (info->control->body_list[0]);
1372       else
1373         {
1374           struct cleanup *old_chain;
1375           char *str;
1376
1377           str = xstrprintf (_("Type commands for breakpoint(s) "
1378                               "%s, one per line."),
1379                             info->arg);
1380
1381           old_chain = make_cleanup (xfree, str);
1382
1383           l = read_command_lines (str,
1384                                   info->from_tty, 1,
1385                                   (is_tracepoint (b)
1386                                    ? check_tracepoint_command : 0),
1387                                   b);
1388
1389           do_cleanups (old_chain);
1390         }
1391
1392       info->cmd = alloc_counted_command_line (l);
1393     }
1394
1395   /* If a breakpoint was on the list more than once, we don't need to
1396      do anything.  */
1397   if (b->commands != info->cmd)
1398     {
1399       validate_commands_for_breakpoint (b, info->cmd->commands);
1400       incref_counted_command_line (info->cmd);
1401       decref_counted_command_line (&b->commands);
1402       b->commands = info->cmd;
1403       observer_notify_breakpoint_modified (b);
1404     }
1405 }
1406
1407 static void
1408 commands_command_1 (char *arg, int from_tty, 
1409                     struct command_line *control)
1410 {
1411   struct cleanup *cleanups;
1412   struct commands_info info;
1413
1414   info.from_tty = from_tty;
1415   info.control = control;
1416   info.cmd = NULL;
1417   /* If we read command lines from the user, then `info' will hold an
1418      extra reference to the commands that we must clean up.  */
1419   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1420
1421   if (arg == NULL || !*arg)
1422     {
1423       if (breakpoint_count - prev_breakpoint_count > 1)
1424         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1425                           breakpoint_count);
1426       else if (breakpoint_count > 0)
1427         arg = xstrprintf ("%d", breakpoint_count);
1428       else
1429         {
1430           /* So that we don't try to free the incoming non-NULL
1431              argument in the cleanup below.  Mapping breakpoint
1432              numbers will fail in this case.  */
1433           arg = NULL;
1434         }
1435     }
1436   else
1437     /* The command loop has some static state, so we need to preserve
1438        our argument.  */
1439     arg = xstrdup (arg);
1440
1441   if (arg != NULL)
1442     make_cleanup (xfree, arg);
1443
1444   info.arg = arg;
1445
1446   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1447
1448   if (info.cmd == NULL)
1449     error (_("No breakpoints specified."));
1450
1451   do_cleanups (cleanups);
1452 }
1453
1454 static void
1455 commands_command (char *arg, int from_tty)
1456 {
1457   commands_command_1 (arg, from_tty, NULL);
1458 }
1459
1460 /* Like commands_command, but instead of reading the commands from
1461    input stream, takes them from an already parsed command structure.
1462
1463    This is used by cli-script.c to DTRT with breakpoint commands
1464    that are part of if and while bodies.  */
1465 enum command_control_type
1466 commands_from_control_command (char *arg, struct command_line *cmd)
1467 {
1468   commands_command_1 (arg, 0, cmd);
1469   return simple_control;
1470 }
1471
1472 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1473
1474 static int
1475 bp_location_has_shadow (struct bp_location *bl)
1476 {
1477   if (bl->loc_type != bp_loc_software_breakpoint)
1478     return 0;
1479   if (!bl->inserted)
1480     return 0;
1481   if (bl->target_info.shadow_len == 0)
1482     /* BL isn't valid, or doesn't shadow memory.  */
1483     return 0;
1484   return 1;
1485 }
1486
1487 /* Update BUF, which is LEN bytes read from the target address
1488    MEMADDR, by replacing a memory breakpoint with its shadowed
1489    contents.
1490
1491    If READBUF is not NULL, this buffer must not overlap with the of
1492    the breakpoint location's shadow_contents buffer.  Otherwise, a
1493    failed assertion internal error will be raised.  */
1494
1495 static void
1496 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1497                             const gdb_byte *writebuf_org,
1498                             ULONGEST memaddr, LONGEST len,
1499                             struct bp_target_info *target_info,
1500                             struct gdbarch *gdbarch)
1501 {
1502   /* Now do full processing of the found relevant range of elements.  */
1503   CORE_ADDR bp_addr = 0;
1504   int bp_size = 0;
1505   int bptoffset = 0;
1506
1507   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1508                                  current_program_space->aspace, 0))
1509     {
1510       /* The breakpoint is inserted in a different address space.  */
1511       return;
1512     }
1513
1514   /* Addresses and length of the part of the breakpoint that
1515      we need to copy.  */
1516   bp_addr = target_info->placed_address;
1517   bp_size = target_info->shadow_len;
1518
1519   if (bp_addr + bp_size <= memaddr)
1520     {
1521       /* The breakpoint is entirely before the chunk of memory we are
1522          reading.  */
1523       return;
1524     }
1525
1526   if (bp_addr >= memaddr + len)
1527     {
1528       /* The breakpoint is entirely after the chunk of memory we are
1529          reading.  */
1530       return;
1531     }
1532
1533   /* Offset within shadow_contents.  */
1534   if (bp_addr < memaddr)
1535     {
1536       /* Only copy the second part of the breakpoint.  */
1537       bp_size -= memaddr - bp_addr;
1538       bptoffset = memaddr - bp_addr;
1539       bp_addr = memaddr;
1540     }
1541
1542   if (bp_addr + bp_size > memaddr + len)
1543     {
1544       /* Only copy the first part of the breakpoint.  */
1545       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1546     }
1547
1548   if (readbuf != NULL)
1549     {
1550       /* Verify that the readbuf buffer does not overlap with the
1551          shadow_contents buffer.  */
1552       gdb_assert (target_info->shadow_contents >= readbuf + len
1553                   || readbuf >= (target_info->shadow_contents
1554                                  + target_info->shadow_len));
1555
1556       /* Update the read buffer with this inserted breakpoint's
1557          shadow.  */
1558       memcpy (readbuf + bp_addr - memaddr,
1559               target_info->shadow_contents + bptoffset, bp_size);
1560     }
1561   else
1562     {
1563       const unsigned char *bp;
1564       CORE_ADDR addr = target_info->reqstd_address;
1565       int placed_size;
1566
1567       /* Update the shadow with what we want to write to memory.  */
1568       memcpy (target_info->shadow_contents + bptoffset,
1569               writebuf_org + bp_addr - memaddr, bp_size);
1570
1571       /* Determine appropriate breakpoint contents and size for this
1572          address.  */
1573       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1574
1575       /* Update the final write buffer with this inserted
1576          breakpoint's INSN.  */
1577       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1578     }
1579 }
1580
1581 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1582    by replacing any memory breakpoints with their shadowed contents.
1583
1584    If READBUF is not NULL, this buffer must not overlap with any of
1585    the breakpoint location's shadow_contents buffers.  Otherwise,
1586    a failed assertion internal error will be raised.
1587
1588    The range of shadowed area by each bp_location is:
1589      bl->address - bp_location_placed_address_before_address_max
1590      up to bl->address + bp_location_shadow_len_after_address_max
1591    The range we were requested to resolve shadows for is:
1592      memaddr ... memaddr + len
1593    Thus the safe cutoff boundaries for performance optimization are
1594      memaddr + len <= (bl->address
1595                        - bp_location_placed_address_before_address_max)
1596    and:
1597      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1598
1599 void
1600 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1601                         const gdb_byte *writebuf_org,
1602                         ULONGEST memaddr, LONGEST len)
1603 {
1604   /* Left boundary, right boundary and median element of our binary
1605      search.  */
1606   unsigned bc_l, bc_r, bc;
1607
1608   /* Find BC_L which is a leftmost element which may affect BUF
1609      content.  It is safe to report lower value but a failure to
1610      report higher one.  */
1611
1612   bc_l = 0;
1613   bc_r = bp_location_count;
1614   while (bc_l + 1 < bc_r)
1615     {
1616       struct bp_location *bl;
1617
1618       bc = (bc_l + bc_r) / 2;
1619       bl = bp_location[bc];
1620
1621       /* Check first BL->ADDRESS will not overflow due to the added
1622          constant.  Then advance the left boundary only if we are sure
1623          the BC element can in no way affect the BUF content (MEMADDR
1624          to MEMADDR + LEN range).
1625
1626          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1627          offset so that we cannot miss a breakpoint with its shadow
1628          range tail still reaching MEMADDR.  */
1629
1630       if ((bl->address + bp_location_shadow_len_after_address_max
1631            >= bl->address)
1632           && (bl->address + bp_location_shadow_len_after_address_max
1633               <= memaddr))
1634         bc_l = bc;
1635       else
1636         bc_r = bc;
1637     }
1638
1639   /* Due to the binary search above, we need to make sure we pick the
1640      first location that's at BC_L's address.  E.g., if there are
1641      multiple locations at the same address, BC_L may end up pointing
1642      at a duplicate location, and miss the "master"/"inserted"
1643      location.  Say, given locations L1, L2 and L3 at addresses A and
1644      B:
1645
1646       L1@A, L2@A, L3@B, ...
1647
1648      BC_L could end up pointing at location L2, while the "master"
1649      location could be L1.  Since the `loc->inserted' flag is only set
1650      on "master" locations, we'd forget to restore the shadow of L1
1651      and L2.  */
1652   while (bc_l > 0
1653          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1654     bc_l--;
1655
1656   /* Now do full processing of the found relevant range of elements.  */
1657
1658   for (bc = bc_l; bc < bp_location_count; bc++)
1659   {
1660     struct bp_location *bl = bp_location[bc];
1661
1662     /* bp_location array has BL->OWNER always non-NULL.  */
1663     if (bl->owner->type == bp_none)
1664       warning (_("reading through apparently deleted breakpoint #%d?"),
1665                bl->owner->number);
1666
1667     /* Performance optimization: any further element can no longer affect BUF
1668        content.  */
1669
1670     if (bl->address >= bp_location_placed_address_before_address_max
1671         && memaddr + len <= (bl->address
1672                              - bp_location_placed_address_before_address_max))
1673       break;
1674
1675     if (!bp_location_has_shadow (bl))
1676       continue;
1677
1678     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1679                                 memaddr, len, &bl->target_info, bl->gdbarch);
1680   }
1681 }
1682
1683 \f
1684
1685 /* Return true if BPT is either a software breakpoint or a hardware
1686    breakpoint.  */
1687
1688 int
1689 is_breakpoint (const struct breakpoint *bpt)
1690 {
1691   return (bpt->type == bp_breakpoint
1692           || bpt->type == bp_hardware_breakpoint
1693           || bpt->type == bp_dprintf);
1694 }
1695
1696 /* Return true if BPT is of any hardware watchpoint kind.  */
1697
1698 static int
1699 is_hardware_watchpoint (const struct breakpoint *bpt)
1700 {
1701   return (bpt->type == bp_hardware_watchpoint
1702           || bpt->type == bp_read_watchpoint
1703           || bpt->type == bp_access_watchpoint);
1704 }
1705
1706 /* Return true if BPT is of any watchpoint kind, hardware or
1707    software.  */
1708
1709 int
1710 is_watchpoint (const struct breakpoint *bpt)
1711 {
1712   return (is_hardware_watchpoint (bpt)
1713           || bpt->type == bp_watchpoint);
1714 }
1715
1716 /* Returns true if the current thread and its running state are safe
1717    to evaluate or update watchpoint B.  Watchpoints on local
1718    expressions need to be evaluated in the context of the thread that
1719    was current when the watchpoint was created, and, that thread needs
1720    to be stopped to be able to select the correct frame context.
1721    Watchpoints on global expressions can be evaluated on any thread,
1722    and in any state.  It is presently left to the target allowing
1723    memory accesses when threads are running.  */
1724
1725 static int
1726 watchpoint_in_thread_scope (struct watchpoint *b)
1727 {
1728   return (b->base.pspace == current_program_space
1729           && (ptid_equal (b->watchpoint_thread, null_ptid)
1730               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1731                   && !is_executing (inferior_ptid))));
1732 }
1733
1734 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1735    associated bp_watchpoint_scope breakpoint.  */
1736
1737 static void
1738 watchpoint_del_at_next_stop (struct watchpoint *w)
1739 {
1740   struct breakpoint *b = &w->base;
1741
1742   if (b->related_breakpoint != b)
1743     {
1744       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1745       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1746       b->related_breakpoint->disposition = disp_del_at_next_stop;
1747       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1748       b->related_breakpoint = b;
1749     }
1750   b->disposition = disp_del_at_next_stop;
1751 }
1752
1753 /* Extract a bitfield value from value VAL using the bit parameters contained in
1754    watchpoint W.  */
1755
1756 static struct value *
1757 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1758 {
1759   struct value *bit_val;
1760
1761   if (val == NULL)
1762     return NULL;
1763
1764   bit_val = allocate_value (value_type (val));
1765
1766   unpack_value_bitfield (bit_val,
1767                          w->val_bitpos,
1768                          w->val_bitsize,
1769                          value_contents_for_printing (val),
1770                          value_offset (val),
1771                          val);
1772
1773   return bit_val;
1774 }
1775
1776 /* Allocate a dummy location and add it to B, which must be a software
1777    watchpoint.  This is required because even if a software watchpoint
1778    is not watching any memory, bpstat_stop_status requires a location
1779    to be able to report stops.  */
1780
1781 static void
1782 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1783                                             struct program_space *pspace)
1784 {
1785   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1786
1787   b->loc = allocate_bp_location (b);
1788   b->loc->pspace = pspace;
1789   b->loc->address = -1;
1790   b->loc->length = -1;
1791 }
1792
1793 /* Returns true if B is a software watchpoint that is not watching any
1794    memory (e.g., "watch $pc").  */
1795
1796 static int
1797 is_no_memory_software_watchpoint (struct breakpoint *b)
1798 {
1799   return (b->type == bp_watchpoint
1800           && b->loc != NULL
1801           && b->loc->next == NULL
1802           && b->loc->address == -1
1803           && b->loc->length == -1);
1804 }
1805
1806 /* Assuming that B is a watchpoint:
1807    - Reparse watchpoint expression, if REPARSE is non-zero
1808    - Evaluate expression and store the result in B->val
1809    - Evaluate the condition if there is one, and store the result
1810      in b->loc->cond.
1811    - Update the list of values that must be watched in B->loc.
1812
1813    If the watchpoint disposition is disp_del_at_next_stop, then do
1814    nothing.  If this is local watchpoint that is out of scope, delete
1815    it.
1816
1817    Even with `set breakpoint always-inserted on' the watchpoints are
1818    removed + inserted on each stop here.  Normal breakpoints must
1819    never be removed because they might be missed by a running thread
1820    when debugging in non-stop mode.  On the other hand, hardware
1821    watchpoints (is_hardware_watchpoint; processed here) are specific
1822    to each LWP since they are stored in each LWP's hardware debug
1823    registers.  Therefore, such LWP must be stopped first in order to
1824    be able to modify its hardware watchpoints.
1825
1826    Hardware watchpoints must be reset exactly once after being
1827    presented to the user.  It cannot be done sooner, because it would
1828    reset the data used to present the watchpoint hit to the user.  And
1829    it must not be done later because it could display the same single
1830    watchpoint hit during multiple GDB stops.  Note that the latter is
1831    relevant only to the hardware watchpoint types bp_read_watchpoint
1832    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1833    not user-visible - its hit is suppressed if the memory content has
1834    not changed.
1835
1836    The following constraints influence the location where we can reset
1837    hardware watchpoints:
1838
1839    * target_stopped_by_watchpoint and target_stopped_data_address are
1840      called several times when GDB stops.
1841
1842    [linux] 
1843    * Multiple hardware watchpoints can be hit at the same time,
1844      causing GDB to stop.  GDB only presents one hardware watchpoint
1845      hit at a time as the reason for stopping, and all the other hits
1846      are presented later, one after the other, each time the user
1847      requests the execution to be resumed.  Execution is not resumed
1848      for the threads still having pending hit event stored in
1849      LWP_INFO->STATUS.  While the watchpoint is already removed from
1850      the inferior on the first stop the thread hit event is kept being
1851      reported from its cached value by linux_nat_stopped_data_address
1852      until the real thread resume happens after the watchpoint gets
1853      presented and thus its LWP_INFO->STATUS gets reset.
1854
1855    Therefore the hardware watchpoint hit can get safely reset on the
1856    watchpoint removal from inferior.  */
1857
1858 static void
1859 update_watchpoint (struct watchpoint *b, int reparse)
1860 {
1861   int within_current_scope;
1862   struct frame_id saved_frame_id;
1863   int frame_saved;
1864
1865   /* If this is a local watchpoint, we only want to check if the
1866      watchpoint frame is in scope if the current thread is the thread
1867      that was used to create the watchpoint.  */
1868   if (!watchpoint_in_thread_scope (b))
1869     return;
1870
1871   if (b->base.disposition == disp_del_at_next_stop)
1872     return;
1873  
1874   frame_saved = 0;
1875
1876   /* Determine if the watchpoint is within scope.  */
1877   if (b->exp_valid_block == NULL)
1878     within_current_scope = 1;
1879   else
1880     {
1881       struct frame_info *fi = get_current_frame ();
1882       struct gdbarch *frame_arch = get_frame_arch (fi);
1883       CORE_ADDR frame_pc = get_frame_pc (fi);
1884
1885       /* If we're at a point where the stack has been destroyed
1886          (e.g. in a function epilogue), unwinding may not work
1887          properly. Do not attempt to recreate locations at this
1888          point.  See similar comments in watchpoint_check.  */
1889       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1890         return;
1891
1892       /* Save the current frame's ID so we can restore it after
1893          evaluating the watchpoint expression on its own frame.  */
1894       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1895          took a frame parameter, so that we didn't have to change the
1896          selected frame.  */
1897       frame_saved = 1;
1898       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1899
1900       fi = frame_find_by_id (b->watchpoint_frame);
1901       within_current_scope = (fi != NULL);
1902       if (within_current_scope)
1903         select_frame (fi);
1904     }
1905
1906   /* We don't free locations.  They are stored in the bp_location array
1907      and update_global_location_list will eventually delete them and
1908      remove breakpoints if needed.  */
1909   b->base.loc = NULL;
1910
1911   if (within_current_scope && reparse)
1912     {
1913       const char *s;
1914
1915       if (b->exp)
1916         {
1917           xfree (b->exp);
1918           b->exp = NULL;
1919         }
1920       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1921       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1922       /* If the meaning of expression itself changed, the old value is
1923          no longer relevant.  We don't want to report a watchpoint hit
1924          to the user when the old value and the new value may actually
1925          be completely different objects.  */
1926       value_free (b->val);
1927       b->val = NULL;
1928       b->val_valid = 0;
1929
1930       /* Note that unlike with breakpoints, the watchpoint's condition
1931          expression is stored in the breakpoint object, not in the
1932          locations (re)created below.  */
1933       if (b->base.cond_string != NULL)
1934         {
1935           if (b->cond_exp != NULL)
1936             {
1937               xfree (b->cond_exp);
1938               b->cond_exp = NULL;
1939             }
1940
1941           s = b->base.cond_string;
1942           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1943         }
1944     }
1945
1946   /* If we failed to parse the expression, for example because
1947      it refers to a global variable in a not-yet-loaded shared library,
1948      don't try to insert watchpoint.  We don't automatically delete
1949      such watchpoint, though, since failure to parse expression
1950      is different from out-of-scope watchpoint.  */
1951   if (!target_has_execution)
1952     {
1953       /* Without execution, memory can't change.  No use to try and
1954          set watchpoint locations.  The watchpoint will be reset when
1955          the target gains execution, through breakpoint_re_set.  */
1956       if (!can_use_hw_watchpoints)
1957         {
1958           if (b->base.ops->works_in_software_mode (&b->base))
1959             b->base.type = bp_watchpoint;
1960           else
1961             error (_("Can't set read/access watchpoint when "
1962                      "hardware watchpoints are disabled."));
1963         }
1964     }
1965   else if (within_current_scope && b->exp)
1966     {
1967       int pc = 0;
1968       struct value *val_chain, *v, *result, *next;
1969       struct program_space *frame_pspace;
1970
1971       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1972
1973       /* Avoid setting b->val if it's already set.  The meaning of
1974          b->val is 'the last value' user saw, and we should update
1975          it only if we reported that last value to user.  As it
1976          happens, the code that reports it updates b->val directly.
1977          We don't keep track of the memory value for masked
1978          watchpoints.  */
1979       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1980         {
1981           if (b->val_bitsize != 0)
1982             {
1983               v = extract_bitfield_from_watchpoint_value (b, v);
1984               if (v != NULL)
1985                 release_value (v);
1986             }
1987           b->val = v;
1988           b->val_valid = 1;
1989         }
1990
1991       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1992
1993       /* Look at each value on the value chain.  */
1994       for (v = val_chain; v; v = value_next (v))
1995         {
1996           /* If it's a memory location, and GDB actually needed
1997              its contents to evaluate the expression, then we
1998              must watch it.  If the first value returned is
1999              still lazy, that means an error occurred reading it;
2000              watch it anyway in case it becomes readable.  */
2001           if (VALUE_LVAL (v) == lval_memory
2002               && (v == val_chain || ! value_lazy (v)))
2003             {
2004               struct type *vtype = check_typedef (value_type (v));
2005
2006               /* We only watch structs and arrays if user asked
2007                  for it explicitly, never if they just happen to
2008                  appear in the middle of some value chain.  */
2009               if (v == result
2010                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
2011                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
2012                 {
2013                   CORE_ADDR addr;
2014                   enum target_hw_bp_type type;
2015                   struct bp_location *loc, **tmp;
2016                   int bitpos = 0, bitsize = 0;
2017
2018                   if (value_bitsize (v) != 0)
2019                     {
2020                       /* Extract the bit parameters out from the bitfield
2021                          sub-expression.  */
2022                       bitpos = value_bitpos (v);
2023                       bitsize = value_bitsize (v);
2024                     }
2025                   else if (v == result && b->val_bitsize != 0)
2026                     {
2027                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2028                         lvalue whose bit parameters are saved in the fields
2029                         VAL_BITPOS and VAL_BITSIZE.  */
2030                       bitpos = b->val_bitpos;
2031                       bitsize = b->val_bitsize;
2032                     }
2033
2034                   addr = value_address (v);
2035                   if (bitsize != 0)
2036                     {
2037                       /* Skip the bytes that don't contain the bitfield.  */
2038                       addr += bitpos / 8;
2039                     }
2040
2041                   type = hw_write;
2042                   if (b->base.type == bp_read_watchpoint)
2043                     type = hw_read;
2044                   else if (b->base.type == bp_access_watchpoint)
2045                     type = hw_access;
2046
2047                   loc = allocate_bp_location (&b->base);
2048                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2049                     ;
2050                   *tmp = loc;
2051                   loc->gdbarch = get_type_arch (value_type (v));
2052
2053                   loc->pspace = frame_pspace;
2054                   loc->address = addr;
2055
2056                   if (bitsize != 0)
2057                     {
2058                       /* Just cover the bytes that make up the bitfield.  */
2059                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2060                     }
2061                   else
2062                     loc->length = TYPE_LENGTH (value_type (v));
2063
2064                   loc->watchpoint_type = type;
2065                 }
2066             }
2067         }
2068
2069       /* Change the type of breakpoint between hardware assisted or
2070          an ordinary watchpoint depending on the hardware support
2071          and free hardware slots.  REPARSE is set when the inferior
2072          is started.  */
2073       if (reparse)
2074         {
2075           int reg_cnt;
2076           enum bp_loc_type loc_type;
2077           struct bp_location *bl;
2078
2079           reg_cnt = can_use_hardware_watchpoint (val_chain);
2080
2081           if (reg_cnt)
2082             {
2083               int i, target_resources_ok, other_type_used;
2084               enum bptype type;
2085
2086               /* Use an exact watchpoint when there's only one memory region to be
2087                  watched, and only one debug register is needed to watch it.  */
2088               b->exact = target_exact_watchpoints && reg_cnt == 1;
2089
2090               /* We need to determine how many resources are already
2091                  used for all other hardware watchpoints plus this one
2092                  to see if we still have enough resources to also fit
2093                  this watchpoint in as well.  */
2094
2095               /* If this is a software watchpoint, we try to turn it
2096                  to a hardware one -- count resources as if B was of
2097                  hardware watchpoint type.  */
2098               type = b->base.type;
2099               if (type == bp_watchpoint)
2100                 type = bp_hardware_watchpoint;
2101
2102               /* This watchpoint may or may not have been placed on
2103                  the list yet at this point (it won't be in the list
2104                  if we're trying to create it for the first time,
2105                  through watch_command), so always account for it
2106                  manually.  */
2107
2108               /* Count resources used by all watchpoints except B.  */
2109               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2110
2111               /* Add in the resources needed for B.  */
2112               i += hw_watchpoint_use_count (&b->base);
2113
2114               target_resources_ok
2115                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2116               if (target_resources_ok <= 0)
2117                 {
2118                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2119
2120                   if (target_resources_ok == 0 && !sw_mode)
2121                     error (_("Target does not support this type of "
2122                              "hardware watchpoint."));
2123                   else if (target_resources_ok < 0 && !sw_mode)
2124                     error (_("There are not enough available hardware "
2125                              "resources for this watchpoint."));
2126
2127                   /* Downgrade to software watchpoint.  */
2128                   b->base.type = bp_watchpoint;
2129                 }
2130               else
2131                 {
2132                   /* If this was a software watchpoint, we've just
2133                      found we have enough resources to turn it to a
2134                      hardware watchpoint.  Otherwise, this is a
2135                      nop.  */
2136                   b->base.type = type;
2137                 }
2138             }
2139           else if (!b->base.ops->works_in_software_mode (&b->base))
2140             {
2141               if (!can_use_hw_watchpoints)
2142                 error (_("Can't set read/access watchpoint when "
2143                          "hardware watchpoints are disabled."));
2144               else
2145                 error (_("Expression cannot be implemented with "
2146                          "read/access watchpoint."));
2147             }
2148           else
2149             b->base.type = bp_watchpoint;
2150
2151           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2152                       : bp_loc_hardware_watchpoint);
2153           for (bl = b->base.loc; bl; bl = bl->next)
2154             bl->loc_type = loc_type;
2155         }
2156
2157       for (v = val_chain; v; v = next)
2158         {
2159           next = value_next (v);
2160           if (v != b->val)
2161             value_free (v);
2162         }
2163
2164       /* If a software watchpoint is not watching any memory, then the
2165          above left it without any location set up.  But,
2166          bpstat_stop_status requires a location to be able to report
2167          stops, so make sure there's at least a dummy one.  */
2168       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2169         software_watchpoint_add_no_memory_location (&b->base, frame_pspace);
2170     }
2171   else if (!within_current_scope)
2172     {
2173       printf_filtered (_("\
2174 Watchpoint %d deleted because the program has left the block\n\
2175 in which its expression is valid.\n"),
2176                        b->base.number);
2177       watchpoint_del_at_next_stop (b);
2178     }
2179
2180   /* Restore the selected frame.  */
2181   if (frame_saved)
2182     select_frame (frame_find_by_id (saved_frame_id));
2183 }
2184
2185
2186 /* Returns 1 iff breakpoint location should be
2187    inserted in the inferior.  We don't differentiate the type of BL's owner
2188    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2189    breakpoint_ops is not defined, because in insert_bp_location,
2190    tracepoint's insert_location will not be called.  */
2191 static int
2192 should_be_inserted (struct bp_location *bl)
2193 {
2194   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2195     return 0;
2196
2197   if (bl->owner->disposition == disp_del_at_next_stop)
2198     return 0;
2199
2200   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2201     return 0;
2202
2203   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2204     return 0;
2205
2206   /* This is set for example, when we're attached to the parent of a
2207      vfork, and have detached from the child.  The child is running
2208      free, and we expect it to do an exec or exit, at which point the
2209      OS makes the parent schedulable again (and the target reports
2210      that the vfork is done).  Until the child is done with the shared
2211      memory region, do not insert breakpoints in the parent, otherwise
2212      the child could still trip on the parent's breakpoints.  Since
2213      the parent is blocked anyway, it won't miss any breakpoint.  */
2214   if (bl->pspace->breakpoints_not_allowed)
2215     return 0;
2216
2217   /* Don't insert a breakpoint if we're trying to step past its
2218      location, except if the breakpoint is a single-step breakpoint,
2219      and the breakpoint's thread is the thread which is stepping past
2220      a breakpoint.  */
2221   if ((bl->loc_type == bp_loc_software_breakpoint
2222        || bl->loc_type == bp_loc_hardware_breakpoint)
2223       && stepping_past_instruction_at (bl->pspace->aspace,
2224                                        bl->address)
2225       /* The single-step breakpoint may be inserted at the location
2226          we're trying to step if the instruction branches to itself.
2227          However, the instruction won't be executed at all and it may
2228          break the semantics of the instruction, for example, the
2229          instruction is a conditional branch or updates some flags.
2230          We can't fix it unless GDB is able to emulate the instruction
2231          or switch to displaced stepping.  */
2232       && !(bl->owner->type == bp_single_step
2233            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2234     {
2235       if (debug_infrun)
2236         {
2237           fprintf_unfiltered (gdb_stdlog,
2238                               "infrun: skipping breakpoint: "
2239                               "stepping past insn at: %s\n",
2240                               paddress (bl->gdbarch, bl->address));
2241         }
2242       return 0;
2243     }
2244
2245   /* Don't insert watchpoints if we're trying to step past the
2246      instruction that triggered one.  */
2247   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2248       && stepping_past_nonsteppable_watchpoint ())
2249     {
2250       if (debug_infrun)
2251         {
2252           fprintf_unfiltered (gdb_stdlog,
2253                               "infrun: stepping past non-steppable watchpoint. "
2254                               "skipping watchpoint at %s:%d\n",
2255                               paddress (bl->gdbarch, bl->address),
2256                               bl->length);
2257         }
2258       return 0;
2259     }
2260
2261   return 1;
2262 }
2263
2264 /* Same as should_be_inserted but does the check assuming
2265    that the location is not duplicated.  */
2266
2267 static int
2268 unduplicated_should_be_inserted (struct bp_location *bl)
2269 {
2270   int result;
2271   const int save_duplicate = bl->duplicate;
2272
2273   bl->duplicate = 0;
2274   result = should_be_inserted (bl);
2275   bl->duplicate = save_duplicate;
2276   return result;
2277 }
2278
2279 /* Parses a conditional described by an expression COND into an
2280    agent expression bytecode suitable for evaluation
2281    by the bytecode interpreter.  Return NULL if there was
2282    any error during parsing.  */
2283
2284 static struct agent_expr *
2285 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2286 {
2287   struct agent_expr *aexpr = NULL;
2288
2289   if (!cond)
2290     return NULL;
2291
2292   /* We don't want to stop processing, so catch any errors
2293      that may show up.  */
2294   TRY
2295     {
2296       aexpr = gen_eval_for_expr (scope, cond);
2297     }
2298
2299   CATCH (ex, RETURN_MASK_ERROR)
2300     {
2301       /* If we got here, it means the condition could not be parsed to a valid
2302          bytecode expression and thus can't be evaluated on the target's side.
2303          It's no use iterating through the conditions.  */
2304       return NULL;
2305     }
2306   END_CATCH
2307
2308   /* We have a valid agent expression.  */
2309   return aexpr;
2310 }
2311
2312 /* Based on location BL, create a list of breakpoint conditions to be
2313    passed on to the target.  If we have duplicated locations with different
2314    conditions, we will add such conditions to the list.  The idea is that the
2315    target will evaluate the list of conditions and will only notify GDB when
2316    one of them is true.  */
2317
2318 static void
2319 build_target_condition_list (struct bp_location *bl)
2320 {
2321   struct bp_location **locp = NULL, **loc2p;
2322   int null_condition_or_parse_error = 0;
2323   int modified = bl->needs_update;
2324   struct bp_location *loc;
2325
2326   /* Release conditions left over from a previous insert.  */
2327   VEC_free (agent_expr_p, bl->target_info.conditions);
2328
2329   /* This is only meaningful if the target is
2330      evaluating conditions and if the user has
2331      opted for condition evaluation on the target's
2332      side.  */
2333   if (gdb_evaluates_breakpoint_condition_p ()
2334       || !target_supports_evaluation_of_breakpoint_conditions ())
2335     return;
2336
2337   /* Do a first pass to check for locations with no assigned
2338      conditions or conditions that fail to parse to a valid agent expression
2339      bytecode.  If any of these happen, then it's no use to send conditions
2340      to the target since this location will always trigger and generate a
2341      response back to GDB.  */
2342   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2343     {
2344       loc = (*loc2p);
2345       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2346         {
2347           if (modified)
2348             {
2349               struct agent_expr *aexpr;
2350
2351               /* Re-parse the conditions since something changed.  In that
2352                  case we already freed the condition bytecodes (see
2353                  force_breakpoint_reinsertion).  We just
2354                  need to parse the condition to bytecodes again.  */
2355               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2356               loc->cond_bytecode = aexpr;
2357             }
2358
2359           /* If we have a NULL bytecode expression, it means something
2360              went wrong or we have a null condition expression.  */
2361           if (!loc->cond_bytecode)
2362             {
2363               null_condition_or_parse_error = 1;
2364               break;
2365             }
2366         }
2367     }
2368
2369   /* If any of these happened, it means we will have to evaluate the conditions
2370      for the location's address on gdb's side.  It is no use keeping bytecodes
2371      for all the other duplicate locations, thus we free all of them here.
2372
2373      This is so we have a finer control over which locations' conditions are
2374      being evaluated by GDB or the remote stub.  */
2375   if (null_condition_or_parse_error)
2376     {
2377       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2378         {
2379           loc = (*loc2p);
2380           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2381             {
2382               /* Only go as far as the first NULL bytecode is
2383                  located.  */
2384               if (!loc->cond_bytecode)
2385                 return;
2386
2387               free_agent_expr (loc->cond_bytecode);
2388               loc->cond_bytecode = NULL;
2389             }
2390         }
2391     }
2392
2393   /* No NULL conditions or failed bytecode generation.  Build a condition list
2394      for this location's address.  */
2395   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2396     {
2397       loc = (*loc2p);
2398       if (loc->cond
2399           && is_breakpoint (loc->owner)
2400           && loc->pspace->num == bl->pspace->num
2401           && loc->owner->enable_state == bp_enabled
2402           && loc->enabled)
2403         /* Add the condition to the vector.  This will be used later to send the
2404            conditions to the target.  */
2405         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2406                        loc->cond_bytecode);
2407     }
2408
2409   return;
2410 }
2411
2412 /* Parses a command described by string CMD into an agent expression
2413    bytecode suitable for evaluation by the bytecode interpreter.
2414    Return NULL if there was any error during parsing.  */
2415
2416 static struct agent_expr *
2417 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2418 {
2419   struct cleanup *old_cleanups = 0;
2420   struct expression *expr, **argvec;
2421   struct agent_expr *aexpr = NULL;
2422   const char *cmdrest;
2423   const char *format_start, *format_end;
2424   struct format_piece *fpieces;
2425   int nargs;
2426   struct gdbarch *gdbarch = get_current_arch ();
2427
2428   if (!cmd)
2429     return NULL;
2430
2431   cmdrest = cmd;
2432
2433   if (*cmdrest == ',')
2434     ++cmdrest;
2435   cmdrest = skip_spaces_const (cmdrest);
2436
2437   if (*cmdrest++ != '"')
2438     error (_("No format string following the location"));
2439
2440   format_start = cmdrest;
2441
2442   fpieces = parse_format_string (&cmdrest);
2443
2444   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2445
2446   format_end = cmdrest;
2447
2448   if (*cmdrest++ != '"')
2449     error (_("Bad format string, non-terminated '\"'."));
2450   
2451   cmdrest = skip_spaces_const (cmdrest);
2452
2453   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2454     error (_("Invalid argument syntax"));
2455
2456   if (*cmdrest == ',')
2457     cmdrest++;
2458   cmdrest = skip_spaces_const (cmdrest);
2459
2460   /* For each argument, make an expression.  */
2461
2462   argvec = (struct expression **) alloca (strlen (cmd)
2463                                          * sizeof (struct expression *));
2464
2465   nargs = 0;
2466   while (*cmdrest != '\0')
2467     {
2468       const char *cmd1;
2469
2470       cmd1 = cmdrest;
2471       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2472       argvec[nargs++] = expr;
2473       cmdrest = cmd1;
2474       if (*cmdrest == ',')
2475         ++cmdrest;
2476     }
2477
2478   /* We don't want to stop processing, so catch any errors
2479      that may show up.  */
2480   TRY
2481     {
2482       aexpr = gen_printf (scope, gdbarch, 0, 0,
2483                           format_start, format_end - format_start,
2484                           fpieces, nargs, argvec);
2485     }
2486   CATCH (ex, RETURN_MASK_ERROR)
2487     {
2488       /* If we got here, it means the command could not be parsed to a valid
2489          bytecode expression and thus can't be evaluated on the target's side.
2490          It's no use iterating through the other commands.  */
2491       aexpr = NULL;
2492     }
2493   END_CATCH
2494
2495   do_cleanups (old_cleanups);
2496
2497   /* We have a valid agent expression, return it.  */
2498   return aexpr;
2499 }
2500
2501 /* Based on location BL, create a list of breakpoint commands to be
2502    passed on to the target.  If we have duplicated locations with
2503    different commands, we will add any such to the list.  */
2504
2505 static void
2506 build_target_command_list (struct bp_location *bl)
2507 {
2508   struct bp_location **locp = NULL, **loc2p;
2509   int null_command_or_parse_error = 0;
2510   int modified = bl->needs_update;
2511   struct bp_location *loc;
2512
2513   /* Release commands left over from a previous insert.  */
2514   VEC_free (agent_expr_p, bl->target_info.tcommands);
2515
2516   if (!target_can_run_breakpoint_commands ())
2517     return;
2518
2519   /* For now, limit to agent-style dprintf breakpoints.  */
2520   if (dprintf_style != dprintf_style_agent)
2521     return;
2522
2523   /* For now, if we have any duplicate location that isn't a dprintf,
2524      don't install the target-side commands, as that would make the
2525      breakpoint not be reported to the core, and we'd lose
2526      control.  */
2527   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2528     {
2529       loc = (*loc2p);
2530       if (is_breakpoint (loc->owner)
2531           && loc->pspace->num == bl->pspace->num
2532           && loc->owner->type != bp_dprintf)
2533         return;
2534     }
2535
2536   /* Do a first pass to check for locations with no assigned
2537      conditions or conditions that fail to parse to a valid agent expression
2538      bytecode.  If any of these happen, then it's no use to send conditions
2539      to the target since this location will always trigger and generate a
2540      response back to GDB.  */
2541   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2542     {
2543       loc = (*loc2p);
2544       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2545         {
2546           if (modified)
2547             {
2548               struct agent_expr *aexpr;
2549
2550               /* Re-parse the commands since something changed.  In that
2551                  case we already freed the command bytecodes (see
2552                  force_breakpoint_reinsertion).  We just
2553                  need to parse the command to bytecodes again.  */
2554               aexpr = parse_cmd_to_aexpr (bl->address,
2555                                           loc->owner->extra_string);
2556               loc->cmd_bytecode = aexpr;
2557             }
2558
2559           /* If we have a NULL bytecode expression, it means something
2560              went wrong or we have a null command expression.  */
2561           if (!loc->cmd_bytecode)
2562             {
2563               null_command_or_parse_error = 1;
2564               break;
2565             }
2566         }
2567     }
2568
2569   /* If anything failed, then we're not doing target-side commands,
2570      and so clean up.  */
2571   if (null_command_or_parse_error)
2572     {
2573       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2574         {
2575           loc = (*loc2p);
2576           if (is_breakpoint (loc->owner)
2577               && loc->pspace->num == bl->pspace->num)
2578             {
2579               /* Only go as far as the first NULL bytecode is
2580                  located.  */
2581               if (loc->cmd_bytecode == NULL)
2582                 return;
2583
2584               free_agent_expr (loc->cmd_bytecode);
2585               loc->cmd_bytecode = NULL;
2586             }
2587         }
2588     }
2589
2590   /* No NULL commands or failed bytecode generation.  Build a command list
2591      for this location's address.  */
2592   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2593     {
2594       loc = (*loc2p);
2595       if (loc->owner->extra_string
2596           && is_breakpoint (loc->owner)
2597           && loc->pspace->num == bl->pspace->num
2598           && loc->owner->enable_state == bp_enabled
2599           && loc->enabled)
2600         /* Add the command to the vector.  This will be used later
2601            to send the commands to the target.  */
2602         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2603                        loc->cmd_bytecode);
2604     }
2605
2606   bl->target_info.persist = 0;
2607   /* Maybe flag this location as persistent.  */
2608   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2609     bl->target_info.persist = 1;
2610 }
2611
2612 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2613    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2614    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2615    Returns 0 for success, 1 if the bp_location type is not supported or
2616    -1 for failure.
2617
2618    NOTE drow/2003-09-09: This routine could be broken down to an
2619    object-style method for each breakpoint or catchpoint type.  */
2620 static int
2621 insert_bp_location (struct bp_location *bl,
2622                     struct ui_file *tmp_error_stream,
2623                     int *disabled_breaks,
2624                     int *hw_breakpoint_error,
2625                     int *hw_bp_error_explained_already)
2626 {
2627   enum errors bp_err = GDB_NO_ERROR;
2628   const char *bp_err_message = NULL;
2629
2630   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2631     return 0;
2632
2633   /* Note we don't initialize bl->target_info, as that wipes out
2634      the breakpoint location's shadow_contents if the breakpoint
2635      is still inserted at that location.  This in turn breaks
2636      target_read_memory which depends on these buffers when
2637      a memory read is requested at the breakpoint location:
2638      Once the target_info has been wiped, we fail to see that
2639      we have a breakpoint inserted at that address and thus
2640      read the breakpoint instead of returning the data saved in
2641      the breakpoint location's shadow contents.  */
2642   bl->target_info.reqstd_address = bl->address;
2643   bl->target_info.placed_address_space = bl->pspace->aspace;
2644   bl->target_info.length = bl->length;
2645
2646   /* When working with target-side conditions, we must pass all the conditions
2647      for the same breakpoint address down to the target since GDB will not
2648      insert those locations.  With a list of breakpoint conditions, the target
2649      can decide when to stop and notify GDB.  */
2650
2651   if (is_breakpoint (bl->owner))
2652     {
2653       build_target_condition_list (bl);
2654       build_target_command_list (bl);
2655       /* Reset the modification marker.  */
2656       bl->needs_update = 0;
2657     }
2658
2659   if (bl->loc_type == bp_loc_software_breakpoint
2660       || bl->loc_type == bp_loc_hardware_breakpoint)
2661     {
2662       if (bl->owner->type != bp_hardware_breakpoint)
2663         {
2664           /* If the explicitly specified breakpoint type
2665              is not hardware breakpoint, check the memory map to see
2666              if the breakpoint address is in read only memory or not.
2667
2668              Two important cases are:
2669              - location type is not hardware breakpoint, memory
2670              is readonly.  We change the type of the location to
2671              hardware breakpoint.
2672              - location type is hardware breakpoint, memory is
2673              read-write.  This means we've previously made the
2674              location hardware one, but then the memory map changed,
2675              so we undo.
2676              
2677              When breakpoints are removed, remove_breakpoints will use
2678              location types we've just set here, the only possible
2679              problem is that memory map has changed during running
2680              program, but it's not going to work anyway with current
2681              gdb.  */
2682           struct mem_region *mr 
2683             = lookup_mem_region (bl->target_info.reqstd_address);
2684           
2685           if (mr)
2686             {
2687               if (automatic_hardware_breakpoints)
2688                 {
2689                   enum bp_loc_type new_type;
2690                   
2691                   if (mr->attrib.mode != MEM_RW)
2692                     new_type = bp_loc_hardware_breakpoint;
2693                   else 
2694                     new_type = bp_loc_software_breakpoint;
2695                   
2696                   if (new_type != bl->loc_type)
2697                     {
2698                       static int said = 0;
2699
2700                       bl->loc_type = new_type;
2701                       if (!said)
2702                         {
2703                           fprintf_filtered (gdb_stdout,
2704                                             _("Note: automatically using "
2705                                               "hardware breakpoints for "
2706                                               "read-only addresses.\n"));
2707                           said = 1;
2708                         }
2709                     }
2710                 }
2711               else if (bl->loc_type == bp_loc_software_breakpoint
2712                        && mr->attrib.mode != MEM_RW)
2713                 {
2714                   fprintf_unfiltered (tmp_error_stream,
2715                                       _("Cannot insert breakpoint %d.\n"
2716                                         "Cannot set software breakpoint "
2717                                         "at read-only address %s\n"),
2718                                       bl->owner->number,
2719                                       paddress (bl->gdbarch, bl->address));
2720                   return 1;
2721                 }
2722             }
2723         }
2724         
2725       /* First check to see if we have to handle an overlay.  */
2726       if (overlay_debugging == ovly_off
2727           || bl->section == NULL
2728           || !(section_is_overlay (bl->section)))
2729         {
2730           /* No overlay handling: just set the breakpoint.  */
2731           TRY
2732             {
2733               int val;
2734
2735               val = bl->owner->ops->insert_location (bl);
2736               if (val)
2737                 bp_err = GENERIC_ERROR;
2738             }
2739           CATCH (e, RETURN_MASK_ALL)
2740             {
2741               bp_err = e.error;
2742               bp_err_message = e.message;
2743             }
2744           END_CATCH
2745         }
2746       else
2747         {
2748           /* This breakpoint is in an overlay section.
2749              Shall we set a breakpoint at the LMA?  */
2750           if (!overlay_events_enabled)
2751             {
2752               /* Yes -- overlay event support is not active, 
2753                  so we must try to set a breakpoint at the LMA.
2754                  This will not work for a hardware breakpoint.  */
2755               if (bl->loc_type == bp_loc_hardware_breakpoint)
2756                 warning (_("hardware breakpoint %d not supported in overlay!"),
2757                          bl->owner->number);
2758               else
2759                 {
2760                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2761                                                              bl->section);
2762                   /* Set a software (trap) breakpoint at the LMA.  */
2763                   bl->overlay_target_info = bl->target_info;
2764                   bl->overlay_target_info.reqstd_address = addr;
2765
2766                   /* No overlay handling: just set the breakpoint.  */
2767                   TRY
2768                     {
2769                       int val;
2770
2771                       val = target_insert_breakpoint (bl->gdbarch,
2772                                                       &bl->overlay_target_info);
2773                       if (val)
2774                         bp_err = GENERIC_ERROR;
2775                     }
2776                   CATCH (e, RETURN_MASK_ALL)
2777                     {
2778                       bp_err = e.error;
2779                       bp_err_message = e.message;
2780                     }
2781                   END_CATCH
2782
2783                   if (bp_err != GDB_NO_ERROR)
2784                     fprintf_unfiltered (tmp_error_stream,
2785                                         "Overlay breakpoint %d "
2786                                         "failed: in ROM?\n",
2787                                         bl->owner->number);
2788                 }
2789             }
2790           /* Shall we set a breakpoint at the VMA? */
2791           if (section_is_mapped (bl->section))
2792             {
2793               /* Yes.  This overlay section is mapped into memory.  */
2794               TRY
2795                 {
2796                   int val;
2797
2798                   val = bl->owner->ops->insert_location (bl);
2799                   if (val)
2800                     bp_err = GENERIC_ERROR;
2801                 }
2802               CATCH (e, RETURN_MASK_ALL)
2803                 {
2804                   bp_err = e.error;
2805                   bp_err_message = e.message;
2806                 }
2807               END_CATCH
2808             }
2809           else
2810             {
2811               /* No.  This breakpoint will not be inserted.  
2812                  No error, but do not mark the bp as 'inserted'.  */
2813               return 0;
2814             }
2815         }
2816
2817       if (bp_err != GDB_NO_ERROR)
2818         {
2819           /* Can't set the breakpoint.  */
2820
2821           /* In some cases, we might not be able to insert a
2822              breakpoint in a shared library that has already been
2823              removed, but we have not yet processed the shlib unload
2824              event.  Unfortunately, some targets that implement
2825              breakpoint insertion themselves can't tell why the
2826              breakpoint insertion failed (e.g., the remote target
2827              doesn't define error codes), so we must treat generic
2828              errors as memory errors.  */
2829           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2830               && bl->loc_type == bp_loc_software_breakpoint
2831               && (solib_name_from_address (bl->pspace, bl->address)
2832                   || shared_objfile_contains_address_p (bl->pspace,
2833                                                         bl->address)))
2834             {
2835               /* See also: disable_breakpoints_in_shlibs.  */
2836               bl->shlib_disabled = 1;
2837               observer_notify_breakpoint_modified (bl->owner);
2838               if (!*disabled_breaks)
2839                 {
2840                   fprintf_unfiltered (tmp_error_stream, 
2841                                       "Cannot insert breakpoint %d.\n", 
2842                                       bl->owner->number);
2843                   fprintf_unfiltered (tmp_error_stream, 
2844                                       "Temporarily disabling shared "
2845                                       "library breakpoints:\n");
2846                 }
2847               *disabled_breaks = 1;
2848               fprintf_unfiltered (tmp_error_stream,
2849                                   "breakpoint #%d\n", bl->owner->number);
2850               return 0;
2851             }
2852           else
2853             {
2854               if (bl->loc_type == bp_loc_hardware_breakpoint)
2855                 {
2856                   *hw_breakpoint_error = 1;
2857                   *hw_bp_error_explained_already = bp_err_message != NULL;
2858                   fprintf_unfiltered (tmp_error_stream,
2859                                       "Cannot insert hardware breakpoint %d%s",
2860                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2861                   if (bp_err_message != NULL)
2862                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2863                 }
2864               else
2865                 {
2866                   if (bp_err_message == NULL)
2867                     {
2868                       char *message
2869                         = memory_error_message (TARGET_XFER_E_IO,
2870                                                 bl->gdbarch, bl->address);
2871                       struct cleanup *old_chain = make_cleanup (xfree, message);
2872
2873                       fprintf_unfiltered (tmp_error_stream,
2874                                           "Cannot insert breakpoint %d.\n"
2875                                           "%s\n",
2876                                           bl->owner->number, message);
2877                       do_cleanups (old_chain);
2878                     }
2879                   else
2880                     {
2881                       fprintf_unfiltered (tmp_error_stream,
2882                                           "Cannot insert breakpoint %d: %s\n",
2883                                           bl->owner->number,
2884                                           bp_err_message);
2885                     }
2886                 }
2887               return 1;
2888
2889             }
2890         }
2891       else
2892         bl->inserted = 1;
2893
2894       return 0;
2895     }
2896
2897   else if (bl->loc_type == bp_loc_hardware_watchpoint
2898            /* NOTE drow/2003-09-08: This state only exists for removing
2899               watchpoints.  It's not clear that it's necessary...  */
2900            && bl->owner->disposition != disp_del_at_next_stop)
2901     {
2902       int val;
2903
2904       gdb_assert (bl->owner->ops != NULL
2905                   && bl->owner->ops->insert_location != NULL);
2906
2907       val = bl->owner->ops->insert_location (bl);
2908
2909       /* If trying to set a read-watchpoint, and it turns out it's not
2910          supported, try emulating one with an access watchpoint.  */
2911       if (val == 1 && bl->watchpoint_type == hw_read)
2912         {
2913           struct bp_location *loc, **loc_temp;
2914
2915           /* But don't try to insert it, if there's already another
2916              hw_access location that would be considered a duplicate
2917              of this one.  */
2918           ALL_BP_LOCATIONS (loc, loc_temp)
2919             if (loc != bl
2920                 && loc->watchpoint_type == hw_access
2921                 && watchpoint_locations_match (bl, loc))
2922               {
2923                 bl->duplicate = 1;
2924                 bl->inserted = 1;
2925                 bl->target_info = loc->target_info;
2926                 bl->watchpoint_type = hw_access;
2927                 val = 0;
2928                 break;
2929               }
2930
2931           if (val == 1)
2932             {
2933               bl->watchpoint_type = hw_access;
2934               val = bl->owner->ops->insert_location (bl);
2935
2936               if (val)
2937                 /* Back to the original value.  */
2938                 bl->watchpoint_type = hw_read;
2939             }
2940         }
2941
2942       bl->inserted = (val == 0);
2943     }
2944
2945   else if (bl->owner->type == bp_catchpoint)
2946     {
2947       int val;
2948
2949       gdb_assert (bl->owner->ops != NULL
2950                   && bl->owner->ops->insert_location != NULL);
2951
2952       val = bl->owner->ops->insert_location (bl);
2953       if (val)
2954         {
2955           bl->owner->enable_state = bp_disabled;
2956
2957           if (val == 1)
2958             warning (_("\
2959 Error inserting catchpoint %d: Your system does not support this type\n\
2960 of catchpoint."), bl->owner->number);
2961           else
2962             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2963         }
2964
2965       bl->inserted = (val == 0);
2966
2967       /* We've already printed an error message if there was a problem
2968          inserting this catchpoint, and we've disabled the catchpoint,
2969          so just return success.  */
2970       return 0;
2971     }
2972
2973   return 0;
2974 }
2975
2976 /* This function is called when program space PSPACE is about to be
2977    deleted.  It takes care of updating breakpoints to not reference
2978    PSPACE anymore.  */
2979
2980 void
2981 breakpoint_program_space_exit (struct program_space *pspace)
2982 {
2983   struct breakpoint *b, *b_temp;
2984   struct bp_location *loc, **loc_temp;
2985
2986   /* Remove any breakpoint that was set through this program space.  */
2987   ALL_BREAKPOINTS_SAFE (b, b_temp)
2988     {
2989       if (b->pspace == pspace)
2990         delete_breakpoint (b);
2991     }
2992
2993   /* Breakpoints set through other program spaces could have locations
2994      bound to PSPACE as well.  Remove those.  */
2995   ALL_BP_LOCATIONS (loc, loc_temp)
2996     {
2997       struct bp_location *tmp;
2998
2999       if (loc->pspace == pspace)
3000         {
3001           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
3002           if (loc->owner->loc == loc)
3003             loc->owner->loc = loc->next;
3004           else
3005             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3006               if (tmp->next == loc)
3007                 {
3008                   tmp->next = loc->next;
3009                   break;
3010                 }
3011         }
3012     }
3013
3014   /* Now update the global location list to permanently delete the
3015      removed locations above.  */
3016   update_global_location_list (UGLL_DONT_INSERT);
3017 }
3018
3019 /* Make sure all breakpoints are inserted in inferior.
3020    Throws exception on any error.
3021    A breakpoint that is already inserted won't be inserted
3022    again, so calling this function twice is safe.  */
3023 void
3024 insert_breakpoints (void)
3025 {
3026   struct breakpoint *bpt;
3027
3028   ALL_BREAKPOINTS (bpt)
3029     if (is_hardware_watchpoint (bpt))
3030       {
3031         struct watchpoint *w = (struct watchpoint *) bpt;
3032
3033         update_watchpoint (w, 0 /* don't reparse.  */);
3034       }
3035
3036   /* Updating watchpoints creates new locations, so update the global
3037      location list.  Explicitly tell ugll to insert locations and
3038      ignore breakpoints_always_inserted_mode.  */
3039   update_global_location_list (UGLL_INSERT);
3040 }
3041
3042 /* Invoke CALLBACK for each of bp_location.  */
3043
3044 void
3045 iterate_over_bp_locations (walk_bp_location_callback callback)
3046 {
3047   struct bp_location *loc, **loc_tmp;
3048
3049   ALL_BP_LOCATIONS (loc, loc_tmp)
3050     {
3051       callback (loc, NULL);
3052     }
3053 }
3054
3055 /* This is used when we need to synch breakpoint conditions between GDB and the
3056    target.  It is the case with deleting and disabling of breakpoints when using
3057    always-inserted mode.  */
3058
3059 static void
3060 update_inserted_breakpoint_locations (void)
3061 {
3062   struct bp_location *bl, **blp_tmp;
3063   int error_flag = 0;
3064   int val = 0;
3065   int disabled_breaks = 0;
3066   int hw_breakpoint_error = 0;
3067   int hw_bp_details_reported = 0;
3068
3069   struct ui_file *tmp_error_stream = mem_fileopen ();
3070   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3071
3072   /* Explicitly mark the warning -- this will only be printed if
3073      there was an error.  */
3074   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3075
3076   save_current_space_and_thread ();
3077
3078   ALL_BP_LOCATIONS (bl, blp_tmp)
3079     {
3080       /* We only want to update software breakpoints and hardware
3081          breakpoints.  */
3082       if (!is_breakpoint (bl->owner))
3083         continue;
3084
3085       /* We only want to update locations that are already inserted
3086          and need updating.  This is to avoid unwanted insertion during
3087          deletion of breakpoints.  */
3088       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3089         continue;
3090
3091       switch_to_program_space_and_thread (bl->pspace);
3092
3093       /* For targets that support global breakpoints, there's no need
3094          to select an inferior to insert breakpoint to.  In fact, even
3095          if we aren't attached to any process yet, we should still
3096          insert breakpoints.  */
3097       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3098           && ptid_equal (inferior_ptid, null_ptid))
3099         continue;
3100
3101       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3102                                     &hw_breakpoint_error, &hw_bp_details_reported);
3103       if (val)
3104         error_flag = val;
3105     }
3106
3107   if (error_flag)
3108     {
3109       target_terminal_ours_for_output ();
3110       error_stream (tmp_error_stream);
3111     }
3112
3113   do_cleanups (cleanups);
3114 }
3115
3116 /* Used when starting or continuing the program.  */
3117
3118 static void
3119 insert_breakpoint_locations (void)
3120 {
3121   struct breakpoint *bpt;
3122   struct bp_location *bl, **blp_tmp;
3123   int error_flag = 0;
3124   int val = 0;
3125   int disabled_breaks = 0;
3126   int hw_breakpoint_error = 0;
3127   int hw_bp_error_explained_already = 0;
3128
3129   struct ui_file *tmp_error_stream = mem_fileopen ();
3130   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3131   
3132   /* Explicitly mark the warning -- this will only be printed if
3133      there was an error.  */
3134   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3135
3136   save_current_space_and_thread ();
3137
3138   ALL_BP_LOCATIONS (bl, blp_tmp)
3139     {
3140       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3141         continue;
3142
3143       /* There is no point inserting thread-specific breakpoints if
3144          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3145          has BL->OWNER always non-NULL.  */
3146       if (bl->owner->thread != -1
3147           && !valid_global_thread_id (bl->owner->thread))
3148         continue;
3149
3150       switch_to_program_space_and_thread (bl->pspace);
3151
3152       /* For targets that support global breakpoints, there's no need
3153          to select an inferior to insert breakpoint to.  In fact, even
3154          if we aren't attached to any process yet, we should still
3155          insert breakpoints.  */
3156       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3157           && ptid_equal (inferior_ptid, null_ptid))
3158         continue;
3159
3160       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3161                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3162       if (val)
3163         error_flag = val;
3164     }
3165
3166   /* If we failed to insert all locations of a watchpoint, remove
3167      them, as half-inserted watchpoint is of limited use.  */
3168   ALL_BREAKPOINTS (bpt)  
3169     {
3170       int some_failed = 0;
3171       struct bp_location *loc;
3172
3173       if (!is_hardware_watchpoint (bpt))
3174         continue;
3175
3176       if (!breakpoint_enabled (bpt))
3177         continue;
3178
3179       if (bpt->disposition == disp_del_at_next_stop)
3180         continue;
3181       
3182       for (loc = bpt->loc; loc; loc = loc->next)
3183         if (!loc->inserted && should_be_inserted (loc))
3184           {
3185             some_failed = 1;
3186             break;
3187           }
3188       if (some_failed)
3189         {
3190           for (loc = bpt->loc; loc; loc = loc->next)
3191             if (loc->inserted)
3192               remove_breakpoint (loc, mark_uninserted);
3193
3194           hw_breakpoint_error = 1;
3195           fprintf_unfiltered (tmp_error_stream,
3196                               "Could not insert hardware watchpoint %d.\n", 
3197                               bpt->number);
3198           error_flag = -1;
3199         }
3200     }
3201
3202   if (error_flag)
3203     {
3204       /* If a hardware breakpoint or watchpoint was inserted, add a
3205          message about possibly exhausted resources.  */
3206       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3207         {
3208           fprintf_unfiltered (tmp_error_stream, 
3209                               "Could not insert hardware breakpoints:\n\
3210 You may have requested too many hardware breakpoints/watchpoints.\n");
3211         }
3212       target_terminal_ours_for_output ();
3213       error_stream (tmp_error_stream);
3214     }
3215
3216   do_cleanups (cleanups);
3217 }
3218
3219 /* Used when the program stops.
3220    Returns zero if successful, or non-zero if there was a problem
3221    removing a breakpoint location.  */
3222
3223 int
3224 remove_breakpoints (void)
3225 {
3226   struct bp_location *bl, **blp_tmp;
3227   int val = 0;
3228
3229   ALL_BP_LOCATIONS (bl, blp_tmp)
3230   {
3231     if (bl->inserted && !is_tracepoint (bl->owner))
3232       val |= remove_breakpoint (bl, mark_uninserted);
3233   }
3234   return val;
3235 }
3236
3237 /* When a thread exits, remove breakpoints that are related to
3238    that thread.  */
3239
3240 static void
3241 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3242 {
3243   struct breakpoint *b, *b_tmp;
3244
3245   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3246     {
3247       if (b->thread == tp->global_num && user_breakpoint_p (b))
3248         {
3249           b->disposition = disp_del_at_next_stop;
3250
3251           printf_filtered (_("\
3252 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3253                            b->number, print_thread_id (tp));
3254
3255           /* Hide it from the user.  */
3256           b->number = 0;
3257        }
3258     }
3259 }
3260
3261 /* Remove breakpoints of process PID.  */
3262
3263 int
3264 remove_breakpoints_pid (int pid)
3265 {
3266   struct bp_location *bl, **blp_tmp;
3267   int val;
3268   struct inferior *inf = find_inferior_pid (pid);
3269
3270   ALL_BP_LOCATIONS (bl, blp_tmp)
3271   {
3272     if (bl->pspace != inf->pspace)
3273       continue;
3274
3275     if (bl->inserted && !bl->target_info.persist)
3276       {
3277         val = remove_breakpoint (bl, mark_uninserted);
3278         if (val != 0)
3279           return val;
3280       }
3281   }
3282   return 0;
3283 }
3284
3285 int
3286 reattach_breakpoints (int pid)
3287 {
3288   struct cleanup *old_chain;
3289   struct bp_location *bl, **blp_tmp;
3290   int val;
3291   struct ui_file *tmp_error_stream;
3292   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3293   struct inferior *inf;
3294   struct thread_info *tp;
3295
3296   tp = any_live_thread_of_process (pid);
3297   if (tp == NULL)
3298     return 1;
3299
3300   inf = find_inferior_pid (pid);
3301   old_chain = save_inferior_ptid ();
3302
3303   inferior_ptid = tp->ptid;
3304
3305   tmp_error_stream = mem_fileopen ();
3306   make_cleanup_ui_file_delete (tmp_error_stream);
3307
3308   ALL_BP_LOCATIONS (bl, blp_tmp)
3309   {
3310     if (bl->pspace != inf->pspace)
3311       continue;
3312
3313     if (bl->inserted)
3314       {
3315         bl->inserted = 0;
3316         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3317         if (val != 0)
3318           {
3319             do_cleanups (old_chain);
3320             return val;
3321           }
3322       }
3323   }
3324   do_cleanups (old_chain);
3325   return 0;
3326 }
3327
3328 static int internal_breakpoint_number = -1;
3329
3330 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3331    If INTERNAL is non-zero, the breakpoint number will be populated
3332    from internal_breakpoint_number and that variable decremented.
3333    Otherwise the breakpoint number will be populated from
3334    breakpoint_count and that value incremented.  Internal breakpoints
3335    do not set the internal var bpnum.  */
3336 static void
3337 set_breakpoint_number (int internal, struct breakpoint *b)
3338 {
3339   if (internal)
3340     b->number = internal_breakpoint_number--;
3341   else
3342     {
3343       set_breakpoint_count (breakpoint_count + 1);
3344       b->number = breakpoint_count;
3345     }
3346 }
3347
3348 static struct breakpoint *
3349 create_internal_breakpoint (struct gdbarch *gdbarch,
3350                             CORE_ADDR address, enum bptype type,
3351                             const struct breakpoint_ops *ops)
3352 {
3353   struct symtab_and_line sal;
3354   struct breakpoint *b;
3355
3356   init_sal (&sal);              /* Initialize to zeroes.  */
3357
3358   sal.pc = address;
3359   sal.section = find_pc_overlay (sal.pc);
3360   sal.pspace = current_program_space;
3361
3362   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3363   b->number = internal_breakpoint_number--;
3364   b->disposition = disp_donttouch;
3365
3366   return b;
3367 }
3368
3369 static const char *const longjmp_names[] =
3370   {
3371     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3372   };
3373 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3374
3375 /* Per-objfile data private to breakpoint.c.  */
3376 struct breakpoint_objfile_data
3377 {
3378   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3379   struct bound_minimal_symbol overlay_msym;
3380
3381   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3382   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3383
3384   /* True if we have looked for longjmp probes.  */
3385   int longjmp_searched;
3386
3387   /* SystemTap probe points for longjmp (if any).  */
3388   VEC (probe_p) *longjmp_probes;
3389
3390   /* Minimal symbol for "std::terminate()" (if any).  */
3391   struct bound_minimal_symbol terminate_msym;
3392
3393   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3394   struct bound_minimal_symbol exception_msym;
3395
3396   /* True if we have looked for exception probes.  */
3397   int exception_searched;
3398
3399   /* SystemTap probe points for unwinding (if any).  */
3400   VEC (probe_p) *exception_probes;
3401 };
3402
3403 static const struct objfile_data *breakpoint_objfile_key;
3404
3405 /* Minimal symbol not found sentinel.  */
3406 static struct minimal_symbol msym_not_found;
3407
3408 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3409
3410 static int
3411 msym_not_found_p (const struct minimal_symbol *msym)
3412 {
3413   return msym == &msym_not_found;
3414 }
3415
3416 /* Return per-objfile data needed by breakpoint.c.
3417    Allocate the data if necessary.  */
3418
3419 static struct breakpoint_objfile_data *
3420 get_breakpoint_objfile_data (struct objfile *objfile)
3421 {
3422   struct breakpoint_objfile_data *bp_objfile_data;
3423
3424   bp_objfile_data = ((struct breakpoint_objfile_data *)
3425                      objfile_data (objfile, breakpoint_objfile_key));
3426   if (bp_objfile_data == NULL)
3427     {
3428       bp_objfile_data =
3429         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3430
3431       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3432       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3433     }
3434   return bp_objfile_data;
3435 }
3436
3437 static void
3438 free_breakpoint_probes (struct objfile *obj, void *data)
3439 {
3440   struct breakpoint_objfile_data *bp_objfile_data
3441     = (struct breakpoint_objfile_data *) data;
3442
3443   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3444   VEC_free (probe_p, bp_objfile_data->exception_probes);
3445 }
3446
3447 static void
3448 create_overlay_event_breakpoint (void)
3449 {
3450   struct objfile *objfile;
3451   const char *const func_name = "_ovly_debug_event";
3452
3453   ALL_OBJFILES (objfile)
3454     {
3455       struct breakpoint *b;
3456       struct breakpoint_objfile_data *bp_objfile_data;
3457       CORE_ADDR addr;
3458       struct explicit_location explicit_loc;
3459
3460       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3461
3462       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3463         continue;
3464
3465       if (bp_objfile_data->overlay_msym.minsym == NULL)
3466         {
3467           struct bound_minimal_symbol m;
3468
3469           m = lookup_minimal_symbol_text (func_name, objfile);
3470           if (m.minsym == NULL)
3471             {
3472               /* Avoid future lookups in this objfile.  */
3473               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3474               continue;
3475             }
3476           bp_objfile_data->overlay_msym = m;
3477         }
3478
3479       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3480       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3481                                       bp_overlay_event,
3482                                       &internal_breakpoint_ops);
3483       initialize_explicit_location (&explicit_loc);
3484       explicit_loc.function_name = ASTRDUP (func_name);
3485       b->location = new_explicit_location (&explicit_loc);
3486
3487       if (overlay_debugging == ovly_auto)
3488         {
3489           b->enable_state = bp_enabled;
3490           overlay_events_enabled = 1;
3491         }
3492       else
3493        {
3494          b->enable_state = bp_disabled;
3495          overlay_events_enabled = 0;
3496        }
3497     }
3498 }
3499
3500 static void
3501 create_longjmp_master_breakpoint (void)
3502 {
3503   struct program_space *pspace;
3504   struct cleanup *old_chain;
3505
3506   old_chain = save_current_program_space ();
3507
3508   ALL_PSPACES (pspace)
3509   {
3510     struct objfile *objfile;
3511
3512     set_current_program_space (pspace);
3513
3514     ALL_OBJFILES (objfile)
3515     {
3516       int i;
3517       struct gdbarch *gdbarch;
3518       struct breakpoint_objfile_data *bp_objfile_data;
3519
3520       gdbarch = get_objfile_arch (objfile);
3521
3522       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3523
3524       if (!bp_objfile_data->longjmp_searched)
3525         {
3526           VEC (probe_p) *ret;
3527
3528           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3529           if (ret != NULL)
3530             {
3531               /* We are only interested in checking one element.  */
3532               struct probe *p = VEC_index (probe_p, ret, 0);
3533
3534               if (!can_evaluate_probe_arguments (p))
3535                 {
3536                   /* We cannot use the probe interface here, because it does
3537                      not know how to evaluate arguments.  */
3538                   VEC_free (probe_p, ret);
3539                   ret = NULL;
3540                 }
3541             }
3542           bp_objfile_data->longjmp_probes = ret;
3543           bp_objfile_data->longjmp_searched = 1;
3544         }
3545
3546       if (bp_objfile_data->longjmp_probes != NULL)
3547         {
3548           int i;
3549           struct probe *probe;
3550           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3551
3552           for (i = 0;
3553                VEC_iterate (probe_p,
3554                             bp_objfile_data->longjmp_probes,
3555                             i, probe);
3556                ++i)
3557             {
3558               struct breakpoint *b;
3559
3560               b = create_internal_breakpoint (gdbarch,
3561                                               get_probe_address (probe,
3562                                                                  objfile),
3563                                               bp_longjmp_master,
3564                                               &internal_breakpoint_ops);
3565               b->location
3566                 = new_probe_location ("-probe-stap libc:longjmp");
3567               b->enable_state = bp_disabled;
3568             }
3569
3570           continue;
3571         }
3572
3573       if (!gdbarch_get_longjmp_target_p (gdbarch))
3574         continue;
3575
3576       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3577         {
3578           struct breakpoint *b;
3579           const char *func_name;
3580           CORE_ADDR addr;
3581           struct explicit_location explicit_loc;
3582
3583           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3584             continue;
3585
3586           func_name = longjmp_names[i];
3587           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3588             {
3589               struct bound_minimal_symbol m;
3590
3591               m = lookup_minimal_symbol_text (func_name, objfile);
3592               if (m.minsym == NULL)
3593                 {
3594                   /* Prevent future lookups in this objfile.  */
3595                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3596                   continue;
3597                 }
3598               bp_objfile_data->longjmp_msym[i] = m;
3599             }
3600
3601           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3602           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3603                                           &internal_breakpoint_ops);
3604           initialize_explicit_location (&explicit_loc);
3605           explicit_loc.function_name = ASTRDUP (func_name);
3606           b->location = new_explicit_location (&explicit_loc);
3607           b->enable_state = bp_disabled;
3608         }
3609     }
3610   }
3611
3612   do_cleanups (old_chain);
3613 }
3614
3615 /* Create a master std::terminate breakpoint.  */
3616 static void
3617 create_std_terminate_master_breakpoint (void)
3618 {
3619   struct program_space *pspace;
3620   struct cleanup *old_chain;
3621   const char *const func_name = "std::terminate()";
3622
3623   old_chain = save_current_program_space ();
3624
3625   ALL_PSPACES (pspace)
3626   {
3627     struct objfile *objfile;
3628     CORE_ADDR addr;
3629
3630     set_current_program_space (pspace);
3631
3632     ALL_OBJFILES (objfile)
3633     {
3634       struct breakpoint *b;
3635       struct breakpoint_objfile_data *bp_objfile_data;
3636       struct explicit_location explicit_loc;
3637
3638       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3639
3640       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3641         continue;
3642
3643       if (bp_objfile_data->terminate_msym.minsym == NULL)
3644         {
3645           struct bound_minimal_symbol m;
3646
3647           m = lookup_minimal_symbol (func_name, NULL, objfile);
3648           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3649                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3650             {
3651               /* Prevent future lookups in this objfile.  */
3652               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3653               continue;
3654             }
3655           bp_objfile_data->terminate_msym = m;
3656         }
3657
3658       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3659       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3660                                       bp_std_terminate_master,
3661                                       &internal_breakpoint_ops);
3662       initialize_explicit_location (&explicit_loc);
3663       explicit_loc.function_name = ASTRDUP (func_name);
3664       b->location = new_explicit_location (&explicit_loc);
3665       b->enable_state = bp_disabled;
3666     }
3667   }
3668
3669   do_cleanups (old_chain);
3670 }
3671
3672 /* Install a master breakpoint on the unwinder's debug hook.  */
3673
3674 static void
3675 create_exception_master_breakpoint (void)
3676 {
3677   struct objfile *objfile;
3678   const char *const func_name = "_Unwind_DebugHook";
3679
3680   ALL_OBJFILES (objfile)
3681     {
3682       struct breakpoint *b;
3683       struct gdbarch *gdbarch;
3684       struct breakpoint_objfile_data *bp_objfile_data;
3685       CORE_ADDR addr;
3686       struct explicit_location explicit_loc;
3687
3688       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3689
3690       /* We prefer the SystemTap probe point if it exists.  */
3691       if (!bp_objfile_data->exception_searched)
3692         {
3693           VEC (probe_p) *ret;
3694
3695           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3696
3697           if (ret != NULL)
3698             {
3699               /* We are only interested in checking one element.  */
3700               struct probe *p = VEC_index (probe_p, ret, 0);
3701
3702               if (!can_evaluate_probe_arguments (p))
3703                 {
3704                   /* We cannot use the probe interface here, because it does
3705                      not know how to evaluate arguments.  */
3706                   VEC_free (probe_p, ret);
3707                   ret = NULL;
3708                 }
3709             }
3710           bp_objfile_data->exception_probes = ret;
3711           bp_objfile_data->exception_searched = 1;
3712         }
3713
3714       if (bp_objfile_data->exception_probes != NULL)
3715         {
3716           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3717           int i;
3718           struct probe *probe;
3719
3720           for (i = 0;
3721                VEC_iterate (probe_p,
3722                             bp_objfile_data->exception_probes,
3723                             i, probe);
3724                ++i)
3725             {
3726               struct breakpoint *b;
3727
3728               b = create_internal_breakpoint (gdbarch,
3729                                               get_probe_address (probe,
3730                                                                  objfile),
3731                                               bp_exception_master,
3732                                               &internal_breakpoint_ops);
3733               b->location
3734                 = new_probe_location ("-probe-stap libgcc:unwind");
3735               b->enable_state = bp_disabled;
3736             }
3737
3738           continue;
3739         }
3740
3741       /* Otherwise, try the hook function.  */
3742
3743       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3744         continue;
3745
3746       gdbarch = get_objfile_arch (objfile);
3747
3748       if (bp_objfile_data->exception_msym.minsym == NULL)
3749         {
3750           struct bound_minimal_symbol debug_hook;
3751
3752           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3753           if (debug_hook.minsym == NULL)
3754             {
3755               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3756               continue;
3757             }
3758
3759           bp_objfile_data->exception_msym = debug_hook;
3760         }
3761
3762       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3763       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3764                                                  &current_target);
3765       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3766                                       &internal_breakpoint_ops);
3767       initialize_explicit_location (&explicit_loc);
3768       explicit_loc.function_name = ASTRDUP (func_name);
3769       b->location = new_explicit_location (&explicit_loc);
3770       b->enable_state = bp_disabled;
3771     }
3772 }
3773
3774 /* Does B have a location spec?  */
3775
3776 static int
3777 breakpoint_event_location_empty_p (const struct breakpoint *b)
3778 {
3779   return b->location != NULL && event_location_empty_p (b->location);
3780 }
3781
3782 void
3783 update_breakpoints_after_exec (void)
3784 {
3785   struct breakpoint *b, *b_tmp;
3786   struct bp_location *bploc, **bplocp_tmp;
3787
3788   /* We're about to delete breakpoints from GDB's lists.  If the
3789      INSERTED flag is true, GDB will try to lift the breakpoints by
3790      writing the breakpoints' "shadow contents" back into memory.  The
3791      "shadow contents" are NOT valid after an exec, so GDB should not
3792      do that.  Instead, the target is responsible from marking
3793      breakpoints out as soon as it detects an exec.  We don't do that
3794      here instead, because there may be other attempts to delete
3795      breakpoints after detecting an exec and before reaching here.  */
3796   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3797     if (bploc->pspace == current_program_space)
3798       gdb_assert (!bploc->inserted);
3799
3800   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3801   {
3802     if (b->pspace != current_program_space)
3803       continue;
3804
3805     /* Solib breakpoints must be explicitly reset after an exec().  */
3806     if (b->type == bp_shlib_event)
3807       {
3808         delete_breakpoint (b);
3809         continue;
3810       }
3811
3812     /* JIT breakpoints must be explicitly reset after an exec().  */
3813     if (b->type == bp_jit_event)
3814       {
3815         delete_breakpoint (b);
3816         continue;
3817       }
3818
3819     /* Thread event breakpoints must be set anew after an exec(),
3820        as must overlay event and longjmp master breakpoints.  */
3821     if (b->type == bp_thread_event || b->type == bp_overlay_event
3822         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3823         || b->type == bp_exception_master)
3824       {
3825         delete_breakpoint (b);
3826         continue;
3827       }
3828
3829     /* Step-resume breakpoints are meaningless after an exec().  */
3830     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3831       {
3832         delete_breakpoint (b);
3833         continue;
3834       }
3835
3836     /* Just like single-step breakpoints.  */
3837     if (b->type == bp_single_step)
3838       {
3839         delete_breakpoint (b);
3840         continue;
3841       }
3842
3843     /* Longjmp and longjmp-resume breakpoints are also meaningless
3844        after an exec.  */
3845     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3846         || b->type == bp_longjmp_call_dummy
3847         || b->type == bp_exception || b->type == bp_exception_resume)
3848       {
3849         delete_breakpoint (b);
3850         continue;
3851       }
3852
3853     if (b->type == bp_catchpoint)
3854       {
3855         /* For now, none of the bp_catchpoint breakpoints need to
3856            do anything at this point.  In the future, if some of
3857            the catchpoints need to something, we will need to add
3858            a new method, and call this method from here.  */
3859         continue;
3860       }
3861
3862     /* bp_finish is a special case.  The only way we ought to be able
3863        to see one of these when an exec() has happened, is if the user
3864        caught a vfork, and then said "finish".  Ordinarily a finish just
3865        carries them to the call-site of the current callee, by setting
3866        a temporary bp there and resuming.  But in this case, the finish
3867        will carry them entirely through the vfork & exec.
3868
3869        We don't want to allow a bp_finish to remain inserted now.  But
3870        we can't safely delete it, 'cause finish_command has a handle to
3871        the bp on a bpstat, and will later want to delete it.  There's a
3872        chance (and I've seen it happen) that if we delete the bp_finish
3873        here, that its storage will get reused by the time finish_command
3874        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3875        We really must allow finish_command to delete a bp_finish.
3876
3877        In the absence of a general solution for the "how do we know
3878        it's safe to delete something others may have handles to?"
3879        problem, what we'll do here is just uninsert the bp_finish, and
3880        let finish_command delete it.
3881
3882        (We know the bp_finish is "doomed" in the sense that it's
3883        momentary, and will be deleted as soon as finish_command sees
3884        the inferior stopped.  So it doesn't matter that the bp's
3885        address is probably bogus in the new a.out, unlike e.g., the
3886        solib breakpoints.)  */
3887
3888     if (b->type == bp_finish)
3889       {
3890         continue;
3891       }
3892
3893     /* Without a symbolic address, we have little hope of the
3894        pre-exec() address meaning the same thing in the post-exec()
3895        a.out.  */
3896     if (breakpoint_event_location_empty_p (b))
3897       {
3898         delete_breakpoint (b);
3899         continue;
3900       }
3901   }
3902 }
3903
3904 int
3905 detach_breakpoints (ptid_t ptid)
3906 {
3907   struct bp_location *bl, **blp_tmp;
3908   int val = 0;
3909   struct cleanup *old_chain = save_inferior_ptid ();
3910   struct inferior *inf = current_inferior ();
3911
3912   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3913     error (_("Cannot detach breakpoints of inferior_ptid"));
3914
3915   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3916   inferior_ptid = ptid;
3917   ALL_BP_LOCATIONS (bl, blp_tmp)
3918   {
3919     if (bl->pspace != inf->pspace)
3920       continue;
3921
3922     /* This function must physically remove breakpoints locations
3923        from the specified ptid, without modifying the breakpoint
3924        package's state.  Locations of type bp_loc_other are only
3925        maintained at GDB side.  So, there is no need to remove
3926        these bp_loc_other locations.  Moreover, removing these
3927        would modify the breakpoint package's state.  */
3928     if (bl->loc_type == bp_loc_other)
3929       continue;
3930
3931     if (bl->inserted)
3932       val |= remove_breakpoint_1 (bl, mark_inserted);
3933   }
3934
3935   do_cleanups (old_chain);
3936   return val;
3937 }
3938
3939 /* Remove the breakpoint location BL from the current address space.
3940    Note that this is used to detach breakpoints from a child fork.
3941    When we get here, the child isn't in the inferior list, and neither
3942    do we have objects to represent its address space --- we should
3943    *not* look at bl->pspace->aspace here.  */
3944
3945 static int
3946 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3947 {
3948   int val;
3949
3950   /* BL is never in moribund_locations by our callers.  */
3951   gdb_assert (bl->owner != NULL);
3952
3953   /* The type of none suggests that owner is actually deleted.
3954      This should not ever happen.  */
3955   gdb_assert (bl->owner->type != bp_none);
3956
3957   if (bl->loc_type == bp_loc_software_breakpoint
3958       || bl->loc_type == bp_loc_hardware_breakpoint)
3959     {
3960       /* "Normal" instruction breakpoint: either the standard
3961          trap-instruction bp (bp_breakpoint), or a
3962          bp_hardware_breakpoint.  */
3963
3964       /* First check to see if we have to handle an overlay.  */
3965       if (overlay_debugging == ovly_off
3966           || bl->section == NULL
3967           || !(section_is_overlay (bl->section)))
3968         {
3969           /* No overlay handling: just remove the breakpoint.  */
3970
3971           /* If we're trying to uninsert a memory breakpoint that we
3972              know is set in a dynamic object that is marked
3973              shlib_disabled, then either the dynamic object was
3974              removed with "remove-symbol-file" or with
3975              "nosharedlibrary".  In the former case, we don't know
3976              whether another dynamic object might have loaded over the
3977              breakpoint's address -- the user might well let us know
3978              about it next with add-symbol-file (the whole point of
3979              add-symbol-file is letting the user manually maintain a
3980              list of dynamically loaded objects).  If we have the
3981              breakpoint's shadow memory, that is, this is a software
3982              breakpoint managed by GDB, check whether the breakpoint
3983              is still inserted in memory, to avoid overwriting wrong
3984              code with stale saved shadow contents.  Note that HW
3985              breakpoints don't have shadow memory, as they're
3986              implemented using a mechanism that is not dependent on
3987              being able to modify the target's memory, and as such
3988              they should always be removed.  */
3989           if (bl->shlib_disabled
3990               && bl->target_info.shadow_len != 0
3991               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3992             val = 0;
3993           else
3994             val = bl->owner->ops->remove_location (bl);
3995         }
3996       else
3997         {
3998           /* This breakpoint is in an overlay section.
3999              Did we set a breakpoint at the LMA?  */
4000           if (!overlay_events_enabled)
4001               {
4002                 /* Yes -- overlay event support is not active, so we
4003                    should have set a breakpoint at the LMA.  Remove it.  
4004                 */
4005                 /* Ignore any failures: if the LMA is in ROM, we will
4006                    have already warned when we failed to insert it.  */
4007                 if (bl->loc_type == bp_loc_hardware_breakpoint)
4008                   target_remove_hw_breakpoint (bl->gdbarch,
4009                                                &bl->overlay_target_info);
4010                 else
4011                   target_remove_breakpoint (bl->gdbarch,
4012                                             &bl->overlay_target_info);
4013               }
4014           /* Did we set a breakpoint at the VMA? 
4015              If so, we will have marked the breakpoint 'inserted'.  */
4016           if (bl->inserted)
4017             {
4018               /* Yes -- remove it.  Previously we did not bother to
4019                  remove the breakpoint if the section had been
4020                  unmapped, but let's not rely on that being safe.  We
4021                  don't know what the overlay manager might do.  */
4022
4023               /* However, we should remove *software* breakpoints only
4024                  if the section is still mapped, or else we overwrite
4025                  wrong code with the saved shadow contents.  */
4026               if (bl->loc_type == bp_loc_hardware_breakpoint
4027                   || section_is_mapped (bl->section))
4028                 val = bl->owner->ops->remove_location (bl);
4029               else
4030                 val = 0;
4031             }
4032           else
4033             {
4034               /* No -- not inserted, so no need to remove.  No error.  */
4035               val = 0;
4036             }
4037         }
4038
4039       /* In some cases, we might not be able to remove a breakpoint in
4040          a shared library that has already been removed, but we have
4041          not yet processed the shlib unload event.  Similarly for an
4042          unloaded add-symbol-file object - the user might not yet have
4043          had the chance to remove-symbol-file it.  shlib_disabled will
4044          be set if the library/object has already been removed, but
4045          the breakpoint hasn't been uninserted yet, e.g., after
4046          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4047          always-inserted mode.  */
4048       if (val
4049           && (bl->loc_type == bp_loc_software_breakpoint
4050               && (bl->shlib_disabled
4051                   || solib_name_from_address (bl->pspace, bl->address)
4052                   || shared_objfile_contains_address_p (bl->pspace,
4053                                                         bl->address))))
4054         val = 0;
4055
4056       if (val)
4057         return val;
4058       bl->inserted = (is == mark_inserted);
4059     }
4060   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4061     {
4062       gdb_assert (bl->owner->ops != NULL
4063                   && bl->owner->ops->remove_location != NULL);
4064
4065       bl->inserted = (is == mark_inserted);
4066       bl->owner->ops->remove_location (bl);
4067
4068       /* Failure to remove any of the hardware watchpoints comes here.  */
4069       if ((is == mark_uninserted) && (bl->inserted))
4070         warning (_("Could not remove hardware watchpoint %d."),
4071                  bl->owner->number);
4072     }
4073   else if (bl->owner->type == bp_catchpoint
4074            && breakpoint_enabled (bl->owner)
4075            && !bl->duplicate)
4076     {
4077       gdb_assert (bl->owner->ops != NULL
4078                   && bl->owner->ops->remove_location != NULL);
4079
4080       val = bl->owner->ops->remove_location (bl);
4081       if (val)
4082         return val;
4083
4084       bl->inserted = (is == mark_inserted);
4085     }
4086
4087   return 0;
4088 }
4089
4090 static int
4091 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4092 {
4093   int ret;
4094   struct cleanup *old_chain;
4095
4096   /* BL is never in moribund_locations by our callers.  */
4097   gdb_assert (bl->owner != NULL);
4098
4099   /* The type of none suggests that owner is actually deleted.
4100      This should not ever happen.  */
4101   gdb_assert (bl->owner->type != bp_none);
4102
4103   old_chain = save_current_space_and_thread ();
4104
4105   switch_to_program_space_and_thread (bl->pspace);
4106
4107   ret = remove_breakpoint_1 (bl, is);
4108
4109   do_cleanups (old_chain);
4110   return ret;
4111 }
4112
4113 /* Clear the "inserted" flag in all breakpoints.  */
4114
4115 void
4116 mark_breakpoints_out (void)
4117 {
4118   struct bp_location *bl, **blp_tmp;
4119
4120   ALL_BP_LOCATIONS (bl, blp_tmp)
4121     if (bl->pspace == current_program_space)
4122       bl->inserted = 0;
4123 }
4124
4125 /* Clear the "inserted" flag in all breakpoints and delete any
4126    breakpoints which should go away between runs of the program.
4127
4128    Plus other such housekeeping that has to be done for breakpoints
4129    between runs.
4130
4131    Note: this function gets called at the end of a run (by
4132    generic_mourn_inferior) and when a run begins (by
4133    init_wait_for_inferior).  */
4134
4135
4136
4137 void
4138 breakpoint_init_inferior (enum inf_context context)
4139 {
4140   struct breakpoint *b, *b_tmp;
4141   struct bp_location *bl;
4142   int ix;
4143   struct program_space *pspace = current_program_space;
4144
4145   /* If breakpoint locations are shared across processes, then there's
4146      nothing to do.  */
4147   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4148     return;
4149
4150   mark_breakpoints_out ();
4151
4152   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4153   {
4154     if (b->loc && b->loc->pspace != pspace)
4155       continue;
4156
4157     switch (b->type)
4158       {
4159       case bp_call_dummy:
4160       case bp_longjmp_call_dummy:
4161
4162         /* If the call dummy breakpoint is at the entry point it will
4163            cause problems when the inferior is rerun, so we better get
4164            rid of it.  */
4165
4166       case bp_watchpoint_scope:
4167
4168         /* Also get rid of scope breakpoints.  */
4169
4170       case bp_shlib_event:
4171
4172         /* Also remove solib event breakpoints.  Their addresses may
4173            have changed since the last time we ran the program.
4174            Actually we may now be debugging against different target;
4175            and so the solib backend that installed this breakpoint may
4176            not be used in by the target.  E.g.,
4177
4178            (gdb) file prog-linux
4179            (gdb) run               # native linux target
4180            ...
4181            (gdb) kill
4182            (gdb) file prog-win.exe
4183            (gdb) tar rem :9999     # remote Windows gdbserver.
4184         */
4185
4186       case bp_step_resume:
4187
4188         /* Also remove step-resume breakpoints.  */
4189
4190       case bp_single_step:
4191
4192         /* Also remove single-step breakpoints.  */
4193
4194         delete_breakpoint (b);
4195         break;
4196
4197       case bp_watchpoint:
4198       case bp_hardware_watchpoint:
4199       case bp_read_watchpoint:
4200       case bp_access_watchpoint:
4201         {
4202           struct watchpoint *w = (struct watchpoint *) b;
4203
4204           /* Likewise for watchpoints on local expressions.  */
4205           if (w->exp_valid_block != NULL)
4206             delete_breakpoint (b);
4207           else if (context == inf_starting)
4208             {
4209               /* Reset val field to force reread of starting value in
4210                  insert_breakpoints.  */
4211               if (w->val)
4212                 value_free (w->val);
4213               w->val = NULL;
4214               w->val_valid = 0;
4215           }
4216         }
4217         break;
4218       default:
4219         break;
4220       }
4221   }
4222
4223   /* Get rid of the moribund locations.  */
4224   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4225     decref_bp_location (&bl);
4226   VEC_free (bp_location_p, moribund_locations);
4227 }
4228
4229 /* These functions concern about actual breakpoints inserted in the
4230    target --- to e.g. check if we need to do decr_pc adjustment or if
4231    we need to hop over the bkpt --- so we check for address space
4232    match, not program space.  */
4233
4234 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4235    exists at PC.  It returns ordinary_breakpoint_here if it's an
4236    ordinary breakpoint, or permanent_breakpoint_here if it's a
4237    permanent breakpoint.
4238    - When continuing from a location with an ordinary breakpoint, we
4239      actually single step once before calling insert_breakpoints.
4240    - When continuing from a location with a permanent breakpoint, we
4241      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4242      the target, to advance the PC past the breakpoint.  */
4243
4244 enum breakpoint_here
4245 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4246 {
4247   struct bp_location *bl, **blp_tmp;
4248   int any_breakpoint_here = 0;
4249
4250   ALL_BP_LOCATIONS (bl, blp_tmp)
4251     {
4252       if (bl->loc_type != bp_loc_software_breakpoint
4253           && bl->loc_type != bp_loc_hardware_breakpoint)
4254         continue;
4255
4256       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4257       if ((breakpoint_enabled (bl->owner)
4258            || bl->permanent)
4259           && breakpoint_location_address_match (bl, aspace, pc))
4260         {
4261           if (overlay_debugging 
4262               && section_is_overlay (bl->section)
4263               && !section_is_mapped (bl->section))
4264             continue;           /* unmapped overlay -- can't be a match */
4265           else if (bl->permanent)
4266             return permanent_breakpoint_here;
4267           else
4268             any_breakpoint_here = 1;
4269         }
4270     }
4271
4272   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4273 }
4274
4275 /* See breakpoint.h.  */
4276
4277 int
4278 breakpoint_in_range_p (struct address_space *aspace,
4279                        CORE_ADDR addr, ULONGEST len)
4280 {
4281   struct bp_location *bl, **blp_tmp;
4282
4283   ALL_BP_LOCATIONS (bl, blp_tmp)
4284     {
4285       if (bl->loc_type != bp_loc_software_breakpoint
4286           && bl->loc_type != bp_loc_hardware_breakpoint)
4287         continue;
4288
4289       if ((breakpoint_enabled (bl->owner)
4290            || bl->permanent)
4291           && breakpoint_location_address_range_overlap (bl, aspace,
4292                                                         addr, len))
4293         {
4294           if (overlay_debugging
4295               && section_is_overlay (bl->section)
4296               && !section_is_mapped (bl->section))
4297             {
4298               /* Unmapped overlay -- can't be a match.  */
4299               continue;
4300             }
4301
4302           return 1;
4303         }
4304     }
4305
4306   return 0;
4307 }
4308
4309 /* Return true if there's a moribund breakpoint at PC.  */
4310
4311 int
4312 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4313 {
4314   struct bp_location *loc;
4315   int ix;
4316
4317   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4318     if (breakpoint_location_address_match (loc, aspace, pc))
4319       return 1;
4320
4321   return 0;
4322 }
4323
4324 /* Returns non-zero iff BL is inserted at PC, in address space
4325    ASPACE.  */
4326
4327 static int
4328 bp_location_inserted_here_p (struct bp_location *bl,
4329                              struct address_space *aspace, CORE_ADDR pc)
4330 {
4331   if (bl->inserted
4332       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4333                                    aspace, pc))
4334     {
4335       if (overlay_debugging
4336           && section_is_overlay (bl->section)
4337           && !section_is_mapped (bl->section))
4338         return 0;               /* unmapped overlay -- can't be a match */
4339       else
4340         return 1;
4341     }
4342   return 0;
4343 }
4344
4345 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4346
4347 int
4348 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4349 {
4350   struct bp_location **blp, **blp_tmp = NULL;
4351
4352   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4353     {
4354       struct bp_location *bl = *blp;
4355
4356       if (bl->loc_type != bp_loc_software_breakpoint
4357           && bl->loc_type != bp_loc_hardware_breakpoint)
4358         continue;
4359
4360       if (bp_location_inserted_here_p (bl, aspace, pc))
4361         return 1;
4362     }
4363   return 0;
4364 }
4365
4366 /* This function returns non-zero iff there is a software breakpoint
4367    inserted at PC.  */
4368
4369 int
4370 software_breakpoint_inserted_here_p (struct address_space *aspace,
4371                                      CORE_ADDR pc)
4372 {
4373   struct bp_location **blp, **blp_tmp = NULL;
4374
4375   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4376     {
4377       struct bp_location *bl = *blp;
4378
4379       if (bl->loc_type != bp_loc_software_breakpoint)
4380         continue;
4381
4382       if (bp_location_inserted_here_p (bl, aspace, pc))
4383         return 1;
4384     }
4385
4386   return 0;
4387 }
4388
4389 /* See breakpoint.h.  */
4390
4391 int
4392 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4393                                      CORE_ADDR pc)
4394 {
4395   struct bp_location **blp, **blp_tmp = NULL;
4396
4397   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4398     {
4399       struct bp_location *bl = *blp;
4400
4401       if (bl->loc_type != bp_loc_hardware_breakpoint)
4402         continue;
4403
4404       if (bp_location_inserted_here_p (bl, aspace, pc))
4405         return 1;
4406     }
4407
4408   return 0;
4409 }
4410
4411 int
4412 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4413                                        CORE_ADDR addr, ULONGEST len)
4414 {
4415   struct breakpoint *bpt;
4416
4417   ALL_BREAKPOINTS (bpt)
4418     {
4419       struct bp_location *loc;
4420
4421       if (bpt->type != bp_hardware_watchpoint
4422           && bpt->type != bp_access_watchpoint)
4423         continue;
4424
4425       if (!breakpoint_enabled (bpt))
4426         continue;
4427
4428       for (loc = bpt->loc; loc; loc = loc->next)
4429         if (loc->pspace->aspace == aspace && loc->inserted)
4430           {
4431             CORE_ADDR l, h;
4432
4433             /* Check for intersection.  */
4434             l = max (loc->address, addr);
4435             h = min (loc->address + loc->length, addr + len);
4436             if (l < h)
4437               return 1;
4438           }
4439     }
4440   return 0;
4441 }
4442 \f
4443
4444 /* bpstat stuff.  External routines' interfaces are documented
4445    in breakpoint.h.  */
4446
4447 int
4448 is_catchpoint (struct breakpoint *ep)
4449 {
4450   return (ep->type == bp_catchpoint);
4451 }
4452
4453 /* Frees any storage that is part of a bpstat.  Does not walk the
4454    'next' chain.  */
4455
4456 static void
4457 bpstat_free (bpstat bs)
4458 {
4459   if (bs->old_val != NULL)
4460     value_free (bs->old_val);
4461   decref_counted_command_line (&bs->commands);
4462   decref_bp_location (&bs->bp_location_at);
4463   xfree (bs);
4464 }
4465
4466 /* Clear a bpstat so that it says we are not at any breakpoint.
4467    Also free any storage that is part of a bpstat.  */
4468
4469 void
4470 bpstat_clear (bpstat *bsp)
4471 {
4472   bpstat p;
4473   bpstat q;
4474
4475   if (bsp == 0)
4476     return;
4477   p = *bsp;
4478   while (p != NULL)
4479     {
4480       q = p->next;
4481       bpstat_free (p);
4482       p = q;
4483     }
4484   *bsp = NULL;
4485 }
4486
4487 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4488    is part of the bpstat is copied as well.  */
4489
4490 bpstat
4491 bpstat_copy (bpstat bs)
4492 {
4493   bpstat p = NULL;
4494   bpstat tmp;
4495   bpstat retval = NULL;
4496
4497   if (bs == NULL)
4498     return bs;
4499
4500   for (; bs != NULL; bs = bs->next)
4501     {
4502       tmp = (bpstat) xmalloc (sizeof (*tmp));
4503       memcpy (tmp, bs, sizeof (*tmp));
4504       incref_counted_command_line (tmp->commands);
4505       incref_bp_location (tmp->bp_location_at);
4506       if (bs->old_val != NULL)
4507         {
4508           tmp->old_val = value_copy (bs->old_val);
4509           release_value (tmp->old_val);
4510         }
4511
4512       if (p == NULL)
4513         /* This is the first thing in the chain.  */
4514         retval = tmp;
4515       else
4516         p->next = tmp;
4517       p = tmp;
4518     }
4519   p->next = NULL;
4520   return retval;
4521 }
4522
4523 /* Find the bpstat associated with this breakpoint.  */
4524
4525 bpstat
4526 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4527 {
4528   if (bsp == NULL)
4529     return NULL;
4530
4531   for (; bsp != NULL; bsp = bsp->next)
4532     {
4533       if (bsp->breakpoint_at == breakpoint)
4534         return bsp;
4535     }
4536   return NULL;
4537 }
4538
4539 /* See breakpoint.h.  */
4540
4541 int
4542 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4543 {
4544   for (; bsp != NULL; bsp = bsp->next)
4545     {
4546       if (bsp->breakpoint_at == NULL)
4547         {
4548           /* A moribund location can never explain a signal other than
4549              GDB_SIGNAL_TRAP.  */
4550           if (sig == GDB_SIGNAL_TRAP)
4551             return 1;
4552         }
4553       else
4554         {
4555           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4556                                                         sig))
4557             return 1;
4558         }
4559     }
4560
4561   return 0;
4562 }
4563
4564 /* Put in *NUM the breakpoint number of the first breakpoint we are
4565    stopped at.  *BSP upon return is a bpstat which points to the
4566    remaining breakpoints stopped at (but which is not guaranteed to be
4567    good for anything but further calls to bpstat_num).
4568
4569    Return 0 if passed a bpstat which does not indicate any breakpoints.
4570    Return -1 if stopped at a breakpoint that has been deleted since
4571    we set it.
4572    Return 1 otherwise.  */
4573
4574 int
4575 bpstat_num (bpstat *bsp, int *num)
4576 {
4577   struct breakpoint *b;
4578
4579   if ((*bsp) == NULL)
4580     return 0;                   /* No more breakpoint values */
4581
4582   /* We assume we'll never have several bpstats that correspond to a
4583      single breakpoint -- otherwise, this function might return the
4584      same number more than once and this will look ugly.  */
4585   b = (*bsp)->breakpoint_at;
4586   *bsp = (*bsp)->next;
4587   if (b == NULL)
4588     return -1;                  /* breakpoint that's been deleted since */
4589
4590   *num = b->number;             /* We have its number */
4591   return 1;
4592 }
4593
4594 /* See breakpoint.h.  */
4595
4596 void
4597 bpstat_clear_actions (void)
4598 {
4599   struct thread_info *tp;
4600   bpstat bs;
4601
4602   if (ptid_equal (inferior_ptid, null_ptid))
4603     return;
4604
4605   tp = find_thread_ptid (inferior_ptid);
4606   if (tp == NULL)
4607     return;
4608
4609   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4610     {
4611       decref_counted_command_line (&bs->commands);
4612
4613       if (bs->old_val != NULL)
4614         {
4615           value_free (bs->old_val);
4616           bs->old_val = NULL;
4617         }
4618     }
4619 }
4620
4621 /* Called when a command is about to proceed the inferior.  */
4622
4623 static void
4624 breakpoint_about_to_proceed (void)
4625 {
4626   if (!ptid_equal (inferior_ptid, null_ptid))
4627     {
4628       struct thread_info *tp = inferior_thread ();
4629
4630       /* Allow inferior function calls in breakpoint commands to not
4631          interrupt the command list.  When the call finishes
4632          successfully, the inferior will be standing at the same
4633          breakpoint as if nothing happened.  */
4634       if (tp->control.in_infcall)
4635         return;
4636     }
4637
4638   breakpoint_proceeded = 1;
4639 }
4640
4641 /* Stub for cleaning up our state if we error-out of a breakpoint
4642    command.  */
4643 static void
4644 cleanup_executing_breakpoints (void *ignore)
4645 {
4646   executing_breakpoint_commands = 0;
4647 }
4648
4649 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4650    or its equivalent.  */
4651
4652 static int
4653 command_line_is_silent (struct command_line *cmd)
4654 {
4655   return cmd && (strcmp ("silent", cmd->line) == 0);
4656 }
4657
4658 /* Execute all the commands associated with all the breakpoints at
4659    this location.  Any of these commands could cause the process to
4660    proceed beyond this point, etc.  We look out for such changes by
4661    checking the global "breakpoint_proceeded" after each command.
4662
4663    Returns true if a breakpoint command resumed the inferior.  In that
4664    case, it is the caller's responsibility to recall it again with the
4665    bpstat of the current thread.  */
4666
4667 static int
4668 bpstat_do_actions_1 (bpstat *bsp)
4669 {
4670   bpstat bs;
4671   struct cleanup *old_chain;
4672   int again = 0;
4673
4674   /* Avoid endless recursion if a `source' command is contained
4675      in bs->commands.  */
4676   if (executing_breakpoint_commands)
4677     return 0;
4678
4679   executing_breakpoint_commands = 1;
4680   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4681
4682   prevent_dont_repeat ();
4683
4684   /* This pointer will iterate over the list of bpstat's.  */
4685   bs = *bsp;
4686
4687   breakpoint_proceeded = 0;
4688   for (; bs != NULL; bs = bs->next)
4689     {
4690       struct counted_command_line *ccmd;
4691       struct command_line *cmd;
4692       struct cleanup *this_cmd_tree_chain;
4693
4694       /* Take ownership of the BSP's command tree, if it has one.
4695
4696          The command tree could legitimately contain commands like
4697          'step' and 'next', which call clear_proceed_status, which
4698          frees stop_bpstat's command tree.  To make sure this doesn't
4699          free the tree we're executing out from under us, we need to
4700          take ownership of the tree ourselves.  Since a given bpstat's
4701          commands are only executed once, we don't need to copy it; we
4702          can clear the pointer in the bpstat, and make sure we free
4703          the tree when we're done.  */
4704       ccmd = bs->commands;
4705       bs->commands = NULL;
4706       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4707       cmd = ccmd ? ccmd->commands : NULL;
4708       if (command_line_is_silent (cmd))
4709         {
4710           /* The action has been already done by bpstat_stop_status.  */
4711           cmd = cmd->next;
4712         }
4713
4714       while (cmd != NULL)
4715         {
4716           execute_control_command (cmd);
4717
4718           if (breakpoint_proceeded)
4719             break;
4720           else
4721             cmd = cmd->next;
4722         }
4723
4724       /* We can free this command tree now.  */
4725       do_cleanups (this_cmd_tree_chain);
4726
4727       if (breakpoint_proceeded)
4728         {
4729           if (interpreter_async)
4730             /* If we are in async mode, then the target might be still
4731                running, not stopped at any breakpoint, so nothing for
4732                us to do here -- just return to the event loop.  */
4733             ;
4734           else
4735             /* In sync mode, when execute_control_command returns
4736                we're already standing on the next breakpoint.
4737                Breakpoint commands for that stop were not run, since
4738                execute_command does not run breakpoint commands --
4739                only command_line_handler does, but that one is not
4740                involved in execution of breakpoint commands.  So, we
4741                can now execute breakpoint commands.  It should be
4742                noted that making execute_command do bpstat actions is
4743                not an option -- in this case we'll have recursive
4744                invocation of bpstat for each breakpoint with a
4745                command, and can easily blow up GDB stack.  Instead, we
4746                return true, which will trigger the caller to recall us
4747                with the new stop_bpstat.  */
4748             again = 1;
4749           break;
4750         }
4751     }
4752   do_cleanups (old_chain);
4753   return again;
4754 }
4755
4756 void
4757 bpstat_do_actions (void)
4758 {
4759   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4760
4761   /* Do any commands attached to breakpoint we are stopped at.  */
4762   while (!ptid_equal (inferior_ptid, null_ptid)
4763          && target_has_execution
4764          && !is_exited (inferior_ptid)
4765          && !is_executing (inferior_ptid))
4766     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4767        and only return when it is stopped at the next breakpoint, we
4768        keep doing breakpoint actions until it returns false to
4769        indicate the inferior was not resumed.  */
4770     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4771       break;
4772
4773   discard_cleanups (cleanup_if_error);
4774 }
4775
4776 /* Print out the (old or new) value associated with a watchpoint.  */
4777
4778 static void
4779 watchpoint_value_print (struct value *val, struct ui_file *stream)
4780 {
4781   if (val == NULL)
4782     fprintf_unfiltered (stream, _("<unreadable>"));
4783   else
4784     {
4785       struct value_print_options opts;
4786       get_user_print_options (&opts);
4787       value_print (val, stream, &opts);
4788     }
4789 }
4790
4791 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4792    debugging multiple threads.  */
4793
4794 void
4795 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4796 {
4797   if (ui_out_is_mi_like_p (uiout))
4798     return;
4799
4800   ui_out_text (uiout, "\n");
4801
4802   if (show_thread_that_caused_stop ())
4803     {
4804       const char *name;
4805       struct thread_info *thr = inferior_thread ();
4806
4807       ui_out_text (uiout, "Thread ");
4808       ui_out_field_fmt (uiout, "thread-id", "%s", print_thread_id (thr));
4809
4810       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4811       if (name != NULL)
4812         {
4813           ui_out_text (uiout, " \"");
4814           ui_out_field_fmt (uiout, "name", "%s", name);
4815           ui_out_text (uiout, "\"");
4816         }
4817
4818       ui_out_text (uiout, " hit ");
4819     }
4820 }
4821
4822 /* Generic routine for printing messages indicating why we
4823    stopped.  The behavior of this function depends on the value
4824    'print_it' in the bpstat structure.  Under some circumstances we
4825    may decide not to print anything here and delegate the task to
4826    normal_stop().  */
4827
4828 static enum print_stop_action
4829 print_bp_stop_message (bpstat bs)
4830 {
4831   switch (bs->print_it)
4832     {
4833     case print_it_noop:
4834       /* Nothing should be printed for this bpstat entry.  */
4835       return PRINT_UNKNOWN;
4836       break;
4837
4838     case print_it_done:
4839       /* We still want to print the frame, but we already printed the
4840          relevant messages.  */
4841       return PRINT_SRC_AND_LOC;
4842       break;
4843
4844     case print_it_normal:
4845       {
4846         struct breakpoint *b = bs->breakpoint_at;
4847
4848         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4849            which has since been deleted.  */
4850         if (b == NULL)
4851           return PRINT_UNKNOWN;
4852
4853         /* Normal case.  Call the breakpoint's print_it method.  */
4854         return b->ops->print_it (bs);
4855       }
4856       break;
4857
4858     default:
4859       internal_error (__FILE__, __LINE__,
4860                       _("print_bp_stop_message: unrecognized enum value"));
4861       break;
4862     }
4863 }
4864
4865 /* A helper function that prints a shared library stopped event.  */
4866
4867 static void
4868 print_solib_event (int is_catchpoint)
4869 {
4870   int any_deleted
4871     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4872   int any_added
4873     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4874
4875   if (!is_catchpoint)
4876     {
4877       if (any_added || any_deleted)
4878         ui_out_text (current_uiout,
4879                      _("Stopped due to shared library event:\n"));
4880       else
4881         ui_out_text (current_uiout,
4882                      _("Stopped due to shared library event (no "
4883                        "libraries added or removed)\n"));
4884     }
4885
4886   if (ui_out_is_mi_like_p (current_uiout))
4887     ui_out_field_string (current_uiout, "reason",
4888                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4889
4890   if (any_deleted)
4891     {
4892       struct cleanup *cleanup;
4893       char *name;
4894       int ix;
4895
4896       ui_out_text (current_uiout, _("  Inferior unloaded "));
4897       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4898                                                     "removed");
4899       for (ix = 0;
4900            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4901                         ix, name);
4902            ++ix)
4903         {
4904           if (ix > 0)
4905             ui_out_text (current_uiout, "    ");
4906           ui_out_field_string (current_uiout, "library", name);
4907           ui_out_text (current_uiout, "\n");
4908         }
4909
4910       do_cleanups (cleanup);
4911     }
4912
4913   if (any_added)
4914     {
4915       struct so_list *iter;
4916       int ix;
4917       struct cleanup *cleanup;
4918
4919       ui_out_text (current_uiout, _("  Inferior loaded "));
4920       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4921                                                     "added");
4922       for (ix = 0;
4923            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4924                         ix, iter);
4925            ++ix)
4926         {
4927           if (ix > 0)
4928             ui_out_text (current_uiout, "    ");
4929           ui_out_field_string (current_uiout, "library", iter->so_name);
4930           ui_out_text (current_uiout, "\n");
4931         }
4932
4933       do_cleanups (cleanup);
4934     }
4935 }
4936
4937 /* Print a message indicating what happened.  This is called from
4938    normal_stop().  The input to this routine is the head of the bpstat
4939    list - a list of the eventpoints that caused this stop.  KIND is
4940    the target_waitkind for the stopping event.  This
4941    routine calls the generic print routine for printing a message
4942    about reasons for stopping.  This will print (for example) the
4943    "Breakpoint n," part of the output.  The return value of this
4944    routine is one of:
4945
4946    PRINT_UNKNOWN: Means we printed nothing.
4947    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4948    code to print the location.  An example is 
4949    "Breakpoint 1, " which should be followed by
4950    the location.
4951    PRINT_SRC_ONLY: Means we printed something, but there is no need
4952    to also print the location part of the message.
4953    An example is the catch/throw messages, which
4954    don't require a location appended to the end.
4955    PRINT_NOTHING: We have done some printing and we don't need any 
4956    further info to be printed.  */
4957
4958 enum print_stop_action
4959 bpstat_print (bpstat bs, int kind)
4960 {
4961   enum print_stop_action val;
4962
4963   /* Maybe another breakpoint in the chain caused us to stop.
4964      (Currently all watchpoints go on the bpstat whether hit or not.
4965      That probably could (should) be changed, provided care is taken
4966      with respect to bpstat_explains_signal).  */
4967   for (; bs; bs = bs->next)
4968     {
4969       val = print_bp_stop_message (bs);
4970       if (val == PRINT_SRC_ONLY 
4971           || val == PRINT_SRC_AND_LOC 
4972           || val == PRINT_NOTHING)
4973         return val;
4974     }
4975
4976   /* If we had hit a shared library event breakpoint,
4977      print_bp_stop_message would print out this message.  If we hit an
4978      OS-level shared library event, do the same thing.  */
4979   if (kind == TARGET_WAITKIND_LOADED)
4980     {
4981       print_solib_event (0);
4982       return PRINT_NOTHING;
4983     }
4984
4985   /* We reached the end of the chain, or we got a null BS to start
4986      with and nothing was printed.  */
4987   return PRINT_UNKNOWN;
4988 }
4989
4990 /* Evaluate the expression EXP and return 1 if value is zero.
4991    This returns the inverse of the condition because it is called
4992    from catch_errors which returns 0 if an exception happened, and if an
4993    exception happens we want execution to stop.
4994    The argument is a "struct expression *" that has been cast to a
4995    "void *" to make it pass through catch_errors.  */
4996
4997 static int
4998 breakpoint_cond_eval (void *exp)
4999 {
5000   struct value *mark = value_mark ();
5001   int i = !value_true (evaluate_expression ((struct expression *) exp));
5002
5003   value_free_to_mark (mark);
5004   return i;
5005 }
5006
5007 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
5008
5009 static bpstat
5010 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
5011 {
5012   bpstat bs;
5013
5014   bs = (bpstat) xmalloc (sizeof (*bs));
5015   bs->next = NULL;
5016   **bs_link_pointer = bs;
5017   *bs_link_pointer = &bs->next;
5018   bs->breakpoint_at = bl->owner;
5019   bs->bp_location_at = bl;
5020   incref_bp_location (bl);
5021   /* If the condition is false, etc., don't do the commands.  */
5022   bs->commands = NULL;
5023   bs->old_val = NULL;
5024   bs->print_it = print_it_normal;
5025   return bs;
5026 }
5027 \f
5028 /* The target has stopped with waitstatus WS.  Check if any hardware
5029    watchpoints have triggered, according to the target.  */
5030
5031 int
5032 watchpoints_triggered (struct target_waitstatus *ws)
5033 {
5034   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
5035   CORE_ADDR addr;
5036   struct breakpoint *b;
5037
5038   if (!stopped_by_watchpoint)
5039     {
5040       /* We were not stopped by a watchpoint.  Mark all watchpoints
5041          as not triggered.  */
5042       ALL_BREAKPOINTS (b)
5043         if (is_hardware_watchpoint (b))
5044           {
5045             struct watchpoint *w = (struct watchpoint *) b;
5046
5047             w->watchpoint_triggered = watch_triggered_no;
5048           }
5049
5050       return 0;
5051     }
5052
5053   if (!target_stopped_data_address (&current_target, &addr))
5054     {
5055       /* We were stopped by a watchpoint, but we don't know where.
5056          Mark all watchpoints as unknown.  */
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_unknown;
5063           }
5064
5065       return 1;
5066     }
5067
5068   /* The target could report the data address.  Mark watchpoints
5069      affected by this data address as triggered, and all others as not
5070      triggered.  */
5071
5072   ALL_BREAKPOINTS (b)
5073     if (is_hardware_watchpoint (b))
5074       {
5075         struct watchpoint *w = (struct watchpoint *) b;
5076         struct bp_location *loc;
5077
5078         w->watchpoint_triggered = watch_triggered_no;
5079         for (loc = b->loc; loc; loc = loc->next)
5080           {
5081             if (is_masked_watchpoint (b))
5082               {
5083                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5084                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5085
5086                 if (newaddr == start)
5087                   {
5088                     w->watchpoint_triggered = watch_triggered_yes;
5089                     break;
5090                   }
5091               }
5092             /* Exact match not required.  Within range is sufficient.  */
5093             else if (target_watchpoint_addr_within_range (&current_target,
5094                                                          addr, loc->address,
5095                                                          loc->length))
5096               {
5097                 w->watchpoint_triggered = watch_triggered_yes;
5098                 break;
5099               }
5100           }
5101       }
5102
5103   return 1;
5104 }
5105
5106 /* Possible return values for watchpoint_check (this can't be an enum
5107    because of check_errors).  */
5108 /* The watchpoint has been deleted.  */
5109 #define WP_DELETED 1
5110 /* The value has changed.  */
5111 #define WP_VALUE_CHANGED 2
5112 /* The value has not changed.  */
5113 #define WP_VALUE_NOT_CHANGED 3
5114 /* Ignore this watchpoint, no matter if the value changed or not.  */
5115 #define WP_IGNORE 4
5116
5117 #define BP_TEMPFLAG 1
5118 #define BP_HARDWAREFLAG 2
5119
5120 /* Evaluate watchpoint condition expression and check if its value
5121    changed.
5122
5123    P should be a pointer to struct bpstat, but is defined as a void *
5124    in order for this function to be usable with catch_errors.  */
5125
5126 static int
5127 watchpoint_check (void *p)
5128 {
5129   bpstat bs = (bpstat) p;
5130   struct watchpoint *b;
5131   struct frame_info *fr;
5132   int within_current_scope;
5133
5134   /* BS is built from an existing struct breakpoint.  */
5135   gdb_assert (bs->breakpoint_at != NULL);
5136   b = (struct watchpoint *) bs->breakpoint_at;
5137
5138   /* If this is a local watchpoint, we only want to check if the
5139      watchpoint frame is in scope if the current thread is the thread
5140      that was used to create the watchpoint.  */
5141   if (!watchpoint_in_thread_scope (b))
5142     return WP_IGNORE;
5143
5144   if (b->exp_valid_block == NULL)
5145     within_current_scope = 1;
5146   else
5147     {
5148       struct frame_info *frame = get_current_frame ();
5149       struct gdbarch *frame_arch = get_frame_arch (frame);
5150       CORE_ADDR frame_pc = get_frame_pc (frame);
5151
5152       /* stack_frame_destroyed_p() returns a non-zero value if we're
5153          still in the function but the stack frame has already been
5154          invalidated.  Since we can't rely on the values of local
5155          variables after the stack has been destroyed, we are treating
5156          the watchpoint in that state as `not changed' without further
5157          checking.  Don't mark watchpoints as changed if the current
5158          frame is in an epilogue - even if they are in some other
5159          frame, our view of the stack is likely to be wrong and
5160          frame_find_by_id could error out.  */
5161       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5162         return WP_IGNORE;
5163
5164       fr = frame_find_by_id (b->watchpoint_frame);
5165       within_current_scope = (fr != NULL);
5166
5167       /* If we've gotten confused in the unwinder, we might have
5168          returned a frame that can't describe this variable.  */
5169       if (within_current_scope)
5170         {
5171           struct symbol *function;
5172
5173           function = get_frame_function (fr);
5174           if (function == NULL
5175               || !contained_in (b->exp_valid_block,
5176                                 SYMBOL_BLOCK_VALUE (function)))
5177             within_current_scope = 0;
5178         }
5179
5180       if (within_current_scope)
5181         /* If we end up stopping, the current frame will get selected
5182            in normal_stop.  So this call to select_frame won't affect
5183            the user.  */
5184         select_frame (fr);
5185     }
5186
5187   if (within_current_scope)
5188     {
5189       /* We use value_{,free_to_}mark because it could be a *long*
5190          time before we return to the command level and call
5191          free_all_values.  We can't call free_all_values because we
5192          might be in the middle of evaluating a function call.  */
5193
5194       int pc = 0;
5195       struct value *mark;
5196       struct value *new_val;
5197
5198       if (is_masked_watchpoint (&b->base))
5199         /* Since we don't know the exact trigger address (from
5200            stopped_data_address), just tell the user we've triggered
5201            a mask watchpoint.  */
5202         return WP_VALUE_CHANGED;
5203
5204       mark = value_mark ();
5205       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5206
5207       if (b->val_bitsize != 0)
5208         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5209
5210       /* We use value_equal_contents instead of value_equal because
5211          the latter coerces an array to a pointer, thus comparing just
5212          the address of the array instead of its contents.  This is
5213          not what we want.  */
5214       if ((b->val != NULL) != (new_val != NULL)
5215           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5216         {
5217           if (new_val != NULL)
5218             {
5219               release_value (new_val);
5220               value_free_to_mark (mark);
5221             }
5222           bs->old_val = b->val;
5223           b->val = new_val;
5224           b->val_valid = 1;
5225           return WP_VALUE_CHANGED;
5226         }
5227       else
5228         {
5229           /* Nothing changed.  */
5230           value_free_to_mark (mark);
5231           return WP_VALUE_NOT_CHANGED;
5232         }
5233     }
5234   else
5235     {
5236       struct ui_out *uiout = current_uiout;
5237
5238       /* This seems like the only logical thing to do because
5239          if we temporarily ignored the watchpoint, then when
5240          we reenter the block in which it is valid it contains
5241          garbage (in the case of a function, it may have two
5242          garbage values, one before and one after the prologue).
5243          So we can't even detect the first assignment to it and
5244          watch after that (since the garbage may or may not equal
5245          the first value assigned).  */
5246       /* We print all the stop information in
5247          breakpoint_ops->print_it, but in this case, by the time we
5248          call breakpoint_ops->print_it this bp will be deleted
5249          already.  So we have no choice but print the information
5250          here.  */
5251       if (ui_out_is_mi_like_p (uiout))
5252         ui_out_field_string
5253           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5254       ui_out_text (uiout, "\nWatchpoint ");
5255       ui_out_field_int (uiout, "wpnum", b->base.number);
5256       ui_out_text (uiout,
5257                    " deleted because the program has left the block in\n\
5258 which its expression is valid.\n");     
5259
5260       /* Make sure the watchpoint's commands aren't executed.  */
5261       decref_counted_command_line (&b->base.commands);
5262       watchpoint_del_at_next_stop (b);
5263
5264       return WP_DELETED;
5265     }
5266 }
5267
5268 /* Return true if it looks like target has stopped due to hitting
5269    breakpoint location BL.  This function does not check if we should
5270    stop, only if BL explains the stop.  */
5271
5272 static int
5273 bpstat_check_location (const struct bp_location *bl,
5274                        struct address_space *aspace, CORE_ADDR bp_addr,
5275                        const struct target_waitstatus *ws)
5276 {
5277   struct breakpoint *b = bl->owner;
5278
5279   /* BL is from an existing breakpoint.  */
5280   gdb_assert (b != NULL);
5281
5282   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5283 }
5284
5285 /* Determine if the watched values have actually changed, and we
5286    should stop.  If not, set BS->stop to 0.  */
5287
5288 static void
5289 bpstat_check_watchpoint (bpstat bs)
5290 {
5291   const struct bp_location *bl;
5292   struct watchpoint *b;
5293
5294   /* BS is built for existing struct breakpoint.  */
5295   bl = bs->bp_location_at;
5296   gdb_assert (bl != NULL);
5297   b = (struct watchpoint *) bs->breakpoint_at;
5298   gdb_assert (b != NULL);
5299
5300     {
5301       int must_check_value = 0;
5302       
5303       if (b->base.type == bp_watchpoint)
5304         /* For a software watchpoint, we must always check the
5305            watched value.  */
5306         must_check_value = 1;
5307       else if (b->watchpoint_triggered == watch_triggered_yes)
5308         /* We have a hardware watchpoint (read, write, or access)
5309            and the target earlier reported an address watched by
5310            this watchpoint.  */
5311         must_check_value = 1;
5312       else if (b->watchpoint_triggered == watch_triggered_unknown
5313                && b->base.type == bp_hardware_watchpoint)
5314         /* We were stopped by a hardware watchpoint, but the target could
5315            not report the data address.  We must check the watchpoint's
5316            value.  Access and read watchpoints are out of luck; without
5317            a data address, we can't figure it out.  */
5318         must_check_value = 1;
5319
5320       if (must_check_value)
5321         {
5322           char *message
5323             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5324                           b->base.number);
5325           struct cleanup *cleanups = make_cleanup (xfree, message);
5326           int e = catch_errors (watchpoint_check, bs, message,
5327                                 RETURN_MASK_ALL);
5328           do_cleanups (cleanups);
5329           switch (e)
5330             {
5331             case WP_DELETED:
5332               /* We've already printed what needs to be printed.  */
5333               bs->print_it = print_it_done;
5334               /* Stop.  */
5335               break;
5336             case WP_IGNORE:
5337               bs->print_it = print_it_noop;
5338               bs->stop = 0;
5339               break;
5340             case WP_VALUE_CHANGED:
5341               if (b->base.type == bp_read_watchpoint)
5342                 {
5343                   /* There are two cases to consider here:
5344
5345                      1. We're watching the triggered memory for reads.
5346                      In that case, trust the target, and always report
5347                      the watchpoint hit to the user.  Even though
5348                      reads don't cause value changes, the value may
5349                      have changed since the last time it was read, and
5350                      since we're not trapping writes, we will not see
5351                      those, and as such we should ignore our notion of
5352                      old value.
5353
5354                      2. We're watching the triggered memory for both
5355                      reads and writes.  There are two ways this may
5356                      happen:
5357
5358                      2.1. This is a target that can't break on data
5359                      reads only, but can break on accesses (reads or
5360                      writes), such as e.g., x86.  We detect this case
5361                      at the time we try to insert read watchpoints.
5362
5363                      2.2. Otherwise, the target supports read
5364                      watchpoints, but, the user set an access or write
5365                      watchpoint watching the same memory as this read
5366                      watchpoint.
5367
5368                      If we're watching memory writes as well as reads,
5369                      ignore watchpoint hits when we find that the
5370                      value hasn't changed, as reads don't cause
5371                      changes.  This still gives false positives when
5372                      the program writes the same value to memory as
5373                      what there was already in memory (we will confuse
5374                      it for a read), but it's much better than
5375                      nothing.  */
5376
5377                   int other_write_watchpoint = 0;
5378
5379                   if (bl->watchpoint_type == hw_read)
5380                     {
5381                       struct breakpoint *other_b;
5382
5383                       ALL_BREAKPOINTS (other_b)
5384                         if (other_b->type == bp_hardware_watchpoint
5385                             || other_b->type == bp_access_watchpoint)
5386                           {
5387                             struct watchpoint *other_w =
5388                               (struct watchpoint *) other_b;
5389
5390                             if (other_w->watchpoint_triggered
5391                                 == watch_triggered_yes)
5392                               {
5393                                 other_write_watchpoint = 1;
5394                                 break;
5395                               }
5396                           }
5397                     }
5398
5399                   if (other_write_watchpoint
5400                       || bl->watchpoint_type == hw_access)
5401                     {
5402                       /* We're watching the same memory for writes,
5403                          and the value changed since the last time we
5404                          updated it, so this trap must be for a write.
5405                          Ignore it.  */
5406                       bs->print_it = print_it_noop;
5407                       bs->stop = 0;
5408                     }
5409                 }
5410               break;
5411             case WP_VALUE_NOT_CHANGED:
5412               if (b->base.type == bp_hardware_watchpoint
5413                   || b->base.type == bp_watchpoint)
5414                 {
5415                   /* Don't stop: write watchpoints shouldn't fire if
5416                      the value hasn't changed.  */
5417                   bs->print_it = print_it_noop;
5418                   bs->stop = 0;
5419                 }
5420               /* Stop.  */
5421               break;
5422             default:
5423               /* Can't happen.  */
5424             case 0:
5425               /* Error from catch_errors.  */
5426               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5427               watchpoint_del_at_next_stop (b);
5428               /* We've already printed what needs to be printed.  */
5429               bs->print_it = print_it_done;
5430               break;
5431             }
5432         }
5433       else      /* must_check_value == 0 */
5434         {
5435           /* This is a case where some watchpoint(s) triggered, but
5436              not at the address of this watchpoint, or else no
5437              watchpoint triggered after all.  So don't print
5438              anything for this watchpoint.  */
5439           bs->print_it = print_it_noop;
5440           bs->stop = 0;
5441         }
5442     }
5443 }
5444
5445 /* For breakpoints that are currently marked as telling gdb to stop,
5446    check conditions (condition proper, frame, thread and ignore count)
5447    of breakpoint referred to by BS.  If we should not stop for this
5448    breakpoint, set BS->stop to 0.  */
5449
5450 static void
5451 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5452 {
5453   const struct bp_location *bl;
5454   struct breakpoint *b;
5455   int value_is_zero = 0;
5456   struct expression *cond;
5457
5458   gdb_assert (bs->stop);
5459
5460   /* BS is built for existing struct breakpoint.  */
5461   bl = bs->bp_location_at;
5462   gdb_assert (bl != NULL);
5463   b = bs->breakpoint_at;
5464   gdb_assert (b != NULL);
5465
5466   /* Even if the target evaluated the condition on its end and notified GDB, we
5467      need to do so again since GDB does not know if we stopped due to a
5468      breakpoint or a single step breakpoint.  */
5469
5470   if (frame_id_p (b->frame_id)
5471       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5472     {
5473       bs->stop = 0;
5474       return;
5475     }
5476
5477   /* If this is a thread/task-specific breakpoint, don't waste cpu
5478      evaluating the condition if this isn't the specified
5479      thread/task.  */
5480   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5481       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5482
5483     {
5484       bs->stop = 0;
5485       return;
5486     }
5487
5488   /* Evaluate extension language breakpoints that have a "stop" method
5489      implemented.  */
5490   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5491
5492   if (is_watchpoint (b))
5493     {
5494       struct watchpoint *w = (struct watchpoint *) b;
5495
5496       cond = w->cond_exp;
5497     }
5498   else
5499     cond = bl->cond;
5500
5501   if (cond && b->disposition != disp_del_at_next_stop)
5502     {
5503       int within_current_scope = 1;
5504       struct watchpoint * w;
5505
5506       /* We use value_mark and value_free_to_mark because it could
5507          be a long time before we return to the command level and
5508          call free_all_values.  We can't call free_all_values
5509          because we might be in the middle of evaluating a
5510          function call.  */
5511       struct value *mark = value_mark ();
5512
5513       if (is_watchpoint (b))
5514         w = (struct watchpoint *) b;
5515       else
5516         w = NULL;
5517
5518       /* Need to select the frame, with all that implies so that
5519          the conditions will have the right context.  Because we
5520          use the frame, we will not see an inlined function's
5521          variables when we arrive at a breakpoint at the start
5522          of the inlined function; the current frame will be the
5523          call site.  */
5524       if (w == NULL || w->cond_exp_valid_block == NULL)
5525         select_frame (get_current_frame ());
5526       else
5527         {
5528           struct frame_info *frame;
5529
5530           /* For local watchpoint expressions, which particular
5531              instance of a local is being watched matters, so we
5532              keep track of the frame to evaluate the expression
5533              in.  To evaluate the condition however, it doesn't
5534              really matter which instantiation of the function
5535              where the condition makes sense triggers the
5536              watchpoint.  This allows an expression like "watch
5537              global if q > 10" set in `func', catch writes to
5538              global on all threads that call `func', or catch
5539              writes on all recursive calls of `func' by a single
5540              thread.  We simply always evaluate the condition in
5541              the innermost frame that's executing where it makes
5542              sense to evaluate the condition.  It seems
5543              intuitive.  */
5544           frame = block_innermost_frame (w->cond_exp_valid_block);
5545           if (frame != NULL)
5546             select_frame (frame);
5547           else
5548             within_current_scope = 0;
5549         }
5550       if (within_current_scope)
5551         value_is_zero
5552           = catch_errors (breakpoint_cond_eval, cond,
5553                           "Error in testing breakpoint condition:\n",
5554                           RETURN_MASK_ALL);
5555       else
5556         {
5557           warning (_("Watchpoint condition cannot be tested "
5558                      "in the current scope"));
5559           /* If we failed to set the right context for this
5560              watchpoint, unconditionally report it.  */
5561           value_is_zero = 0;
5562         }
5563       /* FIXME-someday, should give breakpoint #.  */
5564       value_free_to_mark (mark);
5565     }
5566
5567   if (cond && value_is_zero)
5568     {
5569       bs->stop = 0;
5570     }
5571   else if (b->ignore_count > 0)
5572     {
5573       b->ignore_count--;
5574       bs->stop = 0;
5575       /* Increase the hit count even though we don't stop.  */
5576       ++(b->hit_count);
5577       observer_notify_breakpoint_modified (b);
5578     }   
5579 }
5580
5581 /* Returns true if we need to track moribund locations of LOC's type
5582    on the current target.  */
5583
5584 static int
5585 need_moribund_for_location_type (struct bp_location *loc)
5586 {
5587   return ((loc->loc_type == bp_loc_software_breakpoint
5588            && !target_supports_stopped_by_sw_breakpoint ())
5589           || (loc->loc_type == bp_loc_hardware_breakpoint
5590               && !target_supports_stopped_by_hw_breakpoint ()));
5591 }
5592
5593
5594 /* Get a bpstat associated with having just stopped at address
5595    BP_ADDR in thread PTID.
5596
5597    Determine whether we stopped at a breakpoint, etc, or whether we
5598    don't understand this stop.  Result is a chain of bpstat's such
5599    that:
5600
5601    if we don't understand the stop, the result is a null pointer.
5602
5603    if we understand why we stopped, the result is not null.
5604
5605    Each element of the chain refers to a particular breakpoint or
5606    watchpoint at which we have stopped.  (We may have stopped for
5607    several reasons concurrently.)
5608
5609    Each element of the chain has valid next, breakpoint_at,
5610    commands, FIXME??? fields.  */
5611
5612 bpstat
5613 bpstat_stop_status (struct address_space *aspace,
5614                     CORE_ADDR bp_addr, ptid_t ptid,
5615                     const struct target_waitstatus *ws)
5616 {
5617   struct breakpoint *b = NULL;
5618   struct bp_location *bl;
5619   struct bp_location *loc;
5620   /* First item of allocated bpstat's.  */
5621   bpstat bs_head = NULL, *bs_link = &bs_head;
5622   /* Pointer to the last thing in the chain currently.  */
5623   bpstat bs;
5624   int ix;
5625   int need_remove_insert;
5626   int removed_any;
5627
5628   /* First, build the bpstat chain with locations that explain a
5629      target stop, while being careful to not set the target running,
5630      as that may invalidate locations (in particular watchpoint
5631      locations are recreated).  Resuming will happen here with
5632      breakpoint conditions or watchpoint expressions that include
5633      inferior function calls.  */
5634
5635   ALL_BREAKPOINTS (b)
5636     {
5637       if (!breakpoint_enabled (b))
5638         continue;
5639
5640       for (bl = b->loc; bl != NULL; bl = bl->next)
5641         {
5642           /* For hardware watchpoints, we look only at the first
5643              location.  The watchpoint_check function will work on the
5644              entire expression, not the individual locations.  For
5645              read watchpoints, the watchpoints_triggered function has
5646              checked all locations already.  */
5647           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5648             break;
5649
5650           if (!bl->enabled || bl->shlib_disabled)
5651             continue;
5652
5653           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5654             continue;
5655
5656           /* Come here if it's a watchpoint, or if the break address
5657              matches.  */
5658
5659           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5660                                                    explain stop.  */
5661
5662           /* Assume we stop.  Should we find a watchpoint that is not
5663              actually triggered, or if the condition of the breakpoint
5664              evaluates as false, we'll reset 'stop' to 0.  */
5665           bs->stop = 1;
5666           bs->print = 1;
5667
5668           /* If this is a scope breakpoint, mark the associated
5669              watchpoint as triggered so that we will handle the
5670              out-of-scope event.  We'll get to the watchpoint next
5671              iteration.  */
5672           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5673             {
5674               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5675
5676               w->watchpoint_triggered = watch_triggered_yes;
5677             }
5678         }
5679     }
5680
5681   /* Check if a moribund breakpoint explains the stop.  */
5682   if (!target_supports_stopped_by_sw_breakpoint ()
5683       || !target_supports_stopped_by_hw_breakpoint ())
5684     {
5685       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5686         {
5687           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5688               && need_moribund_for_location_type (loc))
5689             {
5690               bs = bpstat_alloc (loc, &bs_link);
5691               /* For hits of moribund locations, we should just proceed.  */
5692               bs->stop = 0;
5693               bs->print = 0;
5694               bs->print_it = print_it_noop;
5695             }
5696         }
5697     }
5698
5699   /* A bit of special processing for shlib breakpoints.  We need to
5700      process solib loading here, so that the lists of loaded and
5701      unloaded libraries are correct before we handle "catch load" and
5702      "catch unload".  */
5703   for (bs = bs_head; bs != NULL; bs = bs->next)
5704     {
5705       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5706         {
5707           handle_solib_event ();
5708           break;
5709         }
5710     }
5711
5712   /* Now go through the locations that caused the target to stop, and
5713      check whether we're interested in reporting this stop to higher
5714      layers, or whether we should resume the target transparently.  */
5715
5716   removed_any = 0;
5717
5718   for (bs = bs_head; bs != NULL; bs = bs->next)
5719     {
5720       if (!bs->stop)
5721         continue;
5722
5723       b = bs->breakpoint_at;
5724       b->ops->check_status (bs);
5725       if (bs->stop)
5726         {
5727           bpstat_check_breakpoint_conditions (bs, ptid);
5728
5729           if (bs->stop)
5730             {
5731               ++(b->hit_count);
5732               observer_notify_breakpoint_modified (b);
5733
5734               /* We will stop here.  */
5735               if (b->disposition == disp_disable)
5736                 {
5737                   --(b->enable_count);
5738                   if (b->enable_count <= 0)
5739                     b->enable_state = bp_disabled;
5740                   removed_any = 1;
5741                 }
5742               if (b->silent)
5743                 bs->print = 0;
5744               bs->commands = b->commands;
5745               incref_counted_command_line (bs->commands);
5746               if (command_line_is_silent (bs->commands
5747                                           ? bs->commands->commands : NULL))
5748                 bs->print = 0;
5749
5750               b->ops->after_condition_true (bs);
5751             }
5752
5753         }
5754
5755       /* Print nothing for this entry if we don't stop or don't
5756          print.  */
5757       if (!bs->stop || !bs->print)
5758         bs->print_it = print_it_noop;
5759     }
5760
5761   /* If we aren't stopping, the value of some hardware watchpoint may
5762      not have changed, but the intermediate memory locations we are
5763      watching may have.  Don't bother if we're stopping; this will get
5764      done later.  */
5765   need_remove_insert = 0;
5766   if (! bpstat_causes_stop (bs_head))
5767     for (bs = bs_head; bs != NULL; bs = bs->next)
5768       if (!bs->stop
5769           && bs->breakpoint_at
5770           && is_hardware_watchpoint (bs->breakpoint_at))
5771         {
5772           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5773
5774           update_watchpoint (w, 0 /* don't reparse.  */);
5775           need_remove_insert = 1;
5776         }
5777
5778   if (need_remove_insert)
5779     update_global_location_list (UGLL_MAY_INSERT);
5780   else if (removed_any)
5781     update_global_location_list (UGLL_DONT_INSERT);
5782
5783   return bs_head;
5784 }
5785
5786 static void
5787 handle_jit_event (void)
5788 {
5789   struct frame_info *frame;
5790   struct gdbarch *gdbarch;
5791
5792   if (debug_infrun)
5793     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5794
5795   /* Switch terminal for any messages produced by
5796      breakpoint_re_set.  */
5797   target_terminal_ours_for_output ();
5798
5799   frame = get_current_frame ();
5800   gdbarch = get_frame_arch (frame);
5801
5802   jit_event_handler (gdbarch);
5803
5804   target_terminal_inferior ();
5805 }
5806
5807 /* Prepare WHAT final decision for infrun.  */
5808
5809 /* Decide what infrun needs to do with this bpstat.  */
5810
5811 struct bpstat_what
5812 bpstat_what (bpstat bs_head)
5813 {
5814   struct bpstat_what retval;
5815   bpstat bs;
5816
5817   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5818   retval.call_dummy = STOP_NONE;
5819   retval.is_longjmp = 0;
5820
5821   for (bs = bs_head; bs != NULL; bs = bs->next)
5822     {
5823       /* Extract this BS's action.  After processing each BS, we check
5824          if its action overrides all we've seem so far.  */
5825       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5826       enum bptype bptype;
5827
5828       if (bs->breakpoint_at == NULL)
5829         {
5830           /* I suspect this can happen if it was a momentary
5831              breakpoint which has since been deleted.  */
5832           bptype = bp_none;
5833         }
5834       else
5835         bptype = bs->breakpoint_at->type;
5836
5837       switch (bptype)
5838         {
5839         case bp_none:
5840           break;
5841         case bp_breakpoint:
5842         case bp_hardware_breakpoint:
5843         case bp_single_step:
5844         case bp_until:
5845         case bp_finish:
5846         case bp_shlib_event:
5847           if (bs->stop)
5848             {
5849               if (bs->print)
5850                 this_action = BPSTAT_WHAT_STOP_NOISY;
5851               else
5852                 this_action = BPSTAT_WHAT_STOP_SILENT;
5853             }
5854           else
5855             this_action = BPSTAT_WHAT_SINGLE;
5856           break;
5857         case bp_watchpoint:
5858         case bp_hardware_watchpoint:
5859         case bp_read_watchpoint:
5860         case bp_access_watchpoint:
5861           if (bs->stop)
5862             {
5863               if (bs->print)
5864                 this_action = BPSTAT_WHAT_STOP_NOISY;
5865               else
5866                 this_action = BPSTAT_WHAT_STOP_SILENT;
5867             }
5868           else
5869             {
5870               /* There was a watchpoint, but we're not stopping.
5871                  This requires no further action.  */
5872             }
5873           break;
5874         case bp_longjmp:
5875         case bp_longjmp_call_dummy:
5876         case bp_exception:
5877           if (bs->stop)
5878             {
5879               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5880               retval.is_longjmp = bptype != bp_exception;
5881             }
5882           else
5883             this_action = BPSTAT_WHAT_SINGLE;
5884           break;
5885         case bp_longjmp_resume:
5886         case bp_exception_resume:
5887           if (bs->stop)
5888             {
5889               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5890               retval.is_longjmp = bptype == bp_longjmp_resume;
5891             }
5892           else
5893             this_action = BPSTAT_WHAT_SINGLE;
5894           break;
5895         case bp_step_resume:
5896           if (bs->stop)
5897             this_action = BPSTAT_WHAT_STEP_RESUME;
5898           else
5899             {
5900               /* It is for the wrong frame.  */
5901               this_action = BPSTAT_WHAT_SINGLE;
5902             }
5903           break;
5904         case bp_hp_step_resume:
5905           if (bs->stop)
5906             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5907           else
5908             {
5909               /* It is for the wrong frame.  */
5910               this_action = BPSTAT_WHAT_SINGLE;
5911             }
5912           break;
5913         case bp_watchpoint_scope:
5914         case bp_thread_event:
5915         case bp_overlay_event:
5916         case bp_longjmp_master:
5917         case bp_std_terminate_master:
5918         case bp_exception_master:
5919           this_action = BPSTAT_WHAT_SINGLE;
5920           break;
5921         case bp_catchpoint:
5922           if (bs->stop)
5923             {
5924               if (bs->print)
5925                 this_action = BPSTAT_WHAT_STOP_NOISY;
5926               else
5927                 this_action = BPSTAT_WHAT_STOP_SILENT;
5928             }
5929           else
5930             {
5931               /* There was a catchpoint, but we're not stopping.
5932                  This requires no further action.  */
5933             }
5934           break;
5935         case bp_jit_event:
5936           this_action = BPSTAT_WHAT_SINGLE;
5937           break;
5938         case bp_call_dummy:
5939           /* Make sure the action is stop (silent or noisy),
5940              so infrun.c pops the dummy frame.  */
5941           retval.call_dummy = STOP_STACK_DUMMY;
5942           this_action = BPSTAT_WHAT_STOP_SILENT;
5943           break;
5944         case bp_std_terminate:
5945           /* Make sure the action is stop (silent or noisy),
5946              so infrun.c pops the dummy frame.  */
5947           retval.call_dummy = STOP_STD_TERMINATE;
5948           this_action = BPSTAT_WHAT_STOP_SILENT;
5949           break;
5950         case bp_tracepoint:
5951         case bp_fast_tracepoint:
5952         case bp_static_tracepoint:
5953           /* Tracepoint hits should not be reported back to GDB, and
5954              if one got through somehow, it should have been filtered
5955              out already.  */
5956           internal_error (__FILE__, __LINE__,
5957                           _("bpstat_what: tracepoint encountered"));
5958           break;
5959         case bp_gnu_ifunc_resolver:
5960           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5961           this_action = BPSTAT_WHAT_SINGLE;
5962           break;
5963         case bp_gnu_ifunc_resolver_return:
5964           /* The breakpoint will be removed, execution will restart from the
5965              PC of the former breakpoint.  */
5966           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5967           break;
5968
5969         case bp_dprintf:
5970           if (bs->stop)
5971             this_action = BPSTAT_WHAT_STOP_SILENT;
5972           else
5973             this_action = BPSTAT_WHAT_SINGLE;
5974           break;
5975
5976         default:
5977           internal_error (__FILE__, __LINE__,
5978                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5979         }
5980
5981       retval.main_action = max (retval.main_action, this_action);
5982     }
5983
5984   return retval;
5985 }
5986
5987 void
5988 bpstat_run_callbacks (bpstat bs_head)
5989 {
5990   bpstat bs;
5991
5992   for (bs = bs_head; bs != NULL; bs = bs->next)
5993     {
5994       struct breakpoint *b = bs->breakpoint_at;
5995
5996       if (b == NULL)
5997         continue;
5998       switch (b->type)
5999         {
6000         case bp_jit_event:
6001           handle_jit_event ();
6002           break;
6003         case bp_gnu_ifunc_resolver:
6004           gnu_ifunc_resolver_stop (b);
6005           break;
6006         case bp_gnu_ifunc_resolver_return:
6007           gnu_ifunc_resolver_return_stop (b);
6008           break;
6009         }
6010     }
6011 }
6012
6013 /* Nonzero if we should step constantly (e.g. watchpoints on machines
6014    without hardware support).  This isn't related to a specific bpstat,
6015    just to things like whether watchpoints are set.  */
6016
6017 int
6018 bpstat_should_step (void)
6019 {
6020   struct breakpoint *b;
6021
6022   ALL_BREAKPOINTS (b)
6023     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6024       return 1;
6025   return 0;
6026 }
6027
6028 int
6029 bpstat_causes_stop (bpstat bs)
6030 {
6031   for (; bs != NULL; bs = bs->next)
6032     if (bs->stop)
6033       return 1;
6034
6035   return 0;
6036 }
6037
6038 \f
6039
6040 /* Compute a string of spaces suitable to indent the next line
6041    so it starts at the position corresponding to the table column
6042    named COL_NAME in the currently active table of UIOUT.  */
6043
6044 static char *
6045 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6046 {
6047   static char wrap_indent[80];
6048   int i, total_width, width, align;
6049   char *text;
6050
6051   total_width = 0;
6052   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
6053     {
6054       if (strcmp (text, col_name) == 0)
6055         {
6056           gdb_assert (total_width < sizeof wrap_indent);
6057           memset (wrap_indent, ' ', total_width);
6058           wrap_indent[total_width] = 0;
6059
6060           return wrap_indent;
6061         }
6062
6063       total_width += width + 1;
6064     }
6065
6066   return NULL;
6067 }
6068
6069 /* Determine if the locations of this breakpoint will have their conditions
6070    evaluated by the target, host or a mix of both.  Returns the following:
6071
6072     "host": Host evals condition.
6073     "host or target": Host or Target evals condition.
6074     "target": Target evals condition.
6075 */
6076
6077 static const char *
6078 bp_condition_evaluator (struct breakpoint *b)
6079 {
6080   struct bp_location *bl;
6081   char host_evals = 0;
6082   char target_evals = 0;
6083
6084   if (!b)
6085     return NULL;
6086
6087   if (!is_breakpoint (b))
6088     return NULL;
6089
6090   if (gdb_evaluates_breakpoint_condition_p ()
6091       || !target_supports_evaluation_of_breakpoint_conditions ())
6092     return condition_evaluation_host;
6093
6094   for (bl = b->loc; bl; bl = bl->next)
6095     {
6096       if (bl->cond_bytecode)
6097         target_evals++;
6098       else
6099         host_evals++;
6100     }
6101
6102   if (host_evals && target_evals)
6103     return condition_evaluation_both;
6104   else if (target_evals)
6105     return condition_evaluation_target;
6106   else
6107     return condition_evaluation_host;
6108 }
6109
6110 /* Determine the breakpoint location's condition evaluator.  This is
6111    similar to bp_condition_evaluator, but for locations.  */
6112
6113 static const char *
6114 bp_location_condition_evaluator (struct bp_location *bl)
6115 {
6116   if (bl && !is_breakpoint (bl->owner))
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   if (bl && bl->cond_bytecode)
6124     return condition_evaluation_target;
6125   else
6126     return condition_evaluation_host;
6127 }
6128
6129 /* Print the LOC location out of the list of B->LOC locations.  */
6130
6131 static void
6132 print_breakpoint_location (struct breakpoint *b,
6133                            struct bp_location *loc)
6134 {
6135   struct ui_out *uiout = current_uiout;
6136   struct cleanup *old_chain = save_current_program_space ();
6137
6138   if (loc != NULL && loc->shlib_disabled)
6139     loc = NULL;
6140
6141   if (loc != NULL)
6142     set_current_program_space (loc->pspace);
6143
6144   if (b->display_canonical)
6145     ui_out_field_string (uiout, "what",
6146                          event_location_to_string (b->location));
6147   else if (loc && loc->symtab)
6148     {
6149       struct symbol *sym 
6150         = find_pc_sect_function (loc->address, loc->section);
6151       if (sym)
6152         {
6153           ui_out_text (uiout, "in ");
6154           ui_out_field_string (uiout, "func",
6155                                SYMBOL_PRINT_NAME (sym));
6156           ui_out_text (uiout, " ");
6157           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6158           ui_out_text (uiout, "at ");
6159         }
6160       ui_out_field_string (uiout, "file",
6161                            symtab_to_filename_for_display (loc->symtab));
6162       ui_out_text (uiout, ":");
6163
6164       if (ui_out_is_mi_like_p (uiout))
6165         ui_out_field_string (uiout, "fullname",
6166                              symtab_to_fullname (loc->symtab));
6167       
6168       ui_out_field_int (uiout, "line", loc->line_number);
6169     }
6170   else if (loc)
6171     {
6172       struct ui_file *stb = mem_fileopen ();
6173       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6174
6175       print_address_symbolic (loc->gdbarch, loc->address, stb,
6176                               demangle, "");
6177       ui_out_field_stream (uiout, "at", stb);
6178
6179       do_cleanups (stb_chain);
6180     }
6181   else
6182     {
6183       ui_out_field_string (uiout, "pending",
6184                            event_location_to_string (b->location));
6185       /* If extra_string is available, it could be holding a condition
6186          or dprintf arguments.  In either case, make sure it is printed,
6187          too, but only for non-MI streams.  */
6188       if (!ui_out_is_mi_like_p (uiout) && b->extra_string != NULL)
6189         {
6190           if (b->type == bp_dprintf)
6191             ui_out_text (uiout, ",");
6192           else
6193             ui_out_text (uiout, " ");
6194           ui_out_text (uiout, b->extra_string);
6195         }
6196     }
6197
6198   if (loc && is_breakpoint (b)
6199       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6200       && bp_condition_evaluator (b) == condition_evaluation_both)
6201     {
6202       ui_out_text (uiout, " (");
6203       ui_out_field_string (uiout, "evaluated-by",
6204                            bp_location_condition_evaluator (loc));
6205       ui_out_text (uiout, ")");
6206     }
6207
6208   do_cleanups (old_chain);
6209 }
6210
6211 static const char *
6212 bptype_string (enum bptype type)
6213 {
6214   struct ep_type_description
6215     {
6216       enum bptype type;
6217       char *description;
6218     };
6219   static struct ep_type_description bptypes[] =
6220   {
6221     {bp_none, "?deleted?"},
6222     {bp_breakpoint, "breakpoint"},
6223     {bp_hardware_breakpoint, "hw breakpoint"},
6224     {bp_single_step, "sw single-step"},
6225     {bp_until, "until"},
6226     {bp_finish, "finish"},
6227     {bp_watchpoint, "watchpoint"},
6228     {bp_hardware_watchpoint, "hw watchpoint"},
6229     {bp_read_watchpoint, "read watchpoint"},
6230     {bp_access_watchpoint, "acc watchpoint"},
6231     {bp_longjmp, "longjmp"},
6232     {bp_longjmp_resume, "longjmp resume"},
6233     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6234     {bp_exception, "exception"},
6235     {bp_exception_resume, "exception resume"},
6236     {bp_step_resume, "step resume"},
6237     {bp_hp_step_resume, "high-priority step resume"},
6238     {bp_watchpoint_scope, "watchpoint scope"},
6239     {bp_call_dummy, "call dummy"},
6240     {bp_std_terminate, "std::terminate"},
6241     {bp_shlib_event, "shlib events"},
6242     {bp_thread_event, "thread events"},
6243     {bp_overlay_event, "overlay events"},
6244     {bp_longjmp_master, "longjmp master"},
6245     {bp_std_terminate_master, "std::terminate master"},
6246     {bp_exception_master, "exception master"},
6247     {bp_catchpoint, "catchpoint"},
6248     {bp_tracepoint, "tracepoint"},
6249     {bp_fast_tracepoint, "fast tracepoint"},
6250     {bp_static_tracepoint, "static tracepoint"},
6251     {bp_dprintf, "dprintf"},
6252     {bp_jit_event, "jit events"},
6253     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6254     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6255   };
6256
6257   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6258       || ((int) type != bptypes[(int) type].type))
6259     internal_error (__FILE__, __LINE__,
6260                     _("bptypes table does not describe type #%d."),
6261                     (int) type);
6262
6263   return bptypes[(int) type].description;
6264 }
6265
6266 /* For MI, output a field named 'thread-groups' with a list as the value.
6267    For CLI, prefix the list with the string 'inf'. */
6268
6269 static void
6270 output_thread_groups (struct ui_out *uiout,
6271                       const char *field_name,
6272                       VEC(int) *inf_num,
6273                       int mi_only)
6274 {
6275   struct cleanup *back_to;
6276   int is_mi = ui_out_is_mi_like_p (uiout);
6277   int inf;
6278   int i;
6279
6280   /* For backward compatibility, don't display inferiors in CLI unless
6281      there are several.  Always display them for MI. */
6282   if (!is_mi && mi_only)
6283     return;
6284
6285   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6286
6287   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6288     {
6289       if (is_mi)
6290         {
6291           char mi_group[10];
6292
6293           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6294           ui_out_field_string (uiout, NULL, mi_group);
6295         }
6296       else
6297         {
6298           if (i == 0)
6299             ui_out_text (uiout, " inf ");
6300           else
6301             ui_out_text (uiout, ", ");
6302         
6303           ui_out_text (uiout, plongest (inf));
6304         }
6305     }
6306
6307   do_cleanups (back_to);
6308 }
6309
6310 /* Print B to gdb_stdout.  */
6311
6312 static void
6313 print_one_breakpoint_location (struct breakpoint *b,
6314                                struct bp_location *loc,
6315                                int loc_number,
6316                                struct bp_location **last_loc,
6317                                int allflag)
6318 {
6319   struct command_line *l;
6320   static char bpenables[] = "nynny";
6321
6322   struct ui_out *uiout = current_uiout;
6323   int header_of_multiple = 0;
6324   int part_of_multiple = (loc != NULL);
6325   struct value_print_options opts;
6326
6327   get_user_print_options (&opts);
6328
6329   gdb_assert (!loc || loc_number != 0);
6330   /* See comment in print_one_breakpoint concerning treatment of
6331      breakpoints with single disabled location.  */
6332   if (loc == NULL 
6333       && (b->loc != NULL 
6334           && (b->loc->next != NULL || !b->loc->enabled)))
6335     header_of_multiple = 1;
6336   if (loc == NULL)
6337     loc = b->loc;
6338
6339   annotate_record ();
6340
6341   /* 1 */
6342   annotate_field (0);
6343   if (part_of_multiple)
6344     {
6345       char *formatted;
6346       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6347       ui_out_field_string (uiout, "number", formatted);
6348       xfree (formatted);
6349     }
6350   else
6351     {
6352       ui_out_field_int (uiout, "number", b->number);
6353     }
6354
6355   /* 2 */
6356   annotate_field (1);
6357   if (part_of_multiple)
6358     ui_out_field_skip (uiout, "type");
6359   else
6360     ui_out_field_string (uiout, "type", bptype_string (b->type));
6361
6362   /* 3 */
6363   annotate_field (2);
6364   if (part_of_multiple)
6365     ui_out_field_skip (uiout, "disp");
6366   else
6367     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6368
6369
6370   /* 4 */
6371   annotate_field (3);
6372   if (part_of_multiple)
6373     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6374   else
6375     ui_out_field_fmt (uiout, "enabled", "%c", 
6376                       bpenables[(int) b->enable_state]);
6377   ui_out_spaces (uiout, 2);
6378
6379   
6380   /* 5 and 6 */
6381   if (b->ops != NULL && b->ops->print_one != NULL)
6382     {
6383       /* Although the print_one can possibly print all locations,
6384          calling it here is not likely to get any nice result.  So,
6385          make sure there's just one location.  */
6386       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6387       b->ops->print_one (b, last_loc);
6388     }
6389   else
6390     switch (b->type)
6391       {
6392       case bp_none:
6393         internal_error (__FILE__, __LINE__,
6394                         _("print_one_breakpoint: bp_none encountered\n"));
6395         break;
6396
6397       case bp_watchpoint:
6398       case bp_hardware_watchpoint:
6399       case bp_read_watchpoint:
6400       case bp_access_watchpoint:
6401         {
6402           struct watchpoint *w = (struct watchpoint *) b;
6403
6404           /* Field 4, the address, is omitted (which makes the columns
6405              not line up too nicely with the headers, but the effect
6406              is relatively readable).  */
6407           if (opts.addressprint)
6408             ui_out_field_skip (uiout, "addr");
6409           annotate_field (5);
6410           ui_out_field_string (uiout, "what", w->exp_string);
6411         }
6412         break;
6413
6414       case bp_breakpoint:
6415       case bp_hardware_breakpoint:
6416       case bp_single_step:
6417       case bp_until:
6418       case bp_finish:
6419       case bp_longjmp:
6420       case bp_longjmp_resume:
6421       case bp_longjmp_call_dummy:
6422       case bp_exception:
6423       case bp_exception_resume:
6424       case bp_step_resume:
6425       case bp_hp_step_resume:
6426       case bp_watchpoint_scope:
6427       case bp_call_dummy:
6428       case bp_std_terminate:
6429       case bp_shlib_event:
6430       case bp_thread_event:
6431       case bp_overlay_event:
6432       case bp_longjmp_master:
6433       case bp_std_terminate_master:
6434       case bp_exception_master:
6435       case bp_tracepoint:
6436       case bp_fast_tracepoint:
6437       case bp_static_tracepoint:
6438       case bp_dprintf:
6439       case bp_jit_event:
6440       case bp_gnu_ifunc_resolver:
6441       case bp_gnu_ifunc_resolver_return:
6442         if (opts.addressprint)
6443           {
6444             annotate_field (4);
6445             if (header_of_multiple)
6446               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6447             else if (b->loc == NULL || loc->shlib_disabled)
6448               ui_out_field_string (uiout, "addr", "<PENDING>");
6449             else
6450               ui_out_field_core_addr (uiout, "addr",
6451                                       loc->gdbarch, loc->address);
6452           }
6453         annotate_field (5);
6454         if (!header_of_multiple)
6455           print_breakpoint_location (b, loc);
6456         if (b->loc)
6457           *last_loc = b->loc;
6458         break;
6459       }
6460
6461
6462   if (loc != NULL && !header_of_multiple)
6463     {
6464       struct inferior *inf;
6465       VEC(int) *inf_num = NULL;
6466       int mi_only = 1;
6467
6468       ALL_INFERIORS (inf)
6469         {
6470           if (inf->pspace == loc->pspace)
6471             VEC_safe_push (int, inf_num, inf->num);
6472         }
6473
6474         /* For backward compatibility, don't display inferiors in CLI unless
6475            there are several.  Always display for MI. */
6476         if (allflag
6477             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6478                 && (number_of_program_spaces () > 1
6479                     || number_of_inferiors () > 1)
6480                 /* LOC is for existing B, it cannot be in
6481                    moribund_locations and thus having NULL OWNER.  */
6482                 && loc->owner->type != bp_catchpoint))
6483         mi_only = 0;
6484       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6485       VEC_free (int, inf_num);
6486     }
6487
6488   if (!part_of_multiple)
6489     {
6490       if (b->thread != -1)
6491         {
6492           /* FIXME: This seems to be redundant and lost here; see the
6493              "stop only in" line a little further down.  */
6494           ui_out_text (uiout, " thread ");
6495           ui_out_field_int (uiout, "thread", b->thread);
6496         }
6497       else if (b->task != 0)
6498         {
6499           ui_out_text (uiout, " task ");
6500           ui_out_field_int (uiout, "task", b->task);
6501         }
6502     }
6503
6504   ui_out_text (uiout, "\n");
6505
6506   if (!part_of_multiple)
6507     b->ops->print_one_detail (b, uiout);
6508
6509   if (part_of_multiple && frame_id_p (b->frame_id))
6510     {
6511       annotate_field (6);
6512       ui_out_text (uiout, "\tstop only in stack frame at ");
6513       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6514          the frame ID.  */
6515       ui_out_field_core_addr (uiout, "frame",
6516                               b->gdbarch, b->frame_id.stack_addr);
6517       ui_out_text (uiout, "\n");
6518     }
6519   
6520   if (!part_of_multiple && b->cond_string)
6521     {
6522       annotate_field (7);
6523       if (is_tracepoint (b))
6524         ui_out_text (uiout, "\ttrace only if ");
6525       else
6526         ui_out_text (uiout, "\tstop only if ");
6527       ui_out_field_string (uiout, "cond", b->cond_string);
6528
6529       /* Print whether the target is doing the breakpoint's condition
6530          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6531       if (is_breakpoint (b)
6532           && breakpoint_condition_evaluation_mode ()
6533           == condition_evaluation_target)
6534         {
6535           ui_out_text (uiout, " (");
6536           ui_out_field_string (uiout, "evaluated-by",
6537                                bp_condition_evaluator (b));
6538           ui_out_text (uiout, " evals)");
6539         }
6540       ui_out_text (uiout, "\n");
6541     }
6542
6543   if (!part_of_multiple && b->thread != -1)
6544     {
6545       /* FIXME should make an annotation for this.  */
6546       ui_out_text (uiout, "\tstop only in thread ");
6547       if (ui_out_is_mi_like_p (uiout))
6548         ui_out_field_int (uiout, "thread", b->thread);
6549       else
6550         {
6551           struct thread_info *thr = find_thread_global_id (b->thread);
6552
6553           ui_out_field_string (uiout, "thread", print_thread_id (thr));
6554         }
6555       ui_out_text (uiout, "\n");
6556     }
6557   
6558   if (!part_of_multiple)
6559     {
6560       if (b->hit_count)
6561         {
6562           /* FIXME should make an annotation for this.  */
6563           if (is_catchpoint (b))
6564             ui_out_text (uiout, "\tcatchpoint");
6565           else if (is_tracepoint (b))
6566             ui_out_text (uiout, "\ttracepoint");
6567           else
6568             ui_out_text (uiout, "\tbreakpoint");
6569           ui_out_text (uiout, " already hit ");
6570           ui_out_field_int (uiout, "times", b->hit_count);
6571           if (b->hit_count == 1)
6572             ui_out_text (uiout, " time\n");
6573           else
6574             ui_out_text (uiout, " times\n");
6575         }
6576       else
6577         {
6578           /* Output the count also if it is zero, but only if this is mi.  */
6579           if (ui_out_is_mi_like_p (uiout))
6580             ui_out_field_int (uiout, "times", b->hit_count);
6581         }
6582     }
6583
6584   if (!part_of_multiple && b->ignore_count)
6585     {
6586       annotate_field (8);
6587       ui_out_text (uiout, "\tignore next ");
6588       ui_out_field_int (uiout, "ignore", b->ignore_count);
6589       ui_out_text (uiout, " hits\n");
6590     }
6591
6592   /* Note that an enable count of 1 corresponds to "enable once"
6593      behavior, which is reported by the combination of enablement and
6594      disposition, so we don't need to mention it here.  */
6595   if (!part_of_multiple && b->enable_count > 1)
6596     {
6597       annotate_field (8);
6598       ui_out_text (uiout, "\tdisable after ");
6599       /* Tweak the wording to clarify that ignore and enable counts
6600          are distinct, and have additive effect.  */
6601       if (b->ignore_count)
6602         ui_out_text (uiout, "additional ");
6603       else
6604         ui_out_text (uiout, "next ");
6605       ui_out_field_int (uiout, "enable", b->enable_count);
6606       ui_out_text (uiout, " hits\n");
6607     }
6608
6609   if (!part_of_multiple && is_tracepoint (b))
6610     {
6611       struct tracepoint *tp = (struct tracepoint *) b;
6612
6613       if (tp->traceframe_usage)
6614         {
6615           ui_out_text (uiout, "\ttrace buffer usage ");
6616           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6617           ui_out_text (uiout, " bytes\n");
6618         }
6619     }
6620
6621   l = b->commands ? b->commands->commands : NULL;
6622   if (!part_of_multiple && l)
6623     {
6624       struct cleanup *script_chain;
6625
6626       annotate_field (9);
6627       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6628       print_command_lines (uiout, l, 4);
6629       do_cleanups (script_chain);
6630     }
6631
6632   if (is_tracepoint (b))
6633     {
6634       struct tracepoint *t = (struct tracepoint *) b;
6635
6636       if (!part_of_multiple && t->pass_count)
6637         {
6638           annotate_field (10);
6639           ui_out_text (uiout, "\tpass count ");
6640           ui_out_field_int (uiout, "pass", t->pass_count);
6641           ui_out_text (uiout, " \n");
6642         }
6643
6644       /* Don't display it when tracepoint or tracepoint location is
6645          pending.   */
6646       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6647         {
6648           annotate_field (11);
6649
6650           if (ui_out_is_mi_like_p (uiout))
6651             ui_out_field_string (uiout, "installed",
6652                                  loc->inserted ? "y" : "n");
6653           else
6654             {
6655               if (loc->inserted)
6656                 ui_out_text (uiout, "\t");
6657               else
6658                 ui_out_text (uiout, "\tnot ");
6659               ui_out_text (uiout, "installed on target\n");
6660             }
6661         }
6662     }
6663
6664   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6665     {
6666       if (is_watchpoint (b))
6667         {
6668           struct watchpoint *w = (struct watchpoint *) b;
6669
6670           ui_out_field_string (uiout, "original-location", w->exp_string);
6671         }
6672       else if (b->location != NULL
6673                && event_location_to_string (b->location) != NULL)
6674         ui_out_field_string (uiout, "original-location",
6675                              event_location_to_string (b->location));
6676     }
6677 }
6678
6679 static void
6680 print_one_breakpoint (struct breakpoint *b,
6681                       struct bp_location **last_loc, 
6682                       int allflag)
6683 {
6684   struct cleanup *bkpt_chain;
6685   struct ui_out *uiout = current_uiout;
6686
6687   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6688
6689   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6690   do_cleanups (bkpt_chain);
6691
6692   /* If this breakpoint has custom print function,
6693      it's already printed.  Otherwise, print individual
6694      locations, if any.  */
6695   if (b->ops == NULL || b->ops->print_one == NULL)
6696     {
6697       /* If breakpoint has a single location that is disabled, we
6698          print it as if it had several locations, since otherwise it's
6699          hard to represent "breakpoint enabled, location disabled"
6700          situation.
6701
6702          Note that while hardware watchpoints have several locations
6703          internally, that's not a property exposed to user.  */
6704       if (b->loc 
6705           && !is_hardware_watchpoint (b)
6706           && (b->loc->next || !b->loc->enabled))
6707         {
6708           struct bp_location *loc;
6709           int n = 1;
6710
6711           for (loc = b->loc; loc; loc = loc->next, ++n)
6712             {
6713               struct cleanup *inner2 =
6714                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6715               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6716               do_cleanups (inner2);
6717             }
6718         }
6719     }
6720 }
6721
6722 static int
6723 breakpoint_address_bits (struct breakpoint *b)
6724 {
6725   int print_address_bits = 0;
6726   struct bp_location *loc;
6727
6728   /* Software watchpoints that aren't watching memory don't have an
6729      address to print.  */
6730   if (is_no_memory_software_watchpoint (b))
6731     return 0;
6732
6733   for (loc = b->loc; loc; loc = loc->next)
6734     {
6735       int addr_bit;
6736
6737       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6738       if (addr_bit > print_address_bits)
6739         print_address_bits = addr_bit;
6740     }
6741
6742   return print_address_bits;
6743 }
6744
6745 struct captured_breakpoint_query_args
6746   {
6747     int bnum;
6748   };
6749
6750 static int
6751 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6752 {
6753   struct captured_breakpoint_query_args *args
6754     = (struct captured_breakpoint_query_args *) data;
6755   struct breakpoint *b;
6756   struct bp_location *dummy_loc = NULL;
6757
6758   ALL_BREAKPOINTS (b)
6759     {
6760       if (args->bnum == b->number)
6761         {
6762           print_one_breakpoint (b, &dummy_loc, 0);
6763           return GDB_RC_OK;
6764         }
6765     }
6766   return GDB_RC_NONE;
6767 }
6768
6769 enum gdb_rc
6770 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6771                       char **error_message)
6772 {
6773   struct captured_breakpoint_query_args args;
6774
6775   args.bnum = bnum;
6776   /* For the moment we don't trust print_one_breakpoint() to not throw
6777      an error.  */
6778   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6779                                  error_message, RETURN_MASK_ALL) < 0)
6780     return GDB_RC_FAIL;
6781   else
6782     return GDB_RC_OK;
6783 }
6784
6785 /* Return true if this breakpoint was set by the user, false if it is
6786    internal or momentary.  */
6787
6788 int
6789 user_breakpoint_p (struct breakpoint *b)
6790 {
6791   return b->number > 0;
6792 }
6793
6794 /* Print information on user settable breakpoint (watchpoint, etc)
6795    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6796    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6797    FILTER is non-NULL, call it on each breakpoint and only include the
6798    ones for which it returns non-zero.  Return the total number of
6799    breakpoints listed.  */
6800
6801 static int
6802 breakpoint_1 (char *args, int allflag, 
6803               int (*filter) (const struct breakpoint *))
6804 {
6805   struct breakpoint *b;
6806   struct bp_location *last_loc = NULL;
6807   int nr_printable_breakpoints;
6808   struct cleanup *bkpttbl_chain;
6809   struct value_print_options opts;
6810   int print_address_bits = 0;
6811   int print_type_col_width = 14;
6812   struct ui_out *uiout = current_uiout;
6813
6814   get_user_print_options (&opts);
6815
6816   /* Compute the number of rows in the table, as well as the size
6817      required for address fields.  */
6818   nr_printable_breakpoints = 0;
6819   ALL_BREAKPOINTS (b)
6820     {
6821       /* If we have a filter, only list the breakpoints it accepts.  */
6822       if (filter && !filter (b))
6823         continue;
6824
6825       /* If we have an "args" string, it is a list of breakpoints to 
6826          accept.  Skip the others.  */
6827       if (args != NULL && *args != '\0')
6828         {
6829           if (allflag && parse_and_eval_long (args) != b->number)
6830             continue;
6831           if (!allflag && !number_is_in_list (args, b->number))
6832             continue;
6833         }
6834
6835       if (allflag || user_breakpoint_p (b))
6836         {
6837           int addr_bit, type_len;
6838
6839           addr_bit = breakpoint_address_bits (b);
6840           if (addr_bit > print_address_bits)
6841             print_address_bits = addr_bit;
6842
6843           type_len = strlen (bptype_string (b->type));
6844           if (type_len > print_type_col_width)
6845             print_type_col_width = type_len;
6846
6847           nr_printable_breakpoints++;
6848         }
6849     }
6850
6851   if (opts.addressprint)
6852     bkpttbl_chain 
6853       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6854                                              nr_printable_breakpoints,
6855                                              "BreakpointTable");
6856   else
6857     bkpttbl_chain 
6858       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6859                                              nr_printable_breakpoints,
6860                                              "BreakpointTable");
6861
6862   if (nr_printable_breakpoints > 0)
6863     annotate_breakpoints_headers ();
6864   if (nr_printable_breakpoints > 0)
6865     annotate_field (0);
6866   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6867   if (nr_printable_breakpoints > 0)
6868     annotate_field (1);
6869   ui_out_table_header (uiout, print_type_col_width, ui_left,
6870                        "type", "Type");                         /* 2 */
6871   if (nr_printable_breakpoints > 0)
6872     annotate_field (2);
6873   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6874   if (nr_printable_breakpoints > 0)
6875     annotate_field (3);
6876   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6877   if (opts.addressprint)
6878     {
6879       if (nr_printable_breakpoints > 0)
6880         annotate_field (4);
6881       if (print_address_bits <= 32)
6882         ui_out_table_header (uiout, 10, ui_left, 
6883                              "addr", "Address");                /* 5 */
6884       else
6885         ui_out_table_header (uiout, 18, ui_left, 
6886                              "addr", "Address");                /* 5 */
6887     }
6888   if (nr_printable_breakpoints > 0)
6889     annotate_field (5);
6890   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6891   ui_out_table_body (uiout);
6892   if (nr_printable_breakpoints > 0)
6893     annotate_breakpoints_table ();
6894
6895   ALL_BREAKPOINTS (b)
6896     {
6897       QUIT;
6898       /* If we have a filter, only list the breakpoints it accepts.  */
6899       if (filter && !filter (b))
6900         continue;
6901
6902       /* If we have an "args" string, it is a list of breakpoints to 
6903          accept.  Skip the others.  */
6904
6905       if (args != NULL && *args != '\0')
6906         {
6907           if (allflag)  /* maintenance info breakpoint */
6908             {
6909               if (parse_and_eval_long (args) != b->number)
6910                 continue;
6911             }
6912           else          /* all others */
6913             {
6914               if (!number_is_in_list (args, b->number))
6915                 continue;
6916             }
6917         }
6918       /* We only print out user settable breakpoints unless the
6919          allflag is set.  */
6920       if (allflag || user_breakpoint_p (b))
6921         print_one_breakpoint (b, &last_loc, allflag);
6922     }
6923
6924   do_cleanups (bkpttbl_chain);
6925
6926   if (nr_printable_breakpoints == 0)
6927     {
6928       /* If there's a filter, let the caller decide how to report
6929          empty list.  */
6930       if (!filter)
6931         {
6932           if (args == NULL || *args == '\0')
6933             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6934           else
6935             ui_out_message (uiout, 0, 
6936                             "No breakpoint or watchpoint matching '%s'.\n",
6937                             args);
6938         }
6939     }
6940   else
6941     {
6942       if (last_loc && !server_command)
6943         set_next_address (last_loc->gdbarch, last_loc->address);
6944     }
6945
6946   /* FIXME?  Should this be moved up so that it is only called when
6947      there have been breakpoints? */
6948   annotate_breakpoints_table_end ();
6949
6950   return nr_printable_breakpoints;
6951 }
6952
6953 /* Display the value of default-collect in a way that is generally
6954    compatible with the breakpoint list.  */
6955
6956 static void
6957 default_collect_info (void)
6958 {
6959   struct ui_out *uiout = current_uiout;
6960
6961   /* If it has no value (which is frequently the case), say nothing; a
6962      message like "No default-collect." gets in user's face when it's
6963      not wanted.  */
6964   if (!*default_collect)
6965     return;
6966
6967   /* The following phrase lines up nicely with per-tracepoint collect
6968      actions.  */
6969   ui_out_text (uiout, "default collect ");
6970   ui_out_field_string (uiout, "default-collect", default_collect);
6971   ui_out_text (uiout, " \n");
6972 }
6973   
6974 static void
6975 breakpoints_info (char *args, int from_tty)
6976 {
6977   breakpoint_1 (args, 0, NULL);
6978
6979   default_collect_info ();
6980 }
6981
6982 static void
6983 watchpoints_info (char *args, int from_tty)
6984 {
6985   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6986   struct ui_out *uiout = current_uiout;
6987
6988   if (num_printed == 0)
6989     {
6990       if (args == NULL || *args == '\0')
6991         ui_out_message (uiout, 0, "No watchpoints.\n");
6992       else
6993         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6994     }
6995 }
6996
6997 static void
6998 maintenance_info_breakpoints (char *args, int from_tty)
6999 {
7000   breakpoint_1 (args, 1, NULL);
7001
7002   default_collect_info ();
7003 }
7004
7005 static int
7006 breakpoint_has_pc (struct breakpoint *b,
7007                    struct program_space *pspace,
7008                    CORE_ADDR pc, struct obj_section *section)
7009 {
7010   struct bp_location *bl = b->loc;
7011
7012   for (; bl; bl = bl->next)
7013     {
7014       if (bl->pspace == pspace
7015           && bl->address == pc
7016           && (!overlay_debugging || bl->section == section))
7017         return 1;         
7018     }
7019   return 0;
7020 }
7021
7022 /* Print a message describing any user-breakpoints set at PC.  This
7023    concerns with logical breakpoints, so we match program spaces, not
7024    address spaces.  */
7025
7026 static void
7027 describe_other_breakpoints (struct gdbarch *gdbarch,
7028                             struct program_space *pspace, CORE_ADDR pc,
7029                             struct obj_section *section, int thread)
7030 {
7031   int others = 0;
7032   struct breakpoint *b;
7033
7034   ALL_BREAKPOINTS (b)
7035     others += (user_breakpoint_p (b)
7036                && breakpoint_has_pc (b, pspace, pc, section));
7037   if (others > 0)
7038     {
7039       if (others == 1)
7040         printf_filtered (_("Note: breakpoint "));
7041       else /* if (others == ???) */
7042         printf_filtered (_("Note: breakpoints "));
7043       ALL_BREAKPOINTS (b)
7044         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7045           {
7046             others--;
7047             printf_filtered ("%d", b->number);
7048             if (b->thread == -1 && thread != -1)
7049               printf_filtered (" (all threads)");
7050             else if (b->thread != -1)
7051               printf_filtered (" (thread %d)", b->thread);
7052             printf_filtered ("%s%s ",
7053                              ((b->enable_state == bp_disabled
7054                                || b->enable_state == bp_call_disabled)
7055                               ? " (disabled)"
7056                               : ""),
7057                              (others > 1) ? "," 
7058                              : ((others == 1) ? " and" : ""));
7059           }
7060       printf_filtered (_("also set at pc "));
7061       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
7062       printf_filtered (".\n");
7063     }
7064 }
7065 \f
7066
7067 /* Return true iff it is meaningful to use the address member of
7068    BPT locations.  For some breakpoint types, the locations' address members
7069    are irrelevant and it makes no sense to attempt to compare them to other
7070    addresses (or use them for any other purpose either).
7071
7072    More specifically, each of the following breakpoint types will
7073    always have a zero valued location address and we don't want to mark
7074    breakpoints of any of these types to be a duplicate of an actual
7075    breakpoint location at address zero:
7076
7077       bp_watchpoint
7078       bp_catchpoint
7079
7080 */
7081
7082 static int
7083 breakpoint_address_is_meaningful (struct breakpoint *bpt)
7084 {
7085   enum bptype type = bpt->type;
7086
7087   return (type != bp_watchpoint && type != bp_catchpoint);
7088 }
7089
7090 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7091    true if LOC1 and LOC2 represent the same watchpoint location.  */
7092
7093 static int
7094 watchpoint_locations_match (struct bp_location *loc1, 
7095                             struct bp_location *loc2)
7096 {
7097   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7098   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7099
7100   /* Both of them must exist.  */
7101   gdb_assert (w1 != NULL);
7102   gdb_assert (w2 != NULL);
7103
7104   /* If the target can evaluate the condition expression in hardware,
7105      then we we need to insert both watchpoints even if they are at
7106      the same place.  Otherwise the watchpoint will only trigger when
7107      the condition of whichever watchpoint was inserted evaluates to
7108      true, not giving a chance for GDB to check the condition of the
7109      other watchpoint.  */
7110   if ((w1->cond_exp
7111        && target_can_accel_watchpoint_condition (loc1->address, 
7112                                                  loc1->length,
7113                                                  loc1->watchpoint_type,
7114                                                  w1->cond_exp))
7115       || (w2->cond_exp
7116           && target_can_accel_watchpoint_condition (loc2->address, 
7117                                                     loc2->length,
7118                                                     loc2->watchpoint_type,
7119                                                     w2->cond_exp)))
7120     return 0;
7121
7122   /* Note that this checks the owner's type, not the location's.  In
7123      case the target does not support read watchpoints, but does
7124      support access watchpoints, we'll have bp_read_watchpoint
7125      watchpoints with hw_access locations.  Those should be considered
7126      duplicates of hw_read locations.  The hw_read locations will
7127      become hw_access locations later.  */
7128   return (loc1->owner->type == loc2->owner->type
7129           && loc1->pspace->aspace == loc2->pspace->aspace
7130           && loc1->address == loc2->address
7131           && loc1->length == loc2->length);
7132 }
7133
7134 /* See breakpoint.h.  */
7135
7136 int
7137 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7138                           struct address_space *aspace2, CORE_ADDR addr2)
7139 {
7140   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7141            || aspace1 == aspace2)
7142           && addr1 == addr2);
7143 }
7144
7145 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7146    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7147    matches ASPACE2.  On targets that have global breakpoints, the address
7148    space doesn't really matter.  */
7149
7150 static int
7151 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7152                                 int len1, struct address_space *aspace2,
7153                                 CORE_ADDR addr2)
7154 {
7155   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7156            || aspace1 == aspace2)
7157           && addr2 >= addr1 && addr2 < addr1 + len1);
7158 }
7159
7160 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7161    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7162    matches the breakpoint's address space.  On targets that have global
7163    breakpoints, the address space doesn't really matter.  */
7164
7165 static int
7166 breakpoint_location_address_match (struct bp_location *bl,
7167                                    struct address_space *aspace,
7168                                    CORE_ADDR addr)
7169 {
7170   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7171                                     aspace, addr)
7172           || (bl->length
7173               && breakpoint_address_match_range (bl->pspace->aspace,
7174                                                  bl->address, bl->length,
7175                                                  aspace, addr)));
7176 }
7177
7178 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7179    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7180    match happens only if ASPACE matches the breakpoint's address
7181    space.  On targets that have global breakpoints, the address space
7182    doesn't really matter.  */
7183
7184 static int
7185 breakpoint_location_address_range_overlap (struct bp_location *bl,
7186                                            struct address_space *aspace,
7187                                            CORE_ADDR addr, int len)
7188 {
7189   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7190       || bl->pspace->aspace == aspace)
7191     {
7192       int bl_len = bl->length != 0 ? bl->length : 1;
7193
7194       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7195         return 1;
7196     }
7197   return 0;
7198 }
7199
7200 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7201    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7202    true, otherwise returns false.  */
7203
7204 static int
7205 tracepoint_locations_match (struct bp_location *loc1,
7206                             struct bp_location *loc2)
7207 {
7208   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7209     /* Since tracepoint locations are never duplicated with others', tracepoint
7210        locations at the same address of different tracepoints are regarded as
7211        different locations.  */
7212     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7213   else
7214     return 0;
7215 }
7216
7217 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7218    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7219    represent the same location.  */
7220
7221 static int
7222 breakpoint_locations_match (struct bp_location *loc1, 
7223                             struct bp_location *loc2)
7224 {
7225   int hw_point1, hw_point2;
7226
7227   /* Both of them must not be in moribund_locations.  */
7228   gdb_assert (loc1->owner != NULL);
7229   gdb_assert (loc2->owner != NULL);
7230
7231   hw_point1 = is_hardware_watchpoint (loc1->owner);
7232   hw_point2 = is_hardware_watchpoint (loc2->owner);
7233
7234   if (hw_point1 != hw_point2)
7235     return 0;
7236   else if (hw_point1)
7237     return watchpoint_locations_match (loc1, loc2);
7238   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7239     return tracepoint_locations_match (loc1, loc2);
7240   else
7241     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7242     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7243                                      loc2->pspace->aspace, loc2->address)
7244             && loc1->length == loc2->length);
7245 }
7246
7247 static void
7248 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7249                                int bnum, int have_bnum)
7250 {
7251   /* The longest string possibly returned by hex_string_custom
7252      is 50 chars.  These must be at least that big for safety.  */
7253   char astr1[64];
7254   char astr2[64];
7255
7256   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7257   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7258   if (have_bnum)
7259     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7260              bnum, astr1, astr2);
7261   else
7262     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7263 }
7264
7265 /* Adjust a breakpoint's address to account for architectural
7266    constraints on breakpoint placement.  Return the adjusted address.
7267    Note: Very few targets require this kind of adjustment.  For most
7268    targets, this function is simply the identity function.  */
7269
7270 static CORE_ADDR
7271 adjust_breakpoint_address (struct gdbarch *gdbarch,
7272                            CORE_ADDR bpaddr, enum bptype bptype)
7273 {
7274   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7275     {
7276       /* Very few targets need any kind of breakpoint adjustment.  */
7277       return bpaddr;
7278     }
7279   else if (bptype == bp_watchpoint
7280            || bptype == bp_hardware_watchpoint
7281            || bptype == bp_read_watchpoint
7282            || bptype == bp_access_watchpoint
7283            || bptype == bp_catchpoint)
7284     {
7285       /* Watchpoints and the various bp_catch_* eventpoints should not
7286          have their addresses modified.  */
7287       return bpaddr;
7288     }
7289   else if (bptype == bp_single_step)
7290     {
7291       /* Single-step breakpoints should not have their addresses
7292          modified.  If there's any architectural constrain that
7293          applies to this address, then it should have already been
7294          taken into account when the breakpoint was created in the
7295          first place.  If we didn't do this, stepping through e.g.,
7296          Thumb-2 IT blocks would break.  */
7297       return bpaddr;
7298     }
7299   else
7300     {
7301       CORE_ADDR adjusted_bpaddr;
7302
7303       /* Some targets have architectural constraints on the placement
7304          of breakpoint instructions.  Obtain the adjusted address.  */
7305       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7306
7307       /* An adjusted breakpoint address can significantly alter
7308          a user's expectations.  Print a warning if an adjustment
7309          is required.  */
7310       if (adjusted_bpaddr != bpaddr)
7311         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7312
7313       return adjusted_bpaddr;
7314     }
7315 }
7316
7317 void
7318 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7319                   struct breakpoint *owner)
7320 {
7321   memset (loc, 0, sizeof (*loc));
7322
7323   gdb_assert (ops != NULL);
7324
7325   loc->ops = ops;
7326   loc->owner = owner;
7327   loc->cond = NULL;
7328   loc->cond_bytecode = NULL;
7329   loc->shlib_disabled = 0;
7330   loc->enabled = 1;
7331
7332   switch (owner->type)
7333     {
7334     case bp_breakpoint:
7335     case bp_single_step:
7336     case bp_until:
7337     case bp_finish:
7338     case bp_longjmp:
7339     case bp_longjmp_resume:
7340     case bp_longjmp_call_dummy:
7341     case bp_exception:
7342     case bp_exception_resume:
7343     case bp_step_resume:
7344     case bp_hp_step_resume:
7345     case bp_watchpoint_scope:
7346     case bp_call_dummy:
7347     case bp_std_terminate:
7348     case bp_shlib_event:
7349     case bp_thread_event:
7350     case bp_overlay_event:
7351     case bp_jit_event:
7352     case bp_longjmp_master:
7353     case bp_std_terminate_master:
7354     case bp_exception_master:
7355     case bp_gnu_ifunc_resolver:
7356     case bp_gnu_ifunc_resolver_return:
7357     case bp_dprintf:
7358       loc->loc_type = bp_loc_software_breakpoint;
7359       mark_breakpoint_location_modified (loc);
7360       break;
7361     case bp_hardware_breakpoint:
7362       loc->loc_type = bp_loc_hardware_breakpoint;
7363       mark_breakpoint_location_modified (loc);
7364       break;
7365     case bp_hardware_watchpoint:
7366     case bp_read_watchpoint:
7367     case bp_access_watchpoint:
7368       loc->loc_type = bp_loc_hardware_watchpoint;
7369       break;
7370     case bp_watchpoint:
7371     case bp_catchpoint:
7372     case bp_tracepoint:
7373     case bp_fast_tracepoint:
7374     case bp_static_tracepoint:
7375       loc->loc_type = bp_loc_other;
7376       break;
7377     default:
7378       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7379     }
7380
7381   loc->refc = 1;
7382 }
7383
7384 /* Allocate a struct bp_location.  */
7385
7386 static struct bp_location *
7387 allocate_bp_location (struct breakpoint *bpt)
7388 {
7389   return bpt->ops->allocate_location (bpt);
7390 }
7391
7392 static void
7393 free_bp_location (struct bp_location *loc)
7394 {
7395   loc->ops->dtor (loc);
7396   xfree (loc);
7397 }
7398
7399 /* Increment reference count.  */
7400
7401 static void
7402 incref_bp_location (struct bp_location *bl)
7403 {
7404   ++bl->refc;
7405 }
7406
7407 /* Decrement reference count.  If the reference count reaches 0,
7408    destroy the bp_location.  Sets *BLP to NULL.  */
7409
7410 static void
7411 decref_bp_location (struct bp_location **blp)
7412 {
7413   gdb_assert ((*blp)->refc > 0);
7414
7415   if (--(*blp)->refc == 0)
7416     free_bp_location (*blp);
7417   *blp = NULL;
7418 }
7419
7420 /* Add breakpoint B at the end of the global breakpoint chain.  */
7421
7422 static void
7423 add_to_breakpoint_chain (struct breakpoint *b)
7424 {
7425   struct breakpoint *b1;
7426
7427   /* Add this breakpoint to the end of the chain so that a list of
7428      breakpoints will come out in order of increasing numbers.  */
7429
7430   b1 = breakpoint_chain;
7431   if (b1 == 0)
7432     breakpoint_chain = b;
7433   else
7434     {
7435       while (b1->next)
7436         b1 = b1->next;
7437       b1->next = b;
7438     }
7439 }
7440
7441 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7442
7443 static void
7444 init_raw_breakpoint_without_location (struct breakpoint *b,
7445                                       struct gdbarch *gdbarch,
7446                                       enum bptype bptype,
7447                                       const struct breakpoint_ops *ops)
7448 {
7449   memset (b, 0, sizeof (*b));
7450
7451   gdb_assert (ops != NULL);
7452
7453   b->ops = ops;
7454   b->type = bptype;
7455   b->gdbarch = gdbarch;
7456   b->language = current_language->la_language;
7457   b->input_radix = input_radix;
7458   b->thread = -1;
7459   b->enable_state = bp_enabled;
7460   b->next = 0;
7461   b->silent = 0;
7462   b->ignore_count = 0;
7463   b->commands = NULL;
7464   b->frame_id = null_frame_id;
7465   b->condition_not_parsed = 0;
7466   b->py_bp_object = NULL;
7467   b->related_breakpoint = b;
7468   b->location = NULL;
7469 }
7470
7471 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7472    that has type BPTYPE and has no locations as yet.  */
7473
7474 static struct breakpoint *
7475 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7476                                      enum bptype bptype,
7477                                      const struct breakpoint_ops *ops)
7478 {
7479   struct breakpoint *b = XNEW (struct breakpoint);
7480
7481   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7482   add_to_breakpoint_chain (b);
7483   return b;
7484 }
7485
7486 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7487    resolutions should be made as the user specified the location explicitly
7488    enough.  */
7489
7490 static void
7491 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7492 {
7493   gdb_assert (loc->owner != NULL);
7494
7495   if (loc->owner->type == bp_breakpoint
7496       || loc->owner->type == bp_hardware_breakpoint
7497       || is_tracepoint (loc->owner))
7498     {
7499       int is_gnu_ifunc;
7500       const char *function_name;
7501       CORE_ADDR func_addr;
7502
7503       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7504                                           &func_addr, NULL, &is_gnu_ifunc);
7505
7506       if (is_gnu_ifunc && !explicit_loc)
7507         {
7508           struct breakpoint *b = loc->owner;
7509
7510           gdb_assert (loc->pspace == current_program_space);
7511           if (gnu_ifunc_resolve_name (function_name,
7512                                       &loc->requested_address))
7513             {
7514               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7515               loc->address = adjust_breakpoint_address (loc->gdbarch,
7516                                                         loc->requested_address,
7517                                                         b->type);
7518             }
7519           else if (b->type == bp_breakpoint && b->loc == loc
7520                    && loc->next == NULL && b->related_breakpoint == b)
7521             {
7522               /* Create only the whole new breakpoint of this type but do not
7523                  mess more complicated breakpoints with multiple locations.  */
7524               b->type = bp_gnu_ifunc_resolver;
7525               /* Remember the resolver's address for use by the return
7526                  breakpoint.  */
7527               loc->related_address = func_addr;
7528             }
7529         }
7530
7531       if (function_name)
7532         loc->function_name = xstrdup (function_name);
7533     }
7534 }
7535
7536 /* Attempt to determine architecture of location identified by SAL.  */
7537 struct gdbarch *
7538 get_sal_arch (struct symtab_and_line sal)
7539 {
7540   if (sal.section)
7541     return get_objfile_arch (sal.section->objfile);
7542   if (sal.symtab)
7543     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7544
7545   return NULL;
7546 }
7547
7548 /* Low level routine for partially initializing a breakpoint of type
7549    BPTYPE.  The newly created breakpoint's address, section, source
7550    file name, and line number are provided by SAL.
7551
7552    It is expected that the caller will complete the initialization of
7553    the newly created breakpoint struct as well as output any status
7554    information regarding the creation of a new breakpoint.  */
7555
7556 static void
7557 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7558                      struct symtab_and_line sal, enum bptype bptype,
7559                      const struct breakpoint_ops *ops)
7560 {
7561   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7562
7563   add_location_to_breakpoint (b, &sal);
7564
7565   if (bptype != bp_catchpoint)
7566     gdb_assert (sal.pspace != NULL);
7567
7568   /* Store the program space that was used to set the breakpoint,
7569      except for ordinary breakpoints, which are independent of the
7570      program space.  */
7571   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7572     b->pspace = sal.pspace;
7573 }
7574
7575 /* set_raw_breakpoint is a low level routine for allocating and
7576    partially initializing a breakpoint of type BPTYPE.  The newly
7577    created breakpoint's address, section, source file name, and line
7578    number are provided by SAL.  The newly created and partially
7579    initialized breakpoint is added to the breakpoint chain and
7580    is also returned as the value of this function.
7581
7582    It is expected that the caller will complete the initialization of
7583    the newly created breakpoint struct as well as output any status
7584    information regarding the creation of a new breakpoint.  In
7585    particular, set_raw_breakpoint does NOT set the breakpoint
7586    number!  Care should be taken to not allow an error to occur
7587    prior to completing the initialization of the breakpoint.  If this
7588    should happen, a bogus breakpoint will be left on the chain.  */
7589
7590 struct breakpoint *
7591 set_raw_breakpoint (struct gdbarch *gdbarch,
7592                     struct symtab_and_line sal, enum bptype bptype,
7593                     const struct breakpoint_ops *ops)
7594 {
7595   struct breakpoint *b = XNEW (struct breakpoint);
7596
7597   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7598   add_to_breakpoint_chain (b);
7599   return b;
7600 }
7601
7602 /* Call this routine when stepping and nexting to enable a breakpoint
7603    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7604    initiated the operation.  */
7605
7606 void
7607 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7608 {
7609   struct breakpoint *b, *b_tmp;
7610   int thread = tp->global_num;
7611
7612   /* To avoid having to rescan all objfile symbols at every step,
7613      we maintain a list of continually-inserted but always disabled
7614      longjmp "master" breakpoints.  Here, we simply create momentary
7615      clones of those and enable them for the requested thread.  */
7616   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7617     if (b->pspace == current_program_space
7618         && (b->type == bp_longjmp_master
7619             || b->type == bp_exception_master))
7620       {
7621         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7622         struct breakpoint *clone;
7623
7624         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7625            after their removal.  */
7626         clone = momentary_breakpoint_from_master (b, type,
7627                                                   &longjmp_breakpoint_ops, 1);
7628         clone->thread = thread;
7629       }
7630
7631   tp->initiating_frame = frame;
7632 }
7633
7634 /* Delete all longjmp breakpoints from THREAD.  */
7635 void
7636 delete_longjmp_breakpoint (int thread)
7637 {
7638   struct breakpoint *b, *b_tmp;
7639
7640   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7641     if (b->type == bp_longjmp || b->type == bp_exception)
7642       {
7643         if (b->thread == thread)
7644           delete_breakpoint (b);
7645       }
7646 }
7647
7648 void
7649 delete_longjmp_breakpoint_at_next_stop (int thread)
7650 {
7651   struct breakpoint *b, *b_tmp;
7652
7653   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7654     if (b->type == bp_longjmp || b->type == bp_exception)
7655       {
7656         if (b->thread == thread)
7657           b->disposition = disp_del_at_next_stop;
7658       }
7659 }
7660
7661 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7662    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7663    pointer to any of them.  Return NULL if this system cannot place longjmp
7664    breakpoints.  */
7665
7666 struct breakpoint *
7667 set_longjmp_breakpoint_for_call_dummy (void)
7668 {
7669   struct breakpoint *b, *retval = NULL;
7670
7671   ALL_BREAKPOINTS (b)
7672     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7673       {
7674         struct breakpoint *new_b;
7675
7676         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7677                                                   &momentary_breakpoint_ops,
7678                                                   1);
7679         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7680
7681         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7682
7683         gdb_assert (new_b->related_breakpoint == new_b);
7684         if (retval == NULL)
7685           retval = new_b;
7686         new_b->related_breakpoint = retval;
7687         while (retval->related_breakpoint != new_b->related_breakpoint)
7688           retval = retval->related_breakpoint;
7689         retval->related_breakpoint = new_b;
7690       }
7691
7692   return retval;
7693 }
7694
7695 /* Verify all existing dummy frames and their associated breakpoints for
7696    TP.  Remove those which can no longer be found in the current frame
7697    stack.
7698
7699    You should call this function only at places where it is safe to currently
7700    unwind the whole stack.  Failed stack unwind would discard live dummy
7701    frames.  */
7702
7703 void
7704 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7705 {
7706   struct breakpoint *b, *b_tmp;
7707
7708   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7709     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7710       {
7711         struct breakpoint *dummy_b = b->related_breakpoint;
7712
7713         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7714           dummy_b = dummy_b->related_breakpoint;
7715         if (dummy_b->type != bp_call_dummy
7716             || frame_find_by_id (dummy_b->frame_id) != NULL)
7717           continue;
7718         
7719         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7720
7721         while (b->related_breakpoint != b)
7722           {
7723             if (b_tmp == b->related_breakpoint)
7724               b_tmp = b->related_breakpoint->next;
7725             delete_breakpoint (b->related_breakpoint);
7726           }
7727         delete_breakpoint (b);
7728       }
7729 }
7730
7731 void
7732 enable_overlay_breakpoints (void)
7733 {
7734   struct breakpoint *b;
7735
7736   ALL_BREAKPOINTS (b)
7737     if (b->type == bp_overlay_event)
7738     {
7739       b->enable_state = bp_enabled;
7740       update_global_location_list (UGLL_MAY_INSERT);
7741       overlay_events_enabled = 1;
7742     }
7743 }
7744
7745 void
7746 disable_overlay_breakpoints (void)
7747 {
7748   struct breakpoint *b;
7749
7750   ALL_BREAKPOINTS (b)
7751     if (b->type == bp_overlay_event)
7752     {
7753       b->enable_state = bp_disabled;
7754       update_global_location_list (UGLL_DONT_INSERT);
7755       overlay_events_enabled = 0;
7756     }
7757 }
7758
7759 /* Set an active std::terminate breakpoint for each std::terminate
7760    master breakpoint.  */
7761 void
7762 set_std_terminate_breakpoint (void)
7763 {
7764   struct breakpoint *b, *b_tmp;
7765
7766   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7767     if (b->pspace == current_program_space
7768         && b->type == bp_std_terminate_master)
7769       {
7770         momentary_breakpoint_from_master (b, bp_std_terminate,
7771                                           &momentary_breakpoint_ops, 1);
7772       }
7773 }
7774
7775 /* Delete all the std::terminate breakpoints.  */
7776 void
7777 delete_std_terminate_breakpoint (void)
7778 {
7779   struct breakpoint *b, *b_tmp;
7780
7781   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7782     if (b->type == bp_std_terminate)
7783       delete_breakpoint (b);
7784 }
7785
7786 struct breakpoint *
7787 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7788 {
7789   struct breakpoint *b;
7790
7791   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7792                                   &internal_breakpoint_ops);
7793
7794   b->enable_state = bp_enabled;
7795   /* location has to be used or breakpoint_re_set will delete me.  */
7796   b->location = new_address_location (b->loc->address, NULL, 0);
7797
7798   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7799
7800   return b;
7801 }
7802
7803 struct lang_and_radix
7804   {
7805     enum language lang;
7806     int radix;
7807   };
7808
7809 /* Create a breakpoint for JIT code registration and unregistration.  */
7810
7811 struct breakpoint *
7812 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7813 {
7814   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7815                                      &internal_breakpoint_ops);
7816 }
7817
7818 /* Remove JIT code registration and unregistration breakpoint(s).  */
7819
7820 void
7821 remove_jit_event_breakpoints (void)
7822 {
7823   struct breakpoint *b, *b_tmp;
7824
7825   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7826     if (b->type == bp_jit_event
7827         && b->loc->pspace == current_program_space)
7828       delete_breakpoint (b);
7829 }
7830
7831 void
7832 remove_solib_event_breakpoints (void)
7833 {
7834   struct breakpoint *b, *b_tmp;
7835
7836   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7837     if (b->type == bp_shlib_event
7838         && b->loc->pspace == current_program_space)
7839       delete_breakpoint (b);
7840 }
7841
7842 /* See breakpoint.h.  */
7843
7844 void
7845 remove_solib_event_breakpoints_at_next_stop (void)
7846 {
7847   struct breakpoint *b, *b_tmp;
7848
7849   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7850     if (b->type == bp_shlib_event
7851         && b->loc->pspace == current_program_space)
7852       b->disposition = disp_del_at_next_stop;
7853 }
7854
7855 /* Helper for create_solib_event_breakpoint /
7856    create_and_insert_solib_event_breakpoint.  Allows specifying which
7857    INSERT_MODE to pass through to update_global_location_list.  */
7858
7859 static struct breakpoint *
7860 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7861                                  enum ugll_insert_mode insert_mode)
7862 {
7863   struct breakpoint *b;
7864
7865   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7866                                   &internal_breakpoint_ops);
7867   update_global_location_list_nothrow (insert_mode);
7868   return b;
7869 }
7870
7871 struct breakpoint *
7872 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7873 {
7874   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7875 }
7876
7877 /* See breakpoint.h.  */
7878
7879 struct breakpoint *
7880 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7881 {
7882   struct breakpoint *b;
7883
7884   /* Explicitly tell update_global_location_list to insert
7885      locations.  */
7886   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7887   if (!b->loc->inserted)
7888     {
7889       delete_breakpoint (b);
7890       return NULL;
7891     }
7892   return b;
7893 }
7894
7895 /* Disable any breakpoints that are on code in shared libraries.  Only
7896    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7897
7898 void
7899 disable_breakpoints_in_shlibs (void)
7900 {
7901   struct bp_location *loc, **locp_tmp;
7902
7903   ALL_BP_LOCATIONS (loc, locp_tmp)
7904   {
7905     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7906     struct breakpoint *b = loc->owner;
7907
7908     /* We apply the check to all breakpoints, including disabled for
7909        those with loc->duplicate set.  This is so that when breakpoint
7910        becomes enabled, or the duplicate is removed, gdb will try to
7911        insert all breakpoints.  If we don't set shlib_disabled here,
7912        we'll try to insert those breakpoints and fail.  */
7913     if (((b->type == bp_breakpoint)
7914          || (b->type == bp_jit_event)
7915          || (b->type == bp_hardware_breakpoint)
7916          || (is_tracepoint (b)))
7917         && loc->pspace == current_program_space
7918         && !loc->shlib_disabled
7919         && solib_name_from_address (loc->pspace, loc->address)
7920         )
7921       {
7922         loc->shlib_disabled = 1;
7923       }
7924   }
7925 }
7926
7927 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7928    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7929    disabled ones can just stay disabled.  */
7930
7931 static void
7932 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7933 {
7934   struct bp_location *loc, **locp_tmp;
7935   int disabled_shlib_breaks = 0;
7936
7937   /* SunOS a.out shared libraries are always mapped, so do not
7938      disable breakpoints; they will only be reported as unloaded
7939      through clear_solib when GDB discards its shared library
7940      list.  See clear_solib for more information.  */
7941   if (exec_bfd != NULL
7942       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7943     return;
7944
7945   ALL_BP_LOCATIONS (loc, locp_tmp)
7946   {
7947     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7948     struct breakpoint *b = loc->owner;
7949
7950     if (solib->pspace == loc->pspace
7951         && !loc->shlib_disabled
7952         && (((b->type == bp_breakpoint
7953               || b->type == bp_jit_event
7954               || b->type == bp_hardware_breakpoint)
7955              && (loc->loc_type == bp_loc_hardware_breakpoint
7956                  || loc->loc_type == bp_loc_software_breakpoint))
7957             || is_tracepoint (b))
7958         && solib_contains_address_p (solib, loc->address))
7959       {
7960         loc->shlib_disabled = 1;
7961         /* At this point, we cannot rely on remove_breakpoint
7962            succeeding so we must mark the breakpoint as not inserted
7963            to prevent future errors occurring in remove_breakpoints.  */
7964         loc->inserted = 0;
7965
7966         /* This may cause duplicate notifications for the same breakpoint.  */
7967         observer_notify_breakpoint_modified (b);
7968
7969         if (!disabled_shlib_breaks)
7970           {
7971             target_terminal_ours_for_output ();
7972             warning (_("Temporarily disabling breakpoints "
7973                        "for unloaded shared library \"%s\""),
7974                      solib->so_name);
7975           }
7976         disabled_shlib_breaks = 1;
7977       }
7978   }
7979 }
7980
7981 /* Disable any breakpoints and tracepoints in OBJFILE upon
7982    notification of free_objfile.  Only apply to enabled breakpoints,
7983    disabled ones can just stay disabled.  */
7984
7985 static void
7986 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7987 {
7988   struct breakpoint *b;
7989
7990   if (objfile == NULL)
7991     return;
7992
7993   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7994      managed by the user with add-symbol-file/remove-symbol-file.
7995      Similarly to how breakpoints in shared libraries are handled in
7996      response to "nosharedlibrary", mark breakpoints in such modules
7997      shlib_disabled so they end up uninserted on the next global
7998      location list update.  Shared libraries not loaded by the user
7999      aren't handled here -- they're already handled in
8000      disable_breakpoints_in_unloaded_shlib, called by solib.c's
8001      solib_unloaded observer.  We skip objfiles that are not
8002      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
8003      main objfile).  */
8004   if ((objfile->flags & OBJF_SHARED) == 0
8005       || (objfile->flags & OBJF_USERLOADED) == 0)
8006     return;
8007
8008   ALL_BREAKPOINTS (b)
8009     {
8010       struct bp_location *loc;
8011       int bp_modified = 0;
8012
8013       if (!is_breakpoint (b) && !is_tracepoint (b))
8014         continue;
8015
8016       for (loc = b->loc; loc != NULL; loc = loc->next)
8017         {
8018           CORE_ADDR loc_addr = loc->address;
8019
8020           if (loc->loc_type != bp_loc_hardware_breakpoint
8021               && loc->loc_type != bp_loc_software_breakpoint)
8022             continue;
8023
8024           if (loc->shlib_disabled != 0)
8025             continue;
8026
8027           if (objfile->pspace != loc->pspace)
8028             continue;
8029
8030           if (loc->loc_type != bp_loc_hardware_breakpoint
8031               && loc->loc_type != bp_loc_software_breakpoint)
8032             continue;
8033
8034           if (is_addr_in_objfile (loc_addr, objfile))
8035             {
8036               loc->shlib_disabled = 1;
8037               /* At this point, we don't know whether the object was
8038                  unmapped from the inferior or not, so leave the
8039                  inserted flag alone.  We'll handle failure to
8040                  uninsert quietly, in case the object was indeed
8041                  unmapped.  */
8042
8043               mark_breakpoint_location_modified (loc);
8044
8045               bp_modified = 1;
8046             }
8047         }
8048
8049       if (bp_modified)
8050         observer_notify_breakpoint_modified (b);
8051     }
8052 }
8053
8054 /* FORK & VFORK catchpoints.  */
8055
8056 /* An instance of this type is used to represent a fork or vfork
8057    catchpoint.  It includes a "struct breakpoint" as a kind of base
8058    class; users downcast to "struct breakpoint *" when needed.  A
8059    breakpoint is really of this type iff its ops pointer points to
8060    CATCH_FORK_BREAKPOINT_OPS.  */
8061
8062 struct fork_catchpoint
8063 {
8064   /* The base class.  */
8065   struct breakpoint base;
8066
8067   /* Process id of a child process whose forking triggered this
8068      catchpoint.  This field is only valid immediately after this
8069      catchpoint has triggered.  */
8070   ptid_t forked_inferior_pid;
8071 };
8072
8073 /* Implement the "insert" breakpoint_ops method for fork
8074    catchpoints.  */
8075
8076 static int
8077 insert_catch_fork (struct bp_location *bl)
8078 {
8079   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
8080 }
8081
8082 /* Implement the "remove" breakpoint_ops method for fork
8083    catchpoints.  */
8084
8085 static int
8086 remove_catch_fork (struct bp_location *bl)
8087 {
8088   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
8089 }
8090
8091 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
8092    catchpoints.  */
8093
8094 static int
8095 breakpoint_hit_catch_fork (const struct bp_location *bl,
8096                            struct address_space *aspace, CORE_ADDR bp_addr,
8097                            const struct target_waitstatus *ws)
8098 {
8099   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8100
8101   if (ws->kind != TARGET_WAITKIND_FORKED)
8102     return 0;
8103
8104   c->forked_inferior_pid = ws->value.related_pid;
8105   return 1;
8106 }
8107
8108 /* Implement the "print_it" breakpoint_ops method for fork
8109    catchpoints.  */
8110
8111 static enum print_stop_action
8112 print_it_catch_fork (bpstat bs)
8113 {
8114   struct ui_out *uiout = current_uiout;
8115   struct breakpoint *b = bs->breakpoint_at;
8116   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8117
8118   annotate_catchpoint (b->number);
8119   maybe_print_thread_hit_breakpoint (uiout);
8120   if (b->disposition == disp_del)
8121     ui_out_text (uiout, "Temporary catchpoint ");
8122   else
8123     ui_out_text (uiout, "Catchpoint ");
8124   if (ui_out_is_mi_like_p (uiout))
8125     {
8126       ui_out_field_string (uiout, "reason",
8127                            async_reason_lookup (EXEC_ASYNC_FORK));
8128       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8129     }
8130   ui_out_field_int (uiout, "bkptno", b->number);
8131   ui_out_text (uiout, " (forked process ");
8132   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8133   ui_out_text (uiout, "), ");
8134   return PRINT_SRC_AND_LOC;
8135 }
8136
8137 /* Implement the "print_one" breakpoint_ops method for fork
8138    catchpoints.  */
8139
8140 static void
8141 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8142 {
8143   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8144   struct value_print_options opts;
8145   struct ui_out *uiout = current_uiout;
8146
8147   get_user_print_options (&opts);
8148
8149   /* Field 4, the address, is omitted (which makes the columns not
8150      line up too nicely with the headers, but the effect is relatively
8151      readable).  */
8152   if (opts.addressprint)
8153     ui_out_field_skip (uiout, "addr");
8154   annotate_field (5);
8155   ui_out_text (uiout, "fork");
8156   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8157     {
8158       ui_out_text (uiout, ", process ");
8159       ui_out_field_int (uiout, "what",
8160                         ptid_get_pid (c->forked_inferior_pid));
8161       ui_out_spaces (uiout, 1);
8162     }
8163
8164   if (ui_out_is_mi_like_p (uiout))
8165     ui_out_field_string (uiout, "catch-type", "fork");
8166 }
8167
8168 /* Implement the "print_mention" breakpoint_ops method for fork
8169    catchpoints.  */
8170
8171 static void
8172 print_mention_catch_fork (struct breakpoint *b)
8173 {
8174   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8175 }
8176
8177 /* Implement the "print_recreate" breakpoint_ops method for fork
8178    catchpoints.  */
8179
8180 static void
8181 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8182 {
8183   fprintf_unfiltered (fp, "catch fork");
8184   print_recreate_thread (b, fp);
8185 }
8186
8187 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8188
8189 static struct breakpoint_ops catch_fork_breakpoint_ops;
8190
8191 /* Implement the "insert" breakpoint_ops method for vfork
8192    catchpoints.  */
8193
8194 static int
8195 insert_catch_vfork (struct bp_location *bl)
8196 {
8197   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8198 }
8199
8200 /* Implement the "remove" breakpoint_ops method for vfork
8201    catchpoints.  */
8202
8203 static int
8204 remove_catch_vfork (struct bp_location *bl)
8205 {
8206   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8207 }
8208
8209 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8210    catchpoints.  */
8211
8212 static int
8213 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8214                             struct address_space *aspace, CORE_ADDR bp_addr,
8215                             const struct target_waitstatus *ws)
8216 {
8217   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8218
8219   if (ws->kind != TARGET_WAITKIND_VFORKED)
8220     return 0;
8221
8222   c->forked_inferior_pid = ws->value.related_pid;
8223   return 1;
8224 }
8225
8226 /* Implement the "print_it" breakpoint_ops method for vfork
8227    catchpoints.  */
8228
8229 static enum print_stop_action
8230 print_it_catch_vfork (bpstat bs)
8231 {
8232   struct ui_out *uiout = current_uiout;
8233   struct breakpoint *b = bs->breakpoint_at;
8234   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8235
8236   annotate_catchpoint (b->number);
8237   maybe_print_thread_hit_breakpoint (uiout);
8238   if (b->disposition == disp_del)
8239     ui_out_text (uiout, "Temporary catchpoint ");
8240   else
8241     ui_out_text (uiout, "Catchpoint ");
8242   if (ui_out_is_mi_like_p (uiout))
8243     {
8244       ui_out_field_string (uiout, "reason",
8245                            async_reason_lookup (EXEC_ASYNC_VFORK));
8246       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8247     }
8248   ui_out_field_int (uiout, "bkptno", b->number);
8249   ui_out_text (uiout, " (vforked process ");
8250   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8251   ui_out_text (uiout, "), ");
8252   return PRINT_SRC_AND_LOC;
8253 }
8254
8255 /* Implement the "print_one" breakpoint_ops method for vfork
8256    catchpoints.  */
8257
8258 static void
8259 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8260 {
8261   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8262   struct value_print_options opts;
8263   struct ui_out *uiout = current_uiout;
8264
8265   get_user_print_options (&opts);
8266   /* Field 4, the address, is omitted (which makes the columns not
8267      line up too nicely with the headers, but the effect is relatively
8268      readable).  */
8269   if (opts.addressprint)
8270     ui_out_field_skip (uiout, "addr");
8271   annotate_field (5);
8272   ui_out_text (uiout, "vfork");
8273   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8274     {
8275       ui_out_text (uiout, ", process ");
8276       ui_out_field_int (uiout, "what",
8277                         ptid_get_pid (c->forked_inferior_pid));
8278       ui_out_spaces (uiout, 1);
8279     }
8280
8281   if (ui_out_is_mi_like_p (uiout))
8282     ui_out_field_string (uiout, "catch-type", "vfork");
8283 }
8284
8285 /* Implement the "print_mention" breakpoint_ops method for vfork
8286    catchpoints.  */
8287
8288 static void
8289 print_mention_catch_vfork (struct breakpoint *b)
8290 {
8291   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8292 }
8293
8294 /* Implement the "print_recreate" breakpoint_ops method for vfork
8295    catchpoints.  */
8296
8297 static void
8298 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8299 {
8300   fprintf_unfiltered (fp, "catch vfork");
8301   print_recreate_thread (b, fp);
8302 }
8303
8304 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8305
8306 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8307
8308 /* An instance of this type is used to represent an solib catchpoint.
8309    It includes a "struct breakpoint" as a kind of base class; users
8310    downcast to "struct breakpoint *" when needed.  A breakpoint is
8311    really of this type iff its ops pointer points to
8312    CATCH_SOLIB_BREAKPOINT_OPS.  */
8313
8314 struct solib_catchpoint
8315 {
8316   /* The base class.  */
8317   struct breakpoint base;
8318
8319   /* True for "catch load", false for "catch unload".  */
8320   unsigned char is_load;
8321
8322   /* Regular expression to match, if any.  COMPILED is only valid when
8323      REGEX is non-NULL.  */
8324   char *regex;
8325   regex_t compiled;
8326 };
8327
8328 static void
8329 dtor_catch_solib (struct breakpoint *b)
8330 {
8331   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8332
8333   if (self->regex)
8334     regfree (&self->compiled);
8335   xfree (self->regex);
8336
8337   base_breakpoint_ops.dtor (b);
8338 }
8339
8340 static int
8341 insert_catch_solib (struct bp_location *ignore)
8342 {
8343   return 0;
8344 }
8345
8346 static int
8347 remove_catch_solib (struct bp_location *ignore)
8348 {
8349   return 0;
8350 }
8351
8352 static int
8353 breakpoint_hit_catch_solib (const struct bp_location *bl,
8354                             struct address_space *aspace,
8355                             CORE_ADDR bp_addr,
8356                             const struct target_waitstatus *ws)
8357 {
8358   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8359   struct breakpoint *other;
8360
8361   if (ws->kind == TARGET_WAITKIND_LOADED)
8362     return 1;
8363
8364   ALL_BREAKPOINTS (other)
8365   {
8366     struct bp_location *other_bl;
8367
8368     if (other == bl->owner)
8369       continue;
8370
8371     if (other->type != bp_shlib_event)
8372       continue;
8373
8374     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8375       continue;
8376
8377     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8378       {
8379         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8380           return 1;
8381       }
8382   }
8383
8384   return 0;
8385 }
8386
8387 static void
8388 check_status_catch_solib (struct bpstats *bs)
8389 {
8390   struct solib_catchpoint *self
8391     = (struct solib_catchpoint *) bs->breakpoint_at;
8392   int ix;
8393
8394   if (self->is_load)
8395     {
8396       struct so_list *iter;
8397
8398       for (ix = 0;
8399            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8400                         ix, iter);
8401            ++ix)
8402         {
8403           if (!self->regex
8404               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8405             return;
8406         }
8407     }
8408   else
8409     {
8410       char *iter;
8411
8412       for (ix = 0;
8413            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8414                         ix, iter);
8415            ++ix)
8416         {
8417           if (!self->regex
8418               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8419             return;
8420         }
8421     }
8422
8423   bs->stop = 0;
8424   bs->print_it = print_it_noop;
8425 }
8426
8427 static enum print_stop_action
8428 print_it_catch_solib (bpstat bs)
8429 {
8430   struct breakpoint *b = bs->breakpoint_at;
8431   struct ui_out *uiout = current_uiout;
8432
8433   annotate_catchpoint (b->number);
8434   maybe_print_thread_hit_breakpoint (uiout);
8435   if (b->disposition == disp_del)
8436     ui_out_text (uiout, "Temporary catchpoint ");
8437   else
8438     ui_out_text (uiout, "Catchpoint ");
8439   ui_out_field_int (uiout, "bkptno", b->number);
8440   ui_out_text (uiout, "\n");
8441   if (ui_out_is_mi_like_p (uiout))
8442     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8443   print_solib_event (1);
8444   return PRINT_SRC_AND_LOC;
8445 }
8446
8447 static void
8448 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8449 {
8450   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8451   struct value_print_options opts;
8452   struct ui_out *uiout = current_uiout;
8453   char *msg;
8454
8455   get_user_print_options (&opts);
8456   /* Field 4, the address, is omitted (which makes the columns not
8457      line up too nicely with the headers, but the effect is relatively
8458      readable).  */
8459   if (opts.addressprint)
8460     {
8461       annotate_field (4);
8462       ui_out_field_skip (uiout, "addr");
8463     }
8464
8465   annotate_field (5);
8466   if (self->is_load)
8467     {
8468       if (self->regex)
8469         msg = xstrprintf (_("load of library matching %s"), self->regex);
8470       else
8471         msg = xstrdup (_("load of library"));
8472     }
8473   else
8474     {
8475       if (self->regex)
8476         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8477       else
8478         msg = xstrdup (_("unload of library"));
8479     }
8480   ui_out_field_string (uiout, "what", msg);
8481   xfree (msg);
8482
8483   if (ui_out_is_mi_like_p (uiout))
8484     ui_out_field_string (uiout, "catch-type",
8485                          self->is_load ? "load" : "unload");
8486 }
8487
8488 static void
8489 print_mention_catch_solib (struct breakpoint *b)
8490 {
8491   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8492
8493   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8494                    self->is_load ? "load" : "unload");
8495 }
8496
8497 static void
8498 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8499 {
8500   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8501
8502   fprintf_unfiltered (fp, "%s %s",
8503                       b->disposition == disp_del ? "tcatch" : "catch",
8504                       self->is_load ? "load" : "unload");
8505   if (self->regex)
8506     fprintf_unfiltered (fp, " %s", self->regex);
8507   fprintf_unfiltered (fp, "\n");
8508 }
8509
8510 static struct breakpoint_ops catch_solib_breakpoint_ops;
8511
8512 /* Shared helper function (MI and CLI) for creating and installing
8513    a shared object event catchpoint.  If IS_LOAD is non-zero then
8514    the events to be caught are load events, otherwise they are
8515    unload events.  If IS_TEMP is non-zero the catchpoint is a
8516    temporary one.  If ENABLED is non-zero the catchpoint is
8517    created in an enabled state.  */
8518
8519 void
8520 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8521 {
8522   struct solib_catchpoint *c;
8523   struct gdbarch *gdbarch = get_current_arch ();
8524   struct cleanup *cleanup;
8525
8526   if (!arg)
8527     arg = "";
8528   arg = skip_spaces (arg);
8529
8530   c = XCNEW (struct solib_catchpoint);
8531   cleanup = make_cleanup (xfree, c);
8532
8533   if (*arg != '\0')
8534     {
8535       int errcode;
8536
8537       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8538       if (errcode != 0)
8539         {
8540           char *err = get_regcomp_error (errcode, &c->compiled);
8541
8542           make_cleanup (xfree, err);
8543           error (_("Invalid regexp (%s): %s"), err, arg);
8544         }
8545       c->regex = xstrdup (arg);
8546     }
8547
8548   c->is_load = is_load;
8549   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8550                    &catch_solib_breakpoint_ops);
8551
8552   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8553
8554   discard_cleanups (cleanup);
8555   install_breakpoint (0, &c->base, 1);
8556 }
8557
8558 /* A helper function that does all the work for "catch load" and
8559    "catch unload".  */
8560
8561 static void
8562 catch_load_or_unload (char *arg, int from_tty, int is_load,
8563                       struct cmd_list_element *command)
8564 {
8565   int tempflag;
8566   const int enabled = 1;
8567
8568   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8569
8570   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8571 }
8572
8573 static void
8574 catch_load_command_1 (char *arg, int from_tty,
8575                       struct cmd_list_element *command)
8576 {
8577   catch_load_or_unload (arg, from_tty, 1, command);
8578 }
8579
8580 static void
8581 catch_unload_command_1 (char *arg, int from_tty,
8582                         struct cmd_list_element *command)
8583 {
8584   catch_load_or_unload (arg, from_tty, 0, command);
8585 }
8586
8587 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8588    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8589    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8590    the breakpoint_ops structure associated to the catchpoint.  */
8591
8592 void
8593 init_catchpoint (struct breakpoint *b,
8594                  struct gdbarch *gdbarch, int tempflag,
8595                  char *cond_string,
8596                  const struct breakpoint_ops *ops)
8597 {
8598   struct symtab_and_line sal;
8599
8600   init_sal (&sal);
8601   sal.pspace = current_program_space;
8602
8603   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8604
8605   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8606   b->disposition = tempflag ? disp_del : disp_donttouch;
8607 }
8608
8609 void
8610 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8611 {
8612   add_to_breakpoint_chain (b);
8613   set_breakpoint_number (internal, b);
8614   if (is_tracepoint (b))
8615     set_tracepoint_count (breakpoint_count);
8616   if (!internal)
8617     mention (b);
8618   observer_notify_breakpoint_created (b);
8619
8620   if (update_gll)
8621     update_global_location_list (UGLL_MAY_INSERT);
8622 }
8623
8624 static void
8625 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8626                                     int tempflag, char *cond_string,
8627                                     const struct breakpoint_ops *ops)
8628 {
8629   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8630
8631   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8632
8633   c->forked_inferior_pid = null_ptid;
8634
8635   install_breakpoint (0, &c->base, 1);
8636 }
8637
8638 /* Exec catchpoints.  */
8639
8640 /* An instance of this type is used to represent an exec catchpoint.
8641    It includes a "struct breakpoint" as a kind of base class; users
8642    downcast to "struct breakpoint *" when needed.  A breakpoint is
8643    really of this type iff its ops pointer points to
8644    CATCH_EXEC_BREAKPOINT_OPS.  */
8645
8646 struct exec_catchpoint
8647 {
8648   /* The base class.  */
8649   struct breakpoint base;
8650
8651   /* Filename of a program whose exec triggered this catchpoint.
8652      This field is only valid immediately after this catchpoint has
8653      triggered.  */
8654   char *exec_pathname;
8655 };
8656
8657 /* Implement the "dtor" breakpoint_ops method for exec
8658    catchpoints.  */
8659
8660 static void
8661 dtor_catch_exec (struct breakpoint *b)
8662 {
8663   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8664
8665   xfree (c->exec_pathname);
8666
8667   base_breakpoint_ops.dtor (b);
8668 }
8669
8670 static int
8671 insert_catch_exec (struct bp_location *bl)
8672 {
8673   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8674 }
8675
8676 static int
8677 remove_catch_exec (struct bp_location *bl)
8678 {
8679   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8680 }
8681
8682 static int
8683 breakpoint_hit_catch_exec (const struct bp_location *bl,
8684                            struct address_space *aspace, CORE_ADDR bp_addr,
8685                            const struct target_waitstatus *ws)
8686 {
8687   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8688
8689   if (ws->kind != TARGET_WAITKIND_EXECD)
8690     return 0;
8691
8692   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8693   return 1;
8694 }
8695
8696 static enum print_stop_action
8697 print_it_catch_exec (bpstat bs)
8698 {
8699   struct ui_out *uiout = current_uiout;
8700   struct breakpoint *b = bs->breakpoint_at;
8701   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8702
8703   annotate_catchpoint (b->number);
8704   maybe_print_thread_hit_breakpoint (uiout);
8705   if (b->disposition == disp_del)
8706     ui_out_text (uiout, "Temporary catchpoint ");
8707   else
8708     ui_out_text (uiout, "Catchpoint ");
8709   if (ui_out_is_mi_like_p (uiout))
8710     {
8711       ui_out_field_string (uiout, "reason",
8712                            async_reason_lookup (EXEC_ASYNC_EXEC));
8713       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8714     }
8715   ui_out_field_int (uiout, "bkptno", b->number);
8716   ui_out_text (uiout, " (exec'd ");
8717   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8718   ui_out_text (uiout, "), ");
8719
8720   return PRINT_SRC_AND_LOC;
8721 }
8722
8723 static void
8724 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8725 {
8726   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8727   struct value_print_options opts;
8728   struct ui_out *uiout = current_uiout;
8729
8730   get_user_print_options (&opts);
8731
8732   /* Field 4, the address, is omitted (which makes the columns
8733      not line up too nicely with the headers, but the effect
8734      is relatively readable).  */
8735   if (opts.addressprint)
8736     ui_out_field_skip (uiout, "addr");
8737   annotate_field (5);
8738   ui_out_text (uiout, "exec");
8739   if (c->exec_pathname != NULL)
8740     {
8741       ui_out_text (uiout, ", program \"");
8742       ui_out_field_string (uiout, "what", c->exec_pathname);
8743       ui_out_text (uiout, "\" ");
8744     }
8745
8746   if (ui_out_is_mi_like_p (uiout))
8747     ui_out_field_string (uiout, "catch-type", "exec");
8748 }
8749
8750 static void
8751 print_mention_catch_exec (struct breakpoint *b)
8752 {
8753   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8754 }
8755
8756 /* Implement the "print_recreate" breakpoint_ops method for exec
8757    catchpoints.  */
8758
8759 static void
8760 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8761 {
8762   fprintf_unfiltered (fp, "catch exec");
8763   print_recreate_thread (b, fp);
8764 }
8765
8766 static struct breakpoint_ops catch_exec_breakpoint_ops;
8767
8768 static int
8769 hw_breakpoint_used_count (void)
8770 {
8771   int i = 0;
8772   struct breakpoint *b;
8773   struct bp_location *bl;
8774
8775   ALL_BREAKPOINTS (b)
8776   {
8777     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8778       for (bl = b->loc; bl; bl = bl->next)
8779         {
8780           /* Special types of hardware breakpoints may use more than
8781              one register.  */
8782           i += b->ops->resources_needed (bl);
8783         }
8784   }
8785
8786   return i;
8787 }
8788
8789 /* Returns the resources B would use if it were a hardware
8790    watchpoint.  */
8791
8792 static int
8793 hw_watchpoint_use_count (struct breakpoint *b)
8794 {
8795   int i = 0;
8796   struct bp_location *bl;
8797
8798   if (!breakpoint_enabled (b))
8799     return 0;
8800
8801   for (bl = b->loc; bl; bl = bl->next)
8802     {
8803       /* Special types of hardware watchpoints may use more than
8804          one register.  */
8805       i += b->ops->resources_needed (bl);
8806     }
8807
8808   return i;
8809 }
8810
8811 /* Returns the sum the used resources of all hardware watchpoints of
8812    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8813    the sum of the used resources of all hardware watchpoints of other
8814    types _not_ TYPE.  */
8815
8816 static int
8817 hw_watchpoint_used_count_others (struct breakpoint *except,
8818                                  enum bptype type, int *other_type_used)
8819 {
8820   int i = 0;
8821   struct breakpoint *b;
8822
8823   *other_type_used = 0;
8824   ALL_BREAKPOINTS (b)
8825     {
8826       if (b == except)
8827         continue;
8828       if (!breakpoint_enabled (b))
8829         continue;
8830
8831       if (b->type == type)
8832         i += hw_watchpoint_use_count (b);
8833       else if (is_hardware_watchpoint (b))
8834         *other_type_used = 1;
8835     }
8836
8837   return i;
8838 }
8839
8840 void
8841 disable_watchpoints_before_interactive_call_start (void)
8842 {
8843   struct breakpoint *b;
8844
8845   ALL_BREAKPOINTS (b)
8846   {
8847     if (is_watchpoint (b) && breakpoint_enabled (b))
8848       {
8849         b->enable_state = bp_call_disabled;
8850         update_global_location_list (UGLL_DONT_INSERT);
8851       }
8852   }
8853 }
8854
8855 void
8856 enable_watchpoints_after_interactive_call_stop (void)
8857 {
8858   struct breakpoint *b;
8859
8860   ALL_BREAKPOINTS (b)
8861   {
8862     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8863       {
8864         b->enable_state = bp_enabled;
8865         update_global_location_list (UGLL_MAY_INSERT);
8866       }
8867   }
8868 }
8869
8870 void
8871 disable_breakpoints_before_startup (void)
8872 {
8873   current_program_space->executing_startup = 1;
8874   update_global_location_list (UGLL_DONT_INSERT);
8875 }
8876
8877 void
8878 enable_breakpoints_after_startup (void)
8879 {
8880   current_program_space->executing_startup = 0;
8881   breakpoint_re_set ();
8882 }
8883
8884 /* Create a new single-step breakpoint for thread THREAD, with no
8885    locations.  */
8886
8887 static struct breakpoint *
8888 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8889 {
8890   struct breakpoint *b = XNEW (struct breakpoint);
8891
8892   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8893                                         &momentary_breakpoint_ops);
8894
8895   b->disposition = disp_donttouch;
8896   b->frame_id = null_frame_id;
8897
8898   b->thread = thread;
8899   gdb_assert (b->thread != 0);
8900
8901   add_to_breakpoint_chain (b);
8902
8903   return b;
8904 }
8905
8906 /* Set a momentary breakpoint of type TYPE at address specified by
8907    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8908    frame.  */
8909
8910 struct breakpoint *
8911 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8912                           struct frame_id frame_id, enum bptype type)
8913 {
8914   struct breakpoint *b;
8915
8916   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8917      tail-called one.  */
8918   gdb_assert (!frame_id_artificial_p (frame_id));
8919
8920   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8921   b->enable_state = bp_enabled;
8922   b->disposition = disp_donttouch;
8923   b->frame_id = frame_id;
8924
8925   /* If we're debugging a multi-threaded program, then we want
8926      momentary breakpoints to be active in only a single thread of
8927      control.  */
8928   if (in_thread_list (inferior_ptid))
8929     b->thread = ptid_to_global_thread_id (inferior_ptid);
8930
8931   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8932
8933   return b;
8934 }
8935
8936 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8937    The new breakpoint will have type TYPE, use OPS as its
8938    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8939
8940 static struct breakpoint *
8941 momentary_breakpoint_from_master (struct breakpoint *orig,
8942                                   enum bptype type,
8943                                   const struct breakpoint_ops *ops,
8944                                   int loc_enabled)
8945 {
8946   struct breakpoint *copy;
8947
8948   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8949   copy->loc = allocate_bp_location (copy);
8950   set_breakpoint_location_function (copy->loc, 1);
8951
8952   copy->loc->gdbarch = orig->loc->gdbarch;
8953   copy->loc->requested_address = orig->loc->requested_address;
8954   copy->loc->address = orig->loc->address;
8955   copy->loc->section = orig->loc->section;
8956   copy->loc->pspace = orig->loc->pspace;
8957   copy->loc->probe = orig->loc->probe;
8958   copy->loc->line_number = orig->loc->line_number;
8959   copy->loc->symtab = orig->loc->symtab;
8960   copy->loc->enabled = loc_enabled;
8961   copy->frame_id = orig->frame_id;
8962   copy->thread = orig->thread;
8963   copy->pspace = orig->pspace;
8964
8965   copy->enable_state = bp_enabled;
8966   copy->disposition = disp_donttouch;
8967   copy->number = internal_breakpoint_number--;
8968
8969   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8970   return copy;
8971 }
8972
8973 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8974    ORIG is NULL.  */
8975
8976 struct breakpoint *
8977 clone_momentary_breakpoint (struct breakpoint *orig)
8978 {
8979   /* If there's nothing to clone, then return nothing.  */
8980   if (orig == NULL)
8981     return NULL;
8982
8983   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8984 }
8985
8986 struct breakpoint *
8987 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8988                                 enum bptype type)
8989 {
8990   struct symtab_and_line sal;
8991
8992   sal = find_pc_line (pc, 0);
8993   sal.pc = pc;
8994   sal.section = find_pc_overlay (pc);
8995   sal.explicit_pc = 1;
8996
8997   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8998 }
8999 \f
9000
9001 /* Tell the user we have just set a breakpoint B.  */
9002
9003 static void
9004 mention (struct breakpoint *b)
9005 {
9006   b->ops->print_mention (b);
9007   if (ui_out_is_mi_like_p (current_uiout))
9008     return;
9009   printf_filtered ("\n");
9010 }
9011 \f
9012
9013 static int bp_loc_is_permanent (struct bp_location *loc);
9014
9015 static struct bp_location *
9016 add_location_to_breakpoint (struct breakpoint *b,
9017                             const struct symtab_and_line *sal)
9018 {
9019   struct bp_location *loc, **tmp;
9020   CORE_ADDR adjusted_address;
9021   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9022
9023   if (loc_gdbarch == NULL)
9024     loc_gdbarch = b->gdbarch;
9025
9026   /* Adjust the breakpoint's address prior to allocating a location.
9027      Once we call allocate_bp_location(), that mostly uninitialized
9028      location will be placed on the location chain.  Adjustment of the
9029      breakpoint may cause target_read_memory() to be called and we do
9030      not want its scan of the location chain to find a breakpoint and
9031      location that's only been partially initialized.  */
9032   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9033                                                 sal->pc, b->type);
9034
9035   /* Sort the locations by their ADDRESS.  */
9036   loc = allocate_bp_location (b);
9037   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9038        tmp = &((*tmp)->next))
9039     ;
9040   loc->next = *tmp;
9041   *tmp = loc;
9042
9043   loc->requested_address = sal->pc;
9044   loc->address = adjusted_address;
9045   loc->pspace = sal->pspace;
9046   loc->probe.probe = sal->probe;
9047   loc->probe.objfile = sal->objfile;
9048   gdb_assert (loc->pspace != NULL);
9049   loc->section = sal->section;
9050   loc->gdbarch = loc_gdbarch;
9051   loc->line_number = sal->line;
9052   loc->symtab = sal->symtab;
9053
9054   set_breakpoint_location_function (loc,
9055                                     sal->explicit_pc || sal->explicit_line);
9056
9057   /* While by definition, permanent breakpoints are already present in the
9058      code, we don't mark the location as inserted.  Normally one would expect
9059      that GDB could rely on that breakpoint instruction to stop the program,
9060      thus removing the need to insert its own breakpoint, except that executing
9061      the breakpoint instruction can kill the target instead of reporting a
9062      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
9063      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
9064      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
9065      breakpoint be inserted normally results in QEMU knowing about the GDB
9066      breakpoint, and thus trap before the breakpoint instruction is executed.
9067      (If GDB later needs to continue execution past the permanent breakpoint,
9068      it manually increments the PC, thus avoiding executing the breakpoint
9069      instruction.)  */
9070   if (bp_loc_is_permanent (loc))
9071     loc->permanent = 1;
9072
9073   return loc;
9074 }
9075 \f
9076
9077 /* See breakpoint.h.  */
9078
9079 int
9080 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9081 {
9082   int len;
9083   CORE_ADDR addr;
9084   const gdb_byte *bpoint;
9085   gdb_byte *target_mem;
9086   struct cleanup *cleanup;
9087   int retval = 0;
9088
9089   addr = address;
9090   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9091
9092   /* Software breakpoints unsupported?  */
9093   if (bpoint == NULL)
9094     return 0;
9095
9096   target_mem = (gdb_byte *) alloca (len);
9097
9098   /* Enable the automatic memory restoration from breakpoints while
9099      we read the memory.  Otherwise we could say about our temporary
9100      breakpoints they are permanent.  */
9101   cleanup = make_show_memory_breakpoints_cleanup (0);
9102
9103   if (target_read_memory (address, target_mem, len) == 0
9104       && memcmp (target_mem, bpoint, len) == 0)
9105     retval = 1;
9106
9107   do_cleanups (cleanup);
9108
9109   return retval;
9110 }
9111
9112 /* Return 1 if LOC is pointing to a permanent breakpoint,
9113    return 0 otherwise.  */
9114
9115 static int
9116 bp_loc_is_permanent (struct bp_location *loc)
9117 {
9118   struct cleanup *cleanup;
9119   int retval;
9120
9121   gdb_assert (loc != NULL);
9122
9123   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9124      attempt to read from the addresses the locations of these breakpoint types
9125      point to.  program_breakpoint_here_p, below, will attempt to read
9126      memory.  */
9127   if (!breakpoint_address_is_meaningful (loc->owner))
9128     return 0;
9129
9130   cleanup = save_current_space_and_thread ();
9131   switch_to_program_space_and_thread (loc->pspace);
9132
9133   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9134
9135   do_cleanups (cleanup);
9136
9137   return retval;
9138 }
9139
9140 /* Build a command list for the dprintf corresponding to the current
9141    settings of the dprintf style options.  */
9142
9143 static void
9144 update_dprintf_command_list (struct breakpoint *b)
9145 {
9146   char *dprintf_args = b->extra_string;
9147   char *printf_line = NULL;
9148
9149   if (!dprintf_args)
9150     return;
9151
9152   dprintf_args = skip_spaces (dprintf_args);
9153
9154   /* Allow a comma, as it may have terminated a location, but don't
9155      insist on it.  */
9156   if (*dprintf_args == ',')
9157     ++dprintf_args;
9158   dprintf_args = skip_spaces (dprintf_args);
9159
9160   if (*dprintf_args != '"')
9161     error (_("Bad format string, missing '\"'."));
9162
9163   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9164     printf_line = xstrprintf ("printf %s", dprintf_args);
9165   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9166     {
9167       if (!dprintf_function)
9168         error (_("No function supplied for dprintf call"));
9169
9170       if (dprintf_channel && strlen (dprintf_channel) > 0)
9171         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9172                                   dprintf_function,
9173                                   dprintf_channel,
9174                                   dprintf_args);
9175       else
9176         printf_line = xstrprintf ("call (void) %s (%s)",
9177                                   dprintf_function,
9178                                   dprintf_args);
9179     }
9180   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9181     {
9182       if (target_can_run_breakpoint_commands ())
9183         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9184       else
9185         {
9186           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9187           printf_line = xstrprintf ("printf %s", dprintf_args);
9188         }
9189     }
9190   else
9191     internal_error (__FILE__, __LINE__,
9192                     _("Invalid dprintf style."));
9193
9194   gdb_assert (printf_line != NULL);
9195   /* Manufacture a printf sequence.  */
9196   {
9197     struct command_line *printf_cmd_line = XNEW (struct command_line);
9198
9199     printf_cmd_line->control_type = simple_control;
9200     printf_cmd_line->body_count = 0;
9201     printf_cmd_line->body_list = NULL;
9202     printf_cmd_line->next = NULL;
9203     printf_cmd_line->line = printf_line;
9204
9205     breakpoint_set_commands (b, printf_cmd_line);
9206   }
9207 }
9208
9209 /* Update all dprintf commands, making their command lists reflect
9210    current style settings.  */
9211
9212 static void
9213 update_dprintf_commands (char *args, int from_tty,
9214                          struct cmd_list_element *c)
9215 {
9216   struct breakpoint *b;
9217
9218   ALL_BREAKPOINTS (b)
9219     {
9220       if (b->type == bp_dprintf)
9221         update_dprintf_command_list (b);
9222     }
9223 }
9224
9225 /* Create a breakpoint with SAL as location.  Use LOCATION
9226    as a description of the location, and COND_STRING
9227    as condition expression.  If LOCATION is NULL then create an
9228    "address location" from the address in the SAL.  */
9229
9230 static void
9231 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9232                      struct symtabs_and_lines sals,
9233                      struct event_location *location,
9234                      char *filter, char *cond_string,
9235                      char *extra_string,
9236                      enum bptype type, enum bpdisp disposition,
9237                      int thread, int task, int ignore_count,
9238                      const struct breakpoint_ops *ops, int from_tty,
9239                      int enabled, int internal, unsigned flags,
9240                      int display_canonical)
9241 {
9242   int i;
9243
9244   if (type == bp_hardware_breakpoint)
9245     {
9246       int target_resources_ok;
9247
9248       i = hw_breakpoint_used_count ();
9249       target_resources_ok =
9250         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9251                                             i + 1, 0);
9252       if (target_resources_ok == 0)
9253         error (_("No hardware breakpoint support in the target."));
9254       else if (target_resources_ok < 0)
9255         error (_("Hardware breakpoints used exceeds limit."));
9256     }
9257
9258   gdb_assert (sals.nelts > 0);
9259
9260   for (i = 0; i < sals.nelts; ++i)
9261     {
9262       struct symtab_and_line sal = sals.sals[i];
9263       struct bp_location *loc;
9264
9265       if (from_tty)
9266         {
9267           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9268           if (!loc_gdbarch)
9269             loc_gdbarch = gdbarch;
9270
9271           describe_other_breakpoints (loc_gdbarch,
9272                                       sal.pspace, sal.pc, sal.section, thread);
9273         }
9274
9275       if (i == 0)
9276         {
9277           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9278           b->thread = thread;
9279           b->task = task;
9280
9281           b->cond_string = cond_string;
9282           b->extra_string = extra_string;
9283           b->ignore_count = ignore_count;
9284           b->enable_state = enabled ? bp_enabled : bp_disabled;
9285           b->disposition = disposition;
9286
9287           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9288             b->loc->inserted = 1;
9289
9290           if (type == bp_static_tracepoint)
9291             {
9292               struct tracepoint *t = (struct tracepoint *) b;
9293               struct static_tracepoint_marker marker;
9294
9295               if (strace_marker_p (b))
9296                 {
9297                   /* We already know the marker exists, otherwise, we
9298                      wouldn't see a sal for it.  */
9299                   const char *p = &event_location_to_string (b->location)[3];
9300                   const char *endp;
9301                   char *marker_str;
9302
9303                   p = skip_spaces_const (p);
9304
9305                   endp = skip_to_space_const (p);
9306
9307                   marker_str = savestring (p, endp - p);
9308                   t->static_trace_marker_id = marker_str;
9309
9310                   printf_filtered (_("Probed static tracepoint "
9311                                      "marker \"%s\"\n"),
9312                                    t->static_trace_marker_id);
9313                 }
9314               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9315                 {
9316                   t->static_trace_marker_id = xstrdup (marker.str_id);
9317                   release_static_tracepoint_marker (&marker);
9318
9319                   printf_filtered (_("Probed static tracepoint "
9320                                      "marker \"%s\"\n"),
9321                                    t->static_trace_marker_id);
9322                 }
9323               else
9324                 warning (_("Couldn't determine the static "
9325                            "tracepoint marker to probe"));
9326             }
9327
9328           loc = b->loc;
9329         }
9330       else
9331         {
9332           loc = add_location_to_breakpoint (b, &sal);
9333           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9334             loc->inserted = 1;
9335         }
9336
9337       if (b->cond_string)
9338         {
9339           const char *arg = b->cond_string;
9340
9341           loc->cond = parse_exp_1 (&arg, loc->address,
9342                                    block_for_pc (loc->address), 0);
9343           if (*arg)
9344               error (_("Garbage '%s' follows condition"), arg);
9345         }
9346
9347       /* Dynamic printf requires and uses additional arguments on the
9348          command line, otherwise it's an error.  */
9349       if (type == bp_dprintf)
9350         {
9351           if (b->extra_string)
9352             update_dprintf_command_list (b);
9353           else
9354             error (_("Format string required"));
9355         }
9356       else if (b->extra_string)
9357         error (_("Garbage '%s' at end of command"), b->extra_string);
9358     }
9359
9360   b->display_canonical = display_canonical;
9361   if (location != NULL)
9362     b->location = location;
9363   else
9364     {
9365       const char *addr_string = NULL;
9366       int addr_string_len = 0;
9367
9368       if (location != NULL)
9369         addr_string = event_location_to_string (location);
9370       if (addr_string != NULL)
9371         addr_string_len = strlen (addr_string);
9372
9373       b->location = new_address_location (b->loc->address,
9374                                           addr_string, addr_string_len);
9375     }
9376   b->filter = filter;
9377 }
9378
9379 static void
9380 create_breakpoint_sal (struct gdbarch *gdbarch,
9381                        struct symtabs_and_lines sals,
9382                        struct event_location *location,
9383                        char *filter, char *cond_string,
9384                        char *extra_string,
9385                        enum bptype type, enum bpdisp disposition,
9386                        int thread, int task, int ignore_count,
9387                        const struct breakpoint_ops *ops, int from_tty,
9388                        int enabled, int internal, unsigned flags,
9389                        int display_canonical)
9390 {
9391   struct breakpoint *b;
9392   struct cleanup *old_chain;
9393
9394   if (is_tracepoint_type (type))
9395     {
9396       struct tracepoint *t;
9397
9398       t = XCNEW (struct tracepoint);
9399       b = &t->base;
9400     }
9401   else
9402     b = XNEW (struct breakpoint);
9403
9404   old_chain = make_cleanup (xfree, b);
9405
9406   init_breakpoint_sal (b, gdbarch,
9407                        sals, location,
9408                        filter, cond_string, extra_string,
9409                        type, disposition,
9410                        thread, task, ignore_count,
9411                        ops, from_tty,
9412                        enabled, internal, flags,
9413                        display_canonical);
9414   discard_cleanups (old_chain);
9415
9416   install_breakpoint (internal, b, 0);
9417 }
9418
9419 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9420    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9421    value.  COND_STRING, if not NULL, specified the condition to be
9422    used for all breakpoints.  Essentially the only case where
9423    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9424    function.  In that case, it's still not possible to specify
9425    separate conditions for different overloaded functions, so
9426    we take just a single condition string.
9427    
9428    NOTE: If the function succeeds, the caller is expected to cleanup
9429    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9430    array contents).  If the function fails (error() is called), the
9431    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9432    COND and SALS arrays and each of those arrays contents.  */
9433
9434 static void
9435 create_breakpoints_sal (struct gdbarch *gdbarch,
9436                         struct linespec_result *canonical,
9437                         char *cond_string, char *extra_string,
9438                         enum bptype type, enum bpdisp disposition,
9439                         int thread, int task, int ignore_count,
9440                         const struct breakpoint_ops *ops, int from_tty,
9441                         int enabled, int internal, unsigned flags)
9442 {
9443   int i;
9444   struct linespec_sals *lsal;
9445
9446   if (canonical->pre_expanded)
9447     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9448
9449   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9450     {
9451       /* Note that 'location' can be NULL in the case of a plain
9452          'break', without arguments.  */
9453       struct event_location *location
9454         = (canonical->location != NULL
9455            ? copy_event_location (canonical->location) : NULL);
9456       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9457       struct cleanup *inner = make_cleanup_delete_event_location (location);
9458
9459       make_cleanup (xfree, filter_string);
9460       create_breakpoint_sal (gdbarch, lsal->sals,
9461                              location,
9462                              filter_string,
9463                              cond_string, extra_string,
9464                              type, disposition,
9465                              thread, task, ignore_count, ops,
9466                              from_tty, enabled, internal, flags,
9467                              canonical->special_display);
9468       discard_cleanups (inner);
9469     }
9470 }
9471
9472 /* Parse LOCATION which is assumed to be a SAL specification possibly
9473    followed by conditionals.  On return, SALS contains an array of SAL
9474    addresses found.  LOCATION points to the end of the SAL (for
9475    linespec locations).
9476
9477    The array and the line spec strings are allocated on the heap, it is
9478    the caller's responsibility to free them.  */
9479
9480 static void
9481 parse_breakpoint_sals (const struct event_location *location,
9482                        struct linespec_result *canonical)
9483 {
9484   struct symtab_and_line cursal;
9485
9486   if (event_location_type (location) == LINESPEC_LOCATION)
9487     {
9488       const char *address = get_linespec_location (location);
9489
9490       if (address == NULL)
9491         {
9492           /* The last displayed codepoint, if it's valid, is our default
9493              breakpoint address.  */
9494           if (last_displayed_sal_is_valid ())
9495             {
9496               struct linespec_sals lsal;
9497               struct symtab_and_line sal;
9498               CORE_ADDR pc;
9499
9500               init_sal (&sal);          /* Initialize to zeroes.  */
9501               lsal.sals.sals = XNEW (struct symtab_and_line);
9502
9503               /* Set sal's pspace, pc, symtab, and line to the values
9504                  corresponding to the last call to print_frame_info.
9505                  Be sure to reinitialize LINE with NOTCURRENT == 0
9506                  as the breakpoint line number is inappropriate otherwise.
9507                  find_pc_line would adjust PC, re-set it back.  */
9508               get_last_displayed_sal (&sal);
9509               pc = sal.pc;
9510               sal = find_pc_line (pc, 0);
9511
9512               /* "break" without arguments is equivalent to "break *PC"
9513                  where PC is the last displayed codepoint's address.  So
9514                  make sure to set sal.explicit_pc to prevent GDB from
9515                  trying to expand the list of sals to include all other
9516                  instances with the same symtab and line.  */
9517               sal.pc = pc;
9518               sal.explicit_pc = 1;
9519
9520               lsal.sals.sals[0] = sal;
9521               lsal.sals.nelts = 1;
9522               lsal.canonical = NULL;
9523
9524               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9525               return;
9526             }
9527           else
9528             error (_("No default breakpoint address now."));
9529         }
9530     }
9531
9532   /* Force almost all breakpoints to be in terms of the
9533      current_source_symtab (which is decode_line_1's default).
9534      This should produce the results we want almost all of the
9535      time while leaving default_breakpoint_* alone.
9536
9537      ObjC: However, don't match an Objective-C method name which
9538      may have a '+' or '-' succeeded by a '['.  */
9539   cursal = get_current_source_symtab_and_line ();
9540   if (last_displayed_sal_is_valid ())
9541     {
9542       const char *address = NULL;
9543
9544       if (event_location_type (location) == LINESPEC_LOCATION)
9545         address = get_linespec_location (location);
9546
9547       if (!cursal.symtab
9548           || (address != NULL
9549               && strchr ("+-", address[0]) != NULL
9550               && address[1] != '['))
9551         {
9552           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9553                             get_last_displayed_symtab (),
9554                             get_last_displayed_line (),
9555                             canonical, NULL, NULL);
9556           return;
9557         }
9558     }
9559
9560   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9561                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9562 }
9563
9564
9565 /* Convert each SAL into a real PC.  Verify that the PC can be
9566    inserted as a breakpoint.  If it can't throw an error.  */
9567
9568 static void
9569 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9570 {    
9571   int i;
9572
9573   for (i = 0; i < sals->nelts; i++)
9574     resolve_sal_pc (&sals->sals[i]);
9575 }
9576
9577 /* Fast tracepoints may have restrictions on valid locations.  For
9578    instance, a fast tracepoint using a jump instead of a trap will
9579    likely have to overwrite more bytes than a trap would, and so can
9580    only be placed where the instruction is longer than the jump, or a
9581    multi-instruction sequence does not have a jump into the middle of
9582    it, etc.  */
9583
9584 static void
9585 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9586                             struct symtabs_and_lines *sals)
9587 {
9588   int i, rslt;
9589   struct symtab_and_line *sal;
9590   char *msg;
9591   struct cleanup *old_chain;
9592
9593   for (i = 0; i < sals->nelts; i++)
9594     {
9595       struct gdbarch *sarch;
9596
9597       sal = &sals->sals[i];
9598
9599       sarch = get_sal_arch (*sal);
9600       /* We fall back to GDBARCH if there is no architecture
9601          associated with SAL.  */
9602       if (sarch == NULL)
9603         sarch = gdbarch;
9604       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9605       old_chain = make_cleanup (xfree, msg);
9606
9607       if (!rslt)
9608         error (_("May not have a fast tracepoint at 0x%s%s"),
9609                paddress (sarch, sal->pc), (msg ? msg : ""));
9610
9611       do_cleanups (old_chain);
9612     }
9613 }
9614
9615 /* Given TOK, a string specification of condition and thread, as
9616    accepted by the 'break' command, extract the condition
9617    string and thread number and set *COND_STRING and *THREAD.
9618    PC identifies the context at which the condition should be parsed.
9619    If no condition is found, *COND_STRING is set to NULL.
9620    If no thread is found, *THREAD is set to -1.  */
9621
9622 static void
9623 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9624                            char **cond_string, int *thread, int *task,
9625                            char **rest)
9626 {
9627   *cond_string = NULL;
9628   *thread = -1;
9629   *task = 0;
9630   *rest = NULL;
9631
9632   while (tok && *tok)
9633     {
9634       const char *end_tok;
9635       int toklen;
9636       const char *cond_start = NULL;
9637       const char *cond_end = NULL;
9638
9639       tok = skip_spaces_const (tok);
9640
9641       if ((*tok == '"' || *tok == ',') && rest)
9642         {
9643           *rest = savestring (tok, strlen (tok));
9644           return;
9645         }
9646
9647       end_tok = skip_to_space_const (tok);
9648
9649       toklen = end_tok - tok;
9650
9651       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9652         {
9653           struct expression *expr;
9654
9655           tok = cond_start = end_tok + 1;
9656           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9657           xfree (expr);
9658           cond_end = tok;
9659           *cond_string = savestring (cond_start, cond_end - cond_start);
9660         }
9661       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9662         {
9663           const char *tmptok;
9664           struct thread_info *thr;
9665
9666           tok = end_tok + 1;
9667           thr = parse_thread_id (tok, &tmptok);
9668           if (tok == tmptok)
9669             error (_("Junk after thread keyword."));
9670           *thread = thr->global_num;
9671           tok = tmptok;
9672         }
9673       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9674         {
9675           char *tmptok;
9676
9677           tok = end_tok + 1;
9678           *task = strtol (tok, &tmptok, 0);
9679           if (tok == tmptok)
9680             error (_("Junk after task keyword."));
9681           if (!valid_task_id (*task))
9682             error (_("Unknown task %d."), *task);
9683           tok = tmptok;
9684         }
9685       else if (rest)
9686         {
9687           *rest = savestring (tok, strlen (tok));
9688           return;
9689         }
9690       else
9691         error (_("Junk at end of arguments."));
9692     }
9693 }
9694
9695 /* Decode a static tracepoint marker spec.  */
9696
9697 static struct symtabs_and_lines
9698 decode_static_tracepoint_spec (const char **arg_p)
9699 {
9700   VEC(static_tracepoint_marker_p) *markers = NULL;
9701   struct symtabs_and_lines sals;
9702   struct cleanup *old_chain;
9703   const char *p = &(*arg_p)[3];
9704   const char *endp;
9705   char *marker_str;
9706   int i;
9707
9708   p = skip_spaces_const (p);
9709
9710   endp = skip_to_space_const (p);
9711
9712   marker_str = savestring (p, endp - p);
9713   old_chain = make_cleanup (xfree, marker_str);
9714
9715   markers = target_static_tracepoint_markers_by_strid (marker_str);
9716   if (VEC_empty(static_tracepoint_marker_p, markers))
9717     error (_("No known static tracepoint marker named %s"), marker_str);
9718
9719   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9720   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9721
9722   for (i = 0; i < sals.nelts; i++)
9723     {
9724       struct static_tracepoint_marker *marker;
9725
9726       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9727
9728       init_sal (&sals.sals[i]);
9729
9730       sals.sals[i] = find_pc_line (marker->address, 0);
9731       sals.sals[i].pc = marker->address;
9732
9733       release_static_tracepoint_marker (marker);
9734     }
9735
9736   do_cleanups (old_chain);
9737
9738   *arg_p = endp;
9739   return sals;
9740 }
9741
9742 /* See breakpoint.h.  */
9743
9744 int
9745 create_breakpoint (struct gdbarch *gdbarch,
9746                    const struct event_location *location, char *cond_string,
9747                    int thread, char *extra_string,
9748                    int parse_extra,
9749                    int tempflag, enum bptype type_wanted,
9750                    int ignore_count,
9751                    enum auto_boolean pending_break_support,
9752                    const struct breakpoint_ops *ops,
9753                    int from_tty, int enabled, int internal,
9754                    unsigned flags)
9755 {
9756   struct linespec_result canonical;
9757   struct cleanup *old_chain;
9758   struct cleanup *bkpt_chain = NULL;
9759   int pending = 0;
9760   int task = 0;
9761   int prev_bkpt_count = breakpoint_count;
9762
9763   gdb_assert (ops != NULL);
9764
9765   /* If extra_string isn't useful, set it to NULL.  */
9766   if (extra_string != NULL && *extra_string == '\0')
9767     extra_string = NULL;
9768
9769   init_linespec_result (&canonical);
9770
9771   TRY
9772     {
9773       ops->create_sals_from_location (location, &canonical, type_wanted);
9774     }
9775   CATCH (e, RETURN_MASK_ERROR)
9776     {
9777       /* If caller is interested in rc value from parse, set
9778          value.  */
9779       if (e.error == NOT_FOUND_ERROR)
9780         {
9781           /* If pending breakpoint support is turned off, throw
9782              error.  */
9783
9784           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9785             throw_exception (e);
9786
9787           exception_print (gdb_stderr, e);
9788
9789           /* If pending breakpoint support is auto query and the user
9790              selects no, then simply return the error code.  */
9791           if (pending_break_support == AUTO_BOOLEAN_AUTO
9792               && !nquery (_("Make %s pending on future shared library load? "),
9793                           bptype_string (type_wanted)))
9794             return 0;
9795
9796           /* At this point, either the user was queried about setting
9797              a pending breakpoint and selected yes, or pending
9798              breakpoint behavior is on and thus a pending breakpoint
9799              is defaulted on behalf of the user.  */
9800           pending = 1;
9801         }
9802       else
9803         throw_exception (e);
9804     }
9805   END_CATCH
9806
9807   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9808     return 0;
9809
9810   /* Create a chain of things that always need to be cleaned up.  */
9811   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9812
9813   /* ----------------------------- SNIP -----------------------------
9814      Anything added to the cleanup chain beyond this point is assumed
9815      to be part of a breakpoint.  If the breakpoint create succeeds
9816      then the memory is not reclaimed.  */
9817   bkpt_chain = make_cleanup (null_cleanup, 0);
9818
9819   /* Resolve all line numbers to PC's and verify that the addresses
9820      are ok for the target.  */
9821   if (!pending)
9822     {
9823       int ix;
9824       struct linespec_sals *iter;
9825
9826       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9827         breakpoint_sals_to_pc (&iter->sals);
9828     }
9829
9830   /* Fast tracepoints may have additional restrictions on location.  */
9831   if (!pending && type_wanted == bp_fast_tracepoint)
9832     {
9833       int ix;
9834       struct linespec_sals *iter;
9835
9836       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9837         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9838     }
9839
9840   /* Verify that condition can be parsed, before setting any
9841      breakpoints.  Allocate a separate condition expression for each
9842      breakpoint.  */
9843   if (!pending)
9844     {
9845       if (parse_extra)
9846         {
9847           char *rest;
9848           struct linespec_sals *lsal;
9849
9850           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9851
9852           /* Here we only parse 'arg' to separate condition
9853              from thread number, so parsing in context of first
9854              sal is OK.  When setting the breakpoint we'll
9855              re-parse it in context of each sal.  */
9856
9857           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9858                                      &cond_string, &thread, &task, &rest);
9859           if (cond_string)
9860             make_cleanup (xfree, cond_string);
9861           if (rest)
9862             make_cleanup (xfree, rest);
9863           if (rest)
9864             extra_string = rest;
9865           else
9866             extra_string = NULL;
9867         }
9868       else
9869         {
9870           if (type_wanted != bp_dprintf
9871               && extra_string != NULL && *extra_string != '\0')
9872                 error (_("Garbage '%s' at end of location"), extra_string);
9873
9874           /* Create a private copy of condition string.  */
9875           if (cond_string)
9876             {
9877               cond_string = xstrdup (cond_string);
9878               make_cleanup (xfree, cond_string);
9879             }
9880           /* Create a private copy of any extra string.  */
9881           if (extra_string)
9882             {
9883               extra_string = xstrdup (extra_string);
9884               make_cleanup (xfree, extra_string);
9885             }
9886         }
9887
9888       ops->create_breakpoints_sal (gdbarch, &canonical,
9889                                    cond_string, extra_string, type_wanted,
9890                                    tempflag ? disp_del : disp_donttouch,
9891                                    thread, task, ignore_count, ops,
9892                                    from_tty, enabled, internal, flags);
9893     }
9894   else
9895     {
9896       struct breakpoint *b;
9897
9898       if (is_tracepoint_type (type_wanted))
9899         {
9900           struct tracepoint *t;
9901
9902           t = XCNEW (struct tracepoint);
9903           b = &t->base;
9904         }
9905       else
9906         b = XNEW (struct breakpoint);
9907
9908       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9909       b->location = copy_event_location (location);
9910
9911       if (parse_extra)
9912         b->cond_string = NULL;
9913       else
9914         {
9915           /* Create a private copy of condition string.  */
9916           if (cond_string)
9917             {
9918               cond_string = xstrdup (cond_string);
9919               make_cleanup (xfree, cond_string);
9920             }
9921           b->cond_string = cond_string;
9922           b->thread = thread;
9923         }
9924
9925       /* Create a private copy of any extra string.  */
9926       if (extra_string != NULL)
9927         {
9928           extra_string = xstrdup (extra_string);
9929           make_cleanup (xfree, extra_string);
9930         }
9931       b->extra_string = extra_string;
9932       b->ignore_count = ignore_count;
9933       b->disposition = tempflag ? disp_del : disp_donttouch;
9934       b->condition_not_parsed = 1;
9935       b->enable_state = enabled ? bp_enabled : bp_disabled;
9936       if ((type_wanted != bp_breakpoint
9937            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9938         b->pspace = current_program_space;
9939
9940       install_breakpoint (internal, b, 0);
9941     }
9942   
9943   if (VEC_length (linespec_sals, canonical.sals) > 1)
9944     {
9945       warning (_("Multiple breakpoints were set.\nUse the "
9946                  "\"delete\" command to delete unwanted breakpoints."));
9947       prev_breakpoint_count = prev_bkpt_count;
9948     }
9949
9950   /* That's it.  Discard the cleanups for data inserted into the
9951      breakpoint.  */
9952   discard_cleanups (bkpt_chain);
9953   /* But cleanup everything else.  */
9954   do_cleanups (old_chain);
9955
9956   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9957   update_global_location_list (UGLL_MAY_INSERT);
9958
9959   return 1;
9960 }
9961
9962 /* Set a breakpoint.
9963    ARG is a string describing breakpoint address,
9964    condition, and thread.
9965    FLAG specifies if a breakpoint is hardware on,
9966    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9967    and BP_TEMPFLAG.  */
9968
9969 static void
9970 break_command_1 (char *arg, int flag, int from_tty)
9971 {
9972   int tempflag = flag & BP_TEMPFLAG;
9973   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9974                              ? bp_hardware_breakpoint
9975                              : bp_breakpoint);
9976   struct breakpoint_ops *ops;
9977   struct event_location *location;
9978   struct cleanup *cleanup;
9979
9980   location = string_to_event_location (&arg, current_language);
9981   cleanup = make_cleanup_delete_event_location (location);
9982
9983   /* Matching breakpoints on probes.  */
9984   if (location != NULL
9985       && event_location_type (location) == PROBE_LOCATION)
9986     ops = &bkpt_probe_breakpoint_ops;
9987   else
9988     ops = &bkpt_breakpoint_ops;
9989
9990   create_breakpoint (get_current_arch (),
9991                      location,
9992                      NULL, 0, arg, 1 /* parse arg */,
9993                      tempflag, type_wanted,
9994                      0 /* Ignore count */,
9995                      pending_break_support,
9996                      ops,
9997                      from_tty,
9998                      1 /* enabled */,
9999                      0 /* internal */,
10000                      0);
10001   do_cleanups (cleanup);
10002 }
10003
10004 /* Helper function for break_command_1 and disassemble_command.  */
10005
10006 void
10007 resolve_sal_pc (struct symtab_and_line *sal)
10008 {
10009   CORE_ADDR pc;
10010
10011   if (sal->pc == 0 && sal->symtab != NULL)
10012     {
10013       if (!find_line_pc (sal->symtab, sal->line, &pc))
10014         error (_("No line %d in file \"%s\"."),
10015                sal->line, symtab_to_filename_for_display (sal->symtab));
10016       sal->pc = pc;
10017
10018       /* If this SAL corresponds to a breakpoint inserted using a line
10019          number, then skip the function prologue if necessary.  */
10020       if (sal->explicit_line)
10021         skip_prologue_sal (sal);
10022     }
10023
10024   if (sal->section == 0 && sal->symtab != NULL)
10025     {
10026       const struct blockvector *bv;
10027       const struct block *b;
10028       struct symbol *sym;
10029
10030       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
10031                                     SYMTAB_COMPUNIT (sal->symtab));
10032       if (bv != NULL)
10033         {
10034           sym = block_linkage_function (b);
10035           if (sym != NULL)
10036             {
10037               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
10038               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
10039                                                  sym);
10040             }
10041           else
10042             {
10043               /* It really is worthwhile to have the section, so we'll
10044                  just have to look harder. This case can be executed
10045                  if we have line numbers but no functions (as can
10046                  happen in assembly source).  */
10047
10048               struct bound_minimal_symbol msym;
10049               struct cleanup *old_chain = save_current_space_and_thread ();
10050
10051               switch_to_program_space_and_thread (sal->pspace);
10052
10053               msym = lookup_minimal_symbol_by_pc (sal->pc);
10054               if (msym.minsym)
10055                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10056
10057               do_cleanups (old_chain);
10058             }
10059         }
10060     }
10061 }
10062
10063 void
10064 break_command (char *arg, int from_tty)
10065 {
10066   break_command_1 (arg, 0, from_tty);
10067 }
10068
10069 void
10070 tbreak_command (char *arg, int from_tty)
10071 {
10072   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10073 }
10074
10075 static void
10076 hbreak_command (char *arg, int from_tty)
10077 {
10078   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10079 }
10080
10081 static void
10082 thbreak_command (char *arg, int from_tty)
10083 {
10084   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10085 }
10086
10087 static void
10088 stop_command (char *arg, int from_tty)
10089 {
10090   printf_filtered (_("Specify the type of breakpoint to set.\n\
10091 Usage: stop in <function | address>\n\
10092        stop at <line>\n"));
10093 }
10094
10095 static void
10096 stopin_command (char *arg, int from_tty)
10097 {
10098   int badInput = 0;
10099
10100   if (arg == (char *) NULL)
10101     badInput = 1;
10102   else if (*arg != '*')
10103     {
10104       char *argptr = arg;
10105       int hasColon = 0;
10106
10107       /* Look for a ':'.  If this is a line number specification, then
10108          say it is bad, otherwise, it should be an address or
10109          function/method name.  */
10110       while (*argptr && !hasColon)
10111         {
10112           hasColon = (*argptr == ':');
10113           argptr++;
10114         }
10115
10116       if (hasColon)
10117         badInput = (*argptr != ':');    /* Not a class::method */
10118       else
10119         badInput = isdigit (*arg);      /* a simple line number */
10120     }
10121
10122   if (badInput)
10123     printf_filtered (_("Usage: stop in <function | address>\n"));
10124   else
10125     break_command_1 (arg, 0, from_tty);
10126 }
10127
10128 static void
10129 stopat_command (char *arg, int from_tty)
10130 {
10131   int badInput = 0;
10132
10133   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10134     badInput = 1;
10135   else
10136     {
10137       char *argptr = arg;
10138       int hasColon = 0;
10139
10140       /* Look for a ':'.  If there is a '::' then get out, otherwise
10141          it is probably a line number.  */
10142       while (*argptr && !hasColon)
10143         {
10144           hasColon = (*argptr == ':');
10145           argptr++;
10146         }
10147
10148       if (hasColon)
10149         badInput = (*argptr == ':');    /* we have class::method */
10150       else
10151         badInput = !isdigit (*arg);     /* not a line number */
10152     }
10153
10154   if (badInput)
10155     printf_filtered (_("Usage: stop at <line>\n"));
10156   else
10157     break_command_1 (arg, 0, from_tty);
10158 }
10159
10160 /* The dynamic printf command is mostly like a regular breakpoint, but
10161    with a prewired command list consisting of a single output command,
10162    built from extra arguments supplied on the dprintf command
10163    line.  */
10164
10165 static void
10166 dprintf_command (char *arg, int from_tty)
10167 {
10168   struct event_location *location;
10169   struct cleanup *cleanup;
10170
10171   location = string_to_event_location (&arg, current_language);
10172   cleanup = make_cleanup_delete_event_location (location);
10173
10174   /* If non-NULL, ARG should have been advanced past the location;
10175      the next character must be ','.  */
10176   if (arg != NULL)
10177     {
10178       if (arg[0] != ',' || arg[1] == '\0')
10179         error (_("Format string required"));
10180       else
10181         {
10182           /* Skip the comma.  */
10183           ++arg;
10184         }
10185     }
10186
10187   create_breakpoint (get_current_arch (),
10188                      location,
10189                      NULL, 0, arg, 1 /* parse arg */,
10190                      0, bp_dprintf,
10191                      0 /* Ignore count */,
10192                      pending_break_support,
10193                      &dprintf_breakpoint_ops,
10194                      from_tty,
10195                      1 /* enabled */,
10196                      0 /* internal */,
10197                      0);
10198   do_cleanups (cleanup);
10199 }
10200
10201 static void
10202 agent_printf_command (char *arg, int from_tty)
10203 {
10204   error (_("May only run agent-printf on the target"));
10205 }
10206
10207 /* Implement the "breakpoint_hit" breakpoint_ops method for
10208    ranged breakpoints.  */
10209
10210 static int
10211 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10212                                   struct address_space *aspace,
10213                                   CORE_ADDR bp_addr,
10214                                   const struct target_waitstatus *ws)
10215 {
10216   if (ws->kind != TARGET_WAITKIND_STOPPED
10217       || ws->value.sig != GDB_SIGNAL_TRAP)
10218     return 0;
10219
10220   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10221                                          bl->length, aspace, bp_addr);
10222 }
10223
10224 /* Implement the "resources_needed" breakpoint_ops method for
10225    ranged breakpoints.  */
10226
10227 static int
10228 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10229 {
10230   return target_ranged_break_num_registers ();
10231 }
10232
10233 /* Implement the "print_it" breakpoint_ops method for
10234    ranged breakpoints.  */
10235
10236 static enum print_stop_action
10237 print_it_ranged_breakpoint (bpstat bs)
10238 {
10239   struct breakpoint *b = bs->breakpoint_at;
10240   struct bp_location *bl = b->loc;
10241   struct ui_out *uiout = current_uiout;
10242
10243   gdb_assert (b->type == bp_hardware_breakpoint);
10244
10245   /* Ranged breakpoints have only one location.  */
10246   gdb_assert (bl && bl->next == NULL);
10247
10248   annotate_breakpoint (b->number);
10249
10250   maybe_print_thread_hit_breakpoint (uiout);
10251
10252   if (b->disposition == disp_del)
10253     ui_out_text (uiout, "Temporary ranged breakpoint ");
10254   else
10255     ui_out_text (uiout, "Ranged breakpoint ");
10256   if (ui_out_is_mi_like_p (uiout))
10257     {
10258       ui_out_field_string (uiout, "reason",
10259                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10260       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10261     }
10262   ui_out_field_int (uiout, "bkptno", b->number);
10263   ui_out_text (uiout, ", ");
10264
10265   return PRINT_SRC_AND_LOC;
10266 }
10267
10268 /* Implement the "print_one" breakpoint_ops method for
10269    ranged breakpoints.  */
10270
10271 static void
10272 print_one_ranged_breakpoint (struct breakpoint *b,
10273                              struct bp_location **last_loc)
10274 {
10275   struct bp_location *bl = b->loc;
10276   struct value_print_options opts;
10277   struct ui_out *uiout = current_uiout;
10278
10279   /* Ranged breakpoints have only one location.  */
10280   gdb_assert (bl && bl->next == NULL);
10281
10282   get_user_print_options (&opts);
10283
10284   if (opts.addressprint)
10285     /* We don't print the address range here, it will be printed later
10286        by print_one_detail_ranged_breakpoint.  */
10287     ui_out_field_skip (uiout, "addr");
10288   annotate_field (5);
10289   print_breakpoint_location (b, bl);
10290   *last_loc = bl;
10291 }
10292
10293 /* Implement the "print_one_detail" breakpoint_ops method for
10294    ranged breakpoints.  */
10295
10296 static void
10297 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10298                                     struct ui_out *uiout)
10299 {
10300   CORE_ADDR address_start, address_end;
10301   struct bp_location *bl = b->loc;
10302   struct ui_file *stb = mem_fileopen ();
10303   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10304
10305   gdb_assert (bl);
10306
10307   address_start = bl->address;
10308   address_end = address_start + bl->length - 1;
10309
10310   ui_out_text (uiout, "\taddress range: ");
10311   fprintf_unfiltered (stb, "[%s, %s]",
10312                       print_core_address (bl->gdbarch, address_start),
10313                       print_core_address (bl->gdbarch, address_end));
10314   ui_out_field_stream (uiout, "addr", stb);
10315   ui_out_text (uiout, "\n");
10316
10317   do_cleanups (cleanup);
10318 }
10319
10320 /* Implement the "print_mention" breakpoint_ops method for
10321    ranged breakpoints.  */
10322
10323 static void
10324 print_mention_ranged_breakpoint (struct breakpoint *b)
10325 {
10326   struct bp_location *bl = b->loc;
10327   struct ui_out *uiout = current_uiout;
10328
10329   gdb_assert (bl);
10330   gdb_assert (b->type == bp_hardware_breakpoint);
10331
10332   if (ui_out_is_mi_like_p (uiout))
10333     return;
10334
10335   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10336                    b->number, paddress (bl->gdbarch, bl->address),
10337                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10338 }
10339
10340 /* Implement the "print_recreate" breakpoint_ops method for
10341    ranged breakpoints.  */
10342
10343 static void
10344 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10345 {
10346   fprintf_unfiltered (fp, "break-range %s, %s",
10347                       event_location_to_string (b->location),
10348                       event_location_to_string (b->location_range_end));
10349   print_recreate_thread (b, fp);
10350 }
10351
10352 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10353
10354 static struct breakpoint_ops ranged_breakpoint_ops;
10355
10356 /* Find the address where the end of the breakpoint range should be
10357    placed, given the SAL of the end of the range.  This is so that if
10358    the user provides a line number, the end of the range is set to the
10359    last instruction of the given line.  */
10360
10361 static CORE_ADDR
10362 find_breakpoint_range_end (struct symtab_and_line sal)
10363 {
10364   CORE_ADDR end;
10365
10366   /* If the user provided a PC value, use it.  Otherwise,
10367      find the address of the end of the given location.  */
10368   if (sal.explicit_pc)
10369     end = sal.pc;
10370   else
10371     {
10372       int ret;
10373       CORE_ADDR start;
10374
10375       ret = find_line_pc_range (sal, &start, &end);
10376       if (!ret)
10377         error (_("Could not find location of the end of the range."));
10378
10379       /* find_line_pc_range returns the start of the next line.  */
10380       end--;
10381     }
10382
10383   return end;
10384 }
10385
10386 /* Implement the "break-range" CLI command.  */
10387
10388 static void
10389 break_range_command (char *arg, int from_tty)
10390 {
10391   char *arg_start, *addr_string_start;
10392   struct linespec_result canonical_start, canonical_end;
10393   int bp_count, can_use_bp, length;
10394   CORE_ADDR end;
10395   struct breakpoint *b;
10396   struct symtab_and_line sal_start, sal_end;
10397   struct cleanup *cleanup_bkpt;
10398   struct linespec_sals *lsal_start, *lsal_end;
10399   struct event_location *start_location, *end_location;
10400
10401   /* We don't support software ranged breakpoints.  */
10402   if (target_ranged_break_num_registers () < 0)
10403     error (_("This target does not support hardware ranged breakpoints."));
10404
10405   bp_count = hw_breakpoint_used_count ();
10406   bp_count += target_ranged_break_num_registers ();
10407   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10408                                                    bp_count, 0);
10409   if (can_use_bp < 0)
10410     error (_("Hardware breakpoints used exceeds limit."));
10411
10412   arg = skip_spaces (arg);
10413   if (arg == NULL || arg[0] == '\0')
10414     error(_("No address range specified."));
10415
10416   init_linespec_result (&canonical_start);
10417
10418   arg_start = arg;
10419   start_location = string_to_event_location (&arg, current_language);
10420   cleanup_bkpt = make_cleanup_delete_event_location (start_location);
10421   parse_breakpoint_sals (start_location, &canonical_start);
10422   make_cleanup_destroy_linespec_result (&canonical_start);
10423
10424   if (arg[0] != ',')
10425     error (_("Too few arguments."));
10426   else if (VEC_empty (linespec_sals, canonical_start.sals))
10427     error (_("Could not find location of the beginning of the range."));
10428
10429   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10430
10431   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10432       || lsal_start->sals.nelts != 1)
10433     error (_("Cannot create a ranged breakpoint with multiple locations."));
10434
10435   sal_start = lsal_start->sals.sals[0];
10436   addr_string_start = savestring (arg_start, arg - arg_start);
10437   make_cleanup (xfree, addr_string_start);
10438
10439   arg++;        /* Skip the comma.  */
10440   arg = skip_spaces (arg);
10441
10442   /* Parse the end location.  */
10443
10444   init_linespec_result (&canonical_end);
10445   arg_start = arg;
10446
10447   /* We call decode_line_full directly here instead of using
10448      parse_breakpoint_sals because we need to specify the start location's
10449      symtab and line as the default symtab and line for the end of the
10450      range.  This makes it possible to have ranges like "foo.c:27, +14",
10451      where +14 means 14 lines from the start location.  */
10452   end_location = string_to_event_location (&arg, current_language);
10453   make_cleanup_delete_event_location (end_location);
10454   decode_line_full (end_location, DECODE_LINE_FUNFIRSTLINE, NULL,
10455                     sal_start.symtab, sal_start.line,
10456                     &canonical_end, NULL, NULL);
10457
10458   make_cleanup_destroy_linespec_result (&canonical_end);
10459
10460   if (VEC_empty (linespec_sals, canonical_end.sals))
10461     error (_("Could not find location of the end of the range."));
10462
10463   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10464   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10465       || lsal_end->sals.nelts != 1)
10466     error (_("Cannot create a ranged breakpoint with multiple locations."));
10467
10468   sal_end = lsal_end->sals.sals[0];
10469
10470   end = find_breakpoint_range_end (sal_end);
10471   if (sal_start.pc > end)
10472     error (_("Invalid address range, end precedes start."));
10473
10474   length = end - sal_start.pc + 1;
10475   if (length < 0)
10476     /* Length overflowed.  */
10477     error (_("Address range too large."));
10478   else if (length == 1)
10479     {
10480       /* This range is simple enough to be handled by
10481          the `hbreak' command.  */
10482       hbreak_command (addr_string_start, 1);
10483
10484       do_cleanups (cleanup_bkpt);
10485
10486       return;
10487     }
10488
10489   /* Now set up the breakpoint.  */
10490   b = set_raw_breakpoint (get_current_arch (), sal_start,
10491                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10492   set_breakpoint_count (breakpoint_count + 1);
10493   b->number = breakpoint_count;
10494   b->disposition = disp_donttouch;
10495   b->location = copy_event_location (start_location);
10496   b->location_range_end = copy_event_location (end_location);
10497   b->loc->length = length;
10498
10499   do_cleanups (cleanup_bkpt);
10500
10501   mention (b);
10502   observer_notify_breakpoint_created (b);
10503   update_global_location_list (UGLL_MAY_INSERT);
10504 }
10505
10506 /*  Return non-zero if EXP is verified as constant.  Returned zero
10507     means EXP is variable.  Also the constant detection may fail for
10508     some constant expressions and in such case still falsely return
10509     zero.  */
10510
10511 static int
10512 watchpoint_exp_is_const (const struct expression *exp)
10513 {
10514   int i = exp->nelts;
10515
10516   while (i > 0)
10517     {
10518       int oplenp, argsp;
10519
10520       /* We are only interested in the descriptor of each element.  */
10521       operator_length (exp, i, &oplenp, &argsp);
10522       i -= oplenp;
10523
10524       switch (exp->elts[i].opcode)
10525         {
10526         case BINOP_ADD:
10527         case BINOP_SUB:
10528         case BINOP_MUL:
10529         case BINOP_DIV:
10530         case BINOP_REM:
10531         case BINOP_MOD:
10532         case BINOP_LSH:
10533         case BINOP_RSH:
10534         case BINOP_LOGICAL_AND:
10535         case BINOP_LOGICAL_OR:
10536         case BINOP_BITWISE_AND:
10537         case BINOP_BITWISE_IOR:
10538         case BINOP_BITWISE_XOR:
10539         case BINOP_EQUAL:
10540         case BINOP_NOTEQUAL:
10541         case BINOP_LESS:
10542         case BINOP_GTR:
10543         case BINOP_LEQ:
10544         case BINOP_GEQ:
10545         case BINOP_REPEAT:
10546         case BINOP_COMMA:
10547         case BINOP_EXP:
10548         case BINOP_MIN:
10549         case BINOP_MAX:
10550         case BINOP_INTDIV:
10551         case BINOP_CONCAT:
10552         case TERNOP_COND:
10553         case TERNOP_SLICE:
10554
10555         case OP_LONG:
10556         case OP_DOUBLE:
10557         case OP_DECFLOAT:
10558         case OP_LAST:
10559         case OP_COMPLEX:
10560         case OP_STRING:
10561         case OP_ARRAY:
10562         case OP_TYPE:
10563         case OP_TYPEOF:
10564         case OP_DECLTYPE:
10565         case OP_TYPEID:
10566         case OP_NAME:
10567         case OP_OBJC_NSSTRING:
10568
10569         case UNOP_NEG:
10570         case UNOP_LOGICAL_NOT:
10571         case UNOP_COMPLEMENT:
10572         case UNOP_ADDR:
10573         case UNOP_HIGH:
10574         case UNOP_CAST:
10575
10576         case UNOP_CAST_TYPE:
10577         case UNOP_REINTERPRET_CAST:
10578         case UNOP_DYNAMIC_CAST:
10579           /* Unary, binary and ternary operators: We have to check
10580              their operands.  If they are constant, then so is the
10581              result of that operation.  For instance, if A and B are
10582              determined to be constants, then so is "A + B".
10583
10584              UNOP_IND is one exception to the rule above, because the
10585              value of *ADDR is not necessarily a constant, even when
10586              ADDR is.  */
10587           break;
10588
10589         case OP_VAR_VALUE:
10590           /* Check whether the associated symbol is a constant.
10591
10592              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10593              possible that a buggy compiler could mark a variable as
10594              constant even when it is not, and TYPE_CONST would return
10595              true in this case, while SYMBOL_CLASS wouldn't.
10596
10597              We also have to check for function symbols because they
10598              are always constant.  */
10599           {
10600             struct symbol *s = exp->elts[i + 2].symbol;
10601
10602             if (SYMBOL_CLASS (s) != LOC_BLOCK
10603                 && SYMBOL_CLASS (s) != LOC_CONST
10604                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10605               return 0;
10606             break;
10607           }
10608
10609         /* The default action is to return 0 because we are using
10610            the optimistic approach here: If we don't know something,
10611            then it is not a constant.  */
10612         default:
10613           return 0;
10614         }
10615     }
10616
10617   return 1;
10618 }
10619
10620 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10621
10622 static void
10623 dtor_watchpoint (struct breakpoint *self)
10624 {
10625   struct watchpoint *w = (struct watchpoint *) self;
10626
10627   xfree (w->cond_exp);
10628   xfree (w->exp);
10629   xfree (w->exp_string);
10630   xfree (w->exp_string_reparse);
10631   value_free (w->val);
10632
10633   base_breakpoint_ops.dtor (self);
10634 }
10635
10636 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10637
10638 static void
10639 re_set_watchpoint (struct breakpoint *b)
10640 {
10641   struct watchpoint *w = (struct watchpoint *) b;
10642
10643   /* Watchpoint can be either on expression using entirely global
10644      variables, or it can be on local variables.
10645
10646      Watchpoints of the first kind are never auto-deleted, and even
10647      persist across program restarts.  Since they can use variables
10648      from shared libraries, we need to reparse expression as libraries
10649      are loaded and unloaded.
10650
10651      Watchpoints on local variables can also change meaning as result
10652      of solib event.  For example, if a watchpoint uses both a local
10653      and a global variables in expression, it's a local watchpoint,
10654      but unloading of a shared library will make the expression
10655      invalid.  This is not a very common use case, but we still
10656      re-evaluate expression, to avoid surprises to the user.
10657
10658      Note that for local watchpoints, we re-evaluate it only if
10659      watchpoints frame id is still valid.  If it's not, it means the
10660      watchpoint is out of scope and will be deleted soon.  In fact,
10661      I'm not sure we'll ever be called in this case.
10662
10663      If a local watchpoint's frame id is still valid, then
10664      w->exp_valid_block is likewise valid, and we can safely use it.
10665
10666      Don't do anything about disabled watchpoints, since they will be
10667      reevaluated again when enabled.  */
10668   update_watchpoint (w, 1 /* reparse */);
10669 }
10670
10671 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10672
10673 static int
10674 insert_watchpoint (struct bp_location *bl)
10675 {
10676   struct watchpoint *w = (struct watchpoint *) bl->owner;
10677   int length = w->exact ? 1 : bl->length;
10678
10679   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10680                                    w->cond_exp);
10681 }
10682
10683 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10684
10685 static int
10686 remove_watchpoint (struct bp_location *bl)
10687 {
10688   struct watchpoint *w = (struct watchpoint *) bl->owner;
10689   int length = w->exact ? 1 : bl->length;
10690
10691   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10692                                    w->cond_exp);
10693 }
10694
10695 static int
10696 breakpoint_hit_watchpoint (const struct bp_location *bl,
10697                            struct address_space *aspace, CORE_ADDR bp_addr,
10698                            const struct target_waitstatus *ws)
10699 {
10700   struct breakpoint *b = bl->owner;
10701   struct watchpoint *w = (struct watchpoint *) b;
10702
10703   /* Continuable hardware watchpoints are treated as non-existent if the
10704      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10705      some data address).  Otherwise gdb won't stop on a break instruction
10706      in the code (not from a breakpoint) when a hardware watchpoint has
10707      been defined.  Also skip watchpoints which we know did not trigger
10708      (did not match the data address).  */
10709   if (is_hardware_watchpoint (b)
10710       && w->watchpoint_triggered == watch_triggered_no)
10711     return 0;
10712
10713   return 1;
10714 }
10715
10716 static void
10717 check_status_watchpoint (bpstat bs)
10718 {
10719   gdb_assert (is_watchpoint (bs->breakpoint_at));
10720
10721   bpstat_check_watchpoint (bs);
10722 }
10723
10724 /* Implement the "resources_needed" breakpoint_ops method for
10725    hardware watchpoints.  */
10726
10727 static int
10728 resources_needed_watchpoint (const struct bp_location *bl)
10729 {
10730   struct watchpoint *w = (struct watchpoint *) bl->owner;
10731   int length = w->exact? 1 : bl->length;
10732
10733   return target_region_ok_for_hw_watchpoint (bl->address, length);
10734 }
10735
10736 /* Implement the "works_in_software_mode" breakpoint_ops method for
10737    hardware watchpoints.  */
10738
10739 static int
10740 works_in_software_mode_watchpoint (const struct breakpoint *b)
10741 {
10742   /* Read and access watchpoints only work with hardware support.  */
10743   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10744 }
10745
10746 static enum print_stop_action
10747 print_it_watchpoint (bpstat bs)
10748 {
10749   struct cleanup *old_chain;
10750   struct breakpoint *b;
10751   struct ui_file *stb;
10752   enum print_stop_action result;
10753   struct watchpoint *w;
10754   struct ui_out *uiout = current_uiout;
10755
10756   gdb_assert (bs->bp_location_at != NULL);
10757
10758   b = bs->breakpoint_at;
10759   w = (struct watchpoint *) b;
10760
10761   stb = mem_fileopen ();
10762   old_chain = make_cleanup_ui_file_delete (stb);
10763
10764   annotate_watchpoint (b->number);
10765   maybe_print_thread_hit_breakpoint (uiout);
10766
10767   switch (b->type)
10768     {
10769     case bp_watchpoint:
10770     case bp_hardware_watchpoint:
10771       if (ui_out_is_mi_like_p (uiout))
10772         ui_out_field_string
10773           (uiout, "reason",
10774            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10775       mention (b);
10776       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10777       ui_out_text (uiout, "\nOld value = ");
10778       watchpoint_value_print (bs->old_val, stb);
10779       ui_out_field_stream (uiout, "old", stb);
10780       ui_out_text (uiout, "\nNew value = ");
10781       watchpoint_value_print (w->val, stb);
10782       ui_out_field_stream (uiout, "new", stb);
10783       ui_out_text (uiout, "\n");
10784       /* More than one watchpoint may have been triggered.  */
10785       result = PRINT_UNKNOWN;
10786       break;
10787
10788     case bp_read_watchpoint:
10789       if (ui_out_is_mi_like_p (uiout))
10790         ui_out_field_string
10791           (uiout, "reason",
10792            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10793       mention (b);
10794       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10795       ui_out_text (uiout, "\nValue = ");
10796       watchpoint_value_print (w->val, stb);
10797       ui_out_field_stream (uiout, "value", stb);
10798       ui_out_text (uiout, "\n");
10799       result = PRINT_UNKNOWN;
10800       break;
10801
10802     case bp_access_watchpoint:
10803       if (bs->old_val != NULL)
10804         {
10805           if (ui_out_is_mi_like_p (uiout))
10806             ui_out_field_string
10807               (uiout, "reason",
10808                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10809           mention (b);
10810           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10811           ui_out_text (uiout, "\nOld value = ");
10812           watchpoint_value_print (bs->old_val, stb);
10813           ui_out_field_stream (uiout, "old", stb);
10814           ui_out_text (uiout, "\nNew value = ");
10815         }
10816       else
10817         {
10818           mention (b);
10819           if (ui_out_is_mi_like_p (uiout))
10820             ui_out_field_string
10821               (uiout, "reason",
10822                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10823           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10824           ui_out_text (uiout, "\nValue = ");
10825         }
10826       watchpoint_value_print (w->val, stb);
10827       ui_out_field_stream (uiout, "new", stb);
10828       ui_out_text (uiout, "\n");
10829       result = PRINT_UNKNOWN;
10830       break;
10831     default:
10832       result = PRINT_UNKNOWN;
10833     }
10834
10835   do_cleanups (old_chain);
10836   return result;
10837 }
10838
10839 /* Implement the "print_mention" breakpoint_ops method for hardware
10840    watchpoints.  */
10841
10842 static void
10843 print_mention_watchpoint (struct breakpoint *b)
10844 {
10845   struct cleanup *ui_out_chain;
10846   struct watchpoint *w = (struct watchpoint *) b;
10847   struct ui_out *uiout = current_uiout;
10848
10849   switch (b->type)
10850     {
10851     case bp_watchpoint:
10852       ui_out_text (uiout, "Watchpoint ");
10853       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10854       break;
10855     case bp_hardware_watchpoint:
10856       ui_out_text (uiout, "Hardware watchpoint ");
10857       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10858       break;
10859     case bp_read_watchpoint:
10860       ui_out_text (uiout, "Hardware read watchpoint ");
10861       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10862       break;
10863     case bp_access_watchpoint:
10864       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10865       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10866       break;
10867     default:
10868       internal_error (__FILE__, __LINE__,
10869                       _("Invalid hardware watchpoint type."));
10870     }
10871
10872   ui_out_field_int (uiout, "number", b->number);
10873   ui_out_text (uiout, ": ");
10874   ui_out_field_string (uiout, "exp", w->exp_string);
10875   do_cleanups (ui_out_chain);
10876 }
10877
10878 /* Implement the "print_recreate" breakpoint_ops method for
10879    watchpoints.  */
10880
10881 static void
10882 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10883 {
10884   struct watchpoint *w = (struct watchpoint *) b;
10885
10886   switch (b->type)
10887     {
10888     case bp_watchpoint:
10889     case bp_hardware_watchpoint:
10890       fprintf_unfiltered (fp, "watch");
10891       break;
10892     case bp_read_watchpoint:
10893       fprintf_unfiltered (fp, "rwatch");
10894       break;
10895     case bp_access_watchpoint:
10896       fprintf_unfiltered (fp, "awatch");
10897       break;
10898     default:
10899       internal_error (__FILE__, __LINE__,
10900                       _("Invalid watchpoint type."));
10901     }
10902
10903   fprintf_unfiltered (fp, " %s", w->exp_string);
10904   print_recreate_thread (b, fp);
10905 }
10906
10907 /* Implement the "explains_signal" breakpoint_ops method for
10908    watchpoints.  */
10909
10910 static int
10911 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10912 {
10913   /* A software watchpoint cannot cause a signal other than
10914      GDB_SIGNAL_TRAP.  */
10915   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10916     return 0;
10917
10918   return 1;
10919 }
10920
10921 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10922
10923 static struct breakpoint_ops watchpoint_breakpoint_ops;
10924
10925 /* Implement the "insert" breakpoint_ops method for
10926    masked hardware watchpoints.  */
10927
10928 static int
10929 insert_masked_watchpoint (struct bp_location *bl)
10930 {
10931   struct watchpoint *w = (struct watchpoint *) bl->owner;
10932
10933   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10934                                         bl->watchpoint_type);
10935 }
10936
10937 /* Implement the "remove" breakpoint_ops method for
10938    masked hardware watchpoints.  */
10939
10940 static int
10941 remove_masked_watchpoint (struct bp_location *bl)
10942 {
10943   struct watchpoint *w = (struct watchpoint *) bl->owner;
10944
10945   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10946                                         bl->watchpoint_type);
10947 }
10948
10949 /* Implement the "resources_needed" breakpoint_ops method for
10950    masked hardware watchpoints.  */
10951
10952 static int
10953 resources_needed_masked_watchpoint (const struct bp_location *bl)
10954 {
10955   struct watchpoint *w = (struct watchpoint *) bl->owner;
10956
10957   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10958 }
10959
10960 /* Implement the "works_in_software_mode" breakpoint_ops method for
10961    masked hardware watchpoints.  */
10962
10963 static int
10964 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10965 {
10966   return 0;
10967 }
10968
10969 /* Implement the "print_it" breakpoint_ops method for
10970    masked hardware watchpoints.  */
10971
10972 static enum print_stop_action
10973 print_it_masked_watchpoint (bpstat bs)
10974 {
10975   struct breakpoint *b = bs->breakpoint_at;
10976   struct ui_out *uiout = current_uiout;
10977
10978   /* Masked watchpoints have only one location.  */
10979   gdb_assert (b->loc && b->loc->next == NULL);
10980
10981   annotate_watchpoint (b->number);
10982   maybe_print_thread_hit_breakpoint (uiout);
10983
10984   switch (b->type)
10985     {
10986     case bp_hardware_watchpoint:
10987       if (ui_out_is_mi_like_p (uiout))
10988         ui_out_field_string
10989           (uiout, "reason",
10990            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10991       break;
10992
10993     case bp_read_watchpoint:
10994       if (ui_out_is_mi_like_p (uiout))
10995         ui_out_field_string
10996           (uiout, "reason",
10997            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10998       break;
10999
11000     case bp_access_watchpoint:
11001       if (ui_out_is_mi_like_p (uiout))
11002         ui_out_field_string
11003           (uiout, "reason",
11004            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11005       break;
11006     default:
11007       internal_error (__FILE__, __LINE__,
11008                       _("Invalid hardware watchpoint type."));
11009     }
11010
11011   mention (b);
11012   ui_out_text (uiout, _("\n\
11013 Check the underlying instruction at PC for the memory\n\
11014 address and value which triggered this watchpoint.\n"));
11015   ui_out_text (uiout, "\n");
11016
11017   /* More than one watchpoint may have been triggered.  */
11018   return PRINT_UNKNOWN;
11019 }
11020
11021 /* Implement the "print_one_detail" breakpoint_ops method for
11022    masked hardware watchpoints.  */
11023
11024 static void
11025 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11026                                     struct ui_out *uiout)
11027 {
11028   struct watchpoint *w = (struct watchpoint *) b;
11029
11030   /* Masked watchpoints have only one location.  */
11031   gdb_assert (b->loc && b->loc->next == NULL);
11032
11033   ui_out_text (uiout, "\tmask ");
11034   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11035   ui_out_text (uiout, "\n");
11036 }
11037
11038 /* Implement the "print_mention" breakpoint_ops method for
11039    masked hardware watchpoints.  */
11040
11041 static void
11042 print_mention_masked_watchpoint (struct breakpoint *b)
11043 {
11044   struct watchpoint *w = (struct watchpoint *) b;
11045   struct ui_out *uiout = current_uiout;
11046   struct cleanup *ui_out_chain;
11047
11048   switch (b->type)
11049     {
11050     case bp_hardware_watchpoint:
11051       ui_out_text (uiout, "Masked hardware watchpoint ");
11052       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11053       break;
11054     case bp_read_watchpoint:
11055       ui_out_text (uiout, "Masked hardware read watchpoint ");
11056       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11057       break;
11058     case bp_access_watchpoint:
11059       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11060       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11061       break;
11062     default:
11063       internal_error (__FILE__, __LINE__,
11064                       _("Invalid hardware watchpoint type."));
11065     }
11066
11067   ui_out_field_int (uiout, "number", b->number);
11068   ui_out_text (uiout, ": ");
11069   ui_out_field_string (uiout, "exp", w->exp_string);
11070   do_cleanups (ui_out_chain);
11071 }
11072
11073 /* Implement the "print_recreate" breakpoint_ops method for
11074    masked hardware watchpoints.  */
11075
11076 static void
11077 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11078 {
11079   struct watchpoint *w = (struct watchpoint *) b;
11080   char tmp[40];
11081
11082   switch (b->type)
11083     {
11084     case bp_hardware_watchpoint:
11085       fprintf_unfiltered (fp, "watch");
11086       break;
11087     case bp_read_watchpoint:
11088       fprintf_unfiltered (fp, "rwatch");
11089       break;
11090     case bp_access_watchpoint:
11091       fprintf_unfiltered (fp, "awatch");
11092       break;
11093     default:
11094       internal_error (__FILE__, __LINE__,
11095                       _("Invalid hardware watchpoint type."));
11096     }
11097
11098   sprintf_vma (tmp, w->hw_wp_mask);
11099   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11100   print_recreate_thread (b, fp);
11101 }
11102
11103 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11104
11105 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11106
11107 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11108
11109 static int
11110 is_masked_watchpoint (const struct breakpoint *b)
11111 {
11112   return b->ops == &masked_watchpoint_breakpoint_ops;
11113 }
11114
11115 /* accessflag:  hw_write:  watch write, 
11116                 hw_read:   watch read, 
11117                 hw_access: watch access (read or write) */
11118 static void
11119 watch_command_1 (const char *arg, int accessflag, int from_tty,
11120                  int just_location, int internal)
11121 {
11122   struct breakpoint *b, *scope_breakpoint = NULL;
11123   struct expression *exp;
11124   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11125   struct value *val, *mark, *result;
11126   int saved_bitpos = 0, saved_bitsize = 0;
11127   struct frame_info *frame;
11128   const char *exp_start = NULL;
11129   const char *exp_end = NULL;
11130   const char *tok, *end_tok;
11131   int toklen = -1;
11132   const char *cond_start = NULL;
11133   const char *cond_end = NULL;
11134   enum bptype bp_type;
11135   int thread = -1;
11136   int pc = 0;
11137   /* Flag to indicate whether we are going to use masks for
11138      the hardware watchpoint.  */
11139   int use_mask = 0;
11140   CORE_ADDR mask = 0;
11141   struct watchpoint *w;
11142   char *expression;
11143   struct cleanup *back_to;
11144
11145   /* Make sure that we actually have parameters to parse.  */
11146   if (arg != NULL && arg[0] != '\0')
11147     {
11148       const char *value_start;
11149
11150       exp_end = arg + strlen (arg);
11151
11152       /* Look for "parameter value" pairs at the end
11153          of the arguments string.  */
11154       for (tok = exp_end - 1; tok > arg; tok--)
11155         {
11156           /* Skip whitespace at the end of the argument list.  */
11157           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11158             tok--;
11159
11160           /* Find the beginning of the last token.
11161              This is the value of the parameter.  */
11162           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11163             tok--;
11164           value_start = tok + 1;
11165
11166           /* Skip whitespace.  */
11167           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11168             tok--;
11169
11170           end_tok = tok;
11171
11172           /* Find the beginning of the second to last token.
11173              This is the parameter itself.  */
11174           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11175             tok--;
11176           tok++;
11177           toklen = end_tok - tok + 1;
11178
11179           if (toklen == 6 && startswith (tok, "thread"))
11180             {
11181               struct thread_info *thr;
11182               /* At this point we've found a "thread" token, which means
11183                  the user is trying to set a watchpoint that triggers
11184                  only in a specific thread.  */
11185               const char *endp;
11186
11187               if (thread != -1)
11188                 error(_("You can specify only one thread."));
11189
11190               /* Extract the thread ID from the next token.  */
11191               thr = parse_thread_id (value_start, &endp);
11192
11193               /* Check if the user provided a valid thread ID.  */
11194               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11195                 invalid_thread_id_error (value_start);
11196
11197               thread = thr->global_num;
11198             }
11199           else if (toklen == 4 && startswith (tok, "mask"))
11200             {
11201               /* We've found a "mask" token, which means the user wants to
11202                  create a hardware watchpoint that is going to have the mask
11203                  facility.  */
11204               struct value *mask_value, *mark;
11205
11206               if (use_mask)
11207                 error(_("You can specify only one mask."));
11208
11209               use_mask = just_location = 1;
11210
11211               mark = value_mark ();
11212               mask_value = parse_to_comma_and_eval (&value_start);
11213               mask = value_as_address (mask_value);
11214               value_free_to_mark (mark);
11215             }
11216           else
11217             /* We didn't recognize what we found.  We should stop here.  */
11218             break;
11219
11220           /* Truncate the string and get rid of the "parameter value" pair before
11221              the arguments string is parsed by the parse_exp_1 function.  */
11222           exp_end = tok;
11223         }
11224     }
11225   else
11226     exp_end = arg;
11227
11228   /* Parse the rest of the arguments.  From here on out, everything
11229      is in terms of a newly allocated string instead of the original
11230      ARG.  */
11231   innermost_block = NULL;
11232   expression = savestring (arg, exp_end - arg);
11233   back_to = make_cleanup (xfree, expression);
11234   exp_start = arg = expression;
11235   exp = parse_exp_1 (&arg, 0, 0, 0);
11236   exp_end = arg;
11237   /* Remove trailing whitespace from the expression before saving it.
11238      This makes the eventual display of the expression string a bit
11239      prettier.  */
11240   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11241     --exp_end;
11242
11243   /* Checking if the expression is not constant.  */
11244   if (watchpoint_exp_is_const (exp))
11245     {
11246       int len;
11247
11248       len = exp_end - exp_start;
11249       while (len > 0 && isspace (exp_start[len - 1]))
11250         len--;
11251       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11252     }
11253
11254   exp_valid_block = innermost_block;
11255   mark = value_mark ();
11256   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11257
11258   if (val != NULL && just_location)
11259     {
11260       saved_bitpos = value_bitpos (val);
11261       saved_bitsize = value_bitsize (val);
11262     }
11263
11264   if (just_location)
11265     {
11266       int ret;
11267
11268       exp_valid_block = NULL;
11269       val = value_addr (result);
11270       release_value (val);
11271       value_free_to_mark (mark);
11272
11273       if (use_mask)
11274         {
11275           ret = target_masked_watch_num_registers (value_as_address (val),
11276                                                    mask);
11277           if (ret == -1)
11278             error (_("This target does not support masked watchpoints."));
11279           else if (ret == -2)
11280             error (_("Invalid mask or memory region."));
11281         }
11282     }
11283   else if (val != NULL)
11284     release_value (val);
11285
11286   tok = skip_spaces_const (arg);
11287   end_tok = skip_to_space_const (tok);
11288
11289   toklen = end_tok - tok;
11290   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11291     {
11292       struct expression *cond;
11293
11294       innermost_block = NULL;
11295       tok = cond_start = end_tok + 1;
11296       cond = parse_exp_1 (&tok, 0, 0, 0);
11297
11298       /* The watchpoint expression may not be local, but the condition
11299          may still be.  E.g.: `watch global if local > 0'.  */
11300       cond_exp_valid_block = innermost_block;
11301
11302       xfree (cond);
11303       cond_end = tok;
11304     }
11305   if (*tok)
11306     error (_("Junk at end of command."));
11307
11308   frame = block_innermost_frame (exp_valid_block);
11309
11310   /* If the expression is "local", then set up a "watchpoint scope"
11311      breakpoint at the point where we've left the scope of the watchpoint
11312      expression.  Create the scope breakpoint before the watchpoint, so
11313      that we will encounter it first in bpstat_stop_status.  */
11314   if (exp_valid_block && frame)
11315     {
11316       if (frame_id_p (frame_unwind_caller_id (frame)))
11317         {
11318           scope_breakpoint
11319             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11320                                           frame_unwind_caller_pc (frame),
11321                                           bp_watchpoint_scope,
11322                                           &momentary_breakpoint_ops);
11323
11324           scope_breakpoint->enable_state = bp_enabled;
11325
11326           /* Automatically delete the breakpoint when it hits.  */
11327           scope_breakpoint->disposition = disp_del;
11328
11329           /* Only break in the proper frame (help with recursion).  */
11330           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11331
11332           /* Set the address at which we will stop.  */
11333           scope_breakpoint->loc->gdbarch
11334             = frame_unwind_caller_arch (frame);
11335           scope_breakpoint->loc->requested_address
11336             = frame_unwind_caller_pc (frame);
11337           scope_breakpoint->loc->address
11338             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11339                                          scope_breakpoint->loc->requested_address,
11340                                          scope_breakpoint->type);
11341         }
11342     }
11343
11344   /* Now set up the breakpoint.  We create all watchpoints as hardware
11345      watchpoints here even if hardware watchpoints are turned off, a call
11346      to update_watchpoint later in this function will cause the type to
11347      drop back to bp_watchpoint (software watchpoint) if required.  */
11348
11349   if (accessflag == hw_read)
11350     bp_type = bp_read_watchpoint;
11351   else if (accessflag == hw_access)
11352     bp_type = bp_access_watchpoint;
11353   else
11354     bp_type = bp_hardware_watchpoint;
11355
11356   w = XCNEW (struct watchpoint);
11357   b = &w->base;
11358   if (use_mask)
11359     init_raw_breakpoint_without_location (b, NULL, bp_type,
11360                                           &masked_watchpoint_breakpoint_ops);
11361   else
11362     init_raw_breakpoint_without_location (b, NULL, bp_type,
11363                                           &watchpoint_breakpoint_ops);
11364   b->thread = thread;
11365   b->disposition = disp_donttouch;
11366   b->pspace = current_program_space;
11367   w->exp = exp;
11368   w->exp_valid_block = exp_valid_block;
11369   w->cond_exp_valid_block = cond_exp_valid_block;
11370   if (just_location)
11371     {
11372       struct type *t = value_type (val);
11373       CORE_ADDR addr = value_as_address (val);
11374       char *name;
11375
11376       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11377       name = type_to_string (t);
11378
11379       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11380                                           core_addr_to_string (addr));
11381       xfree (name);
11382
11383       w->exp_string = xstrprintf ("-location %.*s",
11384                                   (int) (exp_end - exp_start), exp_start);
11385
11386       /* The above expression is in C.  */
11387       b->language = language_c;
11388     }
11389   else
11390     w->exp_string = savestring (exp_start, exp_end - exp_start);
11391
11392   if (use_mask)
11393     {
11394       w->hw_wp_mask = mask;
11395     }
11396   else
11397     {
11398       w->val = val;
11399       w->val_bitpos = saved_bitpos;
11400       w->val_bitsize = saved_bitsize;
11401       w->val_valid = 1;
11402     }
11403
11404   if (cond_start)
11405     b->cond_string = savestring (cond_start, cond_end - cond_start);
11406   else
11407     b->cond_string = 0;
11408
11409   if (frame)
11410     {
11411       w->watchpoint_frame = get_frame_id (frame);
11412       w->watchpoint_thread = inferior_ptid;
11413     }
11414   else
11415     {
11416       w->watchpoint_frame = null_frame_id;
11417       w->watchpoint_thread = null_ptid;
11418     }
11419
11420   if (scope_breakpoint != NULL)
11421     {
11422       /* The scope breakpoint is related to the watchpoint.  We will
11423          need to act on them together.  */
11424       b->related_breakpoint = scope_breakpoint;
11425       scope_breakpoint->related_breakpoint = b;
11426     }
11427
11428   if (!just_location)
11429     value_free_to_mark (mark);
11430
11431   TRY
11432     {
11433       /* Finally update the new watchpoint.  This creates the locations
11434          that should be inserted.  */
11435       update_watchpoint (w, 1);
11436     }
11437   CATCH (e, RETURN_MASK_ALL)
11438     {
11439       delete_breakpoint (b);
11440       throw_exception (e);
11441     }
11442   END_CATCH
11443
11444   install_breakpoint (internal, b, 1);
11445   do_cleanups (back_to);
11446 }
11447
11448 /* Return count of debug registers needed to watch the given expression.
11449    If the watchpoint cannot be handled in hardware return zero.  */
11450
11451 static int
11452 can_use_hardware_watchpoint (struct value *v)
11453 {
11454   int found_memory_cnt = 0;
11455   struct value *head = v;
11456
11457   /* Did the user specifically forbid us to use hardware watchpoints? */
11458   if (!can_use_hw_watchpoints)
11459     return 0;
11460
11461   /* Make sure that the value of the expression depends only upon
11462      memory contents, and values computed from them within GDB.  If we
11463      find any register references or function calls, we can't use a
11464      hardware watchpoint.
11465
11466      The idea here is that evaluating an expression generates a series
11467      of values, one holding the value of every subexpression.  (The
11468      expression a*b+c has five subexpressions: a, b, a*b, c, and
11469      a*b+c.)  GDB's values hold almost enough information to establish
11470      the criteria given above --- they identify memory lvalues,
11471      register lvalues, computed values, etcetera.  So we can evaluate
11472      the expression, and then scan the chain of values that leaves
11473      behind to decide whether we can detect any possible change to the
11474      expression's final value using only hardware watchpoints.
11475
11476      However, I don't think that the values returned by inferior
11477      function calls are special in any way.  So this function may not
11478      notice that an expression involving an inferior function call
11479      can't be watched with hardware watchpoints.  FIXME.  */
11480   for (; v; v = value_next (v))
11481     {
11482       if (VALUE_LVAL (v) == lval_memory)
11483         {
11484           if (v != head && value_lazy (v))
11485             /* A lazy memory lvalue in the chain is one that GDB never
11486                needed to fetch; we either just used its address (e.g.,
11487                `a' in `a.b') or we never needed it at all (e.g., `a'
11488                in `a,b').  This doesn't apply to HEAD; if that is
11489                lazy then it was not readable, but watch it anyway.  */
11490             ;
11491           else
11492             {
11493               /* Ahh, memory we actually used!  Check if we can cover
11494                  it with hardware watchpoints.  */
11495               struct type *vtype = check_typedef (value_type (v));
11496
11497               /* We only watch structs and arrays if user asked for it
11498                  explicitly, never if they just happen to appear in a
11499                  middle of some value chain.  */
11500               if (v == head
11501                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11502                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11503                 {
11504                   CORE_ADDR vaddr = value_address (v);
11505                   int len;
11506                   int num_regs;
11507
11508                   len = (target_exact_watchpoints
11509                          && is_scalar_type_recursive (vtype))?
11510                     1 : TYPE_LENGTH (value_type (v));
11511
11512                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11513                   if (!num_regs)
11514                     return 0;
11515                   else
11516                     found_memory_cnt += num_regs;
11517                 }
11518             }
11519         }
11520       else if (VALUE_LVAL (v) != not_lval
11521                && deprecated_value_modifiable (v) == 0)
11522         return 0;       /* These are values from the history (e.g., $1).  */
11523       else if (VALUE_LVAL (v) == lval_register)
11524         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11525     }
11526
11527   /* The expression itself looks suitable for using a hardware
11528      watchpoint, but give the target machine a chance to reject it.  */
11529   return found_memory_cnt;
11530 }
11531
11532 void
11533 watch_command_wrapper (char *arg, int from_tty, int internal)
11534 {
11535   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11536 }
11537
11538 /* A helper function that looks for the "-location" argument and then
11539    calls watch_command_1.  */
11540
11541 static void
11542 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11543 {
11544   int just_location = 0;
11545
11546   if (arg
11547       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11548           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11549     {
11550       arg = skip_spaces (arg);
11551       just_location = 1;
11552     }
11553
11554   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11555 }
11556
11557 static void
11558 watch_command (char *arg, int from_tty)
11559 {
11560   watch_maybe_just_location (arg, hw_write, from_tty);
11561 }
11562
11563 void
11564 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11565 {
11566   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11567 }
11568
11569 static void
11570 rwatch_command (char *arg, int from_tty)
11571 {
11572   watch_maybe_just_location (arg, hw_read, from_tty);
11573 }
11574
11575 void
11576 awatch_command_wrapper (char *arg, int from_tty, int internal)
11577 {
11578   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11579 }
11580
11581 static void
11582 awatch_command (char *arg, int from_tty)
11583 {
11584   watch_maybe_just_location (arg, hw_access, from_tty);
11585 }
11586 \f
11587
11588 /* Data for the FSM that manages the until(location)/advance commands
11589    in infcmd.c.  Here because it uses the mechanisms of
11590    breakpoints.  */
11591
11592 struct until_break_fsm
11593 {
11594   /* The base class.  */
11595   struct thread_fsm thread_fsm;
11596
11597   /* The thread that as current when the command was executed.  */
11598   int thread;
11599
11600   /* The breakpoint set at the destination location.  */
11601   struct breakpoint *location_breakpoint;
11602
11603   /* Breakpoint set at the return address in the caller frame.  May be
11604      NULL.  */
11605   struct breakpoint *caller_breakpoint;
11606 };
11607
11608 static void until_break_fsm_clean_up (struct thread_fsm *self);
11609 static int until_break_fsm_should_stop (struct thread_fsm *self);
11610 static enum async_reply_reason
11611   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11612
11613 /* until_break_fsm's vtable.  */
11614
11615 static struct thread_fsm_ops until_break_fsm_ops =
11616 {
11617   NULL, /* dtor */
11618   until_break_fsm_clean_up,
11619   until_break_fsm_should_stop,
11620   NULL, /* return_value */
11621   until_break_fsm_async_reply_reason,
11622 };
11623
11624 /* Allocate a new until_break_command_fsm.  */
11625
11626 static struct until_break_fsm *
11627 new_until_break_fsm (int thread,
11628                      struct breakpoint *location_breakpoint,
11629                      struct breakpoint *caller_breakpoint)
11630 {
11631   struct until_break_fsm *sm;
11632
11633   sm = XCNEW (struct until_break_fsm);
11634   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops);
11635
11636   sm->thread = thread;
11637   sm->location_breakpoint = location_breakpoint;
11638   sm->caller_breakpoint = caller_breakpoint;
11639
11640   return sm;
11641 }
11642
11643 /* Implementation of the 'should_stop' FSM method for the
11644    until(location)/advance commands.  */
11645
11646 static int
11647 until_break_fsm_should_stop (struct thread_fsm *self)
11648 {
11649   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11650   struct thread_info *tp = inferior_thread ();
11651
11652   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11653                               sm->location_breakpoint) != NULL
11654       || (sm->caller_breakpoint != NULL
11655           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11656                                      sm->caller_breakpoint) != NULL))
11657     thread_fsm_set_finished (self);
11658
11659   return 1;
11660 }
11661
11662 /* Implementation of the 'clean_up' FSM method for the
11663    until(location)/advance commands.  */
11664
11665 static void
11666 until_break_fsm_clean_up (struct thread_fsm *self)
11667 {
11668   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11669
11670   /* Clean up our temporary breakpoints.  */
11671   if (sm->location_breakpoint != NULL)
11672     {
11673       delete_breakpoint (sm->location_breakpoint);
11674       sm->location_breakpoint = NULL;
11675     }
11676   if (sm->caller_breakpoint != NULL)
11677     {
11678       delete_breakpoint (sm->caller_breakpoint);
11679       sm->caller_breakpoint = NULL;
11680     }
11681   delete_longjmp_breakpoint (sm->thread);
11682 }
11683
11684 /* Implementation of the 'async_reply_reason' FSM method for the
11685    until(location)/advance commands.  */
11686
11687 static enum async_reply_reason
11688 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11689 {
11690   return EXEC_ASYNC_LOCATION_REACHED;
11691 }
11692
11693 void
11694 until_break_command (char *arg, int from_tty, int anywhere)
11695 {
11696   struct symtabs_and_lines sals;
11697   struct symtab_and_line sal;
11698   struct frame_info *frame;
11699   struct gdbarch *frame_gdbarch;
11700   struct frame_id stack_frame_id;
11701   struct frame_id caller_frame_id;
11702   struct breakpoint *location_breakpoint;
11703   struct breakpoint *caller_breakpoint = NULL;
11704   struct cleanup *old_chain, *cleanup;
11705   int thread;
11706   struct thread_info *tp;
11707   struct event_location *location;
11708   struct until_break_fsm *sm;
11709
11710   clear_proceed_status (0);
11711
11712   /* Set a breakpoint where the user wants it and at return from
11713      this function.  */
11714
11715   location = string_to_event_location (&arg, current_language);
11716   cleanup = make_cleanup_delete_event_location (location);
11717
11718   if (last_displayed_sal_is_valid ())
11719     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE, NULL,
11720                           get_last_displayed_symtab (),
11721                           get_last_displayed_line ());
11722   else
11723     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11724                           NULL, (struct symtab *) NULL, 0);
11725
11726   if (sals.nelts != 1)
11727     error (_("Couldn't get information on specified line."));
11728
11729   sal = sals.sals[0];
11730   xfree (sals.sals);    /* malloc'd, so freed.  */
11731
11732   if (*arg)
11733     error (_("Junk at end of arguments."));
11734
11735   resolve_sal_pc (&sal);
11736
11737   tp = inferior_thread ();
11738   thread = tp->global_num;
11739
11740   old_chain = make_cleanup (null_cleanup, NULL);
11741
11742   /* Note linespec handling above invalidates the frame chain.
11743      Installing a breakpoint also invalidates the frame chain (as it
11744      may need to switch threads), so do any frame handling before
11745      that.  */
11746
11747   frame = get_selected_frame (NULL);
11748   frame_gdbarch = get_frame_arch (frame);
11749   stack_frame_id = get_stack_frame_id (frame);
11750   caller_frame_id = frame_unwind_caller_id (frame);
11751
11752   /* Keep within the current frame, or in frames called by the current
11753      one.  */
11754
11755   if (frame_id_p (caller_frame_id))
11756     {
11757       struct symtab_and_line sal2;
11758       struct gdbarch *caller_gdbarch;
11759
11760       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11761       sal2.pc = frame_unwind_caller_pc (frame);
11762       caller_gdbarch = frame_unwind_caller_arch (frame);
11763       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11764                                                     sal2,
11765                                                     caller_frame_id,
11766                                                     bp_until);
11767       make_cleanup_delete_breakpoint (caller_breakpoint);
11768
11769       set_longjmp_breakpoint (tp, caller_frame_id);
11770       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11771     }
11772
11773   /* set_momentary_breakpoint could invalidate FRAME.  */
11774   frame = NULL;
11775
11776   if (anywhere)
11777     /* If the user told us to continue until a specified location,
11778        we don't specify a frame at which we need to stop.  */
11779     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11780                                                     null_frame_id, bp_until);
11781   else
11782     /* Otherwise, specify the selected frame, because we want to stop
11783        only at the very same frame.  */
11784     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11785                                                     stack_frame_id, bp_until);
11786   make_cleanup_delete_breakpoint (location_breakpoint);
11787
11788   sm = new_until_break_fsm (tp->global_num,
11789                             location_breakpoint, caller_breakpoint);
11790   tp->thread_fsm = &sm->thread_fsm;
11791
11792   discard_cleanups (old_chain);
11793
11794   proceed (-1, GDB_SIGNAL_DEFAULT);
11795
11796   do_cleanups (cleanup);
11797 }
11798
11799 /* This function attempts to parse an optional "if <cond>" clause
11800    from the arg string.  If one is not found, it returns NULL.
11801
11802    Else, it returns a pointer to the condition string.  (It does not
11803    attempt to evaluate the string against a particular block.)  And,
11804    it updates arg to point to the first character following the parsed
11805    if clause in the arg string.  */
11806
11807 char *
11808 ep_parse_optional_if_clause (char **arg)
11809 {
11810   char *cond_string;
11811
11812   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11813     return NULL;
11814
11815   /* Skip the "if" keyword.  */
11816   (*arg) += 2;
11817
11818   /* Skip any extra leading whitespace, and record the start of the
11819      condition string.  */
11820   *arg = skip_spaces (*arg);
11821   cond_string = *arg;
11822
11823   /* Assume that the condition occupies the remainder of the arg
11824      string.  */
11825   (*arg) += strlen (cond_string);
11826
11827   return cond_string;
11828 }
11829
11830 /* Commands to deal with catching events, such as signals, exceptions,
11831    process start/exit, etc.  */
11832
11833 typedef enum
11834 {
11835   catch_fork_temporary, catch_vfork_temporary,
11836   catch_fork_permanent, catch_vfork_permanent
11837 }
11838 catch_fork_kind;
11839
11840 static void
11841 catch_fork_command_1 (char *arg, int from_tty, 
11842                       struct cmd_list_element *command)
11843 {
11844   struct gdbarch *gdbarch = get_current_arch ();
11845   char *cond_string = NULL;
11846   catch_fork_kind fork_kind;
11847   int tempflag;
11848
11849   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11850   tempflag = (fork_kind == catch_fork_temporary
11851               || fork_kind == catch_vfork_temporary);
11852
11853   if (!arg)
11854     arg = "";
11855   arg = skip_spaces (arg);
11856
11857   /* The allowed syntax is:
11858      catch [v]fork
11859      catch [v]fork if <cond>
11860
11861      First, check if there's an if clause.  */
11862   cond_string = ep_parse_optional_if_clause (&arg);
11863
11864   if ((*arg != '\0') && !isspace (*arg))
11865     error (_("Junk at end of arguments."));
11866
11867   /* If this target supports it, create a fork or vfork catchpoint
11868      and enable reporting of such events.  */
11869   switch (fork_kind)
11870     {
11871     case catch_fork_temporary:
11872     case catch_fork_permanent:
11873       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11874                                           &catch_fork_breakpoint_ops);
11875       break;
11876     case catch_vfork_temporary:
11877     case catch_vfork_permanent:
11878       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11879                                           &catch_vfork_breakpoint_ops);
11880       break;
11881     default:
11882       error (_("unsupported or unknown fork kind; cannot catch it"));
11883       break;
11884     }
11885 }
11886
11887 static void
11888 catch_exec_command_1 (char *arg, int from_tty, 
11889                       struct cmd_list_element *command)
11890 {
11891   struct exec_catchpoint *c;
11892   struct gdbarch *gdbarch = get_current_arch ();
11893   int tempflag;
11894   char *cond_string = NULL;
11895
11896   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11897
11898   if (!arg)
11899     arg = "";
11900   arg = skip_spaces (arg);
11901
11902   /* The allowed syntax is:
11903      catch exec
11904      catch exec if <cond>
11905
11906      First, check if there's an if clause.  */
11907   cond_string = ep_parse_optional_if_clause (&arg);
11908
11909   if ((*arg != '\0') && !isspace (*arg))
11910     error (_("Junk at end of arguments."));
11911
11912   c = XNEW (struct exec_catchpoint);
11913   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11914                    &catch_exec_breakpoint_ops);
11915   c->exec_pathname = NULL;
11916
11917   install_breakpoint (0, &c->base, 1);
11918 }
11919
11920 void
11921 init_ada_exception_breakpoint (struct breakpoint *b,
11922                                struct gdbarch *gdbarch,
11923                                struct symtab_and_line sal,
11924                                char *addr_string,
11925                                const struct breakpoint_ops *ops,
11926                                int tempflag,
11927                                int enabled,
11928                                int from_tty)
11929 {
11930   if (from_tty)
11931     {
11932       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11933       if (!loc_gdbarch)
11934         loc_gdbarch = gdbarch;
11935
11936       describe_other_breakpoints (loc_gdbarch,
11937                                   sal.pspace, sal.pc, sal.section, -1);
11938       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11939          version for exception catchpoints, because two catchpoints
11940          used for different exception names will use the same address.
11941          In this case, a "breakpoint ... also set at..." warning is
11942          unproductive.  Besides, the warning phrasing is also a bit
11943          inappropriate, we should use the word catchpoint, and tell
11944          the user what type of catchpoint it is.  The above is good
11945          enough for now, though.  */
11946     }
11947
11948   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11949
11950   b->enable_state = enabled ? bp_enabled : bp_disabled;
11951   b->disposition = tempflag ? disp_del : disp_donttouch;
11952   b->location = string_to_event_location (&addr_string,
11953                                           language_def (language_ada));
11954   b->language = language_ada;
11955 }
11956
11957 static void
11958 catch_command (char *arg, int from_tty)
11959 {
11960   error (_("Catch requires an event name."));
11961 }
11962 \f
11963
11964 static void
11965 tcatch_command (char *arg, int from_tty)
11966 {
11967   error (_("Catch requires an event name."));
11968 }
11969
11970 /* A qsort comparison function that sorts breakpoints in order.  */
11971
11972 static int
11973 compare_breakpoints (const void *a, const void *b)
11974 {
11975   const breakpoint_p *ba = (const breakpoint_p *) a;
11976   uintptr_t ua = (uintptr_t) *ba;
11977   const breakpoint_p *bb = (const breakpoint_p *) b;
11978   uintptr_t ub = (uintptr_t) *bb;
11979
11980   if ((*ba)->number < (*bb)->number)
11981     return -1;
11982   else if ((*ba)->number > (*bb)->number)
11983     return 1;
11984
11985   /* Now sort by address, in case we see, e..g, two breakpoints with
11986      the number 0.  */
11987   if (ua < ub)
11988     return -1;
11989   return ua > ub ? 1 : 0;
11990 }
11991
11992 /* Delete breakpoints by address or line.  */
11993
11994 static void
11995 clear_command (char *arg, int from_tty)
11996 {
11997   struct breakpoint *b, *prev;
11998   VEC(breakpoint_p) *found = 0;
11999   int ix;
12000   int default_match;
12001   struct symtabs_and_lines sals;
12002   struct symtab_and_line sal;
12003   int i;
12004   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12005
12006   if (arg)
12007     {
12008       sals = decode_line_with_current_source (arg,
12009                                               (DECODE_LINE_FUNFIRSTLINE
12010                                                | DECODE_LINE_LIST_MODE));
12011       make_cleanup (xfree, sals.sals);
12012       default_match = 0;
12013     }
12014   else
12015     {
12016       sals.sals = XNEW (struct symtab_and_line);
12017       make_cleanup (xfree, sals.sals);
12018       init_sal (&sal);          /* Initialize to zeroes.  */
12019
12020       /* Set sal's line, symtab, pc, and pspace to the values
12021          corresponding to the last call to print_frame_info.  If the
12022          codepoint is not valid, this will set all the fields to 0.  */
12023       get_last_displayed_sal (&sal);
12024       if (sal.symtab == 0)
12025         error (_("No source file specified."));
12026
12027       sals.sals[0] = sal;
12028       sals.nelts = 1;
12029
12030       default_match = 1;
12031     }
12032
12033   /* We don't call resolve_sal_pc here.  That's not as bad as it
12034      seems, because all existing breakpoints typically have both
12035      file/line and pc set.  So, if clear is given file/line, we can
12036      match this to existing breakpoint without obtaining pc at all.
12037
12038      We only support clearing given the address explicitly 
12039      present in breakpoint table.  Say, we've set breakpoint 
12040      at file:line.  There were several PC values for that file:line,
12041      due to optimization, all in one block.
12042
12043      We've picked one PC value.  If "clear" is issued with another
12044      PC corresponding to the same file:line, the breakpoint won't
12045      be cleared.  We probably can still clear the breakpoint, but 
12046      since the other PC value is never presented to user, user
12047      can only find it by guessing, and it does not seem important
12048      to support that.  */
12049
12050   /* For each line spec given, delete bps which correspond to it.  Do
12051      it in two passes, solely to preserve the current behavior that
12052      from_tty is forced true if we delete more than one
12053      breakpoint.  */
12054
12055   found = NULL;
12056   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12057   for (i = 0; i < sals.nelts; i++)
12058     {
12059       const char *sal_fullname;
12060
12061       /* If exact pc given, clear bpts at that pc.
12062          If line given (pc == 0), clear all bpts on specified line.
12063          If defaulting, clear all bpts on default line
12064          or at default pc.
12065
12066          defaulting    sal.pc != 0    tests to do
12067
12068          0              1             pc
12069          1              1             pc _and_ line
12070          0              0             line
12071          1              0             <can't happen> */
12072
12073       sal = sals.sals[i];
12074       sal_fullname = (sal.symtab == NULL
12075                       ? NULL : symtab_to_fullname (sal.symtab));
12076
12077       /* Find all matching breakpoints and add them to 'found'.  */
12078       ALL_BREAKPOINTS (b)
12079         {
12080           int match = 0;
12081           /* Are we going to delete b?  */
12082           if (b->type != bp_none && !is_watchpoint (b))
12083             {
12084               struct bp_location *loc = b->loc;
12085               for (; loc; loc = loc->next)
12086                 {
12087                   /* If the user specified file:line, don't allow a PC
12088                      match.  This matches historical gdb behavior.  */
12089                   int pc_match = (!sal.explicit_line
12090                                   && sal.pc
12091                                   && (loc->pspace == sal.pspace)
12092                                   && (loc->address == sal.pc)
12093                                   && (!section_is_overlay (loc->section)
12094                                       || loc->section == sal.section));
12095                   int line_match = 0;
12096
12097                   if ((default_match || sal.explicit_line)
12098                       && loc->symtab != NULL
12099                       && sal_fullname != NULL
12100                       && sal.pspace == loc->pspace
12101                       && loc->line_number == sal.line
12102                       && filename_cmp (symtab_to_fullname (loc->symtab),
12103                                        sal_fullname) == 0)
12104                     line_match = 1;
12105
12106                   if (pc_match || line_match)
12107                     {
12108                       match = 1;
12109                       break;
12110                     }
12111                 }
12112             }
12113
12114           if (match)
12115             VEC_safe_push(breakpoint_p, found, b);
12116         }
12117     }
12118
12119   /* Now go thru the 'found' chain and delete them.  */
12120   if (VEC_empty(breakpoint_p, found))
12121     {
12122       if (arg)
12123         error (_("No breakpoint at %s."), arg);
12124       else
12125         error (_("No breakpoint at this line."));
12126     }
12127
12128   /* Remove duplicates from the vec.  */
12129   qsort (VEC_address (breakpoint_p, found),
12130          VEC_length (breakpoint_p, found),
12131          sizeof (breakpoint_p),
12132          compare_breakpoints);
12133   prev = VEC_index (breakpoint_p, found, 0);
12134   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12135     {
12136       if (b == prev)
12137         {
12138           VEC_ordered_remove (breakpoint_p, found, ix);
12139           --ix;
12140         }
12141     }
12142
12143   if (VEC_length(breakpoint_p, found) > 1)
12144     from_tty = 1;       /* Always report if deleted more than one.  */
12145   if (from_tty)
12146     {
12147       if (VEC_length(breakpoint_p, found) == 1)
12148         printf_unfiltered (_("Deleted breakpoint "));
12149       else
12150         printf_unfiltered (_("Deleted breakpoints "));
12151     }
12152
12153   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12154     {
12155       if (from_tty)
12156         printf_unfiltered ("%d ", b->number);
12157       delete_breakpoint (b);
12158     }
12159   if (from_tty)
12160     putchar_unfiltered ('\n');
12161
12162   do_cleanups (cleanups);
12163 }
12164 \f
12165 /* Delete breakpoint in BS if they are `delete' breakpoints and
12166    all breakpoints that are marked for deletion, whether hit or not.
12167    This is called after any breakpoint is hit, or after errors.  */
12168
12169 void
12170 breakpoint_auto_delete (bpstat bs)
12171 {
12172   struct breakpoint *b, *b_tmp;
12173
12174   for (; bs; bs = bs->next)
12175     if (bs->breakpoint_at
12176         && bs->breakpoint_at->disposition == disp_del
12177         && bs->stop)
12178       delete_breakpoint (bs->breakpoint_at);
12179
12180   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12181   {
12182     if (b->disposition == disp_del_at_next_stop)
12183       delete_breakpoint (b);
12184   }
12185 }
12186
12187 /* A comparison function for bp_location AP and BP being interfaced to
12188    qsort.  Sort elements primarily by their ADDRESS (no matter what
12189    does breakpoint_address_is_meaningful say for its OWNER),
12190    secondarily by ordering first permanent elements and
12191    terciarily just ensuring the array is sorted stable way despite
12192    qsort being an unstable algorithm.  */
12193
12194 static int
12195 bp_location_compare (const void *ap, const void *bp)
12196 {
12197   const struct bp_location *a = *(const struct bp_location **) ap;
12198   const struct bp_location *b = *(const struct bp_location **) bp;
12199
12200   if (a->address != b->address)
12201     return (a->address > b->address) - (a->address < b->address);
12202
12203   /* Sort locations at the same address by their pspace number, keeping
12204      locations of the same inferior (in a multi-inferior environment)
12205      grouped.  */
12206
12207   if (a->pspace->num != b->pspace->num)
12208     return ((a->pspace->num > b->pspace->num)
12209             - (a->pspace->num < b->pspace->num));
12210
12211   /* Sort permanent breakpoints first.  */
12212   if (a->permanent != b->permanent)
12213     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12214
12215   /* Make the internal GDB representation stable across GDB runs
12216      where A and B memory inside GDB can differ.  Breakpoint locations of
12217      the same type at the same address can be sorted in arbitrary order.  */
12218
12219   if (a->owner->number != b->owner->number)
12220     return ((a->owner->number > b->owner->number)
12221             - (a->owner->number < b->owner->number));
12222
12223   return (a > b) - (a < b);
12224 }
12225
12226 /* Set bp_location_placed_address_before_address_max and
12227    bp_location_shadow_len_after_address_max according to the current
12228    content of the bp_location array.  */
12229
12230 static void
12231 bp_location_target_extensions_update (void)
12232 {
12233   struct bp_location *bl, **blp_tmp;
12234
12235   bp_location_placed_address_before_address_max = 0;
12236   bp_location_shadow_len_after_address_max = 0;
12237
12238   ALL_BP_LOCATIONS (bl, blp_tmp)
12239     {
12240       CORE_ADDR start, end, addr;
12241
12242       if (!bp_location_has_shadow (bl))
12243         continue;
12244
12245       start = bl->target_info.placed_address;
12246       end = start + bl->target_info.shadow_len;
12247
12248       gdb_assert (bl->address >= start);
12249       addr = bl->address - start;
12250       if (addr > bp_location_placed_address_before_address_max)
12251         bp_location_placed_address_before_address_max = addr;
12252
12253       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12254
12255       gdb_assert (bl->address < end);
12256       addr = end - bl->address;
12257       if (addr > bp_location_shadow_len_after_address_max)
12258         bp_location_shadow_len_after_address_max = addr;
12259     }
12260 }
12261
12262 /* Download tracepoint locations if they haven't been.  */
12263
12264 static void
12265 download_tracepoint_locations (void)
12266 {
12267   struct breakpoint *b;
12268   struct cleanup *old_chain;
12269   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12270
12271   old_chain = save_current_space_and_thread ();
12272
12273   ALL_TRACEPOINTS (b)
12274     {
12275       struct bp_location *bl;
12276       struct tracepoint *t;
12277       int bp_location_downloaded = 0;
12278
12279       if ((b->type == bp_fast_tracepoint
12280            ? !may_insert_fast_tracepoints
12281            : !may_insert_tracepoints))
12282         continue;
12283
12284       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12285         {
12286           if (target_can_download_tracepoint ())
12287             can_download_tracepoint = TRIBOOL_TRUE;
12288           else
12289             can_download_tracepoint = TRIBOOL_FALSE;
12290         }
12291
12292       if (can_download_tracepoint == TRIBOOL_FALSE)
12293         break;
12294
12295       for (bl = b->loc; bl; bl = bl->next)
12296         {
12297           /* In tracepoint, locations are _never_ duplicated, so
12298              should_be_inserted is equivalent to
12299              unduplicated_should_be_inserted.  */
12300           if (!should_be_inserted (bl) || bl->inserted)
12301             continue;
12302
12303           switch_to_program_space_and_thread (bl->pspace);
12304
12305           target_download_tracepoint (bl);
12306
12307           bl->inserted = 1;
12308           bp_location_downloaded = 1;
12309         }
12310       t = (struct tracepoint *) b;
12311       t->number_on_target = b->number;
12312       if (bp_location_downloaded)
12313         observer_notify_breakpoint_modified (b);
12314     }
12315
12316   do_cleanups (old_chain);
12317 }
12318
12319 /* Swap the insertion/duplication state between two locations.  */
12320
12321 static void
12322 swap_insertion (struct bp_location *left, struct bp_location *right)
12323 {
12324   const int left_inserted = left->inserted;
12325   const int left_duplicate = left->duplicate;
12326   const int left_needs_update = left->needs_update;
12327   const struct bp_target_info left_target_info = left->target_info;
12328
12329   /* Locations of tracepoints can never be duplicated.  */
12330   if (is_tracepoint (left->owner))
12331     gdb_assert (!left->duplicate);
12332   if (is_tracepoint (right->owner))
12333     gdb_assert (!right->duplicate);
12334
12335   left->inserted = right->inserted;
12336   left->duplicate = right->duplicate;
12337   left->needs_update = right->needs_update;
12338   left->target_info = right->target_info;
12339   right->inserted = left_inserted;
12340   right->duplicate = left_duplicate;
12341   right->needs_update = left_needs_update;
12342   right->target_info = left_target_info;
12343 }
12344
12345 /* Force the re-insertion of the locations at ADDRESS.  This is called
12346    once a new/deleted/modified duplicate location is found and we are evaluating
12347    conditions on the target's side.  Such conditions need to be updated on
12348    the target.  */
12349
12350 static void
12351 force_breakpoint_reinsertion (struct bp_location *bl)
12352 {
12353   struct bp_location **locp = NULL, **loc2p;
12354   struct bp_location *loc;
12355   CORE_ADDR address = 0;
12356   int pspace_num;
12357
12358   address = bl->address;
12359   pspace_num = bl->pspace->num;
12360
12361   /* This is only meaningful if the target is
12362      evaluating conditions and if the user has
12363      opted for condition evaluation on the target's
12364      side.  */
12365   if (gdb_evaluates_breakpoint_condition_p ()
12366       || !target_supports_evaluation_of_breakpoint_conditions ())
12367     return;
12368
12369   /* Flag all breakpoint locations with this address and
12370      the same program space as the location
12371      as "its condition has changed".  We need to
12372      update the conditions on the target's side.  */
12373   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12374     {
12375       loc = *loc2p;
12376
12377       if (!is_breakpoint (loc->owner)
12378           || pspace_num != loc->pspace->num)
12379         continue;
12380
12381       /* Flag the location appropriately.  We use a different state to
12382          let everyone know that we already updated the set of locations
12383          with addr bl->address and program space bl->pspace.  This is so
12384          we don't have to keep calling these functions just to mark locations
12385          that have already been marked.  */
12386       loc->condition_changed = condition_updated;
12387
12388       /* Free the agent expression bytecode as well.  We will compute
12389          it later on.  */
12390       if (loc->cond_bytecode)
12391         {
12392           free_agent_expr (loc->cond_bytecode);
12393           loc->cond_bytecode = NULL;
12394         }
12395     }
12396 }
12397 /* Called whether new breakpoints are created, or existing breakpoints
12398    deleted, to update the global location list and recompute which
12399    locations are duplicate of which.
12400
12401    The INSERT_MODE flag determines whether locations may not, may, or
12402    shall be inserted now.  See 'enum ugll_insert_mode' for more
12403    info.  */
12404
12405 static void
12406 update_global_location_list (enum ugll_insert_mode insert_mode)
12407 {
12408   struct breakpoint *b;
12409   struct bp_location **locp, *loc;
12410   struct cleanup *cleanups;
12411   /* Last breakpoint location address that was marked for update.  */
12412   CORE_ADDR last_addr = 0;
12413   /* Last breakpoint location program space that was marked for update.  */
12414   int last_pspace_num = -1;
12415
12416   /* Used in the duplicates detection below.  When iterating over all
12417      bp_locations, points to the first bp_location of a given address.
12418      Breakpoints and watchpoints of different types are never
12419      duplicates of each other.  Keep one pointer for each type of
12420      breakpoint/watchpoint, so we only need to loop over all locations
12421      once.  */
12422   struct bp_location *bp_loc_first;  /* breakpoint */
12423   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12424   struct bp_location *awp_loc_first; /* access watchpoint */
12425   struct bp_location *rwp_loc_first; /* read watchpoint */
12426
12427   /* Saved former bp_location array which we compare against the newly
12428      built bp_location from the current state of ALL_BREAKPOINTS.  */
12429   struct bp_location **old_location, **old_locp;
12430   unsigned old_location_count;
12431
12432   old_location = bp_location;
12433   old_location_count = bp_location_count;
12434   bp_location = NULL;
12435   bp_location_count = 0;
12436   cleanups = make_cleanup (xfree, old_location);
12437
12438   ALL_BREAKPOINTS (b)
12439     for (loc = b->loc; loc; loc = loc->next)
12440       bp_location_count++;
12441
12442   bp_location = XNEWVEC (struct bp_location *, bp_location_count);
12443   locp = bp_location;
12444   ALL_BREAKPOINTS (b)
12445     for (loc = b->loc; loc; loc = loc->next)
12446       *locp++ = loc;
12447   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12448          bp_location_compare);
12449
12450   bp_location_target_extensions_update ();
12451
12452   /* Identify bp_location instances that are no longer present in the
12453      new list, and therefore should be freed.  Note that it's not
12454      necessary that those locations should be removed from inferior --
12455      if there's another location at the same address (previously
12456      marked as duplicate), we don't need to remove/insert the
12457      location.
12458      
12459      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12460      and former bp_location array state respectively.  */
12461
12462   locp = bp_location;
12463   for (old_locp = old_location; old_locp < old_location + old_location_count;
12464        old_locp++)
12465     {
12466       struct bp_location *old_loc = *old_locp;
12467       struct bp_location **loc2p;
12468
12469       /* Tells if 'old_loc' is found among the new locations.  If
12470          not, we have to free it.  */
12471       int found_object = 0;
12472       /* Tells if the location should remain inserted in the target.  */
12473       int keep_in_target = 0;
12474       int removed = 0;
12475
12476       /* Skip LOCP entries which will definitely never be needed.
12477          Stop either at or being the one matching OLD_LOC.  */
12478       while (locp < bp_location + bp_location_count
12479              && (*locp)->address < old_loc->address)
12480         locp++;
12481
12482       for (loc2p = locp;
12483            (loc2p < bp_location + bp_location_count
12484             && (*loc2p)->address == old_loc->address);
12485            loc2p++)
12486         {
12487           /* Check if this is a new/duplicated location or a duplicated
12488              location that had its condition modified.  If so, we want to send
12489              its condition to the target if evaluation of conditions is taking
12490              place there.  */
12491           if ((*loc2p)->condition_changed == condition_modified
12492               && (last_addr != old_loc->address
12493                   || last_pspace_num != old_loc->pspace->num))
12494             {
12495               force_breakpoint_reinsertion (*loc2p);
12496               last_pspace_num = old_loc->pspace->num;
12497             }
12498
12499           if (*loc2p == old_loc)
12500             found_object = 1;
12501         }
12502
12503       /* We have already handled this address, update it so that we don't
12504          have to go through updates again.  */
12505       last_addr = old_loc->address;
12506
12507       /* Target-side condition evaluation: Handle deleted locations.  */
12508       if (!found_object)
12509         force_breakpoint_reinsertion (old_loc);
12510
12511       /* If this location is no longer present, and inserted, look if
12512          there's maybe a new location at the same address.  If so,
12513          mark that one inserted, and don't remove this one.  This is
12514          needed so that we don't have a time window where a breakpoint
12515          at certain location is not inserted.  */
12516
12517       if (old_loc->inserted)
12518         {
12519           /* If the location is inserted now, we might have to remove
12520              it.  */
12521
12522           if (found_object && should_be_inserted (old_loc))
12523             {
12524               /* The location is still present in the location list,
12525                  and still should be inserted.  Don't do anything.  */
12526               keep_in_target = 1;
12527             }
12528           else
12529             {
12530               /* This location still exists, but it won't be kept in the
12531                  target since it may have been disabled.  We proceed to
12532                  remove its target-side condition.  */
12533
12534               /* The location is either no longer present, or got
12535                  disabled.  See if there's another location at the
12536                  same address, in which case we don't need to remove
12537                  this one from the target.  */
12538
12539               /* OLD_LOC comes from existing struct breakpoint.  */
12540               if (breakpoint_address_is_meaningful (old_loc->owner))
12541                 {
12542                   for (loc2p = locp;
12543                        (loc2p < bp_location + bp_location_count
12544                         && (*loc2p)->address == old_loc->address);
12545                        loc2p++)
12546                     {
12547                       struct bp_location *loc2 = *loc2p;
12548
12549                       if (breakpoint_locations_match (loc2, old_loc))
12550                         {
12551                           /* Read watchpoint locations are switched to
12552                              access watchpoints, if the former are not
12553                              supported, but the latter are.  */
12554                           if (is_hardware_watchpoint (old_loc->owner))
12555                             {
12556                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12557                               loc2->watchpoint_type = old_loc->watchpoint_type;
12558                             }
12559
12560                           /* loc2 is a duplicated location. We need to check
12561                              if it should be inserted in case it will be
12562                              unduplicated.  */
12563                           if (loc2 != old_loc
12564                               && unduplicated_should_be_inserted (loc2))
12565                             {
12566                               swap_insertion (old_loc, loc2);
12567                               keep_in_target = 1;
12568                               break;
12569                             }
12570                         }
12571                     }
12572                 }
12573             }
12574
12575           if (!keep_in_target)
12576             {
12577               if (remove_breakpoint (old_loc, mark_uninserted))
12578                 {
12579                   /* This is just about all we can do.  We could keep
12580                      this location on the global list, and try to
12581                      remove it next time, but there's no particular
12582                      reason why we will succeed next time.
12583                      
12584                      Note that at this point, old_loc->owner is still
12585                      valid, as delete_breakpoint frees the breakpoint
12586                      only after calling us.  */
12587                   printf_filtered (_("warning: Error removing "
12588                                      "breakpoint %d\n"), 
12589                                    old_loc->owner->number);
12590                 }
12591               removed = 1;
12592             }
12593         }
12594
12595       if (!found_object)
12596         {
12597           if (removed && target_is_non_stop_p ()
12598               && need_moribund_for_location_type (old_loc))
12599             {
12600               /* This location was removed from the target.  In
12601                  non-stop mode, a race condition is possible where
12602                  we've removed a breakpoint, but stop events for that
12603                  breakpoint are already queued and will arrive later.
12604                  We apply an heuristic to be able to distinguish such
12605                  SIGTRAPs from other random SIGTRAPs: we keep this
12606                  breakpoint location for a bit, and will retire it
12607                  after we see some number of events.  The theory here
12608                  is that reporting of events should, "on the average",
12609                  be fair, so after a while we'll see events from all
12610                  threads that have anything of interest, and no longer
12611                  need to keep this breakpoint location around.  We
12612                  don't hold locations forever so to reduce chances of
12613                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12614                  SIGTRAP.
12615
12616                  The heuristic failing can be disastrous on
12617                  decr_pc_after_break targets.
12618
12619                  On decr_pc_after_break targets, like e.g., x86-linux,
12620                  if we fail to recognize a late breakpoint SIGTRAP,
12621                  because events_till_retirement has reached 0 too
12622                  soon, we'll fail to do the PC adjustment, and report
12623                  a random SIGTRAP to the user.  When the user resumes
12624                  the inferior, it will most likely immediately crash
12625                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12626                  corrupted, because of being resumed e.g., in the
12627                  middle of a multi-byte instruction, or skipped a
12628                  one-byte instruction.  This was actually seen happen
12629                  on native x86-linux, and should be less rare on
12630                  targets that do not support new thread events, like
12631                  remote, due to the heuristic depending on
12632                  thread_count.
12633
12634                  Mistaking a random SIGTRAP for a breakpoint trap
12635                  causes similar symptoms (PC adjustment applied when
12636                  it shouldn't), but then again, playing with SIGTRAPs
12637                  behind the debugger's back is asking for trouble.
12638
12639                  Since hardware watchpoint traps are always
12640                  distinguishable from other traps, so we don't need to
12641                  apply keep hardware watchpoint moribund locations
12642                  around.  We simply always ignore hardware watchpoint
12643                  traps we can no longer explain.  */
12644
12645               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12646               old_loc->owner = NULL;
12647
12648               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12649             }
12650           else
12651             {
12652               old_loc->owner = NULL;
12653               decref_bp_location (&old_loc);
12654             }
12655         }
12656     }
12657
12658   /* Rescan breakpoints at the same address and section, marking the
12659      first one as "first" and any others as "duplicates".  This is so
12660      that the bpt instruction is only inserted once.  If we have a
12661      permanent breakpoint at the same place as BPT, make that one the
12662      official one, and the rest as duplicates.  Permanent breakpoints
12663      are sorted first for the same address.
12664
12665      Do the same for hardware watchpoints, but also considering the
12666      watchpoint's type (regular/access/read) and length.  */
12667
12668   bp_loc_first = NULL;
12669   wp_loc_first = NULL;
12670   awp_loc_first = NULL;
12671   rwp_loc_first = NULL;
12672   ALL_BP_LOCATIONS (loc, locp)
12673     {
12674       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12675          non-NULL.  */
12676       struct bp_location **loc_first_p;
12677       b = loc->owner;
12678
12679       if (!unduplicated_should_be_inserted (loc)
12680           || !breakpoint_address_is_meaningful (b)
12681           /* Don't detect duplicate for tracepoint locations because they are
12682            never duplicated.  See the comments in field `duplicate' of
12683            `struct bp_location'.  */
12684           || is_tracepoint (b))
12685         {
12686           /* Clear the condition modification flag.  */
12687           loc->condition_changed = condition_unchanged;
12688           continue;
12689         }
12690
12691       if (b->type == bp_hardware_watchpoint)
12692         loc_first_p = &wp_loc_first;
12693       else if (b->type == bp_read_watchpoint)
12694         loc_first_p = &rwp_loc_first;
12695       else if (b->type == bp_access_watchpoint)
12696         loc_first_p = &awp_loc_first;
12697       else
12698         loc_first_p = &bp_loc_first;
12699
12700       if (*loc_first_p == NULL
12701           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12702           || !breakpoint_locations_match (loc, *loc_first_p))
12703         {
12704           *loc_first_p = loc;
12705           loc->duplicate = 0;
12706
12707           if (is_breakpoint (loc->owner) && loc->condition_changed)
12708             {
12709               loc->needs_update = 1;
12710               /* Clear the condition modification flag.  */
12711               loc->condition_changed = condition_unchanged;
12712             }
12713           continue;
12714         }
12715
12716
12717       /* This and the above ensure the invariant that the first location
12718          is not duplicated, and is the inserted one.
12719          All following are marked as duplicated, and are not inserted.  */
12720       if (loc->inserted)
12721         swap_insertion (loc, *loc_first_p);
12722       loc->duplicate = 1;
12723
12724       /* Clear the condition modification flag.  */
12725       loc->condition_changed = condition_unchanged;
12726     }
12727
12728   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12729     {
12730       if (insert_mode != UGLL_DONT_INSERT)
12731         insert_breakpoint_locations ();
12732       else
12733         {
12734           /* Even though the caller told us to not insert new
12735              locations, we may still need to update conditions on the
12736              target's side of breakpoints that were already inserted
12737              if the target is evaluating breakpoint conditions.  We
12738              only update conditions for locations that are marked
12739              "needs_update".  */
12740           update_inserted_breakpoint_locations ();
12741         }
12742     }
12743
12744   if (insert_mode != UGLL_DONT_INSERT)
12745     download_tracepoint_locations ();
12746
12747   do_cleanups (cleanups);
12748 }
12749
12750 void
12751 breakpoint_retire_moribund (void)
12752 {
12753   struct bp_location *loc;
12754   int ix;
12755
12756   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12757     if (--(loc->events_till_retirement) == 0)
12758       {
12759         decref_bp_location (&loc);
12760         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12761         --ix;
12762       }
12763 }
12764
12765 static void
12766 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12767 {
12768
12769   TRY
12770     {
12771       update_global_location_list (insert_mode);
12772     }
12773   CATCH (e, RETURN_MASK_ERROR)
12774     {
12775     }
12776   END_CATCH
12777 }
12778
12779 /* Clear BKP from a BPS.  */
12780
12781 static void
12782 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12783 {
12784   bpstat bs;
12785
12786   for (bs = bps; bs; bs = bs->next)
12787     if (bs->breakpoint_at == bpt)
12788       {
12789         bs->breakpoint_at = NULL;
12790         bs->old_val = NULL;
12791         /* bs->commands will be freed later.  */
12792       }
12793 }
12794
12795 /* Callback for iterate_over_threads.  */
12796 static int
12797 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12798 {
12799   struct breakpoint *bpt = (struct breakpoint *) data;
12800
12801   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12802   return 0;
12803 }
12804
12805 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12806    callbacks.  */
12807
12808 static void
12809 say_where (struct breakpoint *b)
12810 {
12811   struct value_print_options opts;
12812
12813   get_user_print_options (&opts);
12814
12815   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12816      single string.  */
12817   if (b->loc == NULL)
12818     {
12819       /* For pending locations, the output differs slightly based
12820          on b->extra_string.  If this is non-NULL, it contains either
12821          a condition or dprintf arguments.  */
12822       if (b->extra_string == NULL)
12823         {
12824           printf_filtered (_(" (%s) pending."),
12825                            event_location_to_string (b->location));
12826         }
12827       else if (b->type == bp_dprintf)
12828         {
12829           printf_filtered (_(" (%s,%s) pending."),
12830                            event_location_to_string (b->location),
12831                            b->extra_string);
12832         }
12833       else
12834         {
12835           printf_filtered (_(" (%s %s) pending."),
12836                            event_location_to_string (b->location),
12837                            b->extra_string);
12838         }
12839     }
12840   else
12841     {
12842       if (opts.addressprint || b->loc->symtab == NULL)
12843         {
12844           printf_filtered (" at ");
12845           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12846                           gdb_stdout);
12847         }
12848       if (b->loc->symtab != NULL)
12849         {
12850           /* If there is a single location, we can print the location
12851              more nicely.  */
12852           if (b->loc->next == NULL)
12853             printf_filtered (": file %s, line %d.",
12854                              symtab_to_filename_for_display (b->loc->symtab),
12855                              b->loc->line_number);
12856           else
12857             /* This is not ideal, but each location may have a
12858                different file name, and this at least reflects the
12859                real situation somewhat.  */
12860             printf_filtered (": %s.",
12861                              event_location_to_string (b->location));
12862         }
12863
12864       if (b->loc->next)
12865         {
12866           struct bp_location *loc = b->loc;
12867           int n = 0;
12868           for (; loc; loc = loc->next)
12869             ++n;
12870           printf_filtered (" (%d locations)", n);
12871         }
12872     }
12873 }
12874
12875 /* Default bp_location_ops methods.  */
12876
12877 static void
12878 bp_location_dtor (struct bp_location *self)
12879 {
12880   xfree (self->cond);
12881   if (self->cond_bytecode)
12882     free_agent_expr (self->cond_bytecode);
12883   xfree (self->function_name);
12884
12885   VEC_free (agent_expr_p, self->target_info.conditions);
12886   VEC_free (agent_expr_p, self->target_info.tcommands);
12887 }
12888
12889 static const struct bp_location_ops bp_location_ops =
12890 {
12891   bp_location_dtor
12892 };
12893
12894 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12895    inherit from.  */
12896
12897 static void
12898 base_breakpoint_dtor (struct breakpoint *self)
12899 {
12900   decref_counted_command_line (&self->commands);
12901   xfree (self->cond_string);
12902   xfree (self->extra_string);
12903   xfree (self->filter);
12904   delete_event_location (self->location);
12905   delete_event_location (self->location_range_end);
12906 }
12907
12908 static struct bp_location *
12909 base_breakpoint_allocate_location (struct breakpoint *self)
12910 {
12911   struct bp_location *loc;
12912
12913   loc = XNEW (struct bp_location);
12914   init_bp_location (loc, &bp_location_ops, self);
12915   return loc;
12916 }
12917
12918 static void
12919 base_breakpoint_re_set (struct breakpoint *b)
12920 {
12921   /* Nothing to re-set. */
12922 }
12923
12924 #define internal_error_pure_virtual_called() \
12925   gdb_assert_not_reached ("pure virtual function called")
12926
12927 static int
12928 base_breakpoint_insert_location (struct bp_location *bl)
12929 {
12930   internal_error_pure_virtual_called ();
12931 }
12932
12933 static int
12934 base_breakpoint_remove_location (struct bp_location *bl)
12935 {
12936   internal_error_pure_virtual_called ();
12937 }
12938
12939 static int
12940 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12941                                 struct address_space *aspace,
12942                                 CORE_ADDR bp_addr,
12943                                 const struct target_waitstatus *ws)
12944 {
12945   internal_error_pure_virtual_called ();
12946 }
12947
12948 static void
12949 base_breakpoint_check_status (bpstat bs)
12950 {
12951   /* Always stop.   */
12952 }
12953
12954 /* A "works_in_software_mode" breakpoint_ops method that just internal
12955    errors.  */
12956
12957 static int
12958 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12959 {
12960   internal_error_pure_virtual_called ();
12961 }
12962
12963 /* A "resources_needed" breakpoint_ops method that just internal
12964    errors.  */
12965
12966 static int
12967 base_breakpoint_resources_needed (const struct bp_location *bl)
12968 {
12969   internal_error_pure_virtual_called ();
12970 }
12971
12972 static enum print_stop_action
12973 base_breakpoint_print_it (bpstat bs)
12974 {
12975   internal_error_pure_virtual_called ();
12976 }
12977
12978 static void
12979 base_breakpoint_print_one_detail (const struct breakpoint *self,
12980                                   struct ui_out *uiout)
12981 {
12982   /* nothing */
12983 }
12984
12985 static void
12986 base_breakpoint_print_mention (struct breakpoint *b)
12987 {
12988   internal_error_pure_virtual_called ();
12989 }
12990
12991 static void
12992 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12993 {
12994   internal_error_pure_virtual_called ();
12995 }
12996
12997 static void
12998 base_breakpoint_create_sals_from_location
12999   (const struct event_location *location,
13000    struct linespec_result *canonical,
13001    enum bptype type_wanted)
13002 {
13003   internal_error_pure_virtual_called ();
13004 }
13005
13006 static void
13007 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13008                                         struct linespec_result *c,
13009                                         char *cond_string,
13010                                         char *extra_string,
13011                                         enum bptype type_wanted,
13012                                         enum bpdisp disposition,
13013                                         int thread,
13014                                         int task, int ignore_count,
13015                                         const struct breakpoint_ops *o,
13016                                         int from_tty, int enabled,
13017                                         int internal, unsigned flags)
13018 {
13019   internal_error_pure_virtual_called ();
13020 }
13021
13022 static void
13023 base_breakpoint_decode_location (struct breakpoint *b,
13024                                  const struct event_location *location,
13025                                  struct program_space *search_pspace,
13026                                  struct symtabs_and_lines *sals)
13027 {
13028   internal_error_pure_virtual_called ();
13029 }
13030
13031 /* The default 'explains_signal' method.  */
13032
13033 static int
13034 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13035 {
13036   return 1;
13037 }
13038
13039 /* The default "after_condition_true" method.  */
13040
13041 static void
13042 base_breakpoint_after_condition_true (struct bpstats *bs)
13043 {
13044   /* Nothing to do.   */
13045 }
13046
13047 struct breakpoint_ops base_breakpoint_ops =
13048 {
13049   base_breakpoint_dtor,
13050   base_breakpoint_allocate_location,
13051   base_breakpoint_re_set,
13052   base_breakpoint_insert_location,
13053   base_breakpoint_remove_location,
13054   base_breakpoint_breakpoint_hit,
13055   base_breakpoint_check_status,
13056   base_breakpoint_resources_needed,
13057   base_breakpoint_works_in_software_mode,
13058   base_breakpoint_print_it,
13059   NULL,
13060   base_breakpoint_print_one_detail,
13061   base_breakpoint_print_mention,
13062   base_breakpoint_print_recreate,
13063   base_breakpoint_create_sals_from_location,
13064   base_breakpoint_create_breakpoints_sal,
13065   base_breakpoint_decode_location,
13066   base_breakpoint_explains_signal,
13067   base_breakpoint_after_condition_true,
13068 };
13069
13070 /* Default breakpoint_ops methods.  */
13071
13072 static void
13073 bkpt_re_set (struct breakpoint *b)
13074 {
13075   /* FIXME: is this still reachable?  */
13076   if (breakpoint_event_location_empty_p (b))
13077     {
13078       /* Anything without a location can't be re-set.  */
13079       delete_breakpoint (b);
13080       return;
13081     }
13082
13083   breakpoint_re_set_default (b);
13084 }
13085
13086 static int
13087 bkpt_insert_location (struct bp_location *bl)
13088 {
13089   if (bl->loc_type == bp_loc_hardware_breakpoint)
13090     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13091   else
13092     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13093 }
13094
13095 static int
13096 bkpt_remove_location (struct bp_location *bl)
13097 {
13098   if (bl->loc_type == bp_loc_hardware_breakpoint)
13099     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13100   else
13101     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13102 }
13103
13104 static int
13105 bkpt_breakpoint_hit (const struct bp_location *bl,
13106                      struct address_space *aspace, CORE_ADDR bp_addr,
13107                      const struct target_waitstatus *ws)
13108 {
13109   if (ws->kind != TARGET_WAITKIND_STOPPED
13110       || ws->value.sig != GDB_SIGNAL_TRAP)
13111     return 0;
13112
13113   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13114                                  aspace, bp_addr))
13115     return 0;
13116
13117   if (overlay_debugging         /* unmapped overlay section */
13118       && section_is_overlay (bl->section)
13119       && !section_is_mapped (bl->section))
13120     return 0;
13121
13122   return 1;
13123 }
13124
13125 static int
13126 dprintf_breakpoint_hit (const struct bp_location *bl,
13127                         struct address_space *aspace, CORE_ADDR bp_addr,
13128                         const struct target_waitstatus *ws)
13129 {
13130   if (dprintf_style == dprintf_style_agent
13131       && target_can_run_breakpoint_commands ())
13132     {
13133       /* An agent-style dprintf never causes a stop.  If we see a trap
13134          for this address it must be for a breakpoint that happens to
13135          be set at the same address.  */
13136       return 0;
13137     }
13138
13139   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13140 }
13141
13142 static int
13143 bkpt_resources_needed (const struct bp_location *bl)
13144 {
13145   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13146
13147   return 1;
13148 }
13149
13150 static enum print_stop_action
13151 bkpt_print_it (bpstat bs)
13152 {
13153   struct breakpoint *b;
13154   const struct bp_location *bl;
13155   int bp_temp;
13156   struct ui_out *uiout = current_uiout;
13157
13158   gdb_assert (bs->bp_location_at != NULL);
13159
13160   bl = bs->bp_location_at;
13161   b = bs->breakpoint_at;
13162
13163   bp_temp = b->disposition == disp_del;
13164   if (bl->address != bl->requested_address)
13165     breakpoint_adjustment_warning (bl->requested_address,
13166                                    bl->address,
13167                                    b->number, 1);
13168   annotate_breakpoint (b->number);
13169   maybe_print_thread_hit_breakpoint (uiout);
13170
13171   if (bp_temp)
13172     ui_out_text (uiout, "Temporary breakpoint ");
13173   else
13174     ui_out_text (uiout, "Breakpoint ");
13175   if (ui_out_is_mi_like_p (uiout))
13176     {
13177       ui_out_field_string (uiout, "reason",
13178                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13179       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13180     }
13181   ui_out_field_int (uiout, "bkptno", b->number);
13182   ui_out_text (uiout, ", ");
13183
13184   return PRINT_SRC_AND_LOC;
13185 }
13186
13187 static void
13188 bkpt_print_mention (struct breakpoint *b)
13189 {
13190   if (ui_out_is_mi_like_p (current_uiout))
13191     return;
13192
13193   switch (b->type)
13194     {
13195     case bp_breakpoint:
13196     case bp_gnu_ifunc_resolver:
13197       if (b->disposition == disp_del)
13198         printf_filtered (_("Temporary breakpoint"));
13199       else
13200         printf_filtered (_("Breakpoint"));
13201       printf_filtered (_(" %d"), b->number);
13202       if (b->type == bp_gnu_ifunc_resolver)
13203         printf_filtered (_(" at gnu-indirect-function resolver"));
13204       break;
13205     case bp_hardware_breakpoint:
13206       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13207       break;
13208     case bp_dprintf:
13209       printf_filtered (_("Dprintf %d"), b->number);
13210       break;
13211     }
13212
13213   say_where (b);
13214 }
13215
13216 static void
13217 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13218 {
13219   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13220     fprintf_unfiltered (fp, "tbreak");
13221   else if (tp->type == bp_breakpoint)
13222     fprintf_unfiltered (fp, "break");
13223   else if (tp->type == bp_hardware_breakpoint
13224            && tp->disposition == disp_del)
13225     fprintf_unfiltered (fp, "thbreak");
13226   else if (tp->type == bp_hardware_breakpoint)
13227     fprintf_unfiltered (fp, "hbreak");
13228   else
13229     internal_error (__FILE__, __LINE__,
13230                     _("unhandled breakpoint type %d"), (int) tp->type);
13231
13232   fprintf_unfiltered (fp, " %s",
13233                       event_location_to_string (tp->location));
13234
13235   /* Print out extra_string if this breakpoint is pending.  It might
13236      contain, for example, conditions that were set by the user.  */
13237   if (tp->loc == NULL && tp->extra_string != NULL)
13238     fprintf_unfiltered (fp, " %s", tp->extra_string);
13239
13240   print_recreate_thread (tp, fp);
13241 }
13242
13243 static void
13244 bkpt_create_sals_from_location (const struct event_location *location,
13245                                 struct linespec_result *canonical,
13246                                 enum bptype type_wanted)
13247 {
13248   create_sals_from_location_default (location, canonical, type_wanted);
13249 }
13250
13251 static void
13252 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13253                              struct linespec_result *canonical,
13254                              char *cond_string,
13255                              char *extra_string,
13256                              enum bptype type_wanted,
13257                              enum bpdisp disposition,
13258                              int thread,
13259                              int task, int ignore_count,
13260                              const struct breakpoint_ops *ops,
13261                              int from_tty, int enabled,
13262                              int internal, unsigned flags)
13263 {
13264   create_breakpoints_sal_default (gdbarch, canonical,
13265                                   cond_string, extra_string,
13266                                   type_wanted,
13267                                   disposition, thread, task,
13268                                   ignore_count, ops, from_tty,
13269                                   enabled, internal, flags);
13270 }
13271
13272 static void
13273 bkpt_decode_location (struct breakpoint *b,
13274                       const struct event_location *location,
13275                       struct program_space *search_pspace,
13276                       struct symtabs_and_lines *sals)
13277 {
13278   decode_location_default (b, location, search_pspace, sals);
13279 }
13280
13281 /* Virtual table for internal breakpoints.  */
13282
13283 static void
13284 internal_bkpt_re_set (struct breakpoint *b)
13285 {
13286   switch (b->type)
13287     {
13288       /* Delete overlay event and longjmp master breakpoints; they
13289          will be reset later by breakpoint_re_set.  */
13290     case bp_overlay_event:
13291     case bp_longjmp_master:
13292     case bp_std_terminate_master:
13293     case bp_exception_master:
13294       delete_breakpoint (b);
13295       break;
13296
13297       /* This breakpoint is special, it's set up when the inferior
13298          starts and we really don't want to touch it.  */
13299     case bp_shlib_event:
13300
13301       /* Like bp_shlib_event, this breakpoint type is special.  Once
13302          it is set up, we do not want to touch it.  */
13303     case bp_thread_event:
13304       break;
13305     }
13306 }
13307
13308 static void
13309 internal_bkpt_check_status (bpstat bs)
13310 {
13311   if (bs->breakpoint_at->type == bp_shlib_event)
13312     {
13313       /* If requested, stop when the dynamic linker notifies GDB of
13314          events.  This allows the user to get control and place
13315          breakpoints in initializer routines for dynamically loaded
13316          objects (among other things).  */
13317       bs->stop = stop_on_solib_events;
13318       bs->print = stop_on_solib_events;
13319     }
13320   else
13321     bs->stop = 0;
13322 }
13323
13324 static enum print_stop_action
13325 internal_bkpt_print_it (bpstat bs)
13326 {
13327   struct breakpoint *b;
13328
13329   b = bs->breakpoint_at;
13330
13331   switch (b->type)
13332     {
13333     case bp_shlib_event:
13334       /* Did we stop because the user set the stop_on_solib_events
13335          variable?  (If so, we report this as a generic, "Stopped due
13336          to shlib event" message.) */
13337       print_solib_event (0);
13338       break;
13339
13340     case bp_thread_event:
13341       /* Not sure how we will get here.
13342          GDB should not stop for these breakpoints.  */
13343       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13344       break;
13345
13346     case bp_overlay_event:
13347       /* By analogy with the thread event, GDB should not stop for these.  */
13348       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13349       break;
13350
13351     case bp_longjmp_master:
13352       /* These should never be enabled.  */
13353       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13354       break;
13355
13356     case bp_std_terminate_master:
13357       /* These should never be enabled.  */
13358       printf_filtered (_("std::terminate Master Breakpoint: "
13359                          "gdb should not stop!\n"));
13360       break;
13361
13362     case bp_exception_master:
13363       /* These should never be enabled.  */
13364       printf_filtered (_("Exception Master Breakpoint: "
13365                          "gdb should not stop!\n"));
13366       break;
13367     }
13368
13369   return PRINT_NOTHING;
13370 }
13371
13372 static void
13373 internal_bkpt_print_mention (struct breakpoint *b)
13374 {
13375   /* Nothing to mention.  These breakpoints are internal.  */
13376 }
13377
13378 /* Virtual table for momentary breakpoints  */
13379
13380 static void
13381 momentary_bkpt_re_set (struct breakpoint *b)
13382 {
13383   /* Keep temporary breakpoints, which can be encountered when we step
13384      over a dlopen call and solib_add is resetting the breakpoints.
13385      Otherwise these should have been blown away via the cleanup chain
13386      or by breakpoint_init_inferior when we rerun the executable.  */
13387 }
13388
13389 static void
13390 momentary_bkpt_check_status (bpstat bs)
13391 {
13392   /* Nothing.  The point of these breakpoints is causing a stop.  */
13393 }
13394
13395 static enum print_stop_action
13396 momentary_bkpt_print_it (bpstat bs)
13397 {
13398   return PRINT_UNKNOWN;
13399 }
13400
13401 static void
13402 momentary_bkpt_print_mention (struct breakpoint *b)
13403 {
13404   /* Nothing to mention.  These breakpoints are internal.  */
13405 }
13406
13407 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13408
13409    It gets cleared already on the removal of the first one of such placed
13410    breakpoints.  This is OK as they get all removed altogether.  */
13411
13412 static void
13413 longjmp_bkpt_dtor (struct breakpoint *self)
13414 {
13415   struct thread_info *tp = find_thread_global_id (self->thread);
13416
13417   if (tp)
13418     tp->initiating_frame = null_frame_id;
13419
13420   momentary_breakpoint_ops.dtor (self);
13421 }
13422
13423 /* Specific methods for probe breakpoints.  */
13424
13425 static int
13426 bkpt_probe_insert_location (struct bp_location *bl)
13427 {
13428   int v = bkpt_insert_location (bl);
13429
13430   if (v == 0)
13431     {
13432       /* The insertion was successful, now let's set the probe's semaphore
13433          if needed.  */
13434       if (bl->probe.probe->pops->set_semaphore != NULL)
13435         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13436                                               bl->probe.objfile,
13437                                               bl->gdbarch);
13438     }
13439
13440   return v;
13441 }
13442
13443 static int
13444 bkpt_probe_remove_location (struct bp_location *bl)
13445 {
13446   /* Let's clear the semaphore before removing the location.  */
13447   if (bl->probe.probe->pops->clear_semaphore != NULL)
13448     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13449                                             bl->probe.objfile,
13450                                             bl->gdbarch);
13451
13452   return bkpt_remove_location (bl);
13453 }
13454
13455 static void
13456 bkpt_probe_create_sals_from_location (const struct event_location *location,
13457                                       struct linespec_result *canonical,
13458                                       enum bptype type_wanted)
13459 {
13460   struct linespec_sals lsal;
13461
13462   lsal.sals = parse_probes (location, NULL, canonical);
13463   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13464   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13465 }
13466
13467 static void
13468 bkpt_probe_decode_location (struct breakpoint *b,
13469                             const struct event_location *location,
13470                             struct program_space *search_pspace,
13471                             struct symtabs_and_lines *sals)
13472 {
13473   *sals = parse_probes (location, search_pspace, NULL);
13474   if (!sals->sals)
13475     error (_("probe not found"));
13476 }
13477
13478 /* The breakpoint_ops structure to be used in tracepoints.  */
13479
13480 static void
13481 tracepoint_re_set (struct breakpoint *b)
13482 {
13483   breakpoint_re_set_default (b);
13484 }
13485
13486 static int
13487 tracepoint_breakpoint_hit (const struct bp_location *bl,
13488                            struct address_space *aspace, CORE_ADDR bp_addr,
13489                            const struct target_waitstatus *ws)
13490 {
13491   /* By definition, the inferior does not report stops at
13492      tracepoints.  */
13493   return 0;
13494 }
13495
13496 static void
13497 tracepoint_print_one_detail (const struct breakpoint *self,
13498                              struct ui_out *uiout)
13499 {
13500   struct tracepoint *tp = (struct tracepoint *) self;
13501   if (tp->static_trace_marker_id)
13502     {
13503       gdb_assert (self->type == bp_static_tracepoint);
13504
13505       ui_out_text (uiout, "\tmarker id is ");
13506       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13507                            tp->static_trace_marker_id);
13508       ui_out_text (uiout, "\n");
13509     }
13510 }
13511
13512 static void
13513 tracepoint_print_mention (struct breakpoint *b)
13514 {
13515   if (ui_out_is_mi_like_p (current_uiout))
13516     return;
13517
13518   switch (b->type)
13519     {
13520     case bp_tracepoint:
13521       printf_filtered (_("Tracepoint"));
13522       printf_filtered (_(" %d"), b->number);
13523       break;
13524     case bp_fast_tracepoint:
13525       printf_filtered (_("Fast tracepoint"));
13526       printf_filtered (_(" %d"), b->number);
13527       break;
13528     case bp_static_tracepoint:
13529       printf_filtered (_("Static tracepoint"));
13530       printf_filtered (_(" %d"), b->number);
13531       break;
13532     default:
13533       internal_error (__FILE__, __LINE__,
13534                       _("unhandled tracepoint type %d"), (int) b->type);
13535     }
13536
13537   say_where (b);
13538 }
13539
13540 static void
13541 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13542 {
13543   struct tracepoint *tp = (struct tracepoint *) self;
13544
13545   if (self->type == bp_fast_tracepoint)
13546     fprintf_unfiltered (fp, "ftrace");
13547   else if (self->type == bp_static_tracepoint)
13548     fprintf_unfiltered (fp, "strace");
13549   else if (self->type == bp_tracepoint)
13550     fprintf_unfiltered (fp, "trace");
13551   else
13552     internal_error (__FILE__, __LINE__,
13553                     _("unhandled tracepoint type %d"), (int) self->type);
13554
13555   fprintf_unfiltered (fp, " %s",
13556                       event_location_to_string (self->location));
13557   print_recreate_thread (self, fp);
13558
13559   if (tp->pass_count)
13560     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13561 }
13562
13563 static void
13564 tracepoint_create_sals_from_location (const struct event_location *location,
13565                                       struct linespec_result *canonical,
13566                                       enum bptype type_wanted)
13567 {
13568   create_sals_from_location_default (location, canonical, type_wanted);
13569 }
13570
13571 static void
13572 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13573                                    struct linespec_result *canonical,
13574                                    char *cond_string,
13575                                    char *extra_string,
13576                                    enum bptype type_wanted,
13577                                    enum bpdisp disposition,
13578                                    int thread,
13579                                    int task, int ignore_count,
13580                                    const struct breakpoint_ops *ops,
13581                                    int from_tty, int enabled,
13582                                    int internal, unsigned flags)
13583 {
13584   create_breakpoints_sal_default (gdbarch, canonical,
13585                                   cond_string, extra_string,
13586                                   type_wanted,
13587                                   disposition, thread, task,
13588                                   ignore_count, ops, from_tty,
13589                                   enabled, internal, flags);
13590 }
13591
13592 static void
13593 tracepoint_decode_location (struct breakpoint *b,
13594                             const struct event_location *location,
13595                             struct program_space *search_pspace,
13596                             struct symtabs_and_lines *sals)
13597 {
13598   decode_location_default (b, location, search_pspace, sals);
13599 }
13600
13601 struct breakpoint_ops tracepoint_breakpoint_ops;
13602
13603 /* The breakpoint_ops structure to be use on tracepoints placed in a
13604    static probe.  */
13605
13606 static void
13607 tracepoint_probe_create_sals_from_location
13608   (const struct event_location *location,
13609    struct linespec_result *canonical,
13610    enum bptype type_wanted)
13611 {
13612   /* We use the same method for breakpoint on probes.  */
13613   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13614 }
13615
13616 static void
13617 tracepoint_probe_decode_location (struct breakpoint *b,
13618                                   const struct event_location *location,
13619                                   struct program_space *search_pspace,
13620                                   struct symtabs_and_lines *sals)
13621 {
13622   /* We use the same method for breakpoint on probes.  */
13623   bkpt_probe_decode_location (b, location, search_pspace, sals);
13624 }
13625
13626 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13627
13628 /* Dprintf breakpoint_ops methods.  */
13629
13630 static void
13631 dprintf_re_set (struct breakpoint *b)
13632 {
13633   breakpoint_re_set_default (b);
13634
13635   /* extra_string should never be non-NULL for dprintf.  */
13636   gdb_assert (b->extra_string != NULL);
13637
13638   /* 1 - connect to target 1, that can run breakpoint commands.
13639      2 - create a dprintf, which resolves fine.
13640      3 - disconnect from target 1
13641      4 - connect to target 2, that can NOT run breakpoint commands.
13642
13643      After steps #3/#4, you'll want the dprintf command list to
13644      be updated, because target 1 and 2 may well return different
13645      answers for target_can_run_breakpoint_commands().
13646      Given absence of finer grained resetting, we get to do
13647      it all the time.  */
13648   if (b->extra_string != NULL)
13649     update_dprintf_command_list (b);
13650 }
13651
13652 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13653
13654 static void
13655 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13656 {
13657   fprintf_unfiltered (fp, "dprintf %s,%s",
13658                       event_location_to_string (tp->location),
13659                       tp->extra_string);
13660   print_recreate_thread (tp, fp);
13661 }
13662
13663 /* Implement the "after_condition_true" breakpoint_ops method for
13664    dprintf.
13665
13666    dprintf's are implemented with regular commands in their command
13667    list, but we run the commands here instead of before presenting the
13668    stop to the user, as dprintf's don't actually cause a stop.  This
13669    also makes it so that the commands of multiple dprintfs at the same
13670    address are all handled.  */
13671
13672 static void
13673 dprintf_after_condition_true (struct bpstats *bs)
13674 {
13675   struct cleanup *old_chain;
13676   struct bpstats tmp_bs = { NULL };
13677   struct bpstats *tmp_bs_p = &tmp_bs;
13678
13679   /* dprintf's never cause a stop.  This wasn't set in the
13680      check_status hook instead because that would make the dprintf's
13681      condition not be evaluated.  */
13682   bs->stop = 0;
13683
13684   /* Run the command list here.  Take ownership of it instead of
13685      copying.  We never want these commands to run later in
13686      bpstat_do_actions, if a breakpoint that causes a stop happens to
13687      be set at same address as this dprintf, or even if running the
13688      commands here throws.  */
13689   tmp_bs.commands = bs->commands;
13690   bs->commands = NULL;
13691   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13692
13693   bpstat_do_actions_1 (&tmp_bs_p);
13694
13695   /* 'tmp_bs.commands' will usually be NULL by now, but
13696      bpstat_do_actions_1 may return early without processing the whole
13697      list.  */
13698   do_cleanups (old_chain);
13699 }
13700
13701 /* The breakpoint_ops structure to be used on static tracepoints with
13702    markers (`-m').  */
13703
13704 static void
13705 strace_marker_create_sals_from_location (const struct event_location *location,
13706                                          struct linespec_result *canonical,
13707                                          enum bptype type_wanted)
13708 {
13709   struct linespec_sals lsal;
13710   const char *arg_start, *arg;
13711   char *str;
13712   struct cleanup *cleanup;
13713
13714   arg = arg_start = get_linespec_location (location);
13715   lsal.sals = decode_static_tracepoint_spec (&arg);
13716
13717   str = savestring (arg_start, arg - arg_start);
13718   cleanup = make_cleanup (xfree, str);
13719   canonical->location = new_linespec_location (&str);
13720   do_cleanups (cleanup);
13721
13722   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13723   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13724 }
13725
13726 static void
13727 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13728                                       struct linespec_result *canonical,
13729                                       char *cond_string,
13730                                       char *extra_string,
13731                                       enum bptype type_wanted,
13732                                       enum bpdisp disposition,
13733                                       int thread,
13734                                       int task, int ignore_count,
13735                                       const struct breakpoint_ops *ops,
13736                                       int from_tty, int enabled,
13737                                       int internal, unsigned flags)
13738 {
13739   int i;
13740   struct linespec_sals *lsal = VEC_index (linespec_sals,
13741                                           canonical->sals, 0);
13742
13743   /* If the user is creating a static tracepoint by marker id
13744      (strace -m MARKER_ID), then store the sals index, so that
13745      breakpoint_re_set can try to match up which of the newly
13746      found markers corresponds to this one, and, don't try to
13747      expand multiple locations for each sal, given than SALS
13748      already should contain all sals for MARKER_ID.  */
13749
13750   for (i = 0; i < lsal->sals.nelts; ++i)
13751     {
13752       struct symtabs_and_lines expanded;
13753       struct tracepoint *tp;
13754       struct cleanup *old_chain;
13755       struct event_location *location;
13756
13757       expanded.nelts = 1;
13758       expanded.sals = &lsal->sals.sals[i];
13759
13760       location = copy_event_location (canonical->location);
13761       old_chain = make_cleanup_delete_event_location (location);
13762
13763       tp = XCNEW (struct tracepoint);
13764       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13765                            location, NULL,
13766                            cond_string, extra_string,
13767                            type_wanted, disposition,
13768                            thread, task, ignore_count, ops,
13769                            from_tty, enabled, internal, flags,
13770                            canonical->special_display);
13771       /* Given that its possible to have multiple markers with
13772          the same string id, if the user is creating a static
13773          tracepoint by marker id ("strace -m MARKER_ID"), then
13774          store the sals index, so that breakpoint_re_set can
13775          try to match up which of the newly found markers
13776          corresponds to this one  */
13777       tp->static_trace_marker_id_idx = i;
13778
13779       install_breakpoint (internal, &tp->base, 0);
13780
13781       discard_cleanups (old_chain);
13782     }
13783 }
13784
13785 static void
13786 strace_marker_decode_location (struct breakpoint *b,
13787                                const struct event_location *location,
13788                                struct program_space *search_pspace,
13789                                struct symtabs_and_lines *sals)
13790 {
13791   struct tracepoint *tp = (struct tracepoint *) b;
13792   const char *s = get_linespec_location (location);
13793
13794   *sals = decode_static_tracepoint_spec (&s);
13795   if (sals->nelts > tp->static_trace_marker_id_idx)
13796     {
13797       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13798       sals->nelts = 1;
13799     }
13800   else
13801     error (_("marker %s not found"), tp->static_trace_marker_id);
13802 }
13803
13804 static struct breakpoint_ops strace_marker_breakpoint_ops;
13805
13806 static int
13807 strace_marker_p (struct breakpoint *b)
13808 {
13809   return b->ops == &strace_marker_breakpoint_ops;
13810 }
13811
13812 /* Delete a breakpoint and clean up all traces of it in the data
13813    structures.  */
13814
13815 void
13816 delete_breakpoint (struct breakpoint *bpt)
13817 {
13818   struct breakpoint *b;
13819
13820   gdb_assert (bpt != NULL);
13821
13822   /* Has this bp already been deleted?  This can happen because
13823      multiple lists can hold pointers to bp's.  bpstat lists are
13824      especial culprits.
13825
13826      One example of this happening is a watchpoint's scope bp.  When
13827      the scope bp triggers, we notice that the watchpoint is out of
13828      scope, and delete it.  We also delete its scope bp.  But the
13829      scope bp is marked "auto-deleting", and is already on a bpstat.
13830      That bpstat is then checked for auto-deleting bp's, which are
13831      deleted.
13832
13833      A real solution to this problem might involve reference counts in
13834      bp's, and/or giving them pointers back to their referencing
13835      bpstat's, and teaching delete_breakpoint to only free a bp's
13836      storage when no more references were extent.  A cheaper bandaid
13837      was chosen.  */
13838   if (bpt->type == bp_none)
13839     return;
13840
13841   /* At least avoid this stale reference until the reference counting
13842      of breakpoints gets resolved.  */
13843   if (bpt->related_breakpoint != bpt)
13844     {
13845       struct breakpoint *related;
13846       struct watchpoint *w;
13847
13848       if (bpt->type == bp_watchpoint_scope)
13849         w = (struct watchpoint *) bpt->related_breakpoint;
13850       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13851         w = (struct watchpoint *) bpt;
13852       else
13853         w = NULL;
13854       if (w != NULL)
13855         watchpoint_del_at_next_stop (w);
13856
13857       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13858       for (related = bpt; related->related_breakpoint != bpt;
13859            related = related->related_breakpoint);
13860       related->related_breakpoint = bpt->related_breakpoint;
13861       bpt->related_breakpoint = bpt;
13862     }
13863
13864   /* watch_command_1 creates a watchpoint but only sets its number if
13865      update_watchpoint succeeds in creating its bp_locations.  If there's
13866      a problem in that process, we'll be asked to delete the half-created
13867      watchpoint.  In that case, don't announce the deletion.  */
13868   if (bpt->number)
13869     observer_notify_breakpoint_deleted (bpt);
13870
13871   if (breakpoint_chain == bpt)
13872     breakpoint_chain = bpt->next;
13873
13874   ALL_BREAKPOINTS (b)
13875     if (b->next == bpt)
13876     {
13877       b->next = bpt->next;
13878       break;
13879     }
13880
13881   /* Be sure no bpstat's are pointing at the breakpoint after it's
13882      been freed.  */
13883   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13884      in all threads for now.  Note that we cannot just remove bpstats
13885      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13886      commands are associated with the bpstat; if we remove it here,
13887      then the later call to bpstat_do_actions (&stop_bpstat); in
13888      event-top.c won't do anything, and temporary breakpoints with
13889      commands won't work.  */
13890
13891   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13892
13893   /* Now that breakpoint is removed from breakpoint list, update the
13894      global location list.  This will remove locations that used to
13895      belong to this breakpoint.  Do this before freeing the breakpoint
13896      itself, since remove_breakpoint looks at location's owner.  It
13897      might be better design to have location completely
13898      self-contained, but it's not the case now.  */
13899   update_global_location_list (UGLL_DONT_INSERT);
13900
13901   bpt->ops->dtor (bpt);
13902   /* On the chance that someone will soon try again to delete this
13903      same bp, we mark it as deleted before freeing its storage.  */
13904   bpt->type = bp_none;
13905   xfree (bpt);
13906 }
13907
13908 static void
13909 do_delete_breakpoint_cleanup (void *b)
13910 {
13911   delete_breakpoint ((struct breakpoint *) b);
13912 }
13913
13914 struct cleanup *
13915 make_cleanup_delete_breakpoint (struct breakpoint *b)
13916 {
13917   return make_cleanup (do_delete_breakpoint_cleanup, b);
13918 }
13919
13920 /* Iterator function to call a user-provided callback function once
13921    for each of B and its related breakpoints.  */
13922
13923 static void
13924 iterate_over_related_breakpoints (struct breakpoint *b,
13925                                   void (*function) (struct breakpoint *,
13926                                                     void *),
13927                                   void *data)
13928 {
13929   struct breakpoint *related;
13930
13931   related = b;
13932   do
13933     {
13934       struct breakpoint *next;
13935
13936       /* FUNCTION may delete RELATED.  */
13937       next = related->related_breakpoint;
13938
13939       if (next == related)
13940         {
13941           /* RELATED is the last ring entry.  */
13942           function (related, data);
13943
13944           /* FUNCTION may have deleted it, so we'd never reach back to
13945              B.  There's nothing left to do anyway, so just break
13946              out.  */
13947           break;
13948         }
13949       else
13950         function (related, data);
13951
13952       related = next;
13953     }
13954   while (related != b);
13955 }
13956
13957 static void
13958 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13959 {
13960   delete_breakpoint (b);
13961 }
13962
13963 /* A callback for map_breakpoint_numbers that calls
13964    delete_breakpoint.  */
13965
13966 static void
13967 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13968 {
13969   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13970 }
13971
13972 void
13973 delete_command (char *arg, int from_tty)
13974 {
13975   struct breakpoint *b, *b_tmp;
13976
13977   dont_repeat ();
13978
13979   if (arg == 0)
13980     {
13981       int breaks_to_delete = 0;
13982
13983       /* Delete all breakpoints if no argument.  Do not delete
13984          internal breakpoints, these have to be deleted with an
13985          explicit breakpoint number argument.  */
13986       ALL_BREAKPOINTS (b)
13987         if (user_breakpoint_p (b))
13988           {
13989             breaks_to_delete = 1;
13990             break;
13991           }
13992
13993       /* Ask user only if there are some breakpoints to delete.  */
13994       if (!from_tty
13995           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13996         {
13997           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13998             if (user_breakpoint_p (b))
13999               delete_breakpoint (b);
14000         }
14001     }
14002   else
14003     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14004 }
14005
14006 /* Return true if all locations of B bound to PSPACE are pending.  If
14007    PSPACE is NULL, all locations of all program spaces are
14008    considered.  */
14009
14010 static int
14011 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
14012 {
14013   struct bp_location *loc;
14014
14015   for (loc = b->loc; loc != NULL; loc = loc->next)
14016     if ((pspace == NULL
14017          || loc->pspace == pspace)
14018         && !loc->shlib_disabled
14019         && !loc->pspace->executing_startup)
14020       return 0;
14021   return 1;
14022 }
14023
14024 /* Subroutine of update_breakpoint_locations to simplify it.
14025    Return non-zero if multiple fns in list LOC have the same name.
14026    Null names are ignored.  */
14027
14028 static int
14029 ambiguous_names_p (struct bp_location *loc)
14030 {
14031   struct bp_location *l;
14032   htab_t htab = htab_create_alloc (13, htab_hash_string,
14033                                    (int (*) (const void *, 
14034                                              const void *)) streq,
14035                                    NULL, xcalloc, xfree);
14036
14037   for (l = loc; l != NULL; l = l->next)
14038     {
14039       const char **slot;
14040       const char *name = l->function_name;
14041
14042       /* Allow for some names to be NULL, ignore them.  */
14043       if (name == NULL)
14044         continue;
14045
14046       slot = (const char **) htab_find_slot (htab, (const void *) name,
14047                                              INSERT);
14048       /* NOTE: We can assume slot != NULL here because xcalloc never
14049          returns NULL.  */
14050       if (*slot != NULL)
14051         {
14052           htab_delete (htab);
14053           return 1;
14054         }
14055       *slot = name;
14056     }
14057
14058   htab_delete (htab);
14059   return 0;
14060 }
14061
14062 /* When symbols change, it probably means the sources changed as well,
14063    and it might mean the static tracepoint markers are no longer at
14064    the same address or line numbers they used to be at last we
14065    checked.  Losing your static tracepoints whenever you rebuild is
14066    undesirable.  This function tries to resync/rematch gdb static
14067    tracepoints with the markers on the target, for static tracepoints
14068    that have not been set by marker id.  Static tracepoint that have
14069    been set by marker id are reset by marker id in breakpoint_re_set.
14070    The heuristic is:
14071
14072    1) For a tracepoint set at a specific address, look for a marker at
14073    the old PC.  If one is found there, assume to be the same marker.
14074    If the name / string id of the marker found is different from the
14075    previous known name, assume that means the user renamed the marker
14076    in the sources, and output a warning.
14077
14078    2) For a tracepoint set at a given line number, look for a marker
14079    at the new address of the old line number.  If one is found there,
14080    assume to be the same marker.  If the name / string id of the
14081    marker found is different from the previous known name, assume that
14082    means the user renamed the marker in the sources, and output a
14083    warning.
14084
14085    3) If a marker is no longer found at the same address or line, it
14086    may mean the marker no longer exists.  But it may also just mean
14087    the code changed a bit.  Maybe the user added a few lines of code
14088    that made the marker move up or down (in line number terms).  Ask
14089    the target for info about the marker with the string id as we knew
14090    it.  If found, update line number and address in the matching
14091    static tracepoint.  This will get confused if there's more than one
14092    marker with the same ID (possible in UST, although unadvised
14093    precisely because it confuses tools).  */
14094
14095 static struct symtab_and_line
14096 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14097 {
14098   struct tracepoint *tp = (struct tracepoint *) b;
14099   struct static_tracepoint_marker marker;
14100   CORE_ADDR pc;
14101
14102   pc = sal.pc;
14103   if (sal.line)
14104     find_line_pc (sal.symtab, sal.line, &pc);
14105
14106   if (target_static_tracepoint_marker_at (pc, &marker))
14107     {
14108       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14109         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14110                  b->number,
14111                  tp->static_trace_marker_id, marker.str_id);
14112
14113       xfree (tp->static_trace_marker_id);
14114       tp->static_trace_marker_id = xstrdup (marker.str_id);
14115       release_static_tracepoint_marker (&marker);
14116
14117       return sal;
14118     }
14119
14120   /* Old marker wasn't found on target at lineno.  Try looking it up
14121      by string ID.  */
14122   if (!sal.explicit_pc
14123       && sal.line != 0
14124       && sal.symtab != NULL
14125       && tp->static_trace_marker_id != NULL)
14126     {
14127       VEC(static_tracepoint_marker_p) *markers;
14128
14129       markers
14130         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14131
14132       if (!VEC_empty(static_tracepoint_marker_p, markers))
14133         {
14134           struct symtab_and_line sal2;
14135           struct symbol *sym;
14136           struct static_tracepoint_marker *tpmarker;
14137           struct ui_out *uiout = current_uiout;
14138           struct explicit_location explicit_loc;
14139
14140           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14141
14142           xfree (tp->static_trace_marker_id);
14143           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14144
14145           warning (_("marker for static tracepoint %d (%s) not "
14146                      "found at previous line number"),
14147                    b->number, tp->static_trace_marker_id);
14148
14149           init_sal (&sal2);
14150
14151           sal2.pc = tpmarker->address;
14152
14153           sal2 = find_pc_line (tpmarker->address, 0);
14154           sym = find_pc_sect_function (tpmarker->address, NULL);
14155           ui_out_text (uiout, "Now in ");
14156           if (sym)
14157             {
14158               ui_out_field_string (uiout, "func",
14159                                    SYMBOL_PRINT_NAME (sym));
14160               ui_out_text (uiout, " at ");
14161             }
14162           ui_out_field_string (uiout, "file",
14163                                symtab_to_filename_for_display (sal2.symtab));
14164           ui_out_text (uiout, ":");
14165
14166           if (ui_out_is_mi_like_p (uiout))
14167             {
14168               const char *fullname = symtab_to_fullname (sal2.symtab);
14169
14170               ui_out_field_string (uiout, "fullname", fullname);
14171             }
14172
14173           ui_out_field_int (uiout, "line", sal2.line);
14174           ui_out_text (uiout, "\n");
14175
14176           b->loc->line_number = sal2.line;
14177           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14178
14179           delete_event_location (b->location);
14180           initialize_explicit_location (&explicit_loc);
14181           explicit_loc.source_filename
14182             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14183           explicit_loc.line_offset.offset = b->loc->line_number;
14184           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14185           b->location = new_explicit_location (&explicit_loc);
14186
14187           /* Might be nice to check if function changed, and warn if
14188              so.  */
14189
14190           release_static_tracepoint_marker (tpmarker);
14191         }
14192     }
14193   return sal;
14194 }
14195
14196 /* Returns 1 iff locations A and B are sufficiently same that
14197    we don't need to report breakpoint as changed.  */
14198
14199 static int
14200 locations_are_equal (struct bp_location *a, struct bp_location *b)
14201 {
14202   while (a && b)
14203     {
14204       if (a->address != b->address)
14205         return 0;
14206
14207       if (a->shlib_disabled != b->shlib_disabled)
14208         return 0;
14209
14210       if (a->enabled != b->enabled)
14211         return 0;
14212
14213       a = a->next;
14214       b = b->next;
14215     }
14216
14217   if ((a == NULL) != (b == NULL))
14218     return 0;
14219
14220   return 1;
14221 }
14222
14223 /* Split all locations of B that are bound to PSPACE out of B's
14224    location list to a separate list and return that list's head.  If
14225    PSPACE is NULL, hoist out all locations of B.  */
14226
14227 static struct bp_location *
14228 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
14229 {
14230   struct bp_location head;
14231   struct bp_location *i = b->loc;
14232   struct bp_location **i_link = &b->loc;
14233   struct bp_location *hoisted = &head;
14234
14235   if (pspace == NULL)
14236     {
14237       i = b->loc;
14238       b->loc = NULL;
14239       return i;
14240     }
14241
14242   head.next = NULL;
14243
14244   while (i != NULL)
14245     {
14246       if (i->pspace == pspace)
14247         {
14248           *i_link = i->next;
14249           i->next = NULL;
14250           hoisted->next = i;
14251           hoisted = i;
14252         }
14253       else
14254         i_link = &i->next;
14255       i = *i_link;
14256     }
14257
14258   return head.next;
14259 }
14260
14261 /* Create new breakpoint locations for B (a hardware or software
14262    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
14263    zero, then B is a ranged breakpoint.  Only recreates locations for
14264    FILTER_PSPACE.  Locations of other program spaces are left
14265    untouched.  */
14266
14267 void
14268 update_breakpoint_locations (struct breakpoint *b,
14269                              struct program_space *filter_pspace,
14270                              struct symtabs_and_lines sals,
14271                              struct symtabs_and_lines sals_end)
14272 {
14273   int i;
14274   struct bp_location *existing_locations;
14275
14276   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14277     {
14278       /* Ranged breakpoints have only one start location and one end
14279          location.  */
14280       b->enable_state = bp_disabled;
14281       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14282                            "multiple locations found\n"),
14283                          b->number);
14284       return;
14285     }
14286
14287   /* If there's no new locations, and all existing locations are
14288      pending, don't do anything.  This optimizes the common case where
14289      all locations are in the same shared library, that was unloaded.
14290      We'd like to retain the location, so that when the library is
14291      loaded again, we don't loose the enabled/disabled status of the
14292      individual locations.  */
14293   if (all_locations_are_pending (b, filter_pspace) && sals.nelts == 0)
14294     return;
14295
14296   existing_locations = hoist_existing_locations (b, filter_pspace);
14297
14298   for (i = 0; i < sals.nelts; ++i)
14299     {
14300       struct bp_location *new_loc;
14301
14302       switch_to_program_space_and_thread (sals.sals[i].pspace);
14303
14304       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14305
14306       /* Reparse conditions, they might contain references to the
14307          old symtab.  */
14308       if (b->cond_string != NULL)
14309         {
14310           const char *s;
14311
14312           s = b->cond_string;
14313           TRY
14314             {
14315               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14316                                            block_for_pc (sals.sals[i].pc), 
14317                                            0);
14318             }
14319           CATCH (e, RETURN_MASK_ERROR)
14320             {
14321               warning (_("failed to reevaluate condition "
14322                          "for breakpoint %d: %s"), 
14323                        b->number, e.message);
14324               new_loc->enabled = 0;
14325             }
14326           END_CATCH
14327         }
14328
14329       if (sals_end.nelts)
14330         {
14331           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14332
14333           new_loc->length = end - sals.sals[0].pc + 1;
14334         }
14335     }
14336
14337   /* If possible, carry over 'disable' status from existing
14338      breakpoints.  */
14339   {
14340     struct bp_location *e = existing_locations;
14341     /* If there are multiple breakpoints with the same function name,
14342        e.g. for inline functions, comparing function names won't work.
14343        Instead compare pc addresses; this is just a heuristic as things
14344        may have moved, but in practice it gives the correct answer
14345        often enough until a better solution is found.  */
14346     int have_ambiguous_names = ambiguous_names_p (b->loc);
14347
14348     for (; e; e = e->next)
14349       {
14350         if (!e->enabled && e->function_name)
14351           {
14352             struct bp_location *l = b->loc;
14353             if (have_ambiguous_names)
14354               {
14355                 for (; l; l = l->next)
14356                   if (breakpoint_locations_match (e, l))
14357                     {
14358                       l->enabled = 0;
14359                       break;
14360                     }
14361               }
14362             else
14363               {
14364                 for (; l; l = l->next)
14365                   if (l->function_name
14366                       && strcmp (e->function_name, l->function_name) == 0)
14367                     {
14368                       l->enabled = 0;
14369                       break;
14370                     }
14371               }
14372           }
14373       }
14374   }
14375
14376   if (!locations_are_equal (existing_locations, b->loc))
14377     observer_notify_breakpoint_modified (b);
14378 }
14379
14380 /* Find the SaL locations corresponding to the given LOCATION.
14381    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14382
14383 static struct symtabs_and_lines
14384 location_to_sals (struct breakpoint *b, struct event_location *location,
14385                   struct program_space *search_pspace, int *found)
14386 {
14387   struct symtabs_and_lines sals = {0};
14388   struct gdb_exception exception = exception_none;
14389
14390   gdb_assert (b->ops != NULL);
14391
14392   TRY
14393     {
14394       b->ops->decode_location (b, location, search_pspace, &sals);
14395     }
14396   CATCH (e, RETURN_MASK_ERROR)
14397     {
14398       int not_found_and_ok = 0;
14399
14400       exception = e;
14401
14402       /* For pending breakpoints, it's expected that parsing will
14403          fail until the right shared library is loaded.  User has
14404          already told to create pending breakpoints and don't need
14405          extra messages.  If breakpoint is in bp_shlib_disabled
14406          state, then user already saw the message about that
14407          breakpoint being disabled, and don't want to see more
14408          errors.  */
14409       if (e.error == NOT_FOUND_ERROR
14410           && (b->condition_not_parsed
14411               || (b->loc != NULL
14412                   && search_pspace != NULL
14413                   && b->loc->pspace != search_pspace)
14414               || (b->loc && b->loc->shlib_disabled)
14415               || (b->loc && b->loc->pspace->executing_startup)
14416               || b->enable_state == bp_disabled))
14417         not_found_and_ok = 1;
14418
14419       if (!not_found_and_ok)
14420         {
14421           /* We surely don't want to warn about the same breakpoint
14422              10 times.  One solution, implemented here, is disable
14423              the breakpoint on error.  Another solution would be to
14424              have separate 'warning emitted' flag.  Since this
14425              happens only when a binary has changed, I don't know
14426              which approach is better.  */
14427           b->enable_state = bp_disabled;
14428           throw_exception (e);
14429         }
14430     }
14431   END_CATCH
14432
14433   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14434     {
14435       int i;
14436
14437       for (i = 0; i < sals.nelts; ++i)
14438         resolve_sal_pc (&sals.sals[i]);
14439       if (b->condition_not_parsed && b->extra_string != NULL)
14440         {
14441           char *cond_string, *extra_string;
14442           int thread, task;
14443
14444           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14445                                      &cond_string, &thread, &task,
14446                                      &extra_string);
14447           gdb_assert (b->cond_string == NULL);
14448           if (cond_string)
14449             b->cond_string = cond_string;
14450           b->thread = thread;
14451           b->task = task;
14452           if (extra_string)
14453             {
14454               xfree (b->extra_string);
14455               b->extra_string = extra_string;
14456             }
14457           b->condition_not_parsed = 0;
14458         }
14459
14460       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14461         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14462
14463       *found = 1;
14464     }
14465   else
14466     *found = 0;
14467
14468   return sals;
14469 }
14470
14471 /* The default re_set method, for typical hardware or software
14472    breakpoints.  Reevaluate the breakpoint and recreate its
14473    locations.  */
14474
14475 static void
14476 breakpoint_re_set_default (struct breakpoint *b)
14477 {
14478   int found;
14479   struct symtabs_and_lines sals, sals_end;
14480   struct symtabs_and_lines expanded = {0};
14481   struct symtabs_and_lines expanded_end = {0};
14482   struct program_space *filter_pspace = current_program_space;
14483
14484   sals = location_to_sals (b, b->location, filter_pspace, &found);
14485   if (found)
14486     {
14487       make_cleanup (xfree, sals.sals);
14488       expanded = sals;
14489     }
14490
14491   if (b->location_range_end != NULL)
14492     {
14493       sals_end = location_to_sals (b, b->location_range_end,
14494                                    filter_pspace, &found);
14495       if (found)
14496         {
14497           make_cleanup (xfree, sals_end.sals);
14498           expanded_end = sals_end;
14499         }
14500     }
14501
14502   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14503 }
14504
14505 /* Default method for creating SALs from an address string.  It basically
14506    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14507
14508 static void
14509 create_sals_from_location_default (const struct event_location *location,
14510                                    struct linespec_result *canonical,
14511                                    enum bptype type_wanted)
14512 {
14513   parse_breakpoint_sals (location, canonical);
14514 }
14515
14516 /* Call create_breakpoints_sal for the given arguments.  This is the default
14517    function for the `create_breakpoints_sal' method of
14518    breakpoint_ops.  */
14519
14520 static void
14521 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14522                                 struct linespec_result *canonical,
14523                                 char *cond_string,
14524                                 char *extra_string,
14525                                 enum bptype type_wanted,
14526                                 enum bpdisp disposition,
14527                                 int thread,
14528                                 int task, int ignore_count,
14529                                 const struct breakpoint_ops *ops,
14530                                 int from_tty, int enabled,
14531                                 int internal, unsigned flags)
14532 {
14533   create_breakpoints_sal (gdbarch, canonical, cond_string,
14534                           extra_string,
14535                           type_wanted, disposition,
14536                           thread, task, ignore_count, ops, from_tty,
14537                           enabled, internal, flags);
14538 }
14539
14540 /* Decode the line represented by S by calling decode_line_full.  This is the
14541    default function for the `decode_location' method of breakpoint_ops.  */
14542
14543 static void
14544 decode_location_default (struct breakpoint *b,
14545                          const struct event_location *location,
14546                          struct program_space *search_pspace,
14547                          struct symtabs_and_lines *sals)
14548 {
14549   struct linespec_result canonical;
14550
14551   init_linespec_result (&canonical);
14552   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14553                     (struct symtab *) NULL, 0,
14554                     &canonical, multiple_symbols_all,
14555                     b->filter);
14556
14557   /* We should get 0 or 1 resulting SALs.  */
14558   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14559
14560   if (VEC_length (linespec_sals, canonical.sals) > 0)
14561     {
14562       struct linespec_sals *lsal;
14563
14564       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14565       *sals = lsal->sals;
14566       /* Arrange it so the destructor does not free the
14567          contents.  */
14568       lsal->sals.sals = NULL;
14569     }
14570
14571   destroy_linespec_result (&canonical);
14572 }
14573
14574 /* Prepare the global context for a re-set of breakpoint B.  */
14575
14576 static struct cleanup *
14577 prepare_re_set_context (struct breakpoint *b)
14578 {
14579   input_radix = b->input_radix;
14580   set_language (b->language);
14581
14582   return make_cleanup (null_cleanup, NULL);
14583 }
14584
14585 /* Reset a breakpoint given it's struct breakpoint * BINT.
14586    The value we return ends up being the return value from catch_errors.
14587    Unused in this case.  */
14588
14589 static int
14590 breakpoint_re_set_one (void *bint)
14591 {
14592   /* Get past catch_errs.  */
14593   struct breakpoint *b = (struct breakpoint *) bint;
14594   struct cleanup *cleanups;
14595
14596   cleanups = prepare_re_set_context (b);
14597   b->ops->re_set (b);
14598   do_cleanups (cleanups);
14599   return 0;
14600 }
14601
14602 /* Re-set breakpoint locations for the current program space.
14603    Locations bound to other program spaces are left untouched.  */
14604
14605 void
14606 breakpoint_re_set (void)
14607 {
14608   struct breakpoint *b, *b_tmp;
14609   enum language save_language;
14610   int save_input_radix;
14611   struct cleanup *old_chain;
14612
14613   save_language = current_language->la_language;
14614   save_input_radix = input_radix;
14615   old_chain = save_current_space_and_thread ();
14616
14617   /* Note: we must not try to insert locations until after all
14618      breakpoints have been re-set.  Otherwise, e.g., when re-setting
14619      breakpoint 1, we'd insert the locations of breakpoint 2, which
14620      hadn't been re-set yet, and thus may have stale locations.  */
14621
14622   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14623   {
14624     /* Format possible error msg.  */
14625     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14626                                 b->number);
14627     struct cleanup *cleanups = make_cleanup (xfree, message);
14628     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14629     do_cleanups (cleanups);
14630   }
14631   set_language (save_language);
14632   input_radix = save_input_radix;
14633
14634   jit_breakpoint_re_set ();
14635
14636   do_cleanups (old_chain);
14637
14638   create_overlay_event_breakpoint ();
14639   create_longjmp_master_breakpoint ();
14640   create_std_terminate_master_breakpoint ();
14641   create_exception_master_breakpoint ();
14642
14643   /* Now we can insert.  */
14644   update_global_location_list (UGLL_MAY_INSERT);
14645 }
14646 \f
14647 /* Reset the thread number of this breakpoint:
14648
14649    - If the breakpoint is for all threads, leave it as-is.
14650    - Else, reset it to the current thread for inferior_ptid.  */
14651 void
14652 breakpoint_re_set_thread (struct breakpoint *b)
14653 {
14654   if (b->thread != -1)
14655     {
14656       if (in_thread_list (inferior_ptid))
14657         b->thread = ptid_to_global_thread_id (inferior_ptid);
14658
14659       /* We're being called after following a fork.  The new fork is
14660          selected as current, and unless this was a vfork will have a
14661          different program space from the original thread.  Reset that
14662          as well.  */
14663       b->loc->pspace = current_program_space;
14664     }
14665 }
14666
14667 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14668    If from_tty is nonzero, it prints a message to that effect,
14669    which ends with a period (no newline).  */
14670
14671 void
14672 set_ignore_count (int bptnum, int count, int from_tty)
14673 {
14674   struct breakpoint *b;
14675
14676   if (count < 0)
14677     count = 0;
14678
14679   ALL_BREAKPOINTS (b)
14680     if (b->number == bptnum)
14681     {
14682       if (is_tracepoint (b))
14683         {
14684           if (from_tty && count != 0)
14685             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14686                              bptnum);
14687           return;
14688         }
14689       
14690       b->ignore_count = count;
14691       if (from_tty)
14692         {
14693           if (count == 0)
14694             printf_filtered (_("Will stop next time "
14695                                "breakpoint %d is reached."),
14696                              bptnum);
14697           else if (count == 1)
14698             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14699                              bptnum);
14700           else
14701             printf_filtered (_("Will ignore next %d "
14702                                "crossings of breakpoint %d."),
14703                              count, bptnum);
14704         }
14705       observer_notify_breakpoint_modified (b);
14706       return;
14707     }
14708
14709   error (_("No breakpoint number %d."), bptnum);
14710 }
14711
14712 /* Command to set ignore-count of breakpoint N to COUNT.  */
14713
14714 static void
14715 ignore_command (char *args, int from_tty)
14716 {
14717   char *p = args;
14718   int num;
14719
14720   if (p == 0)
14721     error_no_arg (_("a breakpoint number"));
14722
14723   num = get_number (&p);
14724   if (num == 0)
14725     error (_("bad breakpoint number: '%s'"), args);
14726   if (*p == 0)
14727     error (_("Second argument (specified ignore-count) is missing."));
14728
14729   set_ignore_count (num,
14730                     longest_to_int (value_as_long (parse_and_eval (p))),
14731                     from_tty);
14732   if (from_tty)
14733     printf_filtered ("\n");
14734 }
14735 \f
14736 /* Call FUNCTION on each of the breakpoints
14737    whose numbers are given in ARGS.  */
14738
14739 static void
14740 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14741                                                       void *),
14742                         void *data)
14743 {
14744   int num;
14745   struct breakpoint *b, *tmp;
14746   int match;
14747   struct get_number_or_range_state state;
14748
14749   if (args == 0 || *args == '\0')
14750     error_no_arg (_("one or more breakpoint numbers"));
14751
14752   init_number_or_range (&state, args);
14753
14754   while (!state.finished)
14755     {
14756       const char *p = state.string;
14757
14758       match = 0;
14759
14760       num = get_number_or_range (&state);
14761       if (num == 0)
14762         {
14763           warning (_("bad breakpoint number at or near '%s'"), p);
14764         }
14765       else
14766         {
14767           ALL_BREAKPOINTS_SAFE (b, tmp)
14768             if (b->number == num)
14769               {
14770                 match = 1;
14771                 function (b, data);
14772                 break;
14773               }
14774           if (match == 0)
14775             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14776         }
14777     }
14778 }
14779
14780 static struct bp_location *
14781 find_location_by_number (char *number)
14782 {
14783   char *dot = strchr (number, '.');
14784   char *p1;
14785   int bp_num;
14786   int loc_num;
14787   struct breakpoint *b;
14788   struct bp_location *loc;  
14789
14790   *dot = '\0';
14791
14792   p1 = number;
14793   bp_num = get_number (&p1);
14794   if (bp_num == 0)
14795     error (_("Bad breakpoint number '%s'"), number);
14796
14797   ALL_BREAKPOINTS (b)
14798     if (b->number == bp_num)
14799       {
14800         break;
14801       }
14802
14803   if (!b || b->number != bp_num)
14804     error (_("Bad breakpoint number '%s'"), number);
14805   
14806   p1 = dot+1;
14807   loc_num = get_number (&p1);
14808   if (loc_num == 0)
14809     error (_("Bad breakpoint location number '%s'"), number);
14810
14811   --loc_num;
14812   loc = b->loc;
14813   for (;loc_num && loc; --loc_num, loc = loc->next)
14814     ;
14815   if (!loc)
14816     error (_("Bad breakpoint location number '%s'"), dot+1);
14817     
14818   return loc;  
14819 }
14820
14821
14822 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14823    If from_tty is nonzero, it prints a message to that effect,
14824    which ends with a period (no newline).  */
14825
14826 void
14827 disable_breakpoint (struct breakpoint *bpt)
14828 {
14829   /* Never disable a watchpoint scope breakpoint; we want to
14830      hit them when we leave scope so we can delete both the
14831      watchpoint and its scope breakpoint at that time.  */
14832   if (bpt->type == bp_watchpoint_scope)
14833     return;
14834
14835   bpt->enable_state = bp_disabled;
14836
14837   /* Mark breakpoint locations modified.  */
14838   mark_breakpoint_modified (bpt);
14839
14840   if (target_supports_enable_disable_tracepoint ()
14841       && current_trace_status ()->running && is_tracepoint (bpt))
14842     {
14843       struct bp_location *location;
14844      
14845       for (location = bpt->loc; location; location = location->next)
14846         target_disable_tracepoint (location);
14847     }
14848
14849   update_global_location_list (UGLL_DONT_INSERT);
14850
14851   observer_notify_breakpoint_modified (bpt);
14852 }
14853
14854 /* A callback for iterate_over_related_breakpoints.  */
14855
14856 static void
14857 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14858 {
14859   disable_breakpoint (b);
14860 }
14861
14862 /* A callback for map_breakpoint_numbers that calls
14863    disable_breakpoint.  */
14864
14865 static void
14866 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14867 {
14868   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14869 }
14870
14871 static void
14872 disable_command (char *args, int from_tty)
14873 {
14874   if (args == 0)
14875     {
14876       struct breakpoint *bpt;
14877
14878       ALL_BREAKPOINTS (bpt)
14879         if (user_breakpoint_p (bpt))
14880           disable_breakpoint (bpt);
14881     }
14882   else
14883     {
14884       char *num = extract_arg (&args);
14885
14886       while (num)
14887         {
14888           if (strchr (num, '.'))
14889             {
14890               struct bp_location *loc = find_location_by_number (num);
14891
14892               if (loc)
14893                 {
14894                   if (loc->enabled)
14895                     {
14896                       loc->enabled = 0;
14897                       mark_breakpoint_location_modified (loc);
14898                     }
14899                   if (target_supports_enable_disable_tracepoint ()
14900                       && current_trace_status ()->running && loc->owner
14901                       && is_tracepoint (loc->owner))
14902                     target_disable_tracepoint (loc);
14903                 }
14904               update_global_location_list (UGLL_DONT_INSERT);
14905             }
14906           else
14907             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14908           num = extract_arg (&args);
14909         }
14910     }
14911 }
14912
14913 static void
14914 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14915                         int count)
14916 {
14917   int target_resources_ok;
14918
14919   if (bpt->type == bp_hardware_breakpoint)
14920     {
14921       int i;
14922       i = hw_breakpoint_used_count ();
14923       target_resources_ok = 
14924         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14925                                             i + 1, 0);
14926       if (target_resources_ok == 0)
14927         error (_("No hardware breakpoint support in the target."));
14928       else if (target_resources_ok < 0)
14929         error (_("Hardware breakpoints used exceeds limit."));
14930     }
14931
14932   if (is_watchpoint (bpt))
14933     {
14934       /* Initialize it just to avoid a GCC false warning.  */
14935       enum enable_state orig_enable_state = bp_disabled;
14936
14937       TRY
14938         {
14939           struct watchpoint *w = (struct watchpoint *) bpt;
14940
14941           orig_enable_state = bpt->enable_state;
14942           bpt->enable_state = bp_enabled;
14943           update_watchpoint (w, 1 /* reparse */);
14944         }
14945       CATCH (e, RETURN_MASK_ALL)
14946         {
14947           bpt->enable_state = orig_enable_state;
14948           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14949                              bpt->number);
14950           return;
14951         }
14952       END_CATCH
14953     }
14954
14955   bpt->enable_state = bp_enabled;
14956
14957   /* Mark breakpoint locations modified.  */
14958   mark_breakpoint_modified (bpt);
14959
14960   if (target_supports_enable_disable_tracepoint ()
14961       && current_trace_status ()->running && is_tracepoint (bpt))
14962     {
14963       struct bp_location *location;
14964
14965       for (location = bpt->loc; location; location = location->next)
14966         target_enable_tracepoint (location);
14967     }
14968
14969   bpt->disposition = disposition;
14970   bpt->enable_count = count;
14971   update_global_location_list (UGLL_MAY_INSERT);
14972
14973   observer_notify_breakpoint_modified (bpt);
14974 }
14975
14976
14977 void
14978 enable_breakpoint (struct breakpoint *bpt)
14979 {
14980   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14981 }
14982
14983 static void
14984 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14985 {
14986   enable_breakpoint (bpt);
14987 }
14988
14989 /* A callback for map_breakpoint_numbers that calls
14990    enable_breakpoint.  */
14991
14992 static void
14993 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14994 {
14995   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14996 }
14997
14998 /* The enable command enables the specified breakpoints (or all defined
14999    breakpoints) so they once again become (or continue to be) effective
15000    in stopping the inferior.  */
15001
15002 static void
15003 enable_command (char *args, int from_tty)
15004 {
15005   if (args == 0)
15006     {
15007       struct breakpoint *bpt;
15008
15009       ALL_BREAKPOINTS (bpt)
15010         if (user_breakpoint_p (bpt))
15011           enable_breakpoint (bpt);
15012     }
15013   else
15014     {
15015       char *num = extract_arg (&args);
15016
15017       while (num)
15018         {
15019           if (strchr (num, '.'))
15020             {
15021               struct bp_location *loc = find_location_by_number (num);
15022
15023               if (loc)
15024                 {
15025                   if (!loc->enabled)
15026                     {
15027                       loc->enabled = 1;
15028                       mark_breakpoint_location_modified (loc);
15029                     }
15030                   if (target_supports_enable_disable_tracepoint ()
15031                       && current_trace_status ()->running && loc->owner
15032                       && is_tracepoint (loc->owner))
15033                     target_enable_tracepoint (loc);
15034                 }
15035               update_global_location_list (UGLL_MAY_INSERT);
15036             }
15037           else
15038             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15039           num = extract_arg (&args);
15040         }
15041     }
15042 }
15043
15044 /* This struct packages up disposition data for application to multiple
15045    breakpoints.  */
15046
15047 struct disp_data
15048 {
15049   enum bpdisp disp;
15050   int count;
15051 };
15052
15053 static void
15054 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15055 {
15056   struct disp_data disp_data = *(struct disp_data *) arg;
15057
15058   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15059 }
15060
15061 static void
15062 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15063 {
15064   struct disp_data disp = { disp_disable, 1 };
15065
15066   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15067 }
15068
15069 static void
15070 enable_once_command (char *args, int from_tty)
15071 {
15072   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15073 }
15074
15075 static void
15076 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15077 {
15078   struct disp_data disp = { disp_disable, *(int *) countptr };
15079
15080   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15081 }
15082
15083 static void
15084 enable_count_command (char *args, int from_tty)
15085 {
15086   int count;
15087
15088   if (args == NULL)
15089     error_no_arg (_("hit count"));
15090
15091   count = get_number (&args);
15092
15093   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15094 }
15095
15096 static void
15097 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15098 {
15099   struct disp_data disp = { disp_del, 1 };
15100
15101   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15102 }
15103
15104 static void
15105 enable_delete_command (char *args, int from_tty)
15106 {
15107   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15108 }
15109 \f
15110 static void
15111 set_breakpoint_cmd (char *args, int from_tty)
15112 {
15113 }
15114
15115 static void
15116 show_breakpoint_cmd (char *args, int from_tty)
15117 {
15118 }
15119
15120 /* Invalidate last known value of any hardware watchpoint if
15121    the memory which that value represents has been written to by
15122    GDB itself.  */
15123
15124 static void
15125 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15126                                       CORE_ADDR addr, ssize_t len,
15127                                       const bfd_byte *data)
15128 {
15129   struct breakpoint *bp;
15130
15131   ALL_BREAKPOINTS (bp)
15132     if (bp->enable_state == bp_enabled
15133         && bp->type == bp_hardware_watchpoint)
15134       {
15135         struct watchpoint *wp = (struct watchpoint *) bp;
15136
15137         if (wp->val_valid && wp->val)
15138           {
15139             struct bp_location *loc;
15140
15141             for (loc = bp->loc; loc != NULL; loc = loc->next)
15142               if (loc->loc_type == bp_loc_hardware_watchpoint
15143                   && loc->address + loc->length > addr
15144                   && addr + len > loc->address)
15145                 {
15146                   value_free (wp->val);
15147                   wp->val = NULL;
15148                   wp->val_valid = 0;
15149                 }
15150           }
15151       }
15152 }
15153
15154 /* Create and insert a breakpoint for software single step.  */
15155
15156 void
15157 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15158                                struct address_space *aspace, 
15159                                CORE_ADDR next_pc)
15160 {
15161   struct thread_info *tp = inferior_thread ();
15162   struct symtab_and_line sal;
15163   CORE_ADDR pc = next_pc;
15164
15165   if (tp->control.single_step_breakpoints == NULL)
15166     {
15167       tp->control.single_step_breakpoints
15168         = new_single_step_breakpoint (tp->global_num, gdbarch);
15169     }
15170
15171   sal = find_pc_line (pc, 0);
15172   sal.pc = pc;
15173   sal.section = find_pc_overlay (pc);
15174   sal.explicit_pc = 1;
15175   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15176
15177   update_global_location_list (UGLL_INSERT);
15178 }
15179
15180 /* See breakpoint.h.  */
15181
15182 int
15183 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15184                                        struct address_space *aspace,
15185                                        CORE_ADDR pc)
15186 {
15187   struct bp_location *loc;
15188
15189   for (loc = bp->loc; loc != NULL; loc = loc->next)
15190     if (loc->inserted
15191         && breakpoint_location_address_match (loc, aspace, pc))
15192       return 1;
15193
15194   return 0;
15195 }
15196
15197 /* Check whether a software single-step breakpoint is inserted at
15198    PC.  */
15199
15200 int
15201 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15202                                         CORE_ADDR pc)
15203 {
15204   struct breakpoint *bpt;
15205
15206   ALL_BREAKPOINTS (bpt)
15207     {
15208       if (bpt->type == bp_single_step
15209           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15210         return 1;
15211     }
15212   return 0;
15213 }
15214
15215 /* Tracepoint-specific operations.  */
15216
15217 /* Set tracepoint count to NUM.  */
15218 static void
15219 set_tracepoint_count (int num)
15220 {
15221   tracepoint_count = num;
15222   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15223 }
15224
15225 static void
15226 trace_command (char *arg, int from_tty)
15227 {
15228   struct breakpoint_ops *ops;
15229   struct event_location *location;
15230   struct cleanup *back_to;
15231
15232   location = string_to_event_location (&arg, current_language);
15233   back_to = make_cleanup_delete_event_location (location);
15234   if (location != NULL
15235       && event_location_type (location) == PROBE_LOCATION)
15236     ops = &tracepoint_probe_breakpoint_ops;
15237   else
15238     ops = &tracepoint_breakpoint_ops;
15239
15240   create_breakpoint (get_current_arch (),
15241                      location,
15242                      NULL, 0, arg, 1 /* parse arg */,
15243                      0 /* tempflag */,
15244                      bp_tracepoint /* type_wanted */,
15245                      0 /* Ignore count */,
15246                      pending_break_support,
15247                      ops,
15248                      from_tty,
15249                      1 /* enabled */,
15250                      0 /* internal */, 0);
15251   do_cleanups (back_to);
15252 }
15253
15254 static void
15255 ftrace_command (char *arg, int from_tty)
15256 {
15257   struct event_location *location;
15258   struct cleanup *back_to;
15259
15260   location = string_to_event_location (&arg, current_language);
15261   back_to = make_cleanup_delete_event_location (location);
15262   create_breakpoint (get_current_arch (),
15263                      location,
15264                      NULL, 0, arg, 1 /* parse arg */,
15265                      0 /* tempflag */,
15266                      bp_fast_tracepoint /* type_wanted */,
15267                      0 /* Ignore count */,
15268                      pending_break_support,
15269                      &tracepoint_breakpoint_ops,
15270                      from_tty,
15271                      1 /* enabled */,
15272                      0 /* internal */, 0);
15273   do_cleanups (back_to);
15274 }
15275
15276 /* strace command implementation.  Creates a static tracepoint.  */
15277
15278 static void
15279 strace_command (char *arg, int from_tty)
15280 {
15281   struct breakpoint_ops *ops;
15282   struct event_location *location;
15283   struct cleanup *back_to;
15284
15285   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15286      or with a normal static tracepoint.  */
15287   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15288     {
15289       ops = &strace_marker_breakpoint_ops;
15290       location = new_linespec_location (&arg);
15291     }
15292   else
15293     {
15294       ops = &tracepoint_breakpoint_ops;
15295       location = string_to_event_location (&arg, current_language);
15296     }
15297
15298   back_to = make_cleanup_delete_event_location (location);
15299   create_breakpoint (get_current_arch (),
15300                      location,
15301                      NULL, 0, arg, 1 /* parse arg */,
15302                      0 /* tempflag */,
15303                      bp_static_tracepoint /* type_wanted */,
15304                      0 /* Ignore count */,
15305                      pending_break_support,
15306                      ops,
15307                      from_tty,
15308                      1 /* enabled */,
15309                      0 /* internal */, 0);
15310   do_cleanups (back_to);
15311 }
15312
15313 /* Set up a fake reader function that gets command lines from a linked
15314    list that was acquired during tracepoint uploading.  */
15315
15316 static struct uploaded_tp *this_utp;
15317 static int next_cmd;
15318
15319 static char *
15320 read_uploaded_action (void)
15321 {
15322   char *rslt;
15323
15324   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15325
15326   next_cmd++;
15327
15328   return rslt;
15329 }
15330
15331 /* Given information about a tracepoint as recorded on a target (which
15332    can be either a live system or a trace file), attempt to create an
15333    equivalent GDB tracepoint.  This is not a reliable process, since
15334    the target does not necessarily have all the information used when
15335    the tracepoint was originally defined.  */
15336   
15337 struct tracepoint *
15338 create_tracepoint_from_upload (struct uploaded_tp *utp)
15339 {
15340   char *addr_str, small_buf[100];
15341   struct tracepoint *tp;
15342   struct event_location *location;
15343   struct cleanup *cleanup;
15344
15345   if (utp->at_string)
15346     addr_str = utp->at_string;
15347   else
15348     {
15349       /* In the absence of a source location, fall back to raw
15350          address.  Since there is no way to confirm that the address
15351          means the same thing as when the trace was started, warn the
15352          user.  */
15353       warning (_("Uploaded tracepoint %d has no "
15354                  "source location, using raw address"),
15355                utp->number);
15356       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15357       addr_str = small_buf;
15358     }
15359
15360   /* There's not much we can do with a sequence of bytecodes.  */
15361   if (utp->cond && !utp->cond_string)
15362     warning (_("Uploaded tracepoint %d condition "
15363                "has no source form, ignoring it"),
15364              utp->number);
15365
15366   location = string_to_event_location (&addr_str, current_language);
15367   cleanup = make_cleanup_delete_event_location (location);
15368   if (!create_breakpoint (get_current_arch (),
15369                           location,
15370                           utp->cond_string, -1, addr_str,
15371                           0 /* parse cond/thread */,
15372                           0 /* tempflag */,
15373                           utp->type /* type_wanted */,
15374                           0 /* Ignore count */,
15375                           pending_break_support,
15376                           &tracepoint_breakpoint_ops,
15377                           0 /* from_tty */,
15378                           utp->enabled /* enabled */,
15379                           0 /* internal */,
15380                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15381     {
15382       do_cleanups (cleanup);
15383       return NULL;
15384     }
15385
15386   do_cleanups (cleanup);
15387
15388   /* Get the tracepoint we just created.  */
15389   tp = get_tracepoint (tracepoint_count);
15390   gdb_assert (tp != NULL);
15391
15392   if (utp->pass > 0)
15393     {
15394       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15395                  tp->base.number);
15396
15397       trace_pass_command (small_buf, 0);
15398     }
15399
15400   /* If we have uploaded versions of the original commands, set up a
15401      special-purpose "reader" function and call the usual command line
15402      reader, then pass the result to the breakpoint command-setting
15403      function.  */
15404   if (!VEC_empty (char_ptr, utp->cmd_strings))
15405     {
15406       struct command_line *cmd_list;
15407
15408       this_utp = utp;
15409       next_cmd = 0;
15410
15411       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15412
15413       breakpoint_set_commands (&tp->base, cmd_list);
15414     }
15415   else if (!VEC_empty (char_ptr, utp->actions)
15416            || !VEC_empty (char_ptr, utp->step_actions))
15417     warning (_("Uploaded tracepoint %d actions "
15418                "have no source form, ignoring them"),
15419              utp->number);
15420
15421   /* Copy any status information that might be available.  */
15422   tp->base.hit_count = utp->hit_count;
15423   tp->traceframe_usage = utp->traceframe_usage;
15424
15425   return tp;
15426 }
15427   
15428 /* Print information on tracepoint number TPNUM_EXP, or all if
15429    omitted.  */
15430
15431 static void
15432 tracepoints_info (char *args, int from_tty)
15433 {
15434   struct ui_out *uiout = current_uiout;
15435   int num_printed;
15436
15437   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15438
15439   if (num_printed == 0)
15440     {
15441       if (args == NULL || *args == '\0')
15442         ui_out_message (uiout, 0, "No tracepoints.\n");
15443       else
15444         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15445     }
15446
15447   default_collect_info ();
15448 }
15449
15450 /* The 'enable trace' command enables tracepoints.
15451    Not supported by all targets.  */
15452 static void
15453 enable_trace_command (char *args, int from_tty)
15454 {
15455   enable_command (args, from_tty);
15456 }
15457
15458 /* The 'disable trace' command disables tracepoints.
15459    Not supported by all targets.  */
15460 static void
15461 disable_trace_command (char *args, int from_tty)
15462 {
15463   disable_command (args, from_tty);
15464 }
15465
15466 /* Remove a tracepoint (or all if no argument).  */
15467 static void
15468 delete_trace_command (char *arg, int from_tty)
15469 {
15470   struct breakpoint *b, *b_tmp;
15471
15472   dont_repeat ();
15473
15474   if (arg == 0)
15475     {
15476       int breaks_to_delete = 0;
15477
15478       /* Delete all breakpoints if no argument.
15479          Do not delete internal or call-dummy breakpoints, these
15480          have to be deleted with an explicit breakpoint number 
15481          argument.  */
15482       ALL_TRACEPOINTS (b)
15483         if (is_tracepoint (b) && user_breakpoint_p (b))
15484           {
15485             breaks_to_delete = 1;
15486             break;
15487           }
15488
15489       /* Ask user only if there are some breakpoints to delete.  */
15490       if (!from_tty
15491           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15492         {
15493           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15494             if (is_tracepoint (b) && user_breakpoint_p (b))
15495               delete_breakpoint (b);
15496         }
15497     }
15498   else
15499     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15500 }
15501
15502 /* Helper function for trace_pass_command.  */
15503
15504 static void
15505 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15506 {
15507   tp->pass_count = count;
15508   observer_notify_breakpoint_modified (&tp->base);
15509   if (from_tty)
15510     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15511                      tp->base.number, count);
15512 }
15513
15514 /* Set passcount for tracepoint.
15515
15516    First command argument is passcount, second is tracepoint number.
15517    If tracepoint number omitted, apply to most recently defined.
15518    Also accepts special argument "all".  */
15519
15520 static void
15521 trace_pass_command (char *args, int from_tty)
15522 {
15523   struct tracepoint *t1;
15524   unsigned int count;
15525
15526   if (args == 0 || *args == 0)
15527     error (_("passcount command requires an "
15528              "argument (count + optional TP num)"));
15529
15530   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15531
15532   args = skip_spaces (args);
15533   if (*args && strncasecmp (args, "all", 3) == 0)
15534     {
15535       struct breakpoint *b;
15536
15537       args += 3;                        /* Skip special argument "all".  */
15538       if (*args)
15539         error (_("Junk at end of arguments."));
15540
15541       ALL_TRACEPOINTS (b)
15542       {
15543         t1 = (struct tracepoint *) b;
15544         trace_pass_set_count (t1, count, from_tty);
15545       }
15546     }
15547   else if (*args == '\0')
15548     {
15549       t1 = get_tracepoint_by_number (&args, NULL);
15550       if (t1)
15551         trace_pass_set_count (t1, count, from_tty);
15552     }
15553   else
15554     {
15555       struct get_number_or_range_state state;
15556
15557       init_number_or_range (&state, args);
15558       while (!state.finished)
15559         {
15560           t1 = get_tracepoint_by_number (&args, &state);
15561           if (t1)
15562             trace_pass_set_count (t1, count, from_tty);
15563         }
15564     }
15565 }
15566
15567 struct tracepoint *
15568 get_tracepoint (int num)
15569 {
15570   struct breakpoint *t;
15571
15572   ALL_TRACEPOINTS (t)
15573     if (t->number == num)
15574       return (struct tracepoint *) t;
15575
15576   return NULL;
15577 }
15578
15579 /* Find the tracepoint with the given target-side number (which may be
15580    different from the tracepoint number after disconnecting and
15581    reconnecting).  */
15582
15583 struct tracepoint *
15584 get_tracepoint_by_number_on_target (int num)
15585 {
15586   struct breakpoint *b;
15587
15588   ALL_TRACEPOINTS (b)
15589     {
15590       struct tracepoint *t = (struct tracepoint *) b;
15591
15592       if (t->number_on_target == num)
15593         return t;
15594     }
15595
15596   return NULL;
15597 }
15598
15599 /* Utility: parse a tracepoint number and look it up in the list.
15600    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15601    If the argument is missing, the most recent tracepoint
15602    (tracepoint_count) is returned.  */
15603
15604 struct tracepoint *
15605 get_tracepoint_by_number (char **arg,
15606                           struct get_number_or_range_state *state)
15607 {
15608   struct breakpoint *t;
15609   int tpnum;
15610   char *instring = arg == NULL ? NULL : *arg;
15611
15612   if (state)
15613     {
15614       gdb_assert (!state->finished);
15615       tpnum = get_number_or_range (state);
15616     }
15617   else if (arg == NULL || *arg == NULL || ! **arg)
15618     tpnum = tracepoint_count;
15619   else
15620     tpnum = get_number (arg);
15621
15622   if (tpnum <= 0)
15623     {
15624       if (instring && *instring)
15625         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15626                          instring);
15627       else
15628         printf_filtered (_("No previous tracepoint\n"));
15629       return NULL;
15630     }
15631
15632   ALL_TRACEPOINTS (t)
15633     if (t->number == tpnum)
15634     {
15635       return (struct tracepoint *) t;
15636     }
15637
15638   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15639   return NULL;
15640 }
15641
15642 void
15643 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15644 {
15645   if (b->thread != -1)
15646     fprintf_unfiltered (fp, " thread %d", b->thread);
15647
15648   if (b->task != 0)
15649     fprintf_unfiltered (fp, " task %d", b->task);
15650
15651   fprintf_unfiltered (fp, "\n");
15652 }
15653
15654 /* Save information on user settable breakpoints (watchpoints, etc) to
15655    a new script file named FILENAME.  If FILTER is non-NULL, call it
15656    on each breakpoint and only include the ones for which it returns
15657    non-zero.  */
15658
15659 static void
15660 save_breakpoints (char *filename, int from_tty,
15661                   int (*filter) (const struct breakpoint *))
15662 {
15663   struct breakpoint *tp;
15664   int any = 0;
15665   struct cleanup *cleanup;
15666   struct ui_file *fp;
15667   int extra_trace_bits = 0;
15668
15669   if (filename == 0 || *filename == 0)
15670     error (_("Argument required (file name in which to save)"));
15671
15672   /* See if we have anything to save.  */
15673   ALL_BREAKPOINTS (tp)
15674   {
15675     /* Skip internal and momentary breakpoints.  */
15676     if (!user_breakpoint_p (tp))
15677       continue;
15678
15679     /* If we have a filter, only save the breakpoints it accepts.  */
15680     if (filter && !filter (tp))
15681       continue;
15682
15683     any = 1;
15684
15685     if (is_tracepoint (tp))
15686       {
15687         extra_trace_bits = 1;
15688
15689         /* We can stop searching.  */
15690         break;
15691       }
15692   }
15693
15694   if (!any)
15695     {
15696       warning (_("Nothing to save."));
15697       return;
15698     }
15699
15700   filename = tilde_expand (filename);
15701   cleanup = make_cleanup (xfree, filename);
15702   fp = gdb_fopen (filename, "w");
15703   if (!fp)
15704     error (_("Unable to open file '%s' for saving (%s)"),
15705            filename, safe_strerror (errno));
15706   make_cleanup_ui_file_delete (fp);
15707
15708   if (extra_trace_bits)
15709     save_trace_state_variables (fp);
15710
15711   ALL_BREAKPOINTS (tp)
15712   {
15713     /* Skip internal and momentary breakpoints.  */
15714     if (!user_breakpoint_p (tp))
15715       continue;
15716
15717     /* If we have a filter, only save the breakpoints it accepts.  */
15718     if (filter && !filter (tp))
15719       continue;
15720
15721     tp->ops->print_recreate (tp, fp);
15722
15723     /* Note, we can't rely on tp->number for anything, as we can't
15724        assume the recreated breakpoint numbers will match.  Use $bpnum
15725        instead.  */
15726
15727     if (tp->cond_string)
15728       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15729
15730     if (tp->ignore_count)
15731       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15732
15733     if (tp->type != bp_dprintf && tp->commands)
15734       {
15735         fprintf_unfiltered (fp, "  commands\n");
15736         
15737         ui_out_redirect (current_uiout, fp);
15738         TRY
15739           {
15740             print_command_lines (current_uiout, tp->commands->commands, 2);
15741           }
15742         CATCH (ex, RETURN_MASK_ALL)
15743           {
15744             ui_out_redirect (current_uiout, NULL);
15745             throw_exception (ex);
15746           }
15747         END_CATCH
15748
15749         ui_out_redirect (current_uiout, NULL);
15750         fprintf_unfiltered (fp, "  end\n");
15751       }
15752
15753     if (tp->enable_state == bp_disabled)
15754       fprintf_unfiltered (fp, "disable $bpnum\n");
15755
15756     /* If this is a multi-location breakpoint, check if the locations
15757        should be individually disabled.  Watchpoint locations are
15758        special, and not user visible.  */
15759     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15760       {
15761         struct bp_location *loc;
15762         int n = 1;
15763
15764         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15765           if (!loc->enabled)
15766             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15767       }
15768   }
15769
15770   if (extra_trace_bits && *default_collect)
15771     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15772
15773   if (from_tty)
15774     printf_filtered (_("Saved to file '%s'.\n"), filename);
15775   do_cleanups (cleanup);
15776 }
15777
15778 /* The `save breakpoints' command.  */
15779
15780 static void
15781 save_breakpoints_command (char *args, int from_tty)
15782 {
15783   save_breakpoints (args, from_tty, NULL);
15784 }
15785
15786 /* The `save tracepoints' command.  */
15787
15788 static void
15789 save_tracepoints_command (char *args, int from_tty)
15790 {
15791   save_breakpoints (args, from_tty, is_tracepoint);
15792 }
15793
15794 /* Create a vector of all tracepoints.  */
15795
15796 VEC(breakpoint_p) *
15797 all_tracepoints (void)
15798 {
15799   VEC(breakpoint_p) *tp_vec = 0;
15800   struct breakpoint *tp;
15801
15802   ALL_TRACEPOINTS (tp)
15803   {
15804     VEC_safe_push (breakpoint_p, tp_vec, tp);
15805   }
15806
15807   return tp_vec;
15808 }
15809
15810 \f
15811 /* This help string is used to consolidate all the help string for specifying
15812    locations used by several commands.  */
15813
15814 #define LOCATION_HELP_STRING \
15815 "Linespecs are colon-separated lists of location parameters, such as\n\
15816 source filename, function name, label name, and line number.\n\
15817 Example: To specify the start of a label named \"the_top\" in the\n\
15818 function \"fact\" in the file \"factorial.c\", use\n\
15819 \"factorial.c:fact:the_top\".\n\
15820 \n\
15821 Address locations begin with \"*\" and specify an exact address in the\n\
15822 program.  Example: To specify the fourth byte past the start function\n\
15823 \"main\", use \"*main + 4\".\n\
15824 \n\
15825 Explicit locations are similar to linespecs but use an option/argument\n\
15826 syntax to specify location parameters.\n\
15827 Example: To specify the start of the label named \"the_top\" in the\n\
15828 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15829 -function fact -label the_top\".\n"
15830
15831 /* This help string is used for the break, hbreak, tbreak and thbreak
15832    commands.  It is defined as a macro to prevent duplication.
15833    COMMAND should be a string constant containing the name of the
15834    command.  */
15835
15836 #define BREAK_ARGS_HELP(command) \
15837 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15838 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15839 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15840 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15841 `-probe-dtrace' (for a DTrace probe).\n\
15842 LOCATION may be a linespec, address, or explicit location as described\n\
15843 below.\n\
15844 \n\
15845 With no LOCATION, uses current execution address of the selected\n\
15846 stack frame.  This is useful for breaking on return to a stack frame.\n\
15847 \n\
15848 THREADNUM is the number from \"info threads\".\n\
15849 CONDITION is a boolean expression.\n\
15850 \n" LOCATION_HELP_STRING "\n\
15851 Multiple breakpoints at one place are permitted, and useful if their\n\
15852 conditions are different.\n\
15853 \n\
15854 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15855
15856 /* List of subcommands for "catch".  */
15857 static struct cmd_list_element *catch_cmdlist;
15858
15859 /* List of subcommands for "tcatch".  */
15860 static struct cmd_list_element *tcatch_cmdlist;
15861
15862 void
15863 add_catch_command (char *name, char *docstring,
15864                    cmd_sfunc_ftype *sfunc,
15865                    completer_ftype *completer,
15866                    void *user_data_catch,
15867                    void *user_data_tcatch)
15868 {
15869   struct cmd_list_element *command;
15870
15871   command = add_cmd (name, class_breakpoint, NULL, docstring,
15872                      &catch_cmdlist);
15873   set_cmd_sfunc (command, sfunc);
15874   set_cmd_context (command, user_data_catch);
15875   set_cmd_completer (command, completer);
15876
15877   command = add_cmd (name, class_breakpoint, NULL, docstring,
15878                      &tcatch_cmdlist);
15879   set_cmd_sfunc (command, sfunc);
15880   set_cmd_context (command, user_data_tcatch);
15881   set_cmd_completer (command, completer);
15882 }
15883
15884 static void
15885 save_command (char *arg, int from_tty)
15886 {
15887   printf_unfiltered (_("\"save\" must be followed by "
15888                        "the name of a save subcommand.\n"));
15889   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15890 }
15891
15892 struct breakpoint *
15893 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15894                           void *data)
15895 {
15896   struct breakpoint *b, *b_tmp;
15897
15898   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15899     {
15900       if ((*callback) (b, data))
15901         return b;
15902     }
15903
15904   return NULL;
15905 }
15906
15907 /* Zero if any of the breakpoint's locations could be a location where
15908    functions have been inlined, nonzero otherwise.  */
15909
15910 static int
15911 is_non_inline_function (struct breakpoint *b)
15912 {
15913   /* The shared library event breakpoint is set on the address of a
15914      non-inline function.  */
15915   if (b->type == bp_shlib_event)
15916     return 1;
15917
15918   return 0;
15919 }
15920
15921 /* Nonzero if the specified PC cannot be a location where functions
15922    have been inlined.  */
15923
15924 int
15925 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15926                            const struct target_waitstatus *ws)
15927 {
15928   struct breakpoint *b;
15929   struct bp_location *bl;
15930
15931   ALL_BREAKPOINTS (b)
15932     {
15933       if (!is_non_inline_function (b))
15934         continue;
15935
15936       for (bl = b->loc; bl != NULL; bl = bl->next)
15937         {
15938           if (!bl->shlib_disabled
15939               && bpstat_check_location (bl, aspace, pc, ws))
15940             return 1;
15941         }
15942     }
15943
15944   return 0;
15945 }
15946
15947 /* Remove any references to OBJFILE which is going to be freed.  */
15948
15949 void
15950 breakpoint_free_objfile (struct objfile *objfile)
15951 {
15952   struct bp_location **locp, *loc;
15953
15954   ALL_BP_LOCATIONS (loc, locp)
15955     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15956       loc->symtab = NULL;
15957 }
15958
15959 void
15960 initialize_breakpoint_ops (void)
15961 {
15962   static int initialized = 0;
15963
15964   struct breakpoint_ops *ops;
15965
15966   if (initialized)
15967     return;
15968   initialized = 1;
15969
15970   /* The breakpoint_ops structure to be inherit by all kinds of
15971      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15972      internal and momentary breakpoints, etc.).  */
15973   ops = &bkpt_base_breakpoint_ops;
15974   *ops = base_breakpoint_ops;
15975   ops->re_set = bkpt_re_set;
15976   ops->insert_location = bkpt_insert_location;
15977   ops->remove_location = bkpt_remove_location;
15978   ops->breakpoint_hit = bkpt_breakpoint_hit;
15979   ops->create_sals_from_location = bkpt_create_sals_from_location;
15980   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15981   ops->decode_location = bkpt_decode_location;
15982
15983   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15984   ops = &bkpt_breakpoint_ops;
15985   *ops = bkpt_base_breakpoint_ops;
15986   ops->re_set = bkpt_re_set;
15987   ops->resources_needed = bkpt_resources_needed;
15988   ops->print_it = bkpt_print_it;
15989   ops->print_mention = bkpt_print_mention;
15990   ops->print_recreate = bkpt_print_recreate;
15991
15992   /* Ranged breakpoints.  */
15993   ops = &ranged_breakpoint_ops;
15994   *ops = bkpt_breakpoint_ops;
15995   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15996   ops->resources_needed = resources_needed_ranged_breakpoint;
15997   ops->print_it = print_it_ranged_breakpoint;
15998   ops->print_one = print_one_ranged_breakpoint;
15999   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16000   ops->print_mention = print_mention_ranged_breakpoint;
16001   ops->print_recreate = print_recreate_ranged_breakpoint;
16002
16003   /* Internal breakpoints.  */
16004   ops = &internal_breakpoint_ops;
16005   *ops = bkpt_base_breakpoint_ops;
16006   ops->re_set = internal_bkpt_re_set;
16007   ops->check_status = internal_bkpt_check_status;
16008   ops->print_it = internal_bkpt_print_it;
16009   ops->print_mention = internal_bkpt_print_mention;
16010
16011   /* Momentary breakpoints.  */
16012   ops = &momentary_breakpoint_ops;
16013   *ops = bkpt_base_breakpoint_ops;
16014   ops->re_set = momentary_bkpt_re_set;
16015   ops->check_status = momentary_bkpt_check_status;
16016   ops->print_it = momentary_bkpt_print_it;
16017   ops->print_mention = momentary_bkpt_print_mention;
16018
16019   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16020   ops = &longjmp_breakpoint_ops;
16021   *ops = momentary_breakpoint_ops;
16022   ops->dtor = longjmp_bkpt_dtor;
16023
16024   /* Probe breakpoints.  */
16025   ops = &bkpt_probe_breakpoint_ops;
16026   *ops = bkpt_breakpoint_ops;
16027   ops->insert_location = bkpt_probe_insert_location;
16028   ops->remove_location = bkpt_probe_remove_location;
16029   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
16030   ops->decode_location = bkpt_probe_decode_location;
16031
16032   /* Watchpoints.  */
16033   ops = &watchpoint_breakpoint_ops;
16034   *ops = base_breakpoint_ops;
16035   ops->dtor = dtor_watchpoint;
16036   ops->re_set = re_set_watchpoint;
16037   ops->insert_location = insert_watchpoint;
16038   ops->remove_location = remove_watchpoint;
16039   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16040   ops->check_status = check_status_watchpoint;
16041   ops->resources_needed = resources_needed_watchpoint;
16042   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16043   ops->print_it = print_it_watchpoint;
16044   ops->print_mention = print_mention_watchpoint;
16045   ops->print_recreate = print_recreate_watchpoint;
16046   ops->explains_signal = explains_signal_watchpoint;
16047
16048   /* Masked watchpoints.  */
16049   ops = &masked_watchpoint_breakpoint_ops;
16050   *ops = watchpoint_breakpoint_ops;
16051   ops->insert_location = insert_masked_watchpoint;
16052   ops->remove_location = remove_masked_watchpoint;
16053   ops->resources_needed = resources_needed_masked_watchpoint;
16054   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16055   ops->print_it = print_it_masked_watchpoint;
16056   ops->print_one_detail = print_one_detail_masked_watchpoint;
16057   ops->print_mention = print_mention_masked_watchpoint;
16058   ops->print_recreate = print_recreate_masked_watchpoint;
16059
16060   /* Tracepoints.  */
16061   ops = &tracepoint_breakpoint_ops;
16062   *ops = base_breakpoint_ops;
16063   ops->re_set = tracepoint_re_set;
16064   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16065   ops->print_one_detail = tracepoint_print_one_detail;
16066   ops->print_mention = tracepoint_print_mention;
16067   ops->print_recreate = tracepoint_print_recreate;
16068   ops->create_sals_from_location = tracepoint_create_sals_from_location;
16069   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16070   ops->decode_location = tracepoint_decode_location;
16071
16072   /* Probe tracepoints.  */
16073   ops = &tracepoint_probe_breakpoint_ops;
16074   *ops = tracepoint_breakpoint_ops;
16075   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
16076   ops->decode_location = tracepoint_probe_decode_location;
16077
16078   /* Static tracepoints with marker (`-m').  */
16079   ops = &strace_marker_breakpoint_ops;
16080   *ops = tracepoint_breakpoint_ops;
16081   ops->create_sals_from_location = strace_marker_create_sals_from_location;
16082   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16083   ops->decode_location = strace_marker_decode_location;
16084
16085   /* Fork catchpoints.  */
16086   ops = &catch_fork_breakpoint_ops;
16087   *ops = base_breakpoint_ops;
16088   ops->insert_location = insert_catch_fork;
16089   ops->remove_location = remove_catch_fork;
16090   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16091   ops->print_it = print_it_catch_fork;
16092   ops->print_one = print_one_catch_fork;
16093   ops->print_mention = print_mention_catch_fork;
16094   ops->print_recreate = print_recreate_catch_fork;
16095
16096   /* Vfork catchpoints.  */
16097   ops = &catch_vfork_breakpoint_ops;
16098   *ops = base_breakpoint_ops;
16099   ops->insert_location = insert_catch_vfork;
16100   ops->remove_location = remove_catch_vfork;
16101   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16102   ops->print_it = print_it_catch_vfork;
16103   ops->print_one = print_one_catch_vfork;
16104   ops->print_mention = print_mention_catch_vfork;
16105   ops->print_recreate = print_recreate_catch_vfork;
16106
16107   /* Exec catchpoints.  */
16108   ops = &catch_exec_breakpoint_ops;
16109   *ops = base_breakpoint_ops;
16110   ops->dtor = dtor_catch_exec;
16111   ops->insert_location = insert_catch_exec;
16112   ops->remove_location = remove_catch_exec;
16113   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16114   ops->print_it = print_it_catch_exec;
16115   ops->print_one = print_one_catch_exec;
16116   ops->print_mention = print_mention_catch_exec;
16117   ops->print_recreate = print_recreate_catch_exec;
16118
16119   /* Solib-related catchpoints.  */
16120   ops = &catch_solib_breakpoint_ops;
16121   *ops = base_breakpoint_ops;
16122   ops->dtor = dtor_catch_solib;
16123   ops->insert_location = insert_catch_solib;
16124   ops->remove_location = remove_catch_solib;
16125   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16126   ops->check_status = check_status_catch_solib;
16127   ops->print_it = print_it_catch_solib;
16128   ops->print_one = print_one_catch_solib;
16129   ops->print_mention = print_mention_catch_solib;
16130   ops->print_recreate = print_recreate_catch_solib;
16131
16132   ops = &dprintf_breakpoint_ops;
16133   *ops = bkpt_base_breakpoint_ops;
16134   ops->re_set = dprintf_re_set;
16135   ops->resources_needed = bkpt_resources_needed;
16136   ops->print_it = bkpt_print_it;
16137   ops->print_mention = bkpt_print_mention;
16138   ops->print_recreate = dprintf_print_recreate;
16139   ops->after_condition_true = dprintf_after_condition_true;
16140   ops->breakpoint_hit = dprintf_breakpoint_hit;
16141 }
16142
16143 /* Chain containing all defined "enable breakpoint" subcommands.  */
16144
16145 static struct cmd_list_element *enablebreaklist = NULL;
16146
16147 void
16148 _initialize_breakpoint (void)
16149 {
16150   struct cmd_list_element *c;
16151
16152   initialize_breakpoint_ops ();
16153
16154   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16155   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16156   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16157
16158   breakpoint_objfile_key
16159     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16160
16161   breakpoint_chain = 0;
16162   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16163      before a breakpoint is set.  */
16164   breakpoint_count = 0;
16165
16166   tracepoint_count = 0;
16167
16168   add_com ("ignore", class_breakpoint, ignore_command, _("\
16169 Set ignore-count of breakpoint number N to COUNT.\n\
16170 Usage is `ignore N COUNT'."));
16171
16172   add_com ("commands", class_breakpoint, commands_command, _("\
16173 Set commands to be executed when a breakpoint is hit.\n\
16174 Give breakpoint number as argument after \"commands\".\n\
16175 With no argument, the targeted breakpoint is the last one set.\n\
16176 The commands themselves follow starting on the next line.\n\
16177 Type a line containing \"end\" to indicate the end of them.\n\
16178 Give \"silent\" as the first line to make the breakpoint silent;\n\
16179 then no output is printed when it is hit, except what the commands print."));
16180
16181   c = add_com ("condition", class_breakpoint, condition_command, _("\
16182 Specify breakpoint number N to break only if COND is true.\n\
16183 Usage is `condition N COND', where N is an integer and COND is an\n\
16184 expression to be evaluated whenever breakpoint N is reached."));
16185   set_cmd_completer (c, condition_completer);
16186
16187   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16188 Set a temporary breakpoint.\n\
16189 Like \"break\" except the breakpoint is only temporary,\n\
16190 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16191 by using \"enable delete\" on the breakpoint number.\n\
16192 \n"
16193 BREAK_ARGS_HELP ("tbreak")));
16194   set_cmd_completer (c, location_completer);
16195
16196   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16197 Set a hardware assisted breakpoint.\n\
16198 Like \"break\" except the breakpoint requires hardware support,\n\
16199 some target hardware may not have this support.\n\
16200 \n"
16201 BREAK_ARGS_HELP ("hbreak")));
16202   set_cmd_completer (c, location_completer);
16203
16204   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16205 Set a temporary hardware assisted breakpoint.\n\
16206 Like \"hbreak\" except the breakpoint is only temporary,\n\
16207 so it will be deleted when hit.\n\
16208 \n"
16209 BREAK_ARGS_HELP ("thbreak")));
16210   set_cmd_completer (c, location_completer);
16211
16212   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16213 Enable some breakpoints.\n\
16214 Give breakpoint numbers (separated by spaces) as arguments.\n\
16215 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16216 This is used to cancel the effect of the \"disable\" command.\n\
16217 With a subcommand you can enable temporarily."),
16218                   &enablelist, "enable ", 1, &cmdlist);
16219
16220   add_com_alias ("en", "enable", class_breakpoint, 1);
16221
16222   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16223 Enable some breakpoints.\n\
16224 Give breakpoint numbers (separated by spaces) as arguments.\n\
16225 This is used to cancel the effect of the \"disable\" command.\n\
16226 May be abbreviated to simply \"enable\".\n"),
16227                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16228
16229   add_cmd ("once", no_class, enable_once_command, _("\
16230 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16231 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16232            &enablebreaklist);
16233
16234   add_cmd ("delete", no_class, enable_delete_command, _("\
16235 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16236 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16237            &enablebreaklist);
16238
16239   add_cmd ("count", no_class, enable_count_command, _("\
16240 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16241 If a breakpoint is hit while enabled in this fashion,\n\
16242 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16243            &enablebreaklist);
16244
16245   add_cmd ("delete", no_class, enable_delete_command, _("\
16246 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16247 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16248            &enablelist);
16249
16250   add_cmd ("once", no_class, enable_once_command, _("\
16251 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16252 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16253            &enablelist);
16254
16255   add_cmd ("count", no_class, enable_count_command, _("\
16256 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16257 If a breakpoint is hit while enabled in this fashion,\n\
16258 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16259            &enablelist);
16260
16261   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16262 Disable some breakpoints.\n\
16263 Arguments are breakpoint numbers with spaces in between.\n\
16264 To disable all breakpoints, give no argument.\n\
16265 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16266                   &disablelist, "disable ", 1, &cmdlist);
16267   add_com_alias ("dis", "disable", class_breakpoint, 1);
16268   add_com_alias ("disa", "disable", class_breakpoint, 1);
16269
16270   add_cmd ("breakpoints", class_alias, disable_command, _("\
16271 Disable some breakpoints.\n\
16272 Arguments are breakpoint numbers with spaces in between.\n\
16273 To disable all breakpoints, give no argument.\n\
16274 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16275 This command may be abbreviated \"disable\"."),
16276            &disablelist);
16277
16278   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16279 Delete some breakpoints or auto-display expressions.\n\
16280 Arguments are breakpoint numbers with spaces in between.\n\
16281 To delete all breakpoints, give no argument.\n\
16282 \n\
16283 Also a prefix command for deletion of other GDB objects.\n\
16284 The \"unset\" command is also an alias for \"delete\"."),
16285                   &deletelist, "delete ", 1, &cmdlist);
16286   add_com_alias ("d", "delete", class_breakpoint, 1);
16287   add_com_alias ("del", "delete", class_breakpoint, 1);
16288
16289   add_cmd ("breakpoints", class_alias, delete_command, _("\
16290 Delete some breakpoints or auto-display expressions.\n\
16291 Arguments are breakpoint numbers with spaces in between.\n\
16292 To delete all breakpoints, give no argument.\n\
16293 This command may be abbreviated \"delete\"."),
16294            &deletelist);
16295
16296   add_com ("clear", class_breakpoint, clear_command, _("\
16297 Clear breakpoint at specified location.\n\
16298 Argument may be a linespec, explicit, or address location as described below.\n\
16299 \n\
16300 With no argument, clears all breakpoints in the line that the selected frame\n\
16301 is executing in.\n"
16302 "\n" LOCATION_HELP_STRING "\n\
16303 See also the \"delete\" command which clears breakpoints by number."));
16304   add_com_alias ("cl", "clear", class_breakpoint, 1);
16305
16306   c = add_com ("break", class_breakpoint, break_command, _("\
16307 Set breakpoint at specified location.\n"
16308 BREAK_ARGS_HELP ("break")));
16309   set_cmd_completer (c, location_completer);
16310
16311   add_com_alias ("b", "break", class_run, 1);
16312   add_com_alias ("br", "break", class_run, 1);
16313   add_com_alias ("bre", "break", class_run, 1);
16314   add_com_alias ("brea", "break", class_run, 1);
16315
16316   if (dbx_commands)
16317     {
16318       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16319 Break in function/address or break at a line in the current file."),
16320                              &stoplist, "stop ", 1, &cmdlist);
16321       add_cmd ("in", class_breakpoint, stopin_command,
16322                _("Break in function or address."), &stoplist);
16323       add_cmd ("at", class_breakpoint, stopat_command,
16324                _("Break at a line in the current file."), &stoplist);
16325       add_com ("status", class_info, breakpoints_info, _("\
16326 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16327 The \"Type\" column indicates one of:\n\
16328 \tbreakpoint     - normal breakpoint\n\
16329 \twatchpoint     - watchpoint\n\
16330 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16331 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16332 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16333 address and file/line number respectively.\n\
16334 \n\
16335 Convenience variable \"$_\" and default examine address for \"x\"\n\
16336 are set to the address of the last breakpoint listed unless the command\n\
16337 is prefixed with \"server \".\n\n\
16338 Convenience variable \"$bpnum\" contains the number of the last\n\
16339 breakpoint set."));
16340     }
16341
16342   add_info ("breakpoints", breakpoints_info, _("\
16343 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16344 The \"Type\" column indicates one of:\n\
16345 \tbreakpoint     - normal breakpoint\n\
16346 \twatchpoint     - watchpoint\n\
16347 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16348 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16349 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16350 address and file/line number respectively.\n\
16351 \n\
16352 Convenience variable \"$_\" and default examine address for \"x\"\n\
16353 are set to the address of the last breakpoint listed unless the command\n\
16354 is prefixed with \"server \".\n\n\
16355 Convenience variable \"$bpnum\" contains the number of the last\n\
16356 breakpoint set."));
16357
16358   add_info_alias ("b", "breakpoints", 1);
16359
16360   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16361 Status of all breakpoints, or breakpoint number NUMBER.\n\
16362 The \"Type\" column indicates one of:\n\
16363 \tbreakpoint     - normal breakpoint\n\
16364 \twatchpoint     - watchpoint\n\
16365 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16366 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16367 \tuntil          - internal breakpoint used by the \"until\" command\n\
16368 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16369 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16370 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16371 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16372 address and file/line number respectively.\n\
16373 \n\
16374 Convenience variable \"$_\" and default examine address for \"x\"\n\
16375 are set to the address of the last breakpoint listed unless the command\n\
16376 is prefixed with \"server \".\n\n\
16377 Convenience variable \"$bpnum\" contains the number of the last\n\
16378 breakpoint set."),
16379            &maintenanceinfolist);
16380
16381   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16382 Set catchpoints to catch events."),
16383                   &catch_cmdlist, "catch ",
16384                   0/*allow-unknown*/, &cmdlist);
16385
16386   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16387 Set temporary catchpoints to catch events."),
16388                   &tcatch_cmdlist, "tcatch ",
16389                   0/*allow-unknown*/, &cmdlist);
16390
16391   add_catch_command ("fork", _("Catch calls to fork."),
16392                      catch_fork_command_1,
16393                      NULL,
16394                      (void *) (uintptr_t) catch_fork_permanent,
16395                      (void *) (uintptr_t) catch_fork_temporary);
16396   add_catch_command ("vfork", _("Catch calls to vfork."),
16397                      catch_fork_command_1,
16398                      NULL,
16399                      (void *) (uintptr_t) catch_vfork_permanent,
16400                      (void *) (uintptr_t) catch_vfork_temporary);
16401   add_catch_command ("exec", _("Catch calls to exec."),
16402                      catch_exec_command_1,
16403                      NULL,
16404                      CATCH_PERMANENT,
16405                      CATCH_TEMPORARY);
16406   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16407 Usage: catch load [REGEX]\n\
16408 If REGEX is given, only stop for libraries matching the regular expression."),
16409                      catch_load_command_1,
16410                      NULL,
16411                      CATCH_PERMANENT,
16412                      CATCH_TEMPORARY);
16413   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16414 Usage: catch unload [REGEX]\n\
16415 If REGEX is given, only stop for libraries matching the regular expression."),
16416                      catch_unload_command_1,
16417                      NULL,
16418                      CATCH_PERMANENT,
16419                      CATCH_TEMPORARY);
16420
16421   c = add_com ("watch", class_breakpoint, watch_command, _("\
16422 Set a watchpoint for an expression.\n\
16423 Usage: watch [-l|-location] EXPRESSION\n\
16424 A watchpoint stops execution of your program whenever the value of\n\
16425 an expression changes.\n\
16426 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16427 the memory to which it refers."));
16428   set_cmd_completer (c, expression_completer);
16429
16430   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16431 Set a read watchpoint for an expression.\n\
16432 Usage: rwatch [-l|-location] EXPRESSION\n\
16433 A watchpoint stops execution of your program whenever the value of\n\
16434 an expression is read.\n\
16435 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16436 the memory to which it refers."));
16437   set_cmd_completer (c, expression_completer);
16438
16439   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16440 Set a watchpoint for an expression.\n\
16441 Usage: awatch [-l|-location] EXPRESSION\n\
16442 A watchpoint stops execution of your program whenever the value of\n\
16443 an expression is either read or written.\n\
16444 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16445 the memory to which it refers."));
16446   set_cmd_completer (c, expression_completer);
16447
16448   add_info ("watchpoints", watchpoints_info, _("\
16449 Status of specified watchpoints (all watchpoints if no argument)."));
16450
16451   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16452      respond to changes - contrary to the description.  */
16453   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16454                             &can_use_hw_watchpoints, _("\
16455 Set debugger's willingness to use watchpoint hardware."), _("\
16456 Show debugger's willingness to use watchpoint hardware."), _("\
16457 If zero, gdb will not use hardware for new watchpoints, even if\n\
16458 such is available.  (However, any hardware watchpoints that were\n\
16459 created before setting this to nonzero, will continue to use watchpoint\n\
16460 hardware.)"),
16461                             NULL,
16462                             show_can_use_hw_watchpoints,
16463                             &setlist, &showlist);
16464
16465   can_use_hw_watchpoints = 1;
16466
16467   /* Tracepoint manipulation commands.  */
16468
16469   c = add_com ("trace", class_breakpoint, trace_command, _("\
16470 Set a tracepoint at specified location.\n\
16471 \n"
16472 BREAK_ARGS_HELP ("trace") "\n\
16473 Do \"help tracepoints\" for info on other tracepoint commands."));
16474   set_cmd_completer (c, location_completer);
16475
16476   add_com_alias ("tp", "trace", class_alias, 0);
16477   add_com_alias ("tr", "trace", class_alias, 1);
16478   add_com_alias ("tra", "trace", class_alias, 1);
16479   add_com_alias ("trac", "trace", class_alias, 1);
16480
16481   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16482 Set a fast tracepoint at specified location.\n\
16483 \n"
16484 BREAK_ARGS_HELP ("ftrace") "\n\
16485 Do \"help tracepoints\" for info on other tracepoint commands."));
16486   set_cmd_completer (c, location_completer);
16487
16488   c = add_com ("strace", class_breakpoint, strace_command, _("\
16489 Set a static tracepoint at location or marker.\n\
16490 \n\
16491 strace [LOCATION] [if CONDITION]\n\
16492 LOCATION may be a linespec, explicit, or address location (described below) \n\
16493 or -m MARKER_ID.\n\n\
16494 If a marker id is specified, probe the marker with that name.  With\n\
16495 no LOCATION, uses current execution address of the selected stack frame.\n\
16496 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16497 This collects arbitrary user data passed in the probe point call to the\n\
16498 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16499 by printing the $_sdata variable like any other convenience variable.\n\
16500 \n\
16501 CONDITION is a boolean expression.\n\
16502 \n" LOCATION_HELP_STRING "\n\
16503 Multiple tracepoints at one place are permitted, and useful if their\n\
16504 conditions are different.\n\
16505 \n\
16506 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16507 Do \"help tracepoints\" for info on other tracepoint commands."));
16508   set_cmd_completer (c, location_completer);
16509
16510   add_info ("tracepoints", tracepoints_info, _("\
16511 Status of specified tracepoints (all tracepoints if no argument).\n\
16512 Convenience variable \"$tpnum\" contains the number of the\n\
16513 last tracepoint set."));
16514
16515   add_info_alias ("tp", "tracepoints", 1);
16516
16517   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16518 Delete specified tracepoints.\n\
16519 Arguments are tracepoint numbers, separated by spaces.\n\
16520 No argument means delete all tracepoints."),
16521            &deletelist);
16522   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16523
16524   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16525 Disable specified tracepoints.\n\
16526 Arguments are tracepoint numbers, separated by spaces.\n\
16527 No argument means disable all tracepoints."),
16528            &disablelist);
16529   deprecate_cmd (c, "disable");
16530
16531   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16532 Enable specified tracepoints.\n\
16533 Arguments are tracepoint numbers, separated by spaces.\n\
16534 No argument means enable all tracepoints."),
16535            &enablelist);
16536   deprecate_cmd (c, "enable");
16537
16538   add_com ("passcount", class_trace, trace_pass_command, _("\
16539 Set the passcount for a tracepoint.\n\
16540 The trace will end when the tracepoint has been passed 'count' times.\n\
16541 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16542 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16543
16544   add_prefix_cmd ("save", class_breakpoint, save_command,
16545                   _("Save breakpoint definitions as a script."),
16546                   &save_cmdlist, "save ",
16547                   0/*allow-unknown*/, &cmdlist);
16548
16549   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16550 Save current breakpoint definitions as a script.\n\
16551 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16552 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16553 session to restore them."),
16554                &save_cmdlist);
16555   set_cmd_completer (c, filename_completer);
16556
16557   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16558 Save current tracepoint definitions as a script.\n\
16559 Use the 'source' command in another debug session to restore them."),
16560                &save_cmdlist);
16561   set_cmd_completer (c, filename_completer);
16562
16563   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16564   deprecate_cmd (c, "save tracepoints");
16565
16566   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16567 Breakpoint specific settings\n\
16568 Configure various breakpoint-specific variables such as\n\
16569 pending breakpoint behavior"),
16570                   &breakpoint_set_cmdlist, "set breakpoint ",
16571                   0/*allow-unknown*/, &setlist);
16572   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16573 Breakpoint specific settings\n\
16574 Configure various breakpoint-specific variables such as\n\
16575 pending breakpoint behavior"),
16576                   &breakpoint_show_cmdlist, "show breakpoint ",
16577                   0/*allow-unknown*/, &showlist);
16578
16579   add_setshow_auto_boolean_cmd ("pending", no_class,
16580                                 &pending_break_support, _("\
16581 Set debugger's behavior regarding pending breakpoints."), _("\
16582 Show debugger's behavior regarding pending breakpoints."), _("\
16583 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16584 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16585 an error.  If auto, an unrecognized breakpoint location results in a\n\
16586 user-query to see if a pending breakpoint should be created."),
16587                                 NULL,
16588                                 show_pending_break_support,
16589                                 &breakpoint_set_cmdlist,
16590                                 &breakpoint_show_cmdlist);
16591
16592   pending_break_support = AUTO_BOOLEAN_AUTO;
16593
16594   add_setshow_boolean_cmd ("auto-hw", no_class,
16595                            &automatic_hardware_breakpoints, _("\
16596 Set automatic usage of hardware breakpoints."), _("\
16597 Show automatic usage of hardware breakpoints."), _("\
16598 If set, the debugger will automatically use hardware breakpoints for\n\
16599 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16600 a warning will be emitted for such breakpoints."),
16601                            NULL,
16602                            show_automatic_hardware_breakpoints,
16603                            &breakpoint_set_cmdlist,
16604                            &breakpoint_show_cmdlist);
16605
16606   add_setshow_boolean_cmd ("always-inserted", class_support,
16607                            &always_inserted_mode, _("\
16608 Set mode for inserting breakpoints."), _("\
16609 Show mode for inserting breakpoints."), _("\
16610 When this mode is on, breakpoints are inserted immediately as soon as\n\
16611 they're created, kept inserted even when execution stops, and removed\n\
16612 only when the user deletes them.  When this mode is off (the default),\n\
16613 breakpoints are inserted only when execution continues, and removed\n\
16614 when execution stops."),
16615                                 NULL,
16616                                 &show_always_inserted_mode,
16617                                 &breakpoint_set_cmdlist,
16618                                 &breakpoint_show_cmdlist);
16619
16620   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16621                         condition_evaluation_enums,
16622                         &condition_evaluation_mode_1, _("\
16623 Set mode of breakpoint condition evaluation."), _("\
16624 Show mode of breakpoint condition evaluation."), _("\
16625 When this is set to \"host\", breakpoint conditions will be\n\
16626 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16627 breakpoint conditions will be downloaded to the target (if the target\n\
16628 supports such feature) and conditions will be evaluated on the target's side.\n\
16629 If this is set to \"auto\" (default), this will be automatically set to\n\
16630 \"target\" if it supports condition evaluation, otherwise it will\n\
16631 be set to \"gdb\""),
16632                            &set_condition_evaluation_mode,
16633                            &show_condition_evaluation_mode,
16634                            &breakpoint_set_cmdlist,
16635                            &breakpoint_show_cmdlist);
16636
16637   add_com ("break-range", class_breakpoint, break_range_command, _("\
16638 Set a breakpoint for an address range.\n\
16639 break-range START-LOCATION, END-LOCATION\n\
16640 where START-LOCATION and END-LOCATION can be one of the following:\n\
16641   LINENUM, for that line in the current file,\n\
16642   FILE:LINENUM, for that line in that file,\n\
16643   +OFFSET, for that number of lines after the current line\n\
16644            or the start of the range\n\
16645   FUNCTION, for the first line in that function,\n\
16646   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16647   *ADDRESS, for the instruction at that address.\n\
16648 \n\
16649 The breakpoint will stop execution of the inferior whenever it executes\n\
16650 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16651 range (including START-LOCATION and END-LOCATION)."));
16652
16653   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16654 Set a dynamic printf at specified location.\n\
16655 dprintf location,format string,arg1,arg2,...\n\
16656 location may be a linespec, explicit, or address location.\n"
16657 "\n" LOCATION_HELP_STRING));
16658   set_cmd_completer (c, location_completer);
16659
16660   add_setshow_enum_cmd ("dprintf-style", class_support,
16661                         dprintf_style_enums, &dprintf_style, _("\
16662 Set the style of usage for dynamic printf."), _("\
16663 Show the style of usage for dynamic printf."), _("\
16664 This setting chooses how GDB will do a dynamic printf.\n\
16665 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16666 console, as with the \"printf\" command.\n\
16667 If the value is \"call\", the print is done by calling a function in your\n\
16668 program; by default printf(), but you can choose a different function or\n\
16669 output stream by setting dprintf-function and dprintf-channel."),
16670                         update_dprintf_commands, NULL,
16671                         &setlist, &showlist);
16672
16673   dprintf_function = xstrdup ("printf");
16674   add_setshow_string_cmd ("dprintf-function", class_support,
16675                           &dprintf_function, _("\
16676 Set the function to use for dynamic printf"), _("\
16677 Show the function to use for dynamic printf"), NULL,
16678                           update_dprintf_commands, NULL,
16679                           &setlist, &showlist);
16680
16681   dprintf_channel = xstrdup ("");
16682   add_setshow_string_cmd ("dprintf-channel", class_support,
16683                           &dprintf_channel, _("\
16684 Set the channel to use for dynamic printf"), _("\
16685 Show the channel to use for dynamic printf"), NULL,
16686                           update_dprintf_commands, NULL,
16687                           &setlist, &showlist);
16688
16689   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16690                            &disconnected_dprintf, _("\
16691 Set whether dprintf continues after GDB disconnects."), _("\
16692 Show whether dprintf continues after GDB disconnects."), _("\
16693 Use this to let dprintf commands continue to hit and produce output\n\
16694 even if GDB disconnects or detaches from the target."),
16695                            NULL,
16696                            NULL,
16697                            &setlist, &showlist);
16698
16699   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16700 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16701 (target agent only) This is useful for formatted output in user-defined commands."));
16702
16703   automatic_hardware_breakpoints = 1;
16704
16705   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16706   observer_attach_thread_exit (remove_threaded_breakpoints);
16707 }