Add some more casts (1/2)
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2015 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
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82
83 /* Enums for exception-handling support.  */
84 enum exception_event_kind
85 {
86   EX_EVENT_THROW,
87   EX_EVENT_RETHROW,
88   EX_EVENT_CATCH
89 };
90
91 /* Prototypes for local functions.  */
92
93 static void enable_delete_command (char *, int);
94
95 static void enable_once_command (char *, int);
96
97 static void enable_count_command (char *, int);
98
99 static void disable_command (char *, int);
100
101 static void enable_command (char *, int);
102
103 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
104                                                       void *),
105                                     void *);
106
107 static void ignore_command (char *, int);
108
109 static int breakpoint_re_set_one (void *);
110
111 static void breakpoint_re_set_default (struct breakpoint *);
112
113 static void
114   create_sals_from_location_default (const struct event_location *location,
115                                      struct linespec_result *canonical,
116                                      enum bptype type_wanted);
117
118 static void create_breakpoints_sal_default (struct gdbarch *,
119                                             struct linespec_result *,
120                                             char *, char *, enum bptype,
121                                             enum bpdisp, int, int,
122                                             int,
123                                             const struct breakpoint_ops *,
124                                             int, int, int, unsigned);
125
126 static void decode_location_default (struct breakpoint *b,
127                                      const struct event_location *location,
128                                      struct symtabs_and_lines *sals);
129
130 static void clear_command (char *, int);
131
132 static void catch_command (char *, int);
133
134 static int can_use_hardware_watchpoint (struct value *);
135
136 static void break_command_1 (char *, int, int);
137
138 static void mention (struct breakpoint *);
139
140 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
141                                                                enum bptype,
142                                                                const struct breakpoint_ops *);
143 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
144                                                        const struct symtab_and_line *);
145
146 /* This function is used in gdbtk sources and thus can not be made
147    static.  */
148 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
149                                        struct symtab_and_line,
150                                        enum bptype,
151                                        const struct breakpoint_ops *);
152
153 static struct breakpoint *
154   momentary_breakpoint_from_master (struct breakpoint *orig,
155                                     enum bptype type,
156                                     const struct breakpoint_ops *ops,
157                                     int loc_enabled);
158
159 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
160
161 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
162                                             CORE_ADDR bpaddr,
163                                             enum bptype bptype);
164
165 static void describe_other_breakpoints (struct gdbarch *,
166                                         struct program_space *, CORE_ADDR,
167                                         struct obj_section *, int);
168
169 static int watchpoint_locations_match (struct bp_location *loc1,
170                                        struct bp_location *loc2);
171
172 static int breakpoint_location_address_match (struct bp_location *bl,
173                                               struct address_space *aspace,
174                                               CORE_ADDR addr);
175
176 static void breakpoints_info (char *, int);
177
178 static void watchpoints_info (char *, int);
179
180 static int breakpoint_1 (char *, int, 
181                          int (*) (const struct breakpoint *));
182
183 static int breakpoint_cond_eval (void *);
184
185 static void cleanup_executing_breakpoints (void *);
186
187 static void commands_command (char *, int);
188
189 static void condition_command (char *, int);
190
191 typedef enum
192   {
193     mark_inserted,
194     mark_uninserted
195   }
196 insertion_state_t;
197
198 static int remove_breakpoint (struct bp_location *, insertion_state_t);
199 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
200
201 static enum print_stop_action print_bp_stop_message (bpstat bs);
202
203 static int watchpoint_check (void *);
204
205 static void maintenance_info_breakpoints (char *, int);
206
207 static int hw_breakpoint_used_count (void);
208
209 static int hw_watchpoint_use_count (struct breakpoint *);
210
211 static int hw_watchpoint_used_count_others (struct breakpoint *except,
212                                             enum bptype type,
213                                             int *other_type_used);
214
215 static void hbreak_command (char *, int);
216
217 static void thbreak_command (char *, int);
218
219 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
220                                     int count);
221
222 static void stop_command (char *arg, int from_tty);
223
224 static void stopin_command (char *arg, int from_tty);
225
226 static void stopat_command (char *arg, int from_tty);
227
228 static void tcatch_command (char *arg, int from_tty);
229
230 static void free_bp_location (struct bp_location *loc);
231 static void incref_bp_location (struct bp_location *loc);
232 static void decref_bp_location (struct bp_location **loc);
233
234 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
235
236 /* update_global_location_list's modes of operation wrt to whether to
237    insert locations now.  */
238 enum ugll_insert_mode
239 {
240   /* Don't insert any breakpoint locations into the inferior, only
241      remove already-inserted locations that no longer should be
242      inserted.  Functions that delete a breakpoint or breakpoints
243      should specify this mode, so that deleting a breakpoint doesn't
244      have the side effect of inserting the locations of other
245      breakpoints that are marked not-inserted, but should_be_inserted
246      returns true on them.
247
248      This behavior is useful is situations close to tear-down -- e.g.,
249      after an exec, while the target still has execution, but
250      breakpoint shadows of the previous executable image should *NOT*
251      be restored to the new image; or before detaching, where the
252      target still has execution and wants to delete breakpoints from
253      GDB's lists, and all breakpoints had already been removed from
254      the inferior.  */
255   UGLL_DONT_INSERT,
256
257   /* May insert breakpoints iff breakpoints_should_be_inserted_now
258      claims breakpoints should be inserted now.  */
259   UGLL_MAY_INSERT,
260
261   /* Insert locations now, irrespective of
262      breakpoints_should_be_inserted_now.  E.g., say all threads are
263      stopped right now, and the user did "continue".  We need to
264      insert breakpoints _before_ resuming the target, but
265      UGLL_MAY_INSERT wouldn't insert them, because
266      breakpoints_should_be_inserted_now returns false at that point,
267      as no thread is running yet.  */
268   UGLL_INSERT
269 };
270
271 static void update_global_location_list (enum ugll_insert_mode);
272
273 static void update_global_location_list_nothrow (enum ugll_insert_mode);
274
275 static int is_hardware_watchpoint (const struct breakpoint *bpt);
276
277 static void insert_breakpoint_locations (void);
278
279 static void tracepoints_info (char *, int);
280
281 static void delete_trace_command (char *, int);
282
283 static void enable_trace_command (char *, int);
284
285 static void disable_trace_command (char *, int);
286
287 static void trace_pass_command (char *, int);
288
289 static void set_tracepoint_count (int num);
290
291 static int is_masked_watchpoint (const struct breakpoint *b);
292
293 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
294
295 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
296    otherwise.  */
297
298 static int strace_marker_p (struct breakpoint *b);
299
300 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
301    that are implemented on top of software or hardware breakpoints
302    (user breakpoints, internal and momentary breakpoints, etc.).  */
303 static struct breakpoint_ops bkpt_base_breakpoint_ops;
304
305 /* Internal breakpoints class type.  */
306 static struct breakpoint_ops internal_breakpoint_ops;
307
308 /* Momentary breakpoints class type.  */
309 static struct breakpoint_ops momentary_breakpoint_ops;
310
311 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
312 static struct breakpoint_ops longjmp_breakpoint_ops;
313
314 /* The breakpoint_ops structure to be used in regular user created
315    breakpoints.  */
316 struct breakpoint_ops bkpt_breakpoint_ops;
317
318 /* Breakpoints set on probes.  */
319 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
320
321 /* Dynamic printf class type.  */
322 struct breakpoint_ops dprintf_breakpoint_ops;
323
324 /* The style in which to perform a dynamic printf.  This is a user
325    option because different output options have different tradeoffs;
326    if GDB does the printing, there is better error handling if there
327    is a problem with any of the arguments, but using an inferior
328    function lets you have special-purpose printers and sending of
329    output to the same place as compiled-in print functions.  */
330
331 static const char dprintf_style_gdb[] = "gdb";
332 static const char dprintf_style_call[] = "call";
333 static const char dprintf_style_agent[] = "agent";
334 static const char *const dprintf_style_enums[] = {
335   dprintf_style_gdb,
336   dprintf_style_call,
337   dprintf_style_agent,
338   NULL
339 };
340 static const char *dprintf_style = dprintf_style_gdb;
341
342 /* The function to use for dynamic printf if the preferred style is to
343    call into the inferior.  The value is simply a string that is
344    copied into the command, so it can be anything that GDB can
345    evaluate to a callable address, not necessarily a function name.  */
346
347 static char *dprintf_function = "";
348
349 /* The channel to use for dynamic printf if the preferred style is to
350    call into the inferior; if a nonempty string, it will be passed to
351    the call as the first argument, with the format string as the
352    second.  As with the dprintf function, this can be anything that
353    GDB knows how to evaluate, so in addition to common choices like
354    "stderr", this could be an app-specific expression like
355    "mystreams[curlogger]".  */
356
357 static char *dprintf_channel = "";
358
359 /* True if dprintf commands should continue to operate even if GDB
360    has disconnected.  */
361 static int disconnected_dprintf = 1;
362
363 /* A reference-counted struct command_line.  This lets multiple
364    breakpoints share a single command list.  */
365 struct counted_command_line
366 {
367   /* The reference count.  */
368   int refc;
369
370   /* The command list.  */
371   struct command_line *commands;
372 };
373
374 struct command_line *
375 breakpoint_commands (struct breakpoint *b)
376 {
377   return b->commands ? b->commands->commands : NULL;
378 }
379
380 /* Flag indicating that a command has proceeded the inferior past the
381    current breakpoint.  */
382
383 static int breakpoint_proceeded;
384
385 const char *
386 bpdisp_text (enum bpdisp disp)
387 {
388   /* NOTE: the following values are a part of MI protocol and
389      represent values of 'disp' field returned when inferior stops at
390      a breakpoint.  */
391   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
392
393   return bpdisps[(int) disp];
394 }
395
396 /* Prototypes for exported functions.  */
397 /* If FALSE, gdb will not use hardware support for watchpoints, even
398    if such is available.  */
399 static int can_use_hw_watchpoints;
400
401 static void
402 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
403                              struct cmd_list_element *c,
404                              const char *value)
405 {
406   fprintf_filtered (file,
407                     _("Debugger's willingness to use "
408                       "watchpoint hardware is %s.\n"),
409                     value);
410 }
411
412 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
413    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
414    for unrecognized breakpoint locations.
415    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
416 static enum auto_boolean pending_break_support;
417 static void
418 show_pending_break_support (struct ui_file *file, int from_tty,
419                             struct cmd_list_element *c,
420                             const char *value)
421 {
422   fprintf_filtered (file,
423                     _("Debugger's behavior regarding "
424                       "pending breakpoints is %s.\n"),
425                     value);
426 }
427
428 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
429    set with "break" but falling in read-only memory.
430    If 0, gdb will warn about such breakpoints, but won't automatically
431    use hardware breakpoints.  */
432 static int automatic_hardware_breakpoints;
433 static void
434 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
435                                      struct cmd_list_element *c,
436                                      const char *value)
437 {
438   fprintf_filtered (file,
439                     _("Automatic usage of hardware breakpoints is %s.\n"),
440                     value);
441 }
442
443 /* If on, GDB keeps breakpoints inserted even if the inferior is
444    stopped, and immediately inserts any new breakpoints as soon as
445    they're created.  If off (default), GDB keeps breakpoints off of
446    the target as long as possible.  That is, it delays inserting
447    breakpoints until the next resume, and removes them again when the
448    target fully stops.  This is a bit safer in case GDB crashes while
449    processing user input.  */
450 static int always_inserted_mode = 0;
451
452 static void
453 show_always_inserted_mode (struct ui_file *file, int from_tty,
454                      struct cmd_list_element *c, const char *value)
455 {
456   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
457                     value);
458 }
459
460 /* See breakpoint.h.  */
461
462 int
463 breakpoints_should_be_inserted_now (void)
464 {
465   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
466     {
467       /* If breakpoints are global, they should be inserted even if no
468          thread under gdb's control is running, or even if there are
469          no threads under GDB's control yet.  */
470       return 1;
471     }
472   else if (target_has_execution)
473     {
474       struct thread_info *tp;
475
476       if (always_inserted_mode)
477         {
478           /* The user wants breakpoints inserted even if all threads
479              are stopped.  */
480           return 1;
481         }
482
483       if (threads_are_executing ())
484         return 1;
485
486       /* Don't remove breakpoints yet if, even though all threads are
487          stopped, we still have events to process.  */
488       ALL_NON_EXITED_THREADS (tp)
489         if (tp->resumed
490             && tp->suspend.waitstatus_pending_p)
491           return 1;
492     }
493   return 0;
494 }
495
496 static const char condition_evaluation_both[] = "host or target";
497
498 /* Modes for breakpoint condition evaluation.  */
499 static const char condition_evaluation_auto[] = "auto";
500 static const char condition_evaluation_host[] = "host";
501 static const char condition_evaluation_target[] = "target";
502 static const char *const condition_evaluation_enums[] = {
503   condition_evaluation_auto,
504   condition_evaluation_host,
505   condition_evaluation_target,
506   NULL
507 };
508
509 /* Global that holds the current mode for breakpoint condition evaluation.  */
510 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
511
512 /* Global that we use to display information to the user (gets its value from
513    condition_evaluation_mode_1.  */
514 static const char *condition_evaluation_mode = condition_evaluation_auto;
515
516 /* Translate a condition evaluation mode MODE into either "host"
517    or "target".  This is used mostly to translate from "auto" to the
518    real setting that is being used.  It returns the translated
519    evaluation mode.  */
520
521 static const char *
522 translate_condition_evaluation_mode (const char *mode)
523 {
524   if (mode == condition_evaluation_auto)
525     {
526       if (target_supports_evaluation_of_breakpoint_conditions ())
527         return condition_evaluation_target;
528       else
529         return condition_evaluation_host;
530     }
531   else
532     return mode;
533 }
534
535 /* Discovers what condition_evaluation_auto translates to.  */
536
537 static const char *
538 breakpoint_condition_evaluation_mode (void)
539 {
540   return translate_condition_evaluation_mode (condition_evaluation_mode);
541 }
542
543 /* Return true if GDB should evaluate breakpoint conditions or false
544    otherwise.  */
545
546 static int
547 gdb_evaluates_breakpoint_condition_p (void)
548 {
549   const char *mode = breakpoint_condition_evaluation_mode ();
550
551   return (mode == condition_evaluation_host);
552 }
553
554 void _initialize_breakpoint (void);
555
556 /* Are we executing breakpoint commands?  */
557 static int executing_breakpoint_commands;
558
559 /* Are overlay event breakpoints enabled? */
560 static int overlay_events_enabled;
561
562 /* See description in breakpoint.h. */
563 int target_exact_watchpoints = 0;
564
565 /* Walk the following statement or block through all breakpoints.
566    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
567    current breakpoint.  */
568
569 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
570
571 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
572         for (B = breakpoint_chain;      \
573              B ? (TMP=B->next, 1): 0;   \
574              B = TMP)
575
576 /* Similar iterator for the low-level breakpoints.  SAFE variant is
577    not provided so update_global_location_list must not be called
578    while executing the block of ALL_BP_LOCATIONS.  */
579
580 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
581         for (BP_TMP = bp_location;                                      \
582              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
583              BP_TMP++)
584
585 /* Iterates through locations with address ADDRESS for the currently selected
586    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
587    to where the loop should start from.
588    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
589    appropriate location to start with.  */
590
591 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
592         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
593              BP_LOCP_TMP = BP_LOCP_START;                               \
594              BP_LOCP_START                                              \
595              && (BP_LOCP_TMP < bp_location + bp_location_count          \
596              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
597              BP_LOCP_TMP++)
598
599 /* Iterator for tracepoints only.  */
600
601 #define ALL_TRACEPOINTS(B)  \
602   for (B = breakpoint_chain; B; B = B->next)  \
603     if (is_tracepoint (B))
604
605 /* Chains of all breakpoints defined.  */
606
607 struct breakpoint *breakpoint_chain;
608
609 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
610
611 static struct bp_location **bp_location;
612
613 /* Number of elements of BP_LOCATION.  */
614
615 static unsigned bp_location_count;
616
617 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
618    ADDRESS for the current elements of BP_LOCATION which get a valid
619    result from bp_location_has_shadow.  You can use it for roughly
620    limiting the subrange of BP_LOCATION to scan for shadow bytes for
621    an address you need to read.  */
622
623 static CORE_ADDR bp_location_placed_address_before_address_max;
624
625 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
626    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
627    BP_LOCATION which get a valid result from bp_location_has_shadow.
628    You can use it for roughly limiting the subrange of BP_LOCATION to
629    scan for shadow bytes for an address you need to read.  */
630
631 static CORE_ADDR bp_location_shadow_len_after_address_max;
632
633 /* The locations that no longer correspond to any breakpoint, unlinked
634    from bp_location array, but for which a hit may still be reported
635    by a target.  */
636 VEC(bp_location_p) *moribund_locations = NULL;
637
638 /* Number of last breakpoint made.  */
639
640 static int breakpoint_count;
641
642 /* The value of `breakpoint_count' before the last command that
643    created breakpoints.  If the last (break-like) command created more
644    than one breakpoint, then the difference between BREAKPOINT_COUNT
645    and PREV_BREAKPOINT_COUNT is more than one.  */
646 static int prev_breakpoint_count;
647
648 /* Number of last tracepoint made.  */
649
650 static int tracepoint_count;
651
652 static struct cmd_list_element *breakpoint_set_cmdlist;
653 static struct cmd_list_element *breakpoint_show_cmdlist;
654 struct cmd_list_element *save_cmdlist;
655
656 /* See declaration at breakpoint.h.  */
657
658 struct breakpoint *
659 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
660                     void *user_data)
661 {
662   struct breakpoint *b = NULL;
663
664   ALL_BREAKPOINTS (b)
665     {
666       if (func (b, user_data) != 0)
667         break;
668     }
669
670   return b;
671 }
672
673 /* Return whether a breakpoint is an active enabled breakpoint.  */
674 static int
675 breakpoint_enabled (struct breakpoint *b)
676 {
677   return (b->enable_state == bp_enabled);
678 }
679
680 /* Set breakpoint count to NUM.  */
681
682 static void
683 set_breakpoint_count (int num)
684 {
685   prev_breakpoint_count = breakpoint_count;
686   breakpoint_count = num;
687   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
688 }
689
690 /* Used by `start_rbreak_breakpoints' below, to record the current
691    breakpoint count before "rbreak" creates any breakpoint.  */
692 static int rbreak_start_breakpoint_count;
693
694 /* Called at the start an "rbreak" command to record the first
695    breakpoint made.  */
696
697 void
698 start_rbreak_breakpoints (void)
699 {
700   rbreak_start_breakpoint_count = breakpoint_count;
701 }
702
703 /* Called at the end of an "rbreak" command to record the last
704    breakpoint made.  */
705
706 void
707 end_rbreak_breakpoints (void)
708 {
709   prev_breakpoint_count = rbreak_start_breakpoint_count;
710 }
711
712 /* Used in run_command to zero the hit count when a new run starts.  */
713
714 void
715 clear_breakpoint_hit_counts (void)
716 {
717   struct breakpoint *b;
718
719   ALL_BREAKPOINTS (b)
720     b->hit_count = 0;
721 }
722
723 /* Allocate a new counted_command_line with reference count of 1.
724    The new structure owns COMMANDS.  */
725
726 static struct counted_command_line *
727 alloc_counted_command_line (struct command_line *commands)
728 {
729   struct counted_command_line *result = XNEW (struct counted_command_line);
730
731   result->refc = 1;
732   result->commands = commands;
733
734   return result;
735 }
736
737 /* Increment reference count.  This does nothing if CMD is NULL.  */
738
739 static void
740 incref_counted_command_line (struct counted_command_line *cmd)
741 {
742   if (cmd)
743     ++cmd->refc;
744 }
745
746 /* Decrement reference count.  If the reference count reaches 0,
747    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
748    nothing if *CMDP is NULL.  */
749
750 static void
751 decref_counted_command_line (struct counted_command_line **cmdp)
752 {
753   if (*cmdp)
754     {
755       if (--(*cmdp)->refc == 0)
756         {
757           free_command_lines (&(*cmdp)->commands);
758           xfree (*cmdp);
759         }
760       *cmdp = NULL;
761     }
762 }
763
764 /* A cleanup function that calls decref_counted_command_line.  */
765
766 static void
767 do_cleanup_counted_command_line (void *arg)
768 {
769   decref_counted_command_line ((struct counted_command_line **) arg);
770 }
771
772 /* Create a cleanup that calls decref_counted_command_line on the
773    argument.  */
774
775 static struct cleanup *
776 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
777 {
778   return make_cleanup (do_cleanup_counted_command_line, cmdp);
779 }
780
781 \f
782 /* Return the breakpoint with the specified number, or NULL
783    if the number does not refer to an existing breakpoint.  */
784
785 struct breakpoint *
786 get_breakpoint (int num)
787 {
788   struct breakpoint *b;
789
790   ALL_BREAKPOINTS (b)
791     if (b->number == num)
792       return b;
793   
794   return NULL;
795 }
796
797 \f
798
799 /* Mark locations as "conditions have changed" in case the target supports
800    evaluating conditions on its side.  */
801
802 static void
803 mark_breakpoint_modified (struct breakpoint *b)
804 {
805   struct bp_location *loc;
806
807   /* This is only meaningful if the target is
808      evaluating conditions and if the user has
809      opted for condition evaluation on the target's
810      side.  */
811   if (gdb_evaluates_breakpoint_condition_p ()
812       || !target_supports_evaluation_of_breakpoint_conditions ())
813     return;
814
815   if (!is_breakpoint (b))
816     return;
817
818   for (loc = b->loc; loc; loc = loc->next)
819     loc->condition_changed = condition_modified;
820 }
821
822 /* Mark location as "conditions have changed" in case the target supports
823    evaluating conditions on its side.  */
824
825 static void
826 mark_breakpoint_location_modified (struct bp_location *loc)
827 {
828   /* This is only meaningful if the target is
829      evaluating conditions and if the user has
830      opted for condition evaluation on the target's
831      side.  */
832   if (gdb_evaluates_breakpoint_condition_p ()
833       || !target_supports_evaluation_of_breakpoint_conditions ())
834
835     return;
836
837   if (!is_breakpoint (loc->owner))
838     return;
839
840   loc->condition_changed = condition_modified;
841 }
842
843 /* Sets the condition-evaluation mode using the static global
844    condition_evaluation_mode.  */
845
846 static void
847 set_condition_evaluation_mode (char *args, int from_tty,
848                                struct cmd_list_element *c)
849 {
850   const char *old_mode, *new_mode;
851
852   if ((condition_evaluation_mode_1 == condition_evaluation_target)
853       && !target_supports_evaluation_of_breakpoint_conditions ())
854     {
855       condition_evaluation_mode_1 = condition_evaluation_mode;
856       warning (_("Target does not support breakpoint condition evaluation.\n"
857                  "Using host evaluation mode instead."));
858       return;
859     }
860
861   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
862   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
863
864   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
865      settings was "auto".  */
866   condition_evaluation_mode = condition_evaluation_mode_1;
867
868   /* Only update the mode if the user picked a different one.  */
869   if (new_mode != old_mode)
870     {
871       struct bp_location *loc, **loc_tmp;
872       /* If the user switched to a different evaluation mode, we
873          need to synch the changes with the target as follows:
874
875          "host" -> "target": Send all (valid) conditions to the target.
876          "target" -> "host": Remove all the conditions from the target.
877       */
878
879       if (new_mode == condition_evaluation_target)
880         {
881           /* Mark everything modified and synch conditions with the
882              target.  */
883           ALL_BP_LOCATIONS (loc, loc_tmp)
884             mark_breakpoint_location_modified (loc);
885         }
886       else
887         {
888           /* Manually mark non-duplicate locations to synch conditions
889              with the target.  We do this to remove all the conditions the
890              target knows about.  */
891           ALL_BP_LOCATIONS (loc, loc_tmp)
892             if (is_breakpoint (loc->owner) && loc->inserted)
893               loc->needs_update = 1;
894         }
895
896       /* Do the update.  */
897       update_global_location_list (UGLL_MAY_INSERT);
898     }
899
900   return;
901 }
902
903 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
904    what "auto" is translating to.  */
905
906 static void
907 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
908                                 struct cmd_list_element *c, const char *value)
909 {
910   if (condition_evaluation_mode == condition_evaluation_auto)
911     fprintf_filtered (file,
912                       _("Breakpoint condition evaluation "
913                         "mode is %s (currently %s).\n"),
914                       value,
915                       breakpoint_condition_evaluation_mode ());
916   else
917     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
918                       value);
919 }
920
921 /* A comparison function for bp_location AP and BP that is used by
922    bsearch.  This comparison function only cares about addresses, unlike
923    the more general bp_location_compare function.  */
924
925 static int
926 bp_location_compare_addrs (const void *ap, const void *bp)
927 {
928   const struct bp_location *a = *(const struct bp_location **) ap;
929   const struct bp_location *b = *(const struct bp_location **) bp;
930
931   if (a->address == b->address)
932     return 0;
933   else
934     return ((a->address > b->address) - (a->address < b->address));
935 }
936
937 /* Helper function to skip all bp_locations with addresses
938    less than ADDRESS.  It returns the first bp_location that
939    is greater than or equal to ADDRESS.  If none is found, just
940    return NULL.  */
941
942 static struct bp_location **
943 get_first_locp_gte_addr (CORE_ADDR address)
944 {
945   struct bp_location dummy_loc;
946   struct bp_location *dummy_locp = &dummy_loc;
947   struct bp_location **locp_found = NULL;
948
949   /* Initialize the dummy location's address field.  */
950   memset (&dummy_loc, 0, sizeof (struct bp_location));
951   dummy_loc.address = address;
952
953   /* Find a close match to the first location at ADDRESS.  */
954   locp_found = ((struct bp_location **)
955                 bsearch (&dummy_locp, bp_location, bp_location_count,
956                          sizeof (struct bp_location **),
957                          bp_location_compare_addrs));
958
959   /* Nothing was found, nothing left to do.  */
960   if (locp_found == NULL)
961     return NULL;
962
963   /* We may have found a location that is at ADDRESS but is not the first in the
964      location's list.  Go backwards (if possible) and locate the first one.  */
965   while ((locp_found - 1) >= bp_location
966          && (*(locp_found - 1))->address == address)
967     locp_found--;
968
969   return locp_found;
970 }
971
972 void
973 set_breakpoint_condition (struct breakpoint *b, const char *exp,
974                           int from_tty)
975 {
976   xfree (b->cond_string);
977   b->cond_string = NULL;
978
979   if (is_watchpoint (b))
980     {
981       struct watchpoint *w = (struct watchpoint *) b;
982
983       xfree (w->cond_exp);
984       w->cond_exp = NULL;
985     }
986   else
987     {
988       struct bp_location *loc;
989
990       for (loc = b->loc; loc; loc = loc->next)
991         {
992           xfree (loc->cond);
993           loc->cond = NULL;
994
995           /* No need to free the condition agent expression
996              bytecode (if we have one).  We will handle this
997              when we go through update_global_location_list.  */
998         }
999     }
1000
1001   if (*exp == 0)
1002     {
1003       if (from_tty)
1004         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1005     }
1006   else
1007     {
1008       const char *arg = exp;
1009
1010       /* I don't know if it matters whether this is the string the user
1011          typed in or the decompiled expression.  */
1012       b->cond_string = xstrdup (arg);
1013       b->condition_not_parsed = 0;
1014
1015       if (is_watchpoint (b))
1016         {
1017           struct watchpoint *w = (struct watchpoint *) b;
1018
1019           innermost_block = NULL;
1020           arg = exp;
1021           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1022           if (*arg)
1023             error (_("Junk at end of expression"));
1024           w->cond_exp_valid_block = innermost_block;
1025         }
1026       else
1027         {
1028           struct bp_location *loc;
1029
1030           for (loc = b->loc; loc; loc = loc->next)
1031             {
1032               arg = exp;
1033               loc->cond =
1034                 parse_exp_1 (&arg, loc->address,
1035                              block_for_pc (loc->address), 0);
1036               if (*arg)
1037                 error (_("Junk at end of expression"));
1038             }
1039         }
1040     }
1041   mark_breakpoint_modified (b);
1042
1043   observer_notify_breakpoint_modified (b);
1044 }
1045
1046 /* Completion for the "condition" command.  */
1047
1048 static VEC (char_ptr) *
1049 condition_completer (struct cmd_list_element *cmd,
1050                      const char *text, const char *word)
1051 {
1052   const char *space;
1053
1054   text = skip_spaces_const (text);
1055   space = skip_to_space_const (text);
1056   if (*space == '\0')
1057     {
1058       int len;
1059       struct breakpoint *b;
1060       VEC (char_ptr) *result = NULL;
1061
1062       if (text[0] == '$')
1063         {
1064           /* We don't support completion of history indices.  */
1065           if (isdigit (text[1]))
1066             return NULL;
1067           return complete_internalvar (&text[1]);
1068         }
1069
1070       /* We're completing the breakpoint number.  */
1071       len = strlen (text);
1072
1073       ALL_BREAKPOINTS (b)
1074         {
1075           char number[50];
1076
1077           xsnprintf (number, sizeof (number), "%d", b->number);
1078
1079           if (strncmp (number, text, len) == 0)
1080             VEC_safe_push (char_ptr, result, xstrdup (number));
1081         }
1082
1083       return result;
1084     }
1085
1086   /* We're completing the expression part.  */
1087   text = skip_spaces_const (space);
1088   return expression_completer (cmd, text, word);
1089 }
1090
1091 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1092
1093 static void
1094 condition_command (char *arg, int from_tty)
1095 {
1096   struct breakpoint *b;
1097   char *p;
1098   int bnum;
1099
1100   if (arg == 0)
1101     error_no_arg (_("breakpoint number"));
1102
1103   p = arg;
1104   bnum = get_number (&p);
1105   if (bnum == 0)
1106     error (_("Bad breakpoint argument: '%s'"), arg);
1107
1108   ALL_BREAKPOINTS (b)
1109     if (b->number == bnum)
1110       {
1111         /* Check if this breakpoint has a "stop" method implemented in an
1112            extension language.  This method and conditions entered into GDB
1113            from the CLI are mutually exclusive.  */
1114         const struct extension_language_defn *extlang
1115           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1116
1117         if (extlang != NULL)
1118           {
1119             error (_("Only one stop condition allowed.  There is currently"
1120                      " a %s stop condition defined for this breakpoint."),
1121                    ext_lang_capitalized_name (extlang));
1122           }
1123         set_breakpoint_condition (b, p, from_tty);
1124
1125         if (is_breakpoint (b))
1126           update_global_location_list (UGLL_MAY_INSERT);
1127
1128         return;
1129       }
1130
1131   error (_("No breakpoint number %d."), bnum);
1132 }
1133
1134 /* Check that COMMAND do not contain commands that are suitable
1135    only for tracepoints and not suitable for ordinary breakpoints.
1136    Throw if any such commands is found.  */
1137
1138 static void
1139 check_no_tracepoint_commands (struct command_line *commands)
1140 {
1141   struct command_line *c;
1142
1143   for (c = commands; c; c = c->next)
1144     {
1145       int i;
1146
1147       if (c->control_type == while_stepping_control)
1148         error (_("The 'while-stepping' command can "
1149                  "only be used for tracepoints"));
1150
1151       for (i = 0; i < c->body_count; ++i)
1152         check_no_tracepoint_commands ((c->body_list)[i]);
1153
1154       /* Not that command parsing removes leading whitespace and comment
1155          lines and also empty lines.  So, we only need to check for
1156          command directly.  */
1157       if (strstr (c->line, "collect ") == c->line)
1158         error (_("The 'collect' command can only be used for tracepoints"));
1159
1160       if (strstr (c->line, "teval ") == c->line)
1161         error (_("The 'teval' command can only be used for tracepoints"));
1162     }
1163 }
1164
1165 /* Encapsulate tests for different types of tracepoints.  */
1166
1167 static int
1168 is_tracepoint_type (enum bptype type)
1169 {
1170   return (type == bp_tracepoint
1171           || type == bp_fast_tracepoint
1172           || type == bp_static_tracepoint);
1173 }
1174
1175 int
1176 is_tracepoint (const struct breakpoint *b)
1177 {
1178   return is_tracepoint_type (b->type);
1179 }
1180
1181 /* A helper function that validates that COMMANDS are valid for a
1182    breakpoint.  This function will throw an exception if a problem is
1183    found.  */
1184
1185 static void
1186 validate_commands_for_breakpoint (struct breakpoint *b,
1187                                   struct command_line *commands)
1188 {
1189   if (is_tracepoint (b))
1190     {
1191       struct tracepoint *t = (struct tracepoint *) b;
1192       struct command_line *c;
1193       struct command_line *while_stepping = 0;
1194
1195       /* Reset the while-stepping step count.  The previous commands
1196          might have included a while-stepping action, while the new
1197          ones might not.  */
1198       t->step_count = 0;
1199
1200       /* We need to verify that each top-level element of commands is
1201          valid for tracepoints, that there's at most one
1202          while-stepping element, and that the while-stepping's body
1203          has valid tracing commands excluding nested while-stepping.
1204          We also need to validate the tracepoint action line in the
1205          context of the tracepoint --- validate_actionline actually
1206          has side effects, like setting the tracepoint's
1207          while-stepping STEP_COUNT, in addition to checking if the
1208          collect/teval actions parse and make sense in the
1209          tracepoint's context.  */
1210       for (c = commands; c; c = c->next)
1211         {
1212           if (c->control_type == while_stepping_control)
1213             {
1214               if (b->type == bp_fast_tracepoint)
1215                 error (_("The 'while-stepping' command "
1216                          "cannot be used for fast tracepoint"));
1217               else if (b->type == bp_static_tracepoint)
1218                 error (_("The 'while-stepping' command "
1219                          "cannot be used for static tracepoint"));
1220
1221               if (while_stepping)
1222                 error (_("The 'while-stepping' command "
1223                          "can be used only once"));
1224               else
1225                 while_stepping = c;
1226             }
1227
1228           validate_actionline (c->line, b);
1229         }
1230       if (while_stepping)
1231         {
1232           struct command_line *c2;
1233
1234           gdb_assert (while_stepping->body_count == 1);
1235           c2 = while_stepping->body_list[0];
1236           for (; c2; c2 = c2->next)
1237             {
1238               if (c2->control_type == while_stepping_control)
1239                 error (_("The 'while-stepping' command cannot be nested"));
1240             }
1241         }
1242     }
1243   else
1244     {
1245       check_no_tracepoint_commands (commands);
1246     }
1247 }
1248
1249 /* Return a vector of all the static tracepoints set at ADDR.  The
1250    caller is responsible for releasing the vector.  */
1251
1252 VEC(breakpoint_p) *
1253 static_tracepoints_here (CORE_ADDR addr)
1254 {
1255   struct breakpoint *b;
1256   VEC(breakpoint_p) *found = 0;
1257   struct bp_location *loc;
1258
1259   ALL_BREAKPOINTS (b)
1260     if (b->type == bp_static_tracepoint)
1261       {
1262         for (loc = b->loc; loc; loc = loc->next)
1263           if (loc->address == addr)
1264             VEC_safe_push(breakpoint_p, found, b);
1265       }
1266
1267   return found;
1268 }
1269
1270 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1271    validate that only allowed commands are included.  */
1272
1273 void
1274 breakpoint_set_commands (struct breakpoint *b, 
1275                          struct command_line *commands)
1276 {
1277   validate_commands_for_breakpoint (b, commands);
1278
1279   decref_counted_command_line (&b->commands);
1280   b->commands = alloc_counted_command_line (commands);
1281   observer_notify_breakpoint_modified (b);
1282 }
1283
1284 /* Set the internal `silent' flag on the breakpoint.  Note that this
1285    is not the same as the "silent" that may appear in the breakpoint's
1286    commands.  */
1287
1288 void
1289 breakpoint_set_silent (struct breakpoint *b, int silent)
1290 {
1291   int old_silent = b->silent;
1292
1293   b->silent = silent;
1294   if (old_silent != silent)
1295     observer_notify_breakpoint_modified (b);
1296 }
1297
1298 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1299    breakpoint work for any thread.  */
1300
1301 void
1302 breakpoint_set_thread (struct breakpoint *b, int thread)
1303 {
1304   int old_thread = b->thread;
1305
1306   b->thread = thread;
1307   if (old_thread != thread)
1308     observer_notify_breakpoint_modified (b);
1309 }
1310
1311 /* Set the task for this breakpoint.  If TASK is 0, make the
1312    breakpoint work for any task.  */
1313
1314 void
1315 breakpoint_set_task (struct breakpoint *b, int task)
1316 {
1317   int old_task = b->task;
1318
1319   b->task = task;
1320   if (old_task != task)
1321     observer_notify_breakpoint_modified (b);
1322 }
1323
1324 void
1325 check_tracepoint_command (char *line, void *closure)
1326 {
1327   struct breakpoint *b = (struct breakpoint *) closure;
1328
1329   validate_actionline (line, b);
1330 }
1331
1332 /* A structure used to pass information through
1333    map_breakpoint_numbers.  */
1334
1335 struct commands_info
1336 {
1337   /* True if the command was typed at a tty.  */
1338   int from_tty;
1339
1340   /* The breakpoint range spec.  */
1341   char *arg;
1342
1343   /* Non-NULL if the body of the commands are being read from this
1344      already-parsed command.  */
1345   struct command_line *control;
1346
1347   /* The command lines read from the user, or NULL if they have not
1348      yet been read.  */
1349   struct counted_command_line *cmd;
1350 };
1351
1352 /* A callback for map_breakpoint_numbers that sets the commands for
1353    commands_command.  */
1354
1355 static void
1356 do_map_commands_command (struct breakpoint *b, void *data)
1357 {
1358   struct commands_info *info = (struct commands_info *) data;
1359
1360   if (info->cmd == NULL)
1361     {
1362       struct command_line *l;
1363
1364       if (info->control != NULL)
1365         l = copy_command_lines (info->control->body_list[0]);
1366       else
1367         {
1368           struct cleanup *old_chain;
1369           char *str;
1370
1371           str = xstrprintf (_("Type commands for breakpoint(s) "
1372                               "%s, one per line."),
1373                             info->arg);
1374
1375           old_chain = make_cleanup (xfree, str);
1376
1377           l = read_command_lines (str,
1378                                   info->from_tty, 1,
1379                                   (is_tracepoint (b)
1380                                    ? check_tracepoint_command : 0),
1381                                   b);
1382
1383           do_cleanups (old_chain);
1384         }
1385
1386       info->cmd = alloc_counted_command_line (l);
1387     }
1388
1389   /* If a breakpoint was on the list more than once, we don't need to
1390      do anything.  */
1391   if (b->commands != info->cmd)
1392     {
1393       validate_commands_for_breakpoint (b, info->cmd->commands);
1394       incref_counted_command_line (info->cmd);
1395       decref_counted_command_line (&b->commands);
1396       b->commands = info->cmd;
1397       observer_notify_breakpoint_modified (b);
1398     }
1399 }
1400
1401 static void
1402 commands_command_1 (char *arg, int from_tty, 
1403                     struct command_line *control)
1404 {
1405   struct cleanup *cleanups;
1406   struct commands_info info;
1407
1408   info.from_tty = from_tty;
1409   info.control = control;
1410   info.cmd = NULL;
1411   /* If we read command lines from the user, then `info' will hold an
1412      extra reference to the commands that we must clean up.  */
1413   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1414
1415   if (arg == NULL || !*arg)
1416     {
1417       if (breakpoint_count - prev_breakpoint_count > 1)
1418         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1419                           breakpoint_count);
1420       else if (breakpoint_count > 0)
1421         arg = xstrprintf ("%d", breakpoint_count);
1422       else
1423         {
1424           /* So that we don't try to free the incoming non-NULL
1425              argument in the cleanup below.  Mapping breakpoint
1426              numbers will fail in this case.  */
1427           arg = NULL;
1428         }
1429     }
1430   else
1431     /* The command loop has some static state, so we need to preserve
1432        our argument.  */
1433     arg = xstrdup (arg);
1434
1435   if (arg != NULL)
1436     make_cleanup (xfree, arg);
1437
1438   info.arg = arg;
1439
1440   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1441
1442   if (info.cmd == NULL)
1443     error (_("No breakpoints specified."));
1444
1445   do_cleanups (cleanups);
1446 }
1447
1448 static void
1449 commands_command (char *arg, int from_tty)
1450 {
1451   commands_command_1 (arg, from_tty, NULL);
1452 }
1453
1454 /* Like commands_command, but instead of reading the commands from
1455    input stream, takes them from an already parsed command structure.
1456
1457    This is used by cli-script.c to DTRT with breakpoint commands
1458    that are part of if and while bodies.  */
1459 enum command_control_type
1460 commands_from_control_command (char *arg, struct command_line *cmd)
1461 {
1462   commands_command_1 (arg, 0, cmd);
1463   return simple_control;
1464 }
1465
1466 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1467
1468 static int
1469 bp_location_has_shadow (struct bp_location *bl)
1470 {
1471   if (bl->loc_type != bp_loc_software_breakpoint)
1472     return 0;
1473   if (!bl->inserted)
1474     return 0;
1475   if (bl->target_info.shadow_len == 0)
1476     /* BL isn't valid, or doesn't shadow memory.  */
1477     return 0;
1478   return 1;
1479 }
1480
1481 /* Update BUF, which is LEN bytes read from the target address
1482    MEMADDR, by replacing a memory breakpoint with its shadowed
1483    contents.
1484
1485    If READBUF is not NULL, this buffer must not overlap with the of
1486    the breakpoint location's shadow_contents buffer.  Otherwise, a
1487    failed assertion internal error will be raised.  */
1488
1489 static void
1490 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1491                             const gdb_byte *writebuf_org,
1492                             ULONGEST memaddr, LONGEST len,
1493                             struct bp_target_info *target_info,
1494                             struct gdbarch *gdbarch)
1495 {
1496   /* Now do full processing of the found relevant range of elements.  */
1497   CORE_ADDR bp_addr = 0;
1498   int bp_size = 0;
1499   int bptoffset = 0;
1500
1501   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1502                                  current_program_space->aspace, 0))
1503     {
1504       /* The breakpoint is inserted in a different address space.  */
1505       return;
1506     }
1507
1508   /* Addresses and length of the part of the breakpoint that
1509      we need to copy.  */
1510   bp_addr = target_info->placed_address;
1511   bp_size = target_info->shadow_len;
1512
1513   if (bp_addr + bp_size <= memaddr)
1514     {
1515       /* The breakpoint is entirely before the chunk of memory we are
1516          reading.  */
1517       return;
1518     }
1519
1520   if (bp_addr >= memaddr + len)
1521     {
1522       /* The breakpoint is entirely after the chunk of memory we are
1523          reading.  */
1524       return;
1525     }
1526
1527   /* Offset within shadow_contents.  */
1528   if (bp_addr < memaddr)
1529     {
1530       /* Only copy the second part of the breakpoint.  */
1531       bp_size -= memaddr - bp_addr;
1532       bptoffset = memaddr - bp_addr;
1533       bp_addr = memaddr;
1534     }
1535
1536   if (bp_addr + bp_size > memaddr + len)
1537     {
1538       /* Only copy the first part of the breakpoint.  */
1539       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1540     }
1541
1542   if (readbuf != NULL)
1543     {
1544       /* Verify that the readbuf buffer does not overlap with the
1545          shadow_contents buffer.  */
1546       gdb_assert (target_info->shadow_contents >= readbuf + len
1547                   || readbuf >= (target_info->shadow_contents
1548                                  + target_info->shadow_len));
1549
1550       /* Update the read buffer with this inserted breakpoint's
1551          shadow.  */
1552       memcpy (readbuf + bp_addr - memaddr,
1553               target_info->shadow_contents + bptoffset, bp_size);
1554     }
1555   else
1556     {
1557       const unsigned char *bp;
1558       CORE_ADDR addr = target_info->reqstd_address;
1559       int placed_size;
1560
1561       /* Update the shadow with what we want to write to memory.  */
1562       memcpy (target_info->shadow_contents + bptoffset,
1563               writebuf_org + bp_addr - memaddr, bp_size);
1564
1565       /* Determine appropriate breakpoint contents and size for this
1566          address.  */
1567       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1568
1569       /* Update the final write buffer with this inserted
1570          breakpoint's INSN.  */
1571       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1572     }
1573 }
1574
1575 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1576    by replacing any memory breakpoints with their shadowed contents.
1577
1578    If READBUF is not NULL, this buffer must not overlap with any of
1579    the breakpoint location's shadow_contents buffers.  Otherwise,
1580    a failed assertion internal error will be raised.
1581
1582    The range of shadowed area by each bp_location is:
1583      bl->address - bp_location_placed_address_before_address_max
1584      up to bl->address + bp_location_shadow_len_after_address_max
1585    The range we were requested to resolve shadows for is:
1586      memaddr ... memaddr + len
1587    Thus the safe cutoff boundaries for performance optimization are
1588      memaddr + len <= (bl->address
1589                        - bp_location_placed_address_before_address_max)
1590    and:
1591      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1592
1593 void
1594 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1595                         const gdb_byte *writebuf_org,
1596                         ULONGEST memaddr, LONGEST len)
1597 {
1598   /* Left boundary, right boundary and median element of our binary
1599      search.  */
1600   unsigned bc_l, bc_r, bc;
1601   size_t i;
1602
1603   /* Find BC_L which is a leftmost element which may affect BUF
1604      content.  It is safe to report lower value but a failure to
1605      report higher one.  */
1606
1607   bc_l = 0;
1608   bc_r = bp_location_count;
1609   while (bc_l + 1 < bc_r)
1610     {
1611       struct bp_location *bl;
1612
1613       bc = (bc_l + bc_r) / 2;
1614       bl = bp_location[bc];
1615
1616       /* Check first BL->ADDRESS will not overflow due to the added
1617          constant.  Then advance the left boundary only if we are sure
1618          the BC element can in no way affect the BUF content (MEMADDR
1619          to MEMADDR + LEN range).
1620
1621          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1622          offset so that we cannot miss a breakpoint with its shadow
1623          range tail still reaching MEMADDR.  */
1624
1625       if ((bl->address + bp_location_shadow_len_after_address_max
1626            >= bl->address)
1627           && (bl->address + bp_location_shadow_len_after_address_max
1628               <= memaddr))
1629         bc_l = bc;
1630       else
1631         bc_r = bc;
1632     }
1633
1634   /* Due to the binary search above, we need to make sure we pick the
1635      first location that's at BC_L's address.  E.g., if there are
1636      multiple locations at the same address, BC_L may end up pointing
1637      at a duplicate location, and miss the "master"/"inserted"
1638      location.  Say, given locations L1, L2 and L3 at addresses A and
1639      B:
1640
1641       L1@A, L2@A, L3@B, ...
1642
1643      BC_L could end up pointing at location L2, while the "master"
1644      location could be L1.  Since the `loc->inserted' flag is only set
1645      on "master" locations, we'd forget to restore the shadow of L1
1646      and L2.  */
1647   while (bc_l > 0
1648          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1649     bc_l--;
1650
1651   /* Now do full processing of the found relevant range of elements.  */
1652
1653   for (bc = bc_l; bc < bp_location_count; bc++)
1654   {
1655     struct bp_location *bl = bp_location[bc];
1656     CORE_ADDR bp_addr = 0;
1657     int bp_size = 0;
1658     int bptoffset = 0;
1659
1660     /* bp_location array has BL->OWNER always non-NULL.  */
1661     if (bl->owner->type == bp_none)
1662       warning (_("reading through apparently deleted breakpoint #%d?"),
1663                bl->owner->number);
1664
1665     /* Performance optimization: any further element can no longer affect BUF
1666        content.  */
1667
1668     if (bl->address >= bp_location_placed_address_before_address_max
1669         && memaddr + len <= (bl->address
1670                              - bp_location_placed_address_before_address_max))
1671       break;
1672
1673     if (!bp_location_has_shadow (bl))
1674       continue;
1675
1676     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1677                                 memaddr, len, &bl->target_info, bl->gdbarch);
1678   }
1679 }
1680
1681 \f
1682
1683 /* Return true if BPT is either a software breakpoint or a hardware
1684    breakpoint.  */
1685
1686 int
1687 is_breakpoint (const struct breakpoint *bpt)
1688 {
1689   return (bpt->type == bp_breakpoint
1690           || bpt->type == bp_hardware_breakpoint
1691           || bpt->type == bp_dprintf);
1692 }
1693
1694 /* Return true if BPT is of any hardware watchpoint kind.  */
1695
1696 static int
1697 is_hardware_watchpoint (const struct breakpoint *bpt)
1698 {
1699   return (bpt->type == bp_hardware_watchpoint
1700           || bpt->type == bp_read_watchpoint
1701           || bpt->type == bp_access_watchpoint);
1702 }
1703
1704 /* Return true if BPT is of any watchpoint kind, hardware or
1705    software.  */
1706
1707 int
1708 is_watchpoint (const struct breakpoint *bpt)
1709 {
1710   return (is_hardware_watchpoint (bpt)
1711           || bpt->type == bp_watchpoint);
1712 }
1713
1714 /* Returns true if the current thread and its running state are safe
1715    to evaluate or update watchpoint B.  Watchpoints on local
1716    expressions need to be evaluated in the context of the thread that
1717    was current when the watchpoint was created, and, that thread needs
1718    to be stopped to be able to select the correct frame context.
1719    Watchpoints on global expressions can be evaluated on any thread,
1720    and in any state.  It is presently left to the target allowing
1721    memory accesses when threads are running.  */
1722
1723 static int
1724 watchpoint_in_thread_scope (struct watchpoint *b)
1725 {
1726   return (b->base.pspace == current_program_space
1727           && (ptid_equal (b->watchpoint_thread, null_ptid)
1728               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1729                   && !is_executing (inferior_ptid))));
1730 }
1731
1732 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1733    associated bp_watchpoint_scope breakpoint.  */
1734
1735 static void
1736 watchpoint_del_at_next_stop (struct watchpoint *w)
1737 {
1738   struct breakpoint *b = &w->base;
1739
1740   if (b->related_breakpoint != b)
1741     {
1742       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1743       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1744       b->related_breakpoint->disposition = disp_del_at_next_stop;
1745       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1746       b->related_breakpoint = b;
1747     }
1748   b->disposition = disp_del_at_next_stop;
1749 }
1750
1751 /* Extract a bitfield value from value VAL using the bit parameters contained in
1752    watchpoint W.  */
1753
1754 static struct value *
1755 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1756 {
1757   struct value *bit_val;
1758
1759   if (val == NULL)
1760     return NULL;
1761
1762   bit_val = allocate_value (value_type (val));
1763
1764   unpack_value_bitfield (bit_val,
1765                          w->val_bitpos,
1766                          w->val_bitsize,
1767                          value_contents_for_printing (val),
1768                          value_offset (val),
1769                          val);
1770
1771   return bit_val;
1772 }
1773
1774 /* Assuming that B is a watchpoint:
1775    - Reparse watchpoint expression, if REPARSE is non-zero
1776    - Evaluate expression and store the result in B->val
1777    - Evaluate the condition if there is one, and store the result
1778      in b->loc->cond.
1779    - Update the list of values that must be watched in B->loc.
1780
1781    If the watchpoint disposition is disp_del_at_next_stop, then do
1782    nothing.  If this is local watchpoint that is out of scope, delete
1783    it.
1784
1785    Even with `set breakpoint always-inserted on' the watchpoints are
1786    removed + inserted on each stop here.  Normal breakpoints must
1787    never be removed because they might be missed by a running thread
1788    when debugging in non-stop mode.  On the other hand, hardware
1789    watchpoints (is_hardware_watchpoint; processed here) are specific
1790    to each LWP since they are stored in each LWP's hardware debug
1791    registers.  Therefore, such LWP must be stopped first in order to
1792    be able to modify its hardware watchpoints.
1793
1794    Hardware watchpoints must be reset exactly once after being
1795    presented to the user.  It cannot be done sooner, because it would
1796    reset the data used to present the watchpoint hit to the user.  And
1797    it must not be done later because it could display the same single
1798    watchpoint hit during multiple GDB stops.  Note that the latter is
1799    relevant only to the hardware watchpoint types bp_read_watchpoint
1800    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1801    not user-visible - its hit is suppressed if the memory content has
1802    not changed.
1803
1804    The following constraints influence the location where we can reset
1805    hardware watchpoints:
1806
1807    * target_stopped_by_watchpoint and target_stopped_data_address are
1808      called several times when GDB stops.
1809
1810    [linux] 
1811    * Multiple hardware watchpoints can be hit at the same time,
1812      causing GDB to stop.  GDB only presents one hardware watchpoint
1813      hit at a time as the reason for stopping, and all the other hits
1814      are presented later, one after the other, each time the user
1815      requests the execution to be resumed.  Execution is not resumed
1816      for the threads still having pending hit event stored in
1817      LWP_INFO->STATUS.  While the watchpoint is already removed from
1818      the inferior on the first stop the thread hit event is kept being
1819      reported from its cached value by linux_nat_stopped_data_address
1820      until the real thread resume happens after the watchpoint gets
1821      presented and thus its LWP_INFO->STATUS gets reset.
1822
1823    Therefore the hardware watchpoint hit can get safely reset on the
1824    watchpoint removal from inferior.  */
1825
1826 static void
1827 update_watchpoint (struct watchpoint *b, int reparse)
1828 {
1829   int within_current_scope;
1830   struct frame_id saved_frame_id;
1831   int frame_saved;
1832
1833   /* If this is a local watchpoint, we only want to check if the
1834      watchpoint frame is in scope if the current thread is the thread
1835      that was used to create the watchpoint.  */
1836   if (!watchpoint_in_thread_scope (b))
1837     return;
1838
1839   if (b->base.disposition == disp_del_at_next_stop)
1840     return;
1841  
1842   frame_saved = 0;
1843
1844   /* Determine if the watchpoint is within scope.  */
1845   if (b->exp_valid_block == NULL)
1846     within_current_scope = 1;
1847   else
1848     {
1849       struct frame_info *fi = get_current_frame ();
1850       struct gdbarch *frame_arch = get_frame_arch (fi);
1851       CORE_ADDR frame_pc = get_frame_pc (fi);
1852
1853       /* If we're at a point where the stack has been destroyed
1854          (e.g. in a function epilogue), unwinding may not work
1855          properly. Do not attempt to recreate locations at this
1856          point.  See similar comments in watchpoint_check.  */
1857       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1858         return;
1859
1860       /* Save the current frame's ID so we can restore it after
1861          evaluating the watchpoint expression on its own frame.  */
1862       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1863          took a frame parameter, so that we didn't have to change the
1864          selected frame.  */
1865       frame_saved = 1;
1866       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1867
1868       fi = frame_find_by_id (b->watchpoint_frame);
1869       within_current_scope = (fi != NULL);
1870       if (within_current_scope)
1871         select_frame (fi);
1872     }
1873
1874   /* We don't free locations.  They are stored in the bp_location array
1875      and update_global_location_list will eventually delete them and
1876      remove breakpoints if needed.  */
1877   b->base.loc = NULL;
1878
1879   if (within_current_scope && reparse)
1880     {
1881       const char *s;
1882
1883       if (b->exp)
1884         {
1885           xfree (b->exp);
1886           b->exp = NULL;
1887         }
1888       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1889       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1890       /* If the meaning of expression itself changed, the old value is
1891          no longer relevant.  We don't want to report a watchpoint hit
1892          to the user when the old value and the new value may actually
1893          be completely different objects.  */
1894       value_free (b->val);
1895       b->val = NULL;
1896       b->val_valid = 0;
1897
1898       /* Note that unlike with breakpoints, the watchpoint's condition
1899          expression is stored in the breakpoint object, not in the
1900          locations (re)created below.  */
1901       if (b->base.cond_string != NULL)
1902         {
1903           if (b->cond_exp != NULL)
1904             {
1905               xfree (b->cond_exp);
1906               b->cond_exp = NULL;
1907             }
1908
1909           s = b->base.cond_string;
1910           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1911         }
1912     }
1913
1914   /* If we failed to parse the expression, for example because
1915      it refers to a global variable in a not-yet-loaded shared library,
1916      don't try to insert watchpoint.  We don't automatically delete
1917      such watchpoint, though, since failure to parse expression
1918      is different from out-of-scope watchpoint.  */
1919   if (!target_has_execution)
1920     {
1921       /* Without execution, memory can't change.  No use to try and
1922          set watchpoint locations.  The watchpoint will be reset when
1923          the target gains execution, through breakpoint_re_set.  */
1924       if (!can_use_hw_watchpoints)
1925         {
1926           if (b->base.ops->works_in_software_mode (&b->base))
1927             b->base.type = bp_watchpoint;
1928           else
1929             error (_("Can't set read/access watchpoint when "
1930                      "hardware watchpoints are disabled."));
1931         }
1932     }
1933   else if (within_current_scope && b->exp)
1934     {
1935       int pc = 0;
1936       struct value *val_chain, *v, *result, *next;
1937       struct program_space *frame_pspace;
1938
1939       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1940
1941       /* Avoid setting b->val if it's already set.  The meaning of
1942          b->val is 'the last value' user saw, and we should update
1943          it only if we reported that last value to user.  As it
1944          happens, the code that reports it updates b->val directly.
1945          We don't keep track of the memory value for masked
1946          watchpoints.  */
1947       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1948         {
1949           if (b->val_bitsize != 0)
1950             {
1951               v = extract_bitfield_from_watchpoint_value (b, v);
1952               if (v != NULL)
1953                 release_value (v);
1954             }
1955           b->val = v;
1956           b->val_valid = 1;
1957         }
1958
1959       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1960
1961       /* Look at each value on the value chain.  */
1962       for (v = val_chain; v; v = value_next (v))
1963         {
1964           /* If it's a memory location, and GDB actually needed
1965              its contents to evaluate the expression, then we
1966              must watch it.  If the first value returned is
1967              still lazy, that means an error occurred reading it;
1968              watch it anyway in case it becomes readable.  */
1969           if (VALUE_LVAL (v) == lval_memory
1970               && (v == val_chain || ! value_lazy (v)))
1971             {
1972               struct type *vtype = check_typedef (value_type (v));
1973
1974               /* We only watch structs and arrays if user asked
1975                  for it explicitly, never if they just happen to
1976                  appear in the middle of some value chain.  */
1977               if (v == result
1978                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1979                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1980                 {
1981                   CORE_ADDR addr;
1982                   enum target_hw_bp_type type;
1983                   struct bp_location *loc, **tmp;
1984                   int bitpos = 0, bitsize = 0;
1985
1986                   if (value_bitsize (v) != 0)
1987                     {
1988                       /* Extract the bit parameters out from the bitfield
1989                          sub-expression.  */
1990                       bitpos = value_bitpos (v);
1991                       bitsize = value_bitsize (v);
1992                     }
1993                   else if (v == result && b->val_bitsize != 0)
1994                     {
1995                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1996                         lvalue whose bit parameters are saved in the fields
1997                         VAL_BITPOS and VAL_BITSIZE.  */
1998                       bitpos = b->val_bitpos;
1999                       bitsize = b->val_bitsize;
2000                     }
2001
2002                   addr = value_address (v);
2003                   if (bitsize != 0)
2004                     {
2005                       /* Skip the bytes that don't contain the bitfield.  */
2006                       addr += bitpos / 8;
2007                     }
2008
2009                   type = hw_write;
2010                   if (b->base.type == bp_read_watchpoint)
2011                     type = hw_read;
2012                   else if (b->base.type == bp_access_watchpoint)
2013                     type = hw_access;
2014
2015                   loc = allocate_bp_location (&b->base);
2016                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2017                     ;
2018                   *tmp = loc;
2019                   loc->gdbarch = get_type_arch (value_type (v));
2020
2021                   loc->pspace = frame_pspace;
2022                   loc->address = addr;
2023
2024                   if (bitsize != 0)
2025                     {
2026                       /* Just cover the bytes that make up the bitfield.  */
2027                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2028                     }
2029                   else
2030                     loc->length = TYPE_LENGTH (value_type (v));
2031
2032                   loc->watchpoint_type = type;
2033                 }
2034             }
2035         }
2036
2037       /* Change the type of breakpoint between hardware assisted or
2038          an ordinary watchpoint depending on the hardware support
2039          and free hardware slots.  REPARSE is set when the inferior
2040          is started.  */
2041       if (reparse)
2042         {
2043           int reg_cnt;
2044           enum bp_loc_type loc_type;
2045           struct bp_location *bl;
2046
2047           reg_cnt = can_use_hardware_watchpoint (val_chain);
2048
2049           if (reg_cnt)
2050             {
2051               int i, target_resources_ok, other_type_used;
2052               enum bptype type;
2053
2054               /* Use an exact watchpoint when there's only one memory region to be
2055                  watched, and only one debug register is needed to watch it.  */
2056               b->exact = target_exact_watchpoints && reg_cnt == 1;
2057
2058               /* We need to determine how many resources are already
2059                  used for all other hardware watchpoints plus this one
2060                  to see if we still have enough resources to also fit
2061                  this watchpoint in as well.  */
2062
2063               /* If this is a software watchpoint, we try to turn it
2064                  to a hardware one -- count resources as if B was of
2065                  hardware watchpoint type.  */
2066               type = b->base.type;
2067               if (type == bp_watchpoint)
2068                 type = bp_hardware_watchpoint;
2069
2070               /* This watchpoint may or may not have been placed on
2071                  the list yet at this point (it won't be in the list
2072                  if we're trying to create it for the first time,
2073                  through watch_command), so always account for it
2074                  manually.  */
2075
2076               /* Count resources used by all watchpoints except B.  */
2077               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2078
2079               /* Add in the resources needed for B.  */
2080               i += hw_watchpoint_use_count (&b->base);
2081
2082               target_resources_ok
2083                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2084               if (target_resources_ok <= 0)
2085                 {
2086                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2087
2088                   if (target_resources_ok == 0 && !sw_mode)
2089                     error (_("Target does not support this type of "
2090                              "hardware watchpoint."));
2091                   else if (target_resources_ok < 0 && !sw_mode)
2092                     error (_("There are not enough available hardware "
2093                              "resources for this watchpoint."));
2094
2095                   /* Downgrade to software watchpoint.  */
2096                   b->base.type = bp_watchpoint;
2097                 }
2098               else
2099                 {
2100                   /* If this was a software watchpoint, we've just
2101                      found we have enough resources to turn it to a
2102                      hardware watchpoint.  Otherwise, this is a
2103                      nop.  */
2104                   b->base.type = type;
2105                 }
2106             }
2107           else if (!b->base.ops->works_in_software_mode (&b->base))
2108             {
2109               if (!can_use_hw_watchpoints)
2110                 error (_("Can't set read/access watchpoint when "
2111                          "hardware watchpoints are disabled."));
2112               else
2113                 error (_("Expression cannot be implemented with "
2114                          "read/access watchpoint."));
2115             }
2116           else
2117             b->base.type = bp_watchpoint;
2118
2119           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2120                       : bp_loc_hardware_watchpoint);
2121           for (bl = b->base.loc; bl; bl = bl->next)
2122             bl->loc_type = loc_type;
2123         }
2124
2125       for (v = val_chain; v; v = next)
2126         {
2127           next = value_next (v);
2128           if (v != b->val)
2129             value_free (v);
2130         }
2131
2132       /* If a software watchpoint is not watching any memory, then the
2133          above left it without any location set up.  But,
2134          bpstat_stop_status requires a location to be able to report
2135          stops, so make sure there's at least a dummy one.  */
2136       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2137         {
2138           struct breakpoint *base = &b->base;
2139           base->loc = allocate_bp_location (base);
2140           base->loc->pspace = frame_pspace;
2141           base->loc->address = -1;
2142           base->loc->length = -1;
2143           base->loc->watchpoint_type = -1;
2144         }
2145     }
2146   else if (!within_current_scope)
2147     {
2148       printf_filtered (_("\
2149 Watchpoint %d deleted because the program has left the block\n\
2150 in which its expression is valid.\n"),
2151                        b->base.number);
2152       watchpoint_del_at_next_stop (b);
2153     }
2154
2155   /* Restore the selected frame.  */
2156   if (frame_saved)
2157     select_frame (frame_find_by_id (saved_frame_id));
2158 }
2159
2160
2161 /* Returns 1 iff breakpoint location should be
2162    inserted in the inferior.  We don't differentiate the type of BL's owner
2163    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2164    breakpoint_ops is not defined, because in insert_bp_location,
2165    tracepoint's insert_location will not be called.  */
2166 static int
2167 should_be_inserted (struct bp_location *bl)
2168 {
2169   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2170     return 0;
2171
2172   if (bl->owner->disposition == disp_del_at_next_stop)
2173     return 0;
2174
2175   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2176     return 0;
2177
2178   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2179     return 0;
2180
2181   /* This is set for example, when we're attached to the parent of a
2182      vfork, and have detached from the child.  The child is running
2183      free, and we expect it to do an exec or exit, at which point the
2184      OS makes the parent schedulable again (and the target reports
2185      that the vfork is done).  Until the child is done with the shared
2186      memory region, do not insert breakpoints in the parent, otherwise
2187      the child could still trip on the parent's breakpoints.  Since
2188      the parent is blocked anyway, it won't miss any breakpoint.  */
2189   if (bl->pspace->breakpoints_not_allowed)
2190     return 0;
2191
2192   /* Don't insert a breakpoint if we're trying to step past its
2193      location.  */
2194   if ((bl->loc_type == bp_loc_software_breakpoint
2195        || bl->loc_type == bp_loc_hardware_breakpoint)
2196       && stepping_past_instruction_at (bl->pspace->aspace,
2197                                        bl->address))
2198     {
2199       if (debug_infrun)
2200         {
2201           fprintf_unfiltered (gdb_stdlog,
2202                               "infrun: skipping breakpoint: "
2203                               "stepping past insn at: %s\n",
2204                               paddress (bl->gdbarch, bl->address));
2205         }
2206       return 0;
2207     }
2208
2209   /* Don't insert watchpoints if we're trying to step past the
2210      instruction that triggered one.  */
2211   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2212       && stepping_past_nonsteppable_watchpoint ())
2213     {
2214       if (debug_infrun)
2215         {
2216           fprintf_unfiltered (gdb_stdlog,
2217                               "infrun: stepping past non-steppable watchpoint. "
2218                               "skipping watchpoint at %s:%d\n",
2219                               paddress (bl->gdbarch, bl->address),
2220                               bl->length);
2221         }
2222       return 0;
2223     }
2224
2225   return 1;
2226 }
2227
2228 /* Same as should_be_inserted but does the check assuming
2229    that the location is not duplicated.  */
2230
2231 static int
2232 unduplicated_should_be_inserted (struct bp_location *bl)
2233 {
2234   int result;
2235   const int save_duplicate = bl->duplicate;
2236
2237   bl->duplicate = 0;
2238   result = should_be_inserted (bl);
2239   bl->duplicate = save_duplicate;
2240   return result;
2241 }
2242
2243 /* Parses a conditional described by an expression COND into an
2244    agent expression bytecode suitable for evaluation
2245    by the bytecode interpreter.  Return NULL if there was
2246    any error during parsing.  */
2247
2248 static struct agent_expr *
2249 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2250 {
2251   struct agent_expr *aexpr = NULL;
2252
2253   if (!cond)
2254     return NULL;
2255
2256   /* We don't want to stop processing, so catch any errors
2257      that may show up.  */
2258   TRY
2259     {
2260       aexpr = gen_eval_for_expr (scope, cond);
2261     }
2262
2263   CATCH (ex, RETURN_MASK_ERROR)
2264     {
2265       /* If we got here, it means the condition could not be parsed to a valid
2266          bytecode expression and thus can't be evaluated on the target's side.
2267          It's no use iterating through the conditions.  */
2268       return NULL;
2269     }
2270   END_CATCH
2271
2272   /* We have a valid agent expression.  */
2273   return aexpr;
2274 }
2275
2276 /* Based on location BL, create a list of breakpoint conditions to be
2277    passed on to the target.  If we have duplicated locations with different
2278    conditions, we will add such conditions to the list.  The idea is that the
2279    target will evaluate the list of conditions and will only notify GDB when
2280    one of them is true.  */
2281
2282 static void
2283 build_target_condition_list (struct bp_location *bl)
2284 {
2285   struct bp_location **locp = NULL, **loc2p;
2286   int null_condition_or_parse_error = 0;
2287   int modified = bl->needs_update;
2288   struct bp_location *loc;
2289
2290   /* Release conditions left over from a previous insert.  */
2291   VEC_free (agent_expr_p, bl->target_info.conditions);
2292
2293   /* This is only meaningful if the target is
2294      evaluating conditions and if the user has
2295      opted for condition evaluation on the target's
2296      side.  */
2297   if (gdb_evaluates_breakpoint_condition_p ()
2298       || !target_supports_evaluation_of_breakpoint_conditions ())
2299     return;
2300
2301   /* Do a first pass to check for locations with no assigned
2302      conditions or conditions that fail to parse to a valid agent expression
2303      bytecode.  If any of these happen, then it's no use to send conditions
2304      to the target since this location will always trigger and generate a
2305      response back to GDB.  */
2306   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2307     {
2308       loc = (*loc2p);
2309       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2310         {
2311           if (modified)
2312             {
2313               struct agent_expr *aexpr;
2314
2315               /* Re-parse the conditions since something changed.  In that
2316                  case we already freed the condition bytecodes (see
2317                  force_breakpoint_reinsertion).  We just
2318                  need to parse the condition to bytecodes again.  */
2319               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2320               loc->cond_bytecode = aexpr;
2321
2322               /* Check if we managed to parse the conditional expression
2323                  correctly.  If not, we will not send this condition
2324                  to the target.  */
2325               if (aexpr)
2326                 continue;
2327             }
2328
2329           /* If we have a NULL bytecode expression, it means something
2330              went wrong or we have a null condition expression.  */
2331           if (!loc->cond_bytecode)
2332             {
2333               null_condition_or_parse_error = 1;
2334               break;
2335             }
2336         }
2337     }
2338
2339   /* If any of these happened, it means we will have to evaluate the conditions
2340      for the location's address on gdb's side.  It is no use keeping bytecodes
2341      for all the other duplicate locations, thus we free all of them here.
2342
2343      This is so we have a finer control over which locations' conditions are
2344      being evaluated by GDB or the remote stub.  */
2345   if (null_condition_or_parse_error)
2346     {
2347       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2348         {
2349           loc = (*loc2p);
2350           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2351             {
2352               /* Only go as far as the first NULL bytecode is
2353                  located.  */
2354               if (!loc->cond_bytecode)
2355                 return;
2356
2357               free_agent_expr (loc->cond_bytecode);
2358               loc->cond_bytecode = NULL;
2359             }
2360         }
2361     }
2362
2363   /* No NULL conditions or failed bytecode generation.  Build a condition list
2364      for this location's address.  */
2365   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2366     {
2367       loc = (*loc2p);
2368       if (loc->cond
2369           && is_breakpoint (loc->owner)
2370           && loc->pspace->num == bl->pspace->num
2371           && loc->owner->enable_state == bp_enabled
2372           && loc->enabled)
2373         /* Add the condition to the vector.  This will be used later to send the
2374            conditions to the target.  */
2375         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2376                        loc->cond_bytecode);
2377     }
2378
2379   return;
2380 }
2381
2382 /* Parses a command described by string CMD into an agent expression
2383    bytecode suitable for evaluation by the bytecode interpreter.
2384    Return NULL if there was any error during parsing.  */
2385
2386 static struct agent_expr *
2387 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2388 {
2389   struct cleanup *old_cleanups = 0;
2390   struct expression *expr, **argvec;
2391   struct agent_expr *aexpr = NULL;
2392   const char *cmdrest;
2393   const char *format_start, *format_end;
2394   struct format_piece *fpieces;
2395   int nargs;
2396   struct gdbarch *gdbarch = get_current_arch ();
2397
2398   if (!cmd)
2399     return NULL;
2400
2401   cmdrest = cmd;
2402
2403   if (*cmdrest == ',')
2404     ++cmdrest;
2405   cmdrest = skip_spaces_const (cmdrest);
2406
2407   if (*cmdrest++ != '"')
2408     error (_("No format string following the location"));
2409
2410   format_start = cmdrest;
2411
2412   fpieces = parse_format_string (&cmdrest);
2413
2414   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2415
2416   format_end = cmdrest;
2417
2418   if (*cmdrest++ != '"')
2419     error (_("Bad format string, non-terminated '\"'."));
2420   
2421   cmdrest = skip_spaces_const (cmdrest);
2422
2423   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2424     error (_("Invalid argument syntax"));
2425
2426   if (*cmdrest == ',')
2427     cmdrest++;
2428   cmdrest = skip_spaces_const (cmdrest);
2429
2430   /* For each argument, make an expression.  */
2431
2432   argvec = (struct expression **) alloca (strlen (cmd)
2433                                          * sizeof (struct expression *));
2434
2435   nargs = 0;
2436   while (*cmdrest != '\0')
2437     {
2438       const char *cmd1;
2439
2440       cmd1 = cmdrest;
2441       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2442       argvec[nargs++] = expr;
2443       cmdrest = cmd1;
2444       if (*cmdrest == ',')
2445         ++cmdrest;
2446     }
2447
2448   /* We don't want to stop processing, so catch any errors
2449      that may show up.  */
2450   TRY
2451     {
2452       aexpr = gen_printf (scope, gdbarch, 0, 0,
2453                           format_start, format_end - format_start,
2454                           fpieces, nargs, argvec);
2455     }
2456   CATCH (ex, RETURN_MASK_ERROR)
2457     {
2458       /* If we got here, it means the command could not be parsed to a valid
2459          bytecode expression and thus can't be evaluated on the target's side.
2460          It's no use iterating through the other commands.  */
2461       aexpr = NULL;
2462     }
2463   END_CATCH
2464
2465   do_cleanups (old_cleanups);
2466
2467   /* We have a valid agent expression, return it.  */
2468   return aexpr;
2469 }
2470
2471 /* Based on location BL, create a list of breakpoint commands to be
2472    passed on to the target.  If we have duplicated locations with
2473    different commands, we will add any such to the list.  */
2474
2475 static void
2476 build_target_command_list (struct bp_location *bl)
2477 {
2478   struct bp_location **locp = NULL, **loc2p;
2479   int null_command_or_parse_error = 0;
2480   int modified = bl->needs_update;
2481   struct bp_location *loc;
2482
2483   /* Release commands left over from a previous insert.  */
2484   VEC_free (agent_expr_p, bl->target_info.tcommands);
2485
2486   if (!target_can_run_breakpoint_commands ())
2487     return;
2488
2489   /* For now, limit to agent-style dprintf breakpoints.  */
2490   if (dprintf_style != dprintf_style_agent)
2491     return;
2492
2493   /* For now, if we have any duplicate location that isn't a dprintf,
2494      don't install the target-side commands, as that would make the
2495      breakpoint not be reported to the core, and we'd lose
2496      control.  */
2497   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2498     {
2499       loc = (*loc2p);
2500       if (is_breakpoint (loc->owner)
2501           && loc->pspace->num == bl->pspace->num
2502           && loc->owner->type != bp_dprintf)
2503         return;
2504     }
2505
2506   /* Do a first pass to check for locations with no assigned
2507      conditions or conditions that fail to parse to a valid agent expression
2508      bytecode.  If any of these happen, then it's no use to send conditions
2509      to the target since this location will always trigger and generate a
2510      response back to GDB.  */
2511   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2512     {
2513       loc = (*loc2p);
2514       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2515         {
2516           if (modified)
2517             {
2518               struct agent_expr *aexpr;
2519
2520               /* Re-parse the commands since something changed.  In that
2521                  case we already freed the command bytecodes (see
2522                  force_breakpoint_reinsertion).  We just
2523                  need to parse the command to bytecodes again.  */
2524               aexpr = parse_cmd_to_aexpr (bl->address,
2525                                           loc->owner->extra_string);
2526               loc->cmd_bytecode = aexpr;
2527
2528               if (!aexpr)
2529                 continue;
2530             }
2531
2532           /* If we have a NULL bytecode expression, it means something
2533              went wrong or we have a null command expression.  */
2534           if (!loc->cmd_bytecode)
2535             {
2536               null_command_or_parse_error = 1;
2537               break;
2538             }
2539         }
2540     }
2541
2542   /* If anything failed, then we're not doing target-side commands,
2543      and so clean up.  */
2544   if (null_command_or_parse_error)
2545     {
2546       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2547         {
2548           loc = (*loc2p);
2549           if (is_breakpoint (loc->owner)
2550               && loc->pspace->num == bl->pspace->num)
2551             {
2552               /* Only go as far as the first NULL bytecode is
2553                  located.  */
2554               if (loc->cmd_bytecode == NULL)
2555                 return;
2556
2557               free_agent_expr (loc->cmd_bytecode);
2558               loc->cmd_bytecode = NULL;
2559             }
2560         }
2561     }
2562
2563   /* No NULL commands or failed bytecode generation.  Build a command list
2564      for this location's address.  */
2565   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2566     {
2567       loc = (*loc2p);
2568       if (loc->owner->extra_string
2569           && is_breakpoint (loc->owner)
2570           && loc->pspace->num == bl->pspace->num
2571           && loc->owner->enable_state == bp_enabled
2572           && loc->enabled)
2573         /* Add the command to the vector.  This will be used later
2574            to send the commands to the target.  */
2575         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2576                        loc->cmd_bytecode);
2577     }
2578
2579   bl->target_info.persist = 0;
2580   /* Maybe flag this location as persistent.  */
2581   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2582     bl->target_info.persist = 1;
2583 }
2584
2585 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2586    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2587    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2588    Returns 0 for success, 1 if the bp_location type is not supported or
2589    -1 for failure.
2590
2591    NOTE drow/2003-09-09: This routine could be broken down to an
2592    object-style method for each breakpoint or catchpoint type.  */
2593 static int
2594 insert_bp_location (struct bp_location *bl,
2595                     struct ui_file *tmp_error_stream,
2596                     int *disabled_breaks,
2597                     int *hw_breakpoint_error,
2598                     int *hw_bp_error_explained_already)
2599 {
2600   enum errors bp_err = GDB_NO_ERROR;
2601   const char *bp_err_message = NULL;
2602
2603   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2604     return 0;
2605
2606   /* Note we don't initialize bl->target_info, as that wipes out
2607      the breakpoint location's shadow_contents if the breakpoint
2608      is still inserted at that location.  This in turn breaks
2609      target_read_memory which depends on these buffers when
2610      a memory read is requested at the breakpoint location:
2611      Once the target_info has been wiped, we fail to see that
2612      we have a breakpoint inserted at that address and thus
2613      read the breakpoint instead of returning the data saved in
2614      the breakpoint location's shadow contents.  */
2615   bl->target_info.reqstd_address = bl->address;
2616   bl->target_info.placed_address_space = bl->pspace->aspace;
2617   bl->target_info.length = bl->length;
2618
2619   /* When working with target-side conditions, we must pass all the conditions
2620      for the same breakpoint address down to the target since GDB will not
2621      insert those locations.  With a list of breakpoint conditions, the target
2622      can decide when to stop and notify GDB.  */
2623
2624   if (is_breakpoint (bl->owner))
2625     {
2626       build_target_condition_list (bl);
2627       build_target_command_list (bl);
2628       /* Reset the modification marker.  */
2629       bl->needs_update = 0;
2630     }
2631
2632   if (bl->loc_type == bp_loc_software_breakpoint
2633       || bl->loc_type == bp_loc_hardware_breakpoint)
2634     {
2635       if (bl->owner->type != bp_hardware_breakpoint)
2636         {
2637           /* If the explicitly specified breakpoint type
2638              is not hardware breakpoint, check the memory map to see
2639              if the breakpoint address is in read only memory or not.
2640
2641              Two important cases are:
2642              - location type is not hardware breakpoint, memory
2643              is readonly.  We change the type of the location to
2644              hardware breakpoint.
2645              - location type is hardware breakpoint, memory is
2646              read-write.  This means we've previously made the
2647              location hardware one, but then the memory map changed,
2648              so we undo.
2649              
2650              When breakpoints are removed, remove_breakpoints will use
2651              location types we've just set here, the only possible
2652              problem is that memory map has changed during running
2653              program, but it's not going to work anyway with current
2654              gdb.  */
2655           struct mem_region *mr 
2656             = lookup_mem_region (bl->target_info.reqstd_address);
2657           
2658           if (mr)
2659             {
2660               if (automatic_hardware_breakpoints)
2661                 {
2662                   enum bp_loc_type new_type;
2663                   
2664                   if (mr->attrib.mode != MEM_RW)
2665                     new_type = bp_loc_hardware_breakpoint;
2666                   else 
2667                     new_type = bp_loc_software_breakpoint;
2668                   
2669                   if (new_type != bl->loc_type)
2670                     {
2671                       static int said = 0;
2672
2673                       bl->loc_type = new_type;
2674                       if (!said)
2675                         {
2676                           fprintf_filtered (gdb_stdout,
2677                                             _("Note: automatically using "
2678                                               "hardware breakpoints for "
2679                                               "read-only addresses.\n"));
2680                           said = 1;
2681                         }
2682                     }
2683                 }
2684               else if (bl->loc_type == bp_loc_software_breakpoint
2685                        && mr->attrib.mode != MEM_RW)
2686                 {
2687                   fprintf_unfiltered (tmp_error_stream,
2688                                       _("Cannot insert breakpoint %d.\n"
2689                                         "Cannot set software breakpoint "
2690                                         "at read-only address %s\n"),
2691                                       bl->owner->number,
2692                                       paddress (bl->gdbarch, bl->address));
2693                   return 1;
2694                 }
2695             }
2696         }
2697         
2698       /* First check to see if we have to handle an overlay.  */
2699       if (overlay_debugging == ovly_off
2700           || bl->section == NULL
2701           || !(section_is_overlay (bl->section)))
2702         {
2703           /* No overlay handling: just set the breakpoint.  */
2704           TRY
2705             {
2706               int val;
2707
2708               val = bl->owner->ops->insert_location (bl);
2709               if (val)
2710                 bp_err = GENERIC_ERROR;
2711             }
2712           CATCH (e, RETURN_MASK_ALL)
2713             {
2714               bp_err = e.error;
2715               bp_err_message = e.message;
2716             }
2717           END_CATCH
2718         }
2719       else
2720         {
2721           /* This breakpoint is in an overlay section.
2722              Shall we set a breakpoint at the LMA?  */
2723           if (!overlay_events_enabled)
2724             {
2725               /* Yes -- overlay event support is not active, 
2726                  so we must try to set a breakpoint at the LMA.
2727                  This will not work for a hardware breakpoint.  */
2728               if (bl->loc_type == bp_loc_hardware_breakpoint)
2729                 warning (_("hardware breakpoint %d not supported in overlay!"),
2730                          bl->owner->number);
2731               else
2732                 {
2733                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2734                                                              bl->section);
2735                   /* Set a software (trap) breakpoint at the LMA.  */
2736                   bl->overlay_target_info = bl->target_info;
2737                   bl->overlay_target_info.reqstd_address = addr;
2738
2739                   /* No overlay handling: just set the breakpoint.  */
2740                   TRY
2741                     {
2742                       int val;
2743
2744                       val = target_insert_breakpoint (bl->gdbarch,
2745                                                       &bl->overlay_target_info);
2746                       if (val)
2747                         bp_err = GENERIC_ERROR;
2748                     }
2749                   CATCH (e, RETURN_MASK_ALL)
2750                     {
2751                       bp_err = e.error;
2752                       bp_err_message = e.message;
2753                     }
2754                   END_CATCH
2755
2756                   if (bp_err != GDB_NO_ERROR)
2757                     fprintf_unfiltered (tmp_error_stream,
2758                                         "Overlay breakpoint %d "
2759                                         "failed: in ROM?\n",
2760                                         bl->owner->number);
2761                 }
2762             }
2763           /* Shall we set a breakpoint at the VMA? */
2764           if (section_is_mapped (bl->section))
2765             {
2766               /* Yes.  This overlay section is mapped into memory.  */
2767               TRY
2768                 {
2769                   int val;
2770
2771                   val = bl->owner->ops->insert_location (bl);
2772                   if (val)
2773                     bp_err = GENERIC_ERROR;
2774                 }
2775               CATCH (e, RETURN_MASK_ALL)
2776                 {
2777                   bp_err = e.error;
2778                   bp_err_message = e.message;
2779                 }
2780               END_CATCH
2781             }
2782           else
2783             {
2784               /* No.  This breakpoint will not be inserted.  
2785                  No error, but do not mark the bp as 'inserted'.  */
2786               return 0;
2787             }
2788         }
2789
2790       if (bp_err != GDB_NO_ERROR)
2791         {
2792           /* Can't set the breakpoint.  */
2793
2794           /* In some cases, we might not be able to insert a
2795              breakpoint in a shared library that has already been
2796              removed, but we have not yet processed the shlib unload
2797              event.  Unfortunately, some targets that implement
2798              breakpoint insertion themselves can't tell why the
2799              breakpoint insertion failed (e.g., the remote target
2800              doesn't define error codes), so we must treat generic
2801              errors as memory errors.  */
2802           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2803               && bl->loc_type == bp_loc_software_breakpoint
2804               && (solib_name_from_address (bl->pspace, bl->address)
2805                   || shared_objfile_contains_address_p (bl->pspace,
2806                                                         bl->address)))
2807             {
2808               /* See also: disable_breakpoints_in_shlibs.  */
2809               bl->shlib_disabled = 1;
2810               observer_notify_breakpoint_modified (bl->owner);
2811               if (!*disabled_breaks)
2812                 {
2813                   fprintf_unfiltered (tmp_error_stream, 
2814                                       "Cannot insert breakpoint %d.\n", 
2815                                       bl->owner->number);
2816                   fprintf_unfiltered (tmp_error_stream, 
2817                                       "Temporarily disabling shared "
2818                                       "library breakpoints:\n");
2819                 }
2820               *disabled_breaks = 1;
2821               fprintf_unfiltered (tmp_error_stream,
2822                                   "breakpoint #%d\n", bl->owner->number);
2823               return 0;
2824             }
2825           else
2826             {
2827               if (bl->loc_type == bp_loc_hardware_breakpoint)
2828                 {
2829                   *hw_breakpoint_error = 1;
2830                   *hw_bp_error_explained_already = bp_err_message != NULL;
2831                   fprintf_unfiltered (tmp_error_stream,
2832                                       "Cannot insert hardware breakpoint %d%s",
2833                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2834                   if (bp_err_message != NULL)
2835                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2836                 }
2837               else
2838                 {
2839                   if (bp_err_message == NULL)
2840                     {
2841                       char *message
2842                         = memory_error_message (TARGET_XFER_E_IO,
2843                                                 bl->gdbarch, bl->address);
2844                       struct cleanup *old_chain = make_cleanup (xfree, message);
2845
2846                       fprintf_unfiltered (tmp_error_stream,
2847                                           "Cannot insert breakpoint %d.\n"
2848                                           "%s\n",
2849                                           bl->owner->number, message);
2850                       do_cleanups (old_chain);
2851                     }
2852                   else
2853                     {
2854                       fprintf_unfiltered (tmp_error_stream,
2855                                           "Cannot insert breakpoint %d: %s\n",
2856                                           bl->owner->number,
2857                                           bp_err_message);
2858                     }
2859                 }
2860               return 1;
2861
2862             }
2863         }
2864       else
2865         bl->inserted = 1;
2866
2867       return 0;
2868     }
2869
2870   else if (bl->loc_type == bp_loc_hardware_watchpoint
2871            /* NOTE drow/2003-09-08: This state only exists for removing
2872               watchpoints.  It's not clear that it's necessary...  */
2873            && bl->owner->disposition != disp_del_at_next_stop)
2874     {
2875       int val;
2876
2877       gdb_assert (bl->owner->ops != NULL
2878                   && bl->owner->ops->insert_location != NULL);
2879
2880       val = bl->owner->ops->insert_location (bl);
2881
2882       /* If trying to set a read-watchpoint, and it turns out it's not
2883          supported, try emulating one with an access watchpoint.  */
2884       if (val == 1 && bl->watchpoint_type == hw_read)
2885         {
2886           struct bp_location *loc, **loc_temp;
2887
2888           /* But don't try to insert it, if there's already another
2889              hw_access location that would be considered a duplicate
2890              of this one.  */
2891           ALL_BP_LOCATIONS (loc, loc_temp)
2892             if (loc != bl
2893                 && loc->watchpoint_type == hw_access
2894                 && watchpoint_locations_match (bl, loc))
2895               {
2896                 bl->duplicate = 1;
2897                 bl->inserted = 1;
2898                 bl->target_info = loc->target_info;
2899                 bl->watchpoint_type = hw_access;
2900                 val = 0;
2901                 break;
2902               }
2903
2904           if (val == 1)
2905             {
2906               bl->watchpoint_type = hw_access;
2907               val = bl->owner->ops->insert_location (bl);
2908
2909               if (val)
2910                 /* Back to the original value.  */
2911                 bl->watchpoint_type = hw_read;
2912             }
2913         }
2914
2915       bl->inserted = (val == 0);
2916     }
2917
2918   else if (bl->owner->type == bp_catchpoint)
2919     {
2920       int val;
2921
2922       gdb_assert (bl->owner->ops != NULL
2923                   && bl->owner->ops->insert_location != NULL);
2924
2925       val = bl->owner->ops->insert_location (bl);
2926       if (val)
2927         {
2928           bl->owner->enable_state = bp_disabled;
2929
2930           if (val == 1)
2931             warning (_("\
2932 Error inserting catchpoint %d: Your system does not support this type\n\
2933 of catchpoint."), bl->owner->number);
2934           else
2935             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2936         }
2937
2938       bl->inserted = (val == 0);
2939
2940       /* We've already printed an error message if there was a problem
2941          inserting this catchpoint, and we've disabled the catchpoint,
2942          so just return success.  */
2943       return 0;
2944     }
2945
2946   return 0;
2947 }
2948
2949 /* This function is called when program space PSPACE is about to be
2950    deleted.  It takes care of updating breakpoints to not reference
2951    PSPACE anymore.  */
2952
2953 void
2954 breakpoint_program_space_exit (struct program_space *pspace)
2955 {
2956   struct breakpoint *b, *b_temp;
2957   struct bp_location *loc, **loc_temp;
2958
2959   /* Remove any breakpoint that was set through this program space.  */
2960   ALL_BREAKPOINTS_SAFE (b, b_temp)
2961     {
2962       if (b->pspace == pspace)
2963         delete_breakpoint (b);
2964     }
2965
2966   /* Breakpoints set through other program spaces could have locations
2967      bound to PSPACE as well.  Remove those.  */
2968   ALL_BP_LOCATIONS (loc, loc_temp)
2969     {
2970       struct bp_location *tmp;
2971
2972       if (loc->pspace == pspace)
2973         {
2974           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2975           if (loc->owner->loc == loc)
2976             loc->owner->loc = loc->next;
2977           else
2978             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2979               if (tmp->next == loc)
2980                 {
2981                   tmp->next = loc->next;
2982                   break;
2983                 }
2984         }
2985     }
2986
2987   /* Now update the global location list to permanently delete the
2988      removed locations above.  */
2989   update_global_location_list (UGLL_DONT_INSERT);
2990 }
2991
2992 /* Make sure all breakpoints are inserted in inferior.
2993    Throws exception on any error.
2994    A breakpoint that is already inserted won't be inserted
2995    again, so calling this function twice is safe.  */
2996 void
2997 insert_breakpoints (void)
2998 {
2999   struct breakpoint *bpt;
3000
3001   ALL_BREAKPOINTS (bpt)
3002     if (is_hardware_watchpoint (bpt))
3003       {
3004         struct watchpoint *w = (struct watchpoint *) bpt;
3005
3006         update_watchpoint (w, 0 /* don't reparse.  */);
3007       }
3008
3009   /* Updating watchpoints creates new locations, so update the global
3010      location list.  Explicitly tell ugll to insert locations and
3011      ignore breakpoints_always_inserted_mode.  */
3012   update_global_location_list (UGLL_INSERT);
3013 }
3014
3015 /* Invoke CALLBACK for each of bp_location.  */
3016
3017 void
3018 iterate_over_bp_locations (walk_bp_location_callback callback)
3019 {
3020   struct bp_location *loc, **loc_tmp;
3021
3022   ALL_BP_LOCATIONS (loc, loc_tmp)
3023     {
3024       callback (loc, NULL);
3025     }
3026 }
3027
3028 /* This is used when we need to synch breakpoint conditions between GDB and the
3029    target.  It is the case with deleting and disabling of breakpoints when using
3030    always-inserted mode.  */
3031
3032 static void
3033 update_inserted_breakpoint_locations (void)
3034 {
3035   struct bp_location *bl, **blp_tmp;
3036   int error_flag = 0;
3037   int val = 0;
3038   int disabled_breaks = 0;
3039   int hw_breakpoint_error = 0;
3040   int hw_bp_details_reported = 0;
3041
3042   struct ui_file *tmp_error_stream = mem_fileopen ();
3043   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3044
3045   /* Explicitly mark the warning -- this will only be printed if
3046      there was an error.  */
3047   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3048
3049   save_current_space_and_thread ();
3050
3051   ALL_BP_LOCATIONS (bl, blp_tmp)
3052     {
3053       /* We only want to update software breakpoints and hardware
3054          breakpoints.  */
3055       if (!is_breakpoint (bl->owner))
3056         continue;
3057
3058       /* We only want to update locations that are already inserted
3059          and need updating.  This is to avoid unwanted insertion during
3060          deletion of breakpoints.  */
3061       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3062         continue;
3063
3064       switch_to_program_space_and_thread (bl->pspace);
3065
3066       /* For targets that support global breakpoints, there's no need
3067          to select an inferior to insert breakpoint to.  In fact, even
3068          if we aren't attached to any process yet, we should still
3069          insert breakpoints.  */
3070       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3071           && ptid_equal (inferior_ptid, null_ptid))
3072         continue;
3073
3074       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3075                                     &hw_breakpoint_error, &hw_bp_details_reported);
3076       if (val)
3077         error_flag = val;
3078     }
3079
3080   if (error_flag)
3081     {
3082       target_terminal_ours_for_output ();
3083       error_stream (tmp_error_stream);
3084     }
3085
3086   do_cleanups (cleanups);
3087 }
3088
3089 /* Used when starting or continuing the program.  */
3090
3091 static void
3092 insert_breakpoint_locations (void)
3093 {
3094   struct breakpoint *bpt;
3095   struct bp_location *bl, **blp_tmp;
3096   int error_flag = 0;
3097   int val = 0;
3098   int disabled_breaks = 0;
3099   int hw_breakpoint_error = 0;
3100   int hw_bp_error_explained_already = 0;
3101
3102   struct ui_file *tmp_error_stream = mem_fileopen ();
3103   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3104   
3105   /* Explicitly mark the warning -- this will only be printed if
3106      there was an error.  */
3107   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3108
3109   save_current_space_and_thread ();
3110
3111   ALL_BP_LOCATIONS (bl, blp_tmp)
3112     {
3113       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3114         continue;
3115
3116       /* There is no point inserting thread-specific breakpoints if
3117          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3118          has BL->OWNER always non-NULL.  */
3119       if (bl->owner->thread != -1
3120           && !valid_thread_id (bl->owner->thread))
3121         continue;
3122
3123       switch_to_program_space_and_thread (bl->pspace);
3124
3125       /* For targets that support global breakpoints, there's no need
3126          to select an inferior to insert breakpoint to.  In fact, even
3127          if we aren't attached to any process yet, we should still
3128          insert breakpoints.  */
3129       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3130           && ptid_equal (inferior_ptid, null_ptid))
3131         continue;
3132
3133       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3134                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3135       if (val)
3136         error_flag = val;
3137     }
3138
3139   /* If we failed to insert all locations of a watchpoint, remove
3140      them, as half-inserted watchpoint is of limited use.  */
3141   ALL_BREAKPOINTS (bpt)  
3142     {
3143       int some_failed = 0;
3144       struct bp_location *loc;
3145
3146       if (!is_hardware_watchpoint (bpt))
3147         continue;
3148
3149       if (!breakpoint_enabled (bpt))
3150         continue;
3151
3152       if (bpt->disposition == disp_del_at_next_stop)
3153         continue;
3154       
3155       for (loc = bpt->loc; loc; loc = loc->next)
3156         if (!loc->inserted && should_be_inserted (loc))
3157           {
3158             some_failed = 1;
3159             break;
3160           }
3161       if (some_failed)
3162         {
3163           for (loc = bpt->loc; loc; loc = loc->next)
3164             if (loc->inserted)
3165               remove_breakpoint (loc, mark_uninserted);
3166
3167           hw_breakpoint_error = 1;
3168           fprintf_unfiltered (tmp_error_stream,
3169                               "Could not insert hardware watchpoint %d.\n", 
3170                               bpt->number);
3171           error_flag = -1;
3172         }
3173     }
3174
3175   if (error_flag)
3176     {
3177       /* If a hardware breakpoint or watchpoint was inserted, add a
3178          message about possibly exhausted resources.  */
3179       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3180         {
3181           fprintf_unfiltered (tmp_error_stream, 
3182                               "Could not insert hardware breakpoints:\n\
3183 You may have requested too many hardware breakpoints/watchpoints.\n");
3184         }
3185       target_terminal_ours_for_output ();
3186       error_stream (tmp_error_stream);
3187     }
3188
3189   do_cleanups (cleanups);
3190 }
3191
3192 /* Used when the program stops.
3193    Returns zero if successful, or non-zero if there was a problem
3194    removing a breakpoint location.  */
3195
3196 int
3197 remove_breakpoints (void)
3198 {
3199   struct bp_location *bl, **blp_tmp;
3200   int val = 0;
3201
3202   ALL_BP_LOCATIONS (bl, blp_tmp)
3203   {
3204     if (bl->inserted && !is_tracepoint (bl->owner))
3205       val |= remove_breakpoint (bl, mark_uninserted);
3206   }
3207   return val;
3208 }
3209
3210 /* When a thread exits, remove breakpoints that are related to
3211    that thread.  */
3212
3213 static void
3214 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3215 {
3216   struct breakpoint *b, *b_tmp;
3217
3218   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3219     {
3220       if (b->thread == tp->num && user_breakpoint_p (b))
3221         {
3222           b->disposition = disp_del_at_next_stop;
3223
3224           printf_filtered (_("\
3225 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3226                           b->number, tp->num);
3227
3228           /* Hide it from the user.  */
3229           b->number = 0;
3230        }
3231     }
3232 }
3233
3234 /* Remove breakpoints of process PID.  */
3235
3236 int
3237 remove_breakpoints_pid (int pid)
3238 {
3239   struct bp_location *bl, **blp_tmp;
3240   int val;
3241   struct inferior *inf = find_inferior_pid (pid);
3242
3243   ALL_BP_LOCATIONS (bl, blp_tmp)
3244   {
3245     if (bl->pspace != inf->pspace)
3246       continue;
3247
3248     if (bl->inserted && !bl->target_info.persist)
3249       {
3250         val = remove_breakpoint (bl, mark_uninserted);
3251         if (val != 0)
3252           return val;
3253       }
3254   }
3255   return 0;
3256 }
3257
3258 int
3259 reattach_breakpoints (int pid)
3260 {
3261   struct cleanup *old_chain;
3262   struct bp_location *bl, **blp_tmp;
3263   int val;
3264   struct ui_file *tmp_error_stream;
3265   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3266   struct inferior *inf;
3267   struct thread_info *tp;
3268
3269   tp = any_live_thread_of_process (pid);
3270   if (tp == NULL)
3271     return 1;
3272
3273   inf = find_inferior_pid (pid);
3274   old_chain = save_inferior_ptid ();
3275
3276   inferior_ptid = tp->ptid;
3277
3278   tmp_error_stream = mem_fileopen ();
3279   make_cleanup_ui_file_delete (tmp_error_stream);
3280
3281   ALL_BP_LOCATIONS (bl, blp_tmp)
3282   {
3283     if (bl->pspace != inf->pspace)
3284       continue;
3285
3286     if (bl->inserted)
3287       {
3288         bl->inserted = 0;
3289         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3290         if (val != 0)
3291           {
3292             do_cleanups (old_chain);
3293             return val;
3294           }
3295       }
3296   }
3297   do_cleanups (old_chain);
3298   return 0;
3299 }
3300
3301 static int internal_breakpoint_number = -1;
3302
3303 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3304    If INTERNAL is non-zero, the breakpoint number will be populated
3305    from internal_breakpoint_number and that variable decremented.
3306    Otherwise the breakpoint number will be populated from
3307    breakpoint_count and that value incremented.  Internal breakpoints
3308    do not set the internal var bpnum.  */
3309 static void
3310 set_breakpoint_number (int internal, struct breakpoint *b)
3311 {
3312   if (internal)
3313     b->number = internal_breakpoint_number--;
3314   else
3315     {
3316       set_breakpoint_count (breakpoint_count + 1);
3317       b->number = breakpoint_count;
3318     }
3319 }
3320
3321 static struct breakpoint *
3322 create_internal_breakpoint (struct gdbarch *gdbarch,
3323                             CORE_ADDR address, enum bptype type,
3324                             const struct breakpoint_ops *ops)
3325 {
3326   struct symtab_and_line sal;
3327   struct breakpoint *b;
3328
3329   init_sal (&sal);              /* Initialize to zeroes.  */
3330
3331   sal.pc = address;
3332   sal.section = find_pc_overlay (sal.pc);
3333   sal.pspace = current_program_space;
3334
3335   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3336   b->number = internal_breakpoint_number--;
3337   b->disposition = disp_donttouch;
3338
3339   return b;
3340 }
3341
3342 static const char *const longjmp_names[] =
3343   {
3344     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3345   };
3346 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3347
3348 /* Per-objfile data private to breakpoint.c.  */
3349 struct breakpoint_objfile_data
3350 {
3351   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3352   struct bound_minimal_symbol overlay_msym;
3353
3354   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3355   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3356
3357   /* True if we have looked for longjmp probes.  */
3358   int longjmp_searched;
3359
3360   /* SystemTap probe points for longjmp (if any).  */
3361   VEC (probe_p) *longjmp_probes;
3362
3363   /* Minimal symbol for "std::terminate()" (if any).  */
3364   struct bound_minimal_symbol terminate_msym;
3365
3366   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3367   struct bound_minimal_symbol exception_msym;
3368
3369   /* True if we have looked for exception probes.  */
3370   int exception_searched;
3371
3372   /* SystemTap probe points for unwinding (if any).  */
3373   VEC (probe_p) *exception_probes;
3374 };
3375
3376 static const struct objfile_data *breakpoint_objfile_key;
3377
3378 /* Minimal symbol not found sentinel.  */
3379 static struct minimal_symbol msym_not_found;
3380
3381 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3382
3383 static int
3384 msym_not_found_p (const struct minimal_symbol *msym)
3385 {
3386   return msym == &msym_not_found;
3387 }
3388
3389 /* Return per-objfile data needed by breakpoint.c.
3390    Allocate the data if necessary.  */
3391
3392 static struct breakpoint_objfile_data *
3393 get_breakpoint_objfile_data (struct objfile *objfile)
3394 {
3395   struct breakpoint_objfile_data *bp_objfile_data;
3396
3397   bp_objfile_data = ((struct breakpoint_objfile_data *)
3398                      objfile_data (objfile, breakpoint_objfile_key));
3399   if (bp_objfile_data == NULL)
3400     {
3401       bp_objfile_data =
3402         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3403
3404       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3405       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3406     }
3407   return bp_objfile_data;
3408 }
3409
3410 static void
3411 free_breakpoint_probes (struct objfile *obj, void *data)
3412 {
3413   struct breakpoint_objfile_data *bp_objfile_data
3414     = (struct breakpoint_objfile_data *) data;
3415
3416   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3417   VEC_free (probe_p, bp_objfile_data->exception_probes);
3418 }
3419
3420 static void
3421 create_overlay_event_breakpoint (void)
3422 {
3423   struct objfile *objfile;
3424   const char *const func_name = "_ovly_debug_event";
3425
3426   ALL_OBJFILES (objfile)
3427     {
3428       struct breakpoint *b;
3429       struct breakpoint_objfile_data *bp_objfile_data;
3430       CORE_ADDR addr;
3431       struct explicit_location explicit_loc;
3432
3433       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3434
3435       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3436         continue;
3437
3438       if (bp_objfile_data->overlay_msym.minsym == NULL)
3439         {
3440           struct bound_minimal_symbol m;
3441
3442           m = lookup_minimal_symbol_text (func_name, objfile);
3443           if (m.minsym == NULL)
3444             {
3445               /* Avoid future lookups in this objfile.  */
3446               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3447               continue;
3448             }
3449           bp_objfile_data->overlay_msym = m;
3450         }
3451
3452       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3453       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3454                                       bp_overlay_event,
3455                                       &internal_breakpoint_ops);
3456       initialize_explicit_location (&explicit_loc);
3457       explicit_loc.function_name = ASTRDUP (func_name);
3458       b->location = new_explicit_location (&explicit_loc);
3459
3460       if (overlay_debugging == ovly_auto)
3461         {
3462           b->enable_state = bp_enabled;
3463           overlay_events_enabled = 1;
3464         }
3465       else
3466        {
3467          b->enable_state = bp_disabled;
3468          overlay_events_enabled = 0;
3469        }
3470     }
3471   update_global_location_list (UGLL_MAY_INSERT);
3472 }
3473
3474 static void
3475 create_longjmp_master_breakpoint (void)
3476 {
3477   struct program_space *pspace;
3478   struct cleanup *old_chain;
3479
3480   old_chain = save_current_program_space ();
3481
3482   ALL_PSPACES (pspace)
3483   {
3484     struct objfile *objfile;
3485
3486     set_current_program_space (pspace);
3487
3488     ALL_OBJFILES (objfile)
3489     {
3490       int i;
3491       struct gdbarch *gdbarch;
3492       struct breakpoint_objfile_data *bp_objfile_data;
3493
3494       gdbarch = get_objfile_arch (objfile);
3495
3496       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3497
3498       if (!bp_objfile_data->longjmp_searched)
3499         {
3500           VEC (probe_p) *ret;
3501
3502           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3503           if (ret != NULL)
3504             {
3505               /* We are only interested in checking one element.  */
3506               struct probe *p = VEC_index (probe_p, ret, 0);
3507
3508               if (!can_evaluate_probe_arguments (p))
3509                 {
3510                   /* We cannot use the probe interface here, because it does
3511                      not know how to evaluate arguments.  */
3512                   VEC_free (probe_p, ret);
3513                   ret = NULL;
3514                 }
3515             }
3516           bp_objfile_data->longjmp_probes = ret;
3517           bp_objfile_data->longjmp_searched = 1;
3518         }
3519
3520       if (bp_objfile_data->longjmp_probes != NULL)
3521         {
3522           int i;
3523           struct probe *probe;
3524           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3525
3526           for (i = 0;
3527                VEC_iterate (probe_p,
3528                             bp_objfile_data->longjmp_probes,
3529                             i, probe);
3530                ++i)
3531             {
3532               struct breakpoint *b;
3533
3534               b = create_internal_breakpoint (gdbarch,
3535                                               get_probe_address (probe,
3536                                                                  objfile),
3537                                               bp_longjmp_master,
3538                                               &internal_breakpoint_ops);
3539               b->location
3540                 = new_probe_location ("-probe-stap libc:longjmp");
3541               b->enable_state = bp_disabled;
3542             }
3543
3544           continue;
3545         }
3546
3547       if (!gdbarch_get_longjmp_target_p (gdbarch))
3548         continue;
3549
3550       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3551         {
3552           struct breakpoint *b;
3553           const char *func_name;
3554           CORE_ADDR addr;
3555           struct explicit_location explicit_loc;
3556
3557           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3558             continue;
3559
3560           func_name = longjmp_names[i];
3561           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3562             {
3563               struct bound_minimal_symbol m;
3564
3565               m = lookup_minimal_symbol_text (func_name, objfile);
3566               if (m.minsym == NULL)
3567                 {
3568                   /* Prevent future lookups in this objfile.  */
3569                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3570                   continue;
3571                 }
3572               bp_objfile_data->longjmp_msym[i] = m;
3573             }
3574
3575           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3576           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3577                                           &internal_breakpoint_ops);
3578           initialize_explicit_location (&explicit_loc);
3579           explicit_loc.function_name = ASTRDUP (func_name);
3580           b->location = new_explicit_location (&explicit_loc);
3581           b->enable_state = bp_disabled;
3582         }
3583     }
3584   }
3585   update_global_location_list (UGLL_MAY_INSERT);
3586
3587   do_cleanups (old_chain);
3588 }
3589
3590 /* Create a master std::terminate breakpoint.  */
3591 static void
3592 create_std_terminate_master_breakpoint (void)
3593 {
3594   struct program_space *pspace;
3595   struct cleanup *old_chain;
3596   const char *const func_name = "std::terminate()";
3597
3598   old_chain = save_current_program_space ();
3599
3600   ALL_PSPACES (pspace)
3601   {
3602     struct objfile *objfile;
3603     CORE_ADDR addr;
3604
3605     set_current_program_space (pspace);
3606
3607     ALL_OBJFILES (objfile)
3608     {
3609       struct breakpoint *b;
3610       struct breakpoint_objfile_data *bp_objfile_data;
3611       struct explicit_location explicit_loc;
3612
3613       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3614
3615       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3616         continue;
3617
3618       if (bp_objfile_data->terminate_msym.minsym == NULL)
3619         {
3620           struct bound_minimal_symbol m;
3621
3622           m = lookup_minimal_symbol (func_name, NULL, objfile);
3623           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3624                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3625             {
3626               /* Prevent future lookups in this objfile.  */
3627               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3628               continue;
3629             }
3630           bp_objfile_data->terminate_msym = m;
3631         }
3632
3633       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3634       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3635                                       bp_std_terminate_master,
3636                                       &internal_breakpoint_ops);
3637       initialize_explicit_location (&explicit_loc);
3638       explicit_loc.function_name = ASTRDUP (func_name);
3639       b->location = new_explicit_location (&explicit_loc);
3640       b->enable_state = bp_disabled;
3641     }
3642   }
3643
3644   update_global_location_list (UGLL_MAY_INSERT);
3645
3646   do_cleanups (old_chain);
3647 }
3648
3649 /* Install a master breakpoint on the unwinder's debug hook.  */
3650
3651 static void
3652 create_exception_master_breakpoint (void)
3653 {
3654   struct objfile *objfile;
3655   const char *const func_name = "_Unwind_DebugHook";
3656
3657   ALL_OBJFILES (objfile)
3658     {
3659       struct breakpoint *b;
3660       struct gdbarch *gdbarch;
3661       struct breakpoint_objfile_data *bp_objfile_data;
3662       CORE_ADDR addr;
3663       struct explicit_location explicit_loc;
3664
3665       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3666
3667       /* We prefer the SystemTap probe point if it exists.  */
3668       if (!bp_objfile_data->exception_searched)
3669         {
3670           VEC (probe_p) *ret;
3671
3672           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3673
3674           if (ret != NULL)
3675             {
3676               /* We are only interested in checking one element.  */
3677               struct probe *p = VEC_index (probe_p, ret, 0);
3678
3679               if (!can_evaluate_probe_arguments (p))
3680                 {
3681                   /* We cannot use the probe interface here, because it does
3682                      not know how to evaluate arguments.  */
3683                   VEC_free (probe_p, ret);
3684                   ret = NULL;
3685                 }
3686             }
3687           bp_objfile_data->exception_probes = ret;
3688           bp_objfile_data->exception_searched = 1;
3689         }
3690
3691       if (bp_objfile_data->exception_probes != NULL)
3692         {
3693           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3694           int i;
3695           struct probe *probe;
3696
3697           for (i = 0;
3698                VEC_iterate (probe_p,
3699                             bp_objfile_data->exception_probes,
3700                             i, probe);
3701                ++i)
3702             {
3703               struct breakpoint *b;
3704
3705               b = create_internal_breakpoint (gdbarch,
3706                                               get_probe_address (probe,
3707                                                                  objfile),
3708                                               bp_exception_master,
3709                                               &internal_breakpoint_ops);
3710               b->location
3711                 = new_probe_location ("-probe-stap libgcc:unwind");
3712               b->enable_state = bp_disabled;
3713             }
3714
3715           continue;
3716         }
3717
3718       /* Otherwise, try the hook function.  */
3719
3720       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3721         continue;
3722
3723       gdbarch = get_objfile_arch (objfile);
3724
3725       if (bp_objfile_data->exception_msym.minsym == NULL)
3726         {
3727           struct bound_minimal_symbol debug_hook;
3728
3729           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3730           if (debug_hook.minsym == NULL)
3731             {
3732               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3733               continue;
3734             }
3735
3736           bp_objfile_data->exception_msym = debug_hook;
3737         }
3738
3739       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3740       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3741                                                  &current_target);
3742       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3743                                       &internal_breakpoint_ops);
3744       initialize_explicit_location (&explicit_loc);
3745       explicit_loc.function_name = ASTRDUP (func_name);
3746       b->location = new_explicit_location (&explicit_loc);
3747       b->enable_state = bp_disabled;
3748     }
3749
3750   update_global_location_list (UGLL_MAY_INSERT);
3751 }
3752
3753 void
3754 update_breakpoints_after_exec (void)
3755 {
3756   struct breakpoint *b, *b_tmp;
3757   struct bp_location *bploc, **bplocp_tmp;
3758
3759   /* We're about to delete breakpoints from GDB's lists.  If the
3760      INSERTED flag is true, GDB will try to lift the breakpoints by
3761      writing the breakpoints' "shadow contents" back into memory.  The
3762      "shadow contents" are NOT valid after an exec, so GDB should not
3763      do that.  Instead, the target is responsible from marking
3764      breakpoints out as soon as it detects an exec.  We don't do that
3765      here instead, because there may be other attempts to delete
3766      breakpoints after detecting an exec and before reaching here.  */
3767   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3768     if (bploc->pspace == current_program_space)
3769       gdb_assert (!bploc->inserted);
3770
3771   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3772   {
3773     if (b->pspace != current_program_space)
3774       continue;
3775
3776     /* Solib breakpoints must be explicitly reset after an exec().  */
3777     if (b->type == bp_shlib_event)
3778       {
3779         delete_breakpoint (b);
3780         continue;
3781       }
3782
3783     /* JIT breakpoints must be explicitly reset after an exec().  */
3784     if (b->type == bp_jit_event)
3785       {
3786         delete_breakpoint (b);
3787         continue;
3788       }
3789
3790     /* Thread event breakpoints must be set anew after an exec(),
3791        as must overlay event and longjmp master breakpoints.  */
3792     if (b->type == bp_thread_event || b->type == bp_overlay_event
3793         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3794         || b->type == bp_exception_master)
3795       {
3796         delete_breakpoint (b);
3797         continue;
3798       }
3799
3800     /* Step-resume breakpoints are meaningless after an exec().  */
3801     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3802       {
3803         delete_breakpoint (b);
3804         continue;
3805       }
3806
3807     /* Just like single-step breakpoints.  */
3808     if (b->type == bp_single_step)
3809       {
3810         delete_breakpoint (b);
3811         continue;
3812       }
3813
3814     /* Longjmp and longjmp-resume breakpoints are also meaningless
3815        after an exec.  */
3816     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3817         || b->type == bp_longjmp_call_dummy
3818         || b->type == bp_exception || b->type == bp_exception_resume)
3819       {
3820         delete_breakpoint (b);
3821         continue;
3822       }
3823
3824     if (b->type == bp_catchpoint)
3825       {
3826         /* For now, none of the bp_catchpoint breakpoints need to
3827            do anything at this point.  In the future, if some of
3828            the catchpoints need to something, we will need to add
3829            a new method, and call this method from here.  */
3830         continue;
3831       }
3832
3833     /* bp_finish is a special case.  The only way we ought to be able
3834        to see one of these when an exec() has happened, is if the user
3835        caught a vfork, and then said "finish".  Ordinarily a finish just
3836        carries them to the call-site of the current callee, by setting
3837        a temporary bp there and resuming.  But in this case, the finish
3838        will carry them entirely through the vfork & exec.
3839
3840        We don't want to allow a bp_finish to remain inserted now.  But
3841        we can't safely delete it, 'cause finish_command has a handle to
3842        the bp on a bpstat, and will later want to delete it.  There's a
3843        chance (and I've seen it happen) that if we delete the bp_finish
3844        here, that its storage will get reused by the time finish_command
3845        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3846        We really must allow finish_command to delete a bp_finish.
3847
3848        In the absence of a general solution for the "how do we know
3849        it's safe to delete something others may have handles to?"
3850        problem, what we'll do here is just uninsert the bp_finish, and
3851        let finish_command delete it.
3852
3853        (We know the bp_finish is "doomed" in the sense that it's
3854        momentary, and will be deleted as soon as finish_command sees
3855        the inferior stopped.  So it doesn't matter that the bp's
3856        address is probably bogus in the new a.out, unlike e.g., the
3857        solib breakpoints.)  */
3858
3859     if (b->type == bp_finish)
3860       {
3861         continue;
3862       }
3863
3864     /* Without a symbolic address, we have little hope of the
3865        pre-exec() address meaning the same thing in the post-exec()
3866        a.out.  */
3867     if (event_location_empty_p (b->location))
3868       {
3869         delete_breakpoint (b);
3870         continue;
3871       }
3872   }
3873 }
3874
3875 int
3876 detach_breakpoints (ptid_t ptid)
3877 {
3878   struct bp_location *bl, **blp_tmp;
3879   int val = 0;
3880   struct cleanup *old_chain = save_inferior_ptid ();
3881   struct inferior *inf = current_inferior ();
3882
3883   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3884     error (_("Cannot detach breakpoints of inferior_ptid"));
3885
3886   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3887   inferior_ptid = ptid;
3888   ALL_BP_LOCATIONS (bl, blp_tmp)
3889   {
3890     if (bl->pspace != inf->pspace)
3891       continue;
3892
3893     /* This function must physically remove breakpoints locations
3894        from the specified ptid, without modifying the breakpoint
3895        package's state.  Locations of type bp_loc_other are only
3896        maintained at GDB side.  So, there is no need to remove
3897        these bp_loc_other locations.  Moreover, removing these
3898        would modify the breakpoint package's state.  */
3899     if (bl->loc_type == bp_loc_other)
3900       continue;
3901
3902     if (bl->inserted)
3903       val |= remove_breakpoint_1 (bl, mark_inserted);
3904   }
3905
3906   do_cleanups (old_chain);
3907   return val;
3908 }
3909
3910 /* Remove the breakpoint location BL from the current address space.
3911    Note that this is used to detach breakpoints from a child fork.
3912    When we get here, the child isn't in the inferior list, and neither
3913    do we have objects to represent its address space --- we should
3914    *not* look at bl->pspace->aspace here.  */
3915
3916 static int
3917 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3918 {
3919   int val;
3920
3921   /* BL is never in moribund_locations by our callers.  */
3922   gdb_assert (bl->owner != NULL);
3923
3924   /* The type of none suggests that owner is actually deleted.
3925      This should not ever happen.  */
3926   gdb_assert (bl->owner->type != bp_none);
3927
3928   if (bl->loc_type == bp_loc_software_breakpoint
3929       || bl->loc_type == bp_loc_hardware_breakpoint)
3930     {
3931       /* "Normal" instruction breakpoint: either the standard
3932          trap-instruction bp (bp_breakpoint), or a
3933          bp_hardware_breakpoint.  */
3934
3935       /* First check to see if we have to handle an overlay.  */
3936       if (overlay_debugging == ovly_off
3937           || bl->section == NULL
3938           || !(section_is_overlay (bl->section)))
3939         {
3940           /* No overlay handling: just remove the breakpoint.  */
3941
3942           /* If we're trying to uninsert a memory breakpoint that we
3943              know is set in a dynamic object that is marked
3944              shlib_disabled, then either the dynamic object was
3945              removed with "remove-symbol-file" or with
3946              "nosharedlibrary".  In the former case, we don't know
3947              whether another dynamic object might have loaded over the
3948              breakpoint's address -- the user might well let us know
3949              about it next with add-symbol-file (the whole point of
3950              add-symbol-file is letting the user manually maintain a
3951              list of dynamically loaded objects).  If we have the
3952              breakpoint's shadow memory, that is, this is a software
3953              breakpoint managed by GDB, check whether the breakpoint
3954              is still inserted in memory, to avoid overwriting wrong
3955              code with stale saved shadow contents.  Note that HW
3956              breakpoints don't have shadow memory, as they're
3957              implemented using a mechanism that is not dependent on
3958              being able to modify the target's memory, and as such
3959              they should always be removed.  */
3960           if (bl->shlib_disabled
3961               && bl->target_info.shadow_len != 0
3962               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3963             val = 0;
3964           else
3965             val = bl->owner->ops->remove_location (bl);
3966         }
3967       else
3968         {
3969           /* This breakpoint is in an overlay section.
3970              Did we set a breakpoint at the LMA?  */
3971           if (!overlay_events_enabled)
3972               {
3973                 /* Yes -- overlay event support is not active, so we
3974                    should have set a breakpoint at the LMA.  Remove it.  
3975                 */
3976                 /* Ignore any failures: if the LMA is in ROM, we will
3977                    have already warned when we failed to insert it.  */
3978                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3979                   target_remove_hw_breakpoint (bl->gdbarch,
3980                                                &bl->overlay_target_info);
3981                 else
3982                   target_remove_breakpoint (bl->gdbarch,
3983                                             &bl->overlay_target_info);
3984               }
3985           /* Did we set a breakpoint at the VMA? 
3986              If so, we will have marked the breakpoint 'inserted'.  */
3987           if (bl->inserted)
3988             {
3989               /* Yes -- remove it.  Previously we did not bother to
3990                  remove the breakpoint if the section had been
3991                  unmapped, but let's not rely on that being safe.  We
3992                  don't know what the overlay manager might do.  */
3993
3994               /* However, we should remove *software* breakpoints only
3995                  if the section is still mapped, or else we overwrite
3996                  wrong code with the saved shadow contents.  */
3997               if (bl->loc_type == bp_loc_hardware_breakpoint
3998                   || section_is_mapped (bl->section))
3999                 val = bl->owner->ops->remove_location (bl);
4000               else
4001                 val = 0;
4002             }
4003           else
4004             {
4005               /* No -- not inserted, so no need to remove.  No error.  */
4006               val = 0;
4007             }
4008         }
4009
4010       /* In some cases, we might not be able to remove a breakpoint in
4011          a shared library that has already been removed, but we have
4012          not yet processed the shlib unload event.  Similarly for an
4013          unloaded add-symbol-file object - the user might not yet have
4014          had the chance to remove-symbol-file it.  shlib_disabled will
4015          be set if the library/object has already been removed, but
4016          the breakpoint hasn't been uninserted yet, e.g., after
4017          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4018          always-inserted mode.  */
4019       if (val
4020           && (bl->loc_type == bp_loc_software_breakpoint
4021               && (bl->shlib_disabled
4022                   || solib_name_from_address (bl->pspace, bl->address)
4023                   || shared_objfile_contains_address_p (bl->pspace,
4024                                                         bl->address))))
4025         val = 0;
4026
4027       if (val)
4028         return val;
4029       bl->inserted = (is == mark_inserted);
4030     }
4031   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4032     {
4033       gdb_assert (bl->owner->ops != NULL
4034                   && bl->owner->ops->remove_location != NULL);
4035
4036       bl->inserted = (is == mark_inserted);
4037       bl->owner->ops->remove_location (bl);
4038
4039       /* Failure to remove any of the hardware watchpoints comes here.  */
4040       if ((is == mark_uninserted) && (bl->inserted))
4041         warning (_("Could not remove hardware watchpoint %d."),
4042                  bl->owner->number);
4043     }
4044   else if (bl->owner->type == bp_catchpoint
4045            && breakpoint_enabled (bl->owner)
4046            && !bl->duplicate)
4047     {
4048       gdb_assert (bl->owner->ops != NULL
4049                   && bl->owner->ops->remove_location != NULL);
4050
4051       val = bl->owner->ops->remove_location (bl);
4052       if (val)
4053         return val;
4054
4055       bl->inserted = (is == mark_inserted);
4056     }
4057
4058   return 0;
4059 }
4060
4061 static int
4062 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4063 {
4064   int ret;
4065   struct cleanup *old_chain;
4066
4067   /* BL is never in moribund_locations by our callers.  */
4068   gdb_assert (bl->owner != NULL);
4069
4070   /* The type of none suggests that owner is actually deleted.
4071      This should not ever happen.  */
4072   gdb_assert (bl->owner->type != bp_none);
4073
4074   old_chain = save_current_space_and_thread ();
4075
4076   switch_to_program_space_and_thread (bl->pspace);
4077
4078   ret = remove_breakpoint_1 (bl, is);
4079
4080   do_cleanups (old_chain);
4081   return ret;
4082 }
4083
4084 /* Clear the "inserted" flag in all breakpoints.  */
4085
4086 void
4087 mark_breakpoints_out (void)
4088 {
4089   struct bp_location *bl, **blp_tmp;
4090
4091   ALL_BP_LOCATIONS (bl, blp_tmp)
4092     if (bl->pspace == current_program_space)
4093       bl->inserted = 0;
4094 }
4095
4096 /* Clear the "inserted" flag in all breakpoints and delete any
4097    breakpoints which should go away between runs of the program.
4098
4099    Plus other such housekeeping that has to be done for breakpoints
4100    between runs.
4101
4102    Note: this function gets called at the end of a run (by
4103    generic_mourn_inferior) and when a run begins (by
4104    init_wait_for_inferior).  */
4105
4106
4107
4108 void
4109 breakpoint_init_inferior (enum inf_context context)
4110 {
4111   struct breakpoint *b, *b_tmp;
4112   struct bp_location *bl, **blp_tmp;
4113   int ix;
4114   struct program_space *pspace = current_program_space;
4115
4116   /* If breakpoint locations are shared across processes, then there's
4117      nothing to do.  */
4118   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4119     return;
4120
4121   mark_breakpoints_out ();
4122
4123   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4124   {
4125     if (b->loc && b->loc->pspace != pspace)
4126       continue;
4127
4128     switch (b->type)
4129       {
4130       case bp_call_dummy:
4131       case bp_longjmp_call_dummy:
4132
4133         /* If the call dummy breakpoint is at the entry point it will
4134            cause problems when the inferior is rerun, so we better get
4135            rid of it.  */
4136
4137       case bp_watchpoint_scope:
4138
4139         /* Also get rid of scope breakpoints.  */
4140
4141       case bp_shlib_event:
4142
4143         /* Also remove solib event breakpoints.  Their addresses may
4144            have changed since the last time we ran the program.
4145            Actually we may now be debugging against different target;
4146            and so the solib backend that installed this breakpoint may
4147            not be used in by the target.  E.g.,
4148
4149            (gdb) file prog-linux
4150            (gdb) run               # native linux target
4151            ...
4152            (gdb) kill
4153            (gdb) file prog-win.exe
4154            (gdb) tar rem :9999     # remote Windows gdbserver.
4155         */
4156
4157       case bp_step_resume:
4158
4159         /* Also remove step-resume breakpoints.  */
4160
4161       case bp_single_step:
4162
4163         /* Also remove single-step breakpoints.  */
4164
4165         delete_breakpoint (b);
4166         break;
4167
4168       case bp_watchpoint:
4169       case bp_hardware_watchpoint:
4170       case bp_read_watchpoint:
4171       case bp_access_watchpoint:
4172         {
4173           struct watchpoint *w = (struct watchpoint *) b;
4174
4175           /* Likewise for watchpoints on local expressions.  */
4176           if (w->exp_valid_block != NULL)
4177             delete_breakpoint (b);
4178           else if (context == inf_starting)
4179             {
4180               /* Reset val field to force reread of starting value in
4181                  insert_breakpoints.  */
4182               if (w->val)
4183                 value_free (w->val);
4184               w->val = NULL;
4185               w->val_valid = 0;
4186           }
4187         }
4188         break;
4189       default:
4190         break;
4191       }
4192   }
4193
4194   /* Get rid of the moribund locations.  */
4195   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4196     decref_bp_location (&bl);
4197   VEC_free (bp_location_p, moribund_locations);
4198 }
4199
4200 /* These functions concern about actual breakpoints inserted in the
4201    target --- to e.g. check if we need to do decr_pc adjustment or if
4202    we need to hop over the bkpt --- so we check for address space
4203    match, not program space.  */
4204
4205 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4206    exists at PC.  It returns ordinary_breakpoint_here if it's an
4207    ordinary breakpoint, or permanent_breakpoint_here if it's a
4208    permanent breakpoint.
4209    - When continuing from a location with an ordinary breakpoint, we
4210      actually single step once before calling insert_breakpoints.
4211    - When continuing from a location with a permanent breakpoint, we
4212      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4213      the target, to advance the PC past the breakpoint.  */
4214
4215 enum breakpoint_here
4216 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4217 {
4218   struct bp_location *bl, **blp_tmp;
4219   int any_breakpoint_here = 0;
4220
4221   ALL_BP_LOCATIONS (bl, blp_tmp)
4222     {
4223       if (bl->loc_type != bp_loc_software_breakpoint
4224           && bl->loc_type != bp_loc_hardware_breakpoint)
4225         continue;
4226
4227       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4228       if ((breakpoint_enabled (bl->owner)
4229            || bl->permanent)
4230           && breakpoint_location_address_match (bl, aspace, pc))
4231         {
4232           if (overlay_debugging 
4233               && section_is_overlay (bl->section)
4234               && !section_is_mapped (bl->section))
4235             continue;           /* unmapped overlay -- can't be a match */
4236           else if (bl->permanent)
4237             return permanent_breakpoint_here;
4238           else
4239             any_breakpoint_here = 1;
4240         }
4241     }
4242
4243   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4244 }
4245
4246 /* Return true if there's a moribund breakpoint at PC.  */
4247
4248 int
4249 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4250 {
4251   struct bp_location *loc;
4252   int ix;
4253
4254   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4255     if (breakpoint_location_address_match (loc, aspace, pc))
4256       return 1;
4257
4258   return 0;
4259 }
4260
4261 /* Returns non-zero iff BL is inserted at PC, in address space
4262    ASPACE.  */
4263
4264 static int
4265 bp_location_inserted_here_p (struct bp_location *bl,
4266                              struct address_space *aspace, CORE_ADDR pc)
4267 {
4268   if (bl->inserted
4269       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4270                                    aspace, pc))
4271     {
4272       if (overlay_debugging
4273           && section_is_overlay (bl->section)
4274           && !section_is_mapped (bl->section))
4275         return 0;               /* unmapped overlay -- can't be a match */
4276       else
4277         return 1;
4278     }
4279   return 0;
4280 }
4281
4282 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4283
4284 int
4285 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4286 {
4287   struct bp_location **blp, **blp_tmp = NULL;
4288   struct bp_location *bl;
4289
4290   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4291     {
4292       struct bp_location *bl = *blp;
4293
4294       if (bl->loc_type != bp_loc_software_breakpoint
4295           && bl->loc_type != bp_loc_hardware_breakpoint)
4296         continue;
4297
4298       if (bp_location_inserted_here_p (bl, aspace, pc))
4299         return 1;
4300     }
4301   return 0;
4302 }
4303
4304 /* This function returns non-zero iff there is a software breakpoint
4305    inserted at PC.  */
4306
4307 int
4308 software_breakpoint_inserted_here_p (struct address_space *aspace,
4309                                      CORE_ADDR pc)
4310 {
4311   struct bp_location **blp, **blp_tmp = NULL;
4312   struct bp_location *bl;
4313
4314   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4315     {
4316       struct bp_location *bl = *blp;
4317
4318       if (bl->loc_type != bp_loc_software_breakpoint)
4319         continue;
4320
4321       if (bp_location_inserted_here_p (bl, aspace, pc))
4322         return 1;
4323     }
4324
4325   return 0;
4326 }
4327
4328 /* See breakpoint.h.  */
4329
4330 int
4331 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4332                                      CORE_ADDR pc)
4333 {
4334   struct bp_location **blp, **blp_tmp = NULL;
4335   struct bp_location *bl;
4336
4337   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4338     {
4339       struct bp_location *bl = *blp;
4340
4341       if (bl->loc_type != bp_loc_hardware_breakpoint)
4342         continue;
4343
4344       if (bp_location_inserted_here_p (bl, aspace, pc))
4345         return 1;
4346     }
4347
4348   return 0;
4349 }
4350
4351 int
4352 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4353                                        CORE_ADDR addr, ULONGEST len)
4354 {
4355   struct breakpoint *bpt;
4356
4357   ALL_BREAKPOINTS (bpt)
4358     {
4359       struct bp_location *loc;
4360
4361       if (bpt->type != bp_hardware_watchpoint
4362           && bpt->type != bp_access_watchpoint)
4363         continue;
4364
4365       if (!breakpoint_enabled (bpt))
4366         continue;
4367
4368       for (loc = bpt->loc; loc; loc = loc->next)
4369         if (loc->pspace->aspace == aspace && loc->inserted)
4370           {
4371             CORE_ADDR l, h;
4372
4373             /* Check for intersection.  */
4374             l = max (loc->address, addr);
4375             h = min (loc->address + loc->length, addr + len);
4376             if (l < h)
4377               return 1;
4378           }
4379     }
4380   return 0;
4381 }
4382 \f
4383
4384 /* bpstat stuff.  External routines' interfaces are documented
4385    in breakpoint.h.  */
4386
4387 int
4388 is_catchpoint (struct breakpoint *ep)
4389 {
4390   return (ep->type == bp_catchpoint);
4391 }
4392
4393 /* Frees any storage that is part of a bpstat.  Does not walk the
4394    'next' chain.  */
4395
4396 static void
4397 bpstat_free (bpstat bs)
4398 {
4399   if (bs->old_val != NULL)
4400     value_free (bs->old_val);
4401   decref_counted_command_line (&bs->commands);
4402   decref_bp_location (&bs->bp_location_at);
4403   xfree (bs);
4404 }
4405
4406 /* Clear a bpstat so that it says we are not at any breakpoint.
4407    Also free any storage that is part of a bpstat.  */
4408
4409 void
4410 bpstat_clear (bpstat *bsp)
4411 {
4412   bpstat p;
4413   bpstat q;
4414
4415   if (bsp == 0)
4416     return;
4417   p = *bsp;
4418   while (p != NULL)
4419     {
4420       q = p->next;
4421       bpstat_free (p);
4422       p = q;
4423     }
4424   *bsp = NULL;
4425 }
4426
4427 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4428    is part of the bpstat is copied as well.  */
4429
4430 bpstat
4431 bpstat_copy (bpstat bs)
4432 {
4433   bpstat p = NULL;
4434   bpstat tmp;
4435   bpstat retval = NULL;
4436
4437   if (bs == NULL)
4438     return bs;
4439
4440   for (; bs != NULL; bs = bs->next)
4441     {
4442       tmp = (bpstat) xmalloc (sizeof (*tmp));
4443       memcpy (tmp, bs, sizeof (*tmp));
4444       incref_counted_command_line (tmp->commands);
4445       incref_bp_location (tmp->bp_location_at);
4446       if (bs->old_val != NULL)
4447         {
4448           tmp->old_val = value_copy (bs->old_val);
4449           release_value (tmp->old_val);
4450         }
4451
4452       if (p == NULL)
4453         /* This is the first thing in the chain.  */
4454         retval = tmp;
4455       else
4456         p->next = tmp;
4457       p = tmp;
4458     }
4459   p->next = NULL;
4460   return retval;
4461 }
4462
4463 /* Find the bpstat associated with this breakpoint.  */
4464
4465 bpstat
4466 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4467 {
4468   if (bsp == NULL)
4469     return NULL;
4470
4471   for (; bsp != NULL; bsp = bsp->next)
4472     {
4473       if (bsp->breakpoint_at == breakpoint)
4474         return bsp;
4475     }
4476   return NULL;
4477 }
4478
4479 /* See breakpoint.h.  */
4480
4481 int
4482 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4483 {
4484   for (; bsp != NULL; bsp = bsp->next)
4485     {
4486       if (bsp->breakpoint_at == NULL)
4487         {
4488           /* A moribund location can never explain a signal other than
4489              GDB_SIGNAL_TRAP.  */
4490           if (sig == GDB_SIGNAL_TRAP)
4491             return 1;
4492         }
4493       else
4494         {
4495           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4496                                                         sig))
4497             return 1;
4498         }
4499     }
4500
4501   return 0;
4502 }
4503
4504 /* Put in *NUM the breakpoint number of the first breakpoint we are
4505    stopped at.  *BSP upon return is a bpstat which points to the
4506    remaining breakpoints stopped at (but which is not guaranteed to be
4507    good for anything but further calls to bpstat_num).
4508
4509    Return 0 if passed a bpstat which does not indicate any breakpoints.
4510    Return -1 if stopped at a breakpoint that has been deleted since
4511    we set it.
4512    Return 1 otherwise.  */
4513
4514 int
4515 bpstat_num (bpstat *bsp, int *num)
4516 {
4517   struct breakpoint *b;
4518
4519   if ((*bsp) == NULL)
4520     return 0;                   /* No more breakpoint values */
4521
4522   /* We assume we'll never have several bpstats that correspond to a
4523      single breakpoint -- otherwise, this function might return the
4524      same number more than once and this will look ugly.  */
4525   b = (*bsp)->breakpoint_at;
4526   *bsp = (*bsp)->next;
4527   if (b == NULL)
4528     return -1;                  /* breakpoint that's been deleted since */
4529
4530   *num = b->number;             /* We have its number */
4531   return 1;
4532 }
4533
4534 /* See breakpoint.h.  */
4535
4536 void
4537 bpstat_clear_actions (void)
4538 {
4539   struct thread_info *tp;
4540   bpstat bs;
4541
4542   if (ptid_equal (inferior_ptid, null_ptid))
4543     return;
4544
4545   tp = find_thread_ptid (inferior_ptid);
4546   if (tp == NULL)
4547     return;
4548
4549   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4550     {
4551       decref_counted_command_line (&bs->commands);
4552
4553       if (bs->old_val != NULL)
4554         {
4555           value_free (bs->old_val);
4556           bs->old_val = NULL;
4557         }
4558     }
4559 }
4560
4561 /* Called when a command is about to proceed the inferior.  */
4562
4563 static void
4564 breakpoint_about_to_proceed (void)
4565 {
4566   if (!ptid_equal (inferior_ptid, null_ptid))
4567     {
4568       struct thread_info *tp = inferior_thread ();
4569
4570       /* Allow inferior function calls in breakpoint commands to not
4571          interrupt the command list.  When the call finishes
4572          successfully, the inferior will be standing at the same
4573          breakpoint as if nothing happened.  */
4574       if (tp->control.in_infcall)
4575         return;
4576     }
4577
4578   breakpoint_proceeded = 1;
4579 }
4580
4581 /* Stub for cleaning up our state if we error-out of a breakpoint
4582    command.  */
4583 static void
4584 cleanup_executing_breakpoints (void *ignore)
4585 {
4586   executing_breakpoint_commands = 0;
4587 }
4588
4589 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4590    or its equivalent.  */
4591
4592 static int
4593 command_line_is_silent (struct command_line *cmd)
4594 {
4595   return cmd && (strcmp ("silent", cmd->line) == 0);
4596 }
4597
4598 /* Execute all the commands associated with all the breakpoints at
4599    this location.  Any of these commands could cause the process to
4600    proceed beyond this point, etc.  We look out for such changes by
4601    checking the global "breakpoint_proceeded" after each command.
4602
4603    Returns true if a breakpoint command resumed the inferior.  In that
4604    case, it is the caller's responsibility to recall it again with the
4605    bpstat of the current thread.  */
4606
4607 static int
4608 bpstat_do_actions_1 (bpstat *bsp)
4609 {
4610   bpstat bs;
4611   struct cleanup *old_chain;
4612   int again = 0;
4613
4614   /* Avoid endless recursion if a `source' command is contained
4615      in bs->commands.  */
4616   if (executing_breakpoint_commands)
4617     return 0;
4618
4619   executing_breakpoint_commands = 1;
4620   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4621
4622   prevent_dont_repeat ();
4623
4624   /* This pointer will iterate over the list of bpstat's.  */
4625   bs = *bsp;
4626
4627   breakpoint_proceeded = 0;
4628   for (; bs != NULL; bs = bs->next)
4629     {
4630       struct counted_command_line *ccmd;
4631       struct command_line *cmd;
4632       struct cleanup *this_cmd_tree_chain;
4633
4634       /* Take ownership of the BSP's command tree, if it has one.
4635
4636          The command tree could legitimately contain commands like
4637          'step' and 'next', which call clear_proceed_status, which
4638          frees stop_bpstat's command tree.  To make sure this doesn't
4639          free the tree we're executing out from under us, we need to
4640          take ownership of the tree ourselves.  Since a given bpstat's
4641          commands are only executed once, we don't need to copy it; we
4642          can clear the pointer in the bpstat, and make sure we free
4643          the tree when we're done.  */
4644       ccmd = bs->commands;
4645       bs->commands = NULL;
4646       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4647       cmd = ccmd ? ccmd->commands : NULL;
4648       if (command_line_is_silent (cmd))
4649         {
4650           /* The action has been already done by bpstat_stop_status.  */
4651           cmd = cmd->next;
4652         }
4653
4654       while (cmd != NULL)
4655         {
4656           execute_control_command (cmd);
4657
4658           if (breakpoint_proceeded)
4659             break;
4660           else
4661             cmd = cmd->next;
4662         }
4663
4664       /* We can free this command tree now.  */
4665       do_cleanups (this_cmd_tree_chain);
4666
4667       if (breakpoint_proceeded)
4668         {
4669           if (interpreter_async)
4670             /* If we are in async mode, then the target might be still
4671                running, not stopped at any breakpoint, so nothing for
4672                us to do here -- just return to the event loop.  */
4673             ;
4674           else
4675             /* In sync mode, when execute_control_command returns
4676                we're already standing on the next breakpoint.
4677                Breakpoint commands for that stop were not run, since
4678                execute_command does not run breakpoint commands --
4679                only command_line_handler does, but that one is not
4680                involved in execution of breakpoint commands.  So, we
4681                can now execute breakpoint commands.  It should be
4682                noted that making execute_command do bpstat actions is
4683                not an option -- in this case we'll have recursive
4684                invocation of bpstat for each breakpoint with a
4685                command, and can easily blow up GDB stack.  Instead, we
4686                return true, which will trigger the caller to recall us
4687                with the new stop_bpstat.  */
4688             again = 1;
4689           break;
4690         }
4691     }
4692   do_cleanups (old_chain);
4693   return again;
4694 }
4695
4696 void
4697 bpstat_do_actions (void)
4698 {
4699   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4700
4701   /* Do any commands attached to breakpoint we are stopped at.  */
4702   while (!ptid_equal (inferior_ptid, null_ptid)
4703          && target_has_execution
4704          && !is_exited (inferior_ptid)
4705          && !is_executing (inferior_ptid))
4706     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4707        and only return when it is stopped at the next breakpoint, we
4708        keep doing breakpoint actions until it returns false to
4709        indicate the inferior was not resumed.  */
4710     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4711       break;
4712
4713   discard_cleanups (cleanup_if_error);
4714 }
4715
4716 /* Print out the (old or new) value associated with a watchpoint.  */
4717
4718 static void
4719 watchpoint_value_print (struct value *val, struct ui_file *stream)
4720 {
4721   if (val == NULL)
4722     fprintf_unfiltered (stream, _("<unreadable>"));
4723   else
4724     {
4725       struct value_print_options opts;
4726       get_user_print_options (&opts);
4727       value_print (val, stream, &opts);
4728     }
4729 }
4730
4731 /* Generic routine for printing messages indicating why we
4732    stopped.  The behavior of this function depends on the value
4733    'print_it' in the bpstat structure.  Under some circumstances we
4734    may decide not to print anything here and delegate the task to
4735    normal_stop().  */
4736
4737 static enum print_stop_action
4738 print_bp_stop_message (bpstat bs)
4739 {
4740   switch (bs->print_it)
4741     {
4742     case print_it_noop:
4743       /* Nothing should be printed for this bpstat entry.  */
4744       return PRINT_UNKNOWN;
4745       break;
4746
4747     case print_it_done:
4748       /* We still want to print the frame, but we already printed the
4749          relevant messages.  */
4750       return PRINT_SRC_AND_LOC;
4751       break;
4752
4753     case print_it_normal:
4754       {
4755         struct breakpoint *b = bs->breakpoint_at;
4756
4757         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4758            which has since been deleted.  */
4759         if (b == NULL)
4760           return PRINT_UNKNOWN;
4761
4762         /* Normal case.  Call the breakpoint's print_it method.  */
4763         return b->ops->print_it (bs);
4764       }
4765       break;
4766
4767     default:
4768       internal_error (__FILE__, __LINE__,
4769                       _("print_bp_stop_message: unrecognized enum value"));
4770       break;
4771     }
4772 }
4773
4774 /* A helper function that prints a shared library stopped event.  */
4775
4776 static void
4777 print_solib_event (int is_catchpoint)
4778 {
4779   int any_deleted
4780     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4781   int any_added
4782     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4783
4784   if (!is_catchpoint)
4785     {
4786       if (any_added || any_deleted)
4787         ui_out_text (current_uiout,
4788                      _("Stopped due to shared library event:\n"));
4789       else
4790         ui_out_text (current_uiout,
4791                      _("Stopped due to shared library event (no "
4792                        "libraries added or removed)\n"));
4793     }
4794
4795   if (ui_out_is_mi_like_p (current_uiout))
4796     ui_out_field_string (current_uiout, "reason",
4797                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4798
4799   if (any_deleted)
4800     {
4801       struct cleanup *cleanup;
4802       char *name;
4803       int ix;
4804
4805       ui_out_text (current_uiout, _("  Inferior unloaded "));
4806       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4807                                                     "removed");
4808       for (ix = 0;
4809            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4810                         ix, name);
4811            ++ix)
4812         {
4813           if (ix > 0)
4814             ui_out_text (current_uiout, "    ");
4815           ui_out_field_string (current_uiout, "library", name);
4816           ui_out_text (current_uiout, "\n");
4817         }
4818
4819       do_cleanups (cleanup);
4820     }
4821
4822   if (any_added)
4823     {
4824       struct so_list *iter;
4825       int ix;
4826       struct cleanup *cleanup;
4827
4828       ui_out_text (current_uiout, _("  Inferior loaded "));
4829       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4830                                                     "added");
4831       for (ix = 0;
4832            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4833                         ix, iter);
4834            ++ix)
4835         {
4836           if (ix > 0)
4837             ui_out_text (current_uiout, "    ");
4838           ui_out_field_string (current_uiout, "library", iter->so_name);
4839           ui_out_text (current_uiout, "\n");
4840         }
4841
4842       do_cleanups (cleanup);
4843     }
4844 }
4845
4846 /* Print a message indicating what happened.  This is called from
4847    normal_stop().  The input to this routine is the head of the bpstat
4848    list - a list of the eventpoints that caused this stop.  KIND is
4849    the target_waitkind for the stopping event.  This
4850    routine calls the generic print routine for printing a message
4851    about reasons for stopping.  This will print (for example) the
4852    "Breakpoint n," part of the output.  The return value of this
4853    routine is one of:
4854
4855    PRINT_UNKNOWN: Means we printed nothing.
4856    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4857    code to print the location.  An example is 
4858    "Breakpoint 1, " which should be followed by
4859    the location.
4860    PRINT_SRC_ONLY: Means we printed something, but there is no need
4861    to also print the location part of the message.
4862    An example is the catch/throw messages, which
4863    don't require a location appended to the end.
4864    PRINT_NOTHING: We have done some printing and we don't need any 
4865    further info to be printed.  */
4866
4867 enum print_stop_action
4868 bpstat_print (bpstat bs, int kind)
4869 {
4870   enum print_stop_action val;
4871
4872   /* Maybe another breakpoint in the chain caused us to stop.
4873      (Currently all watchpoints go on the bpstat whether hit or not.
4874      That probably could (should) be changed, provided care is taken
4875      with respect to bpstat_explains_signal).  */
4876   for (; bs; bs = bs->next)
4877     {
4878       val = print_bp_stop_message (bs);
4879       if (val == PRINT_SRC_ONLY 
4880           || val == PRINT_SRC_AND_LOC 
4881           || val == PRINT_NOTHING)
4882         return val;
4883     }
4884
4885   /* If we had hit a shared library event breakpoint,
4886      print_bp_stop_message would print out this message.  If we hit an
4887      OS-level shared library event, do the same thing.  */
4888   if (kind == TARGET_WAITKIND_LOADED)
4889     {
4890       print_solib_event (0);
4891       return PRINT_NOTHING;
4892     }
4893
4894   /* We reached the end of the chain, or we got a null BS to start
4895      with and nothing was printed.  */
4896   return PRINT_UNKNOWN;
4897 }
4898
4899 /* Evaluate the expression EXP and return 1 if value is zero.
4900    This returns the inverse of the condition because it is called
4901    from catch_errors which returns 0 if an exception happened, and if an
4902    exception happens we want execution to stop.
4903    The argument is a "struct expression *" that has been cast to a
4904    "void *" to make it pass through catch_errors.  */
4905
4906 static int
4907 breakpoint_cond_eval (void *exp)
4908 {
4909   struct value *mark = value_mark ();
4910   int i = !value_true (evaluate_expression ((struct expression *) exp));
4911
4912   value_free_to_mark (mark);
4913   return i;
4914 }
4915
4916 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4917
4918 static bpstat
4919 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4920 {
4921   bpstat bs;
4922
4923   bs = (bpstat) xmalloc (sizeof (*bs));
4924   bs->next = NULL;
4925   **bs_link_pointer = bs;
4926   *bs_link_pointer = &bs->next;
4927   bs->breakpoint_at = bl->owner;
4928   bs->bp_location_at = bl;
4929   incref_bp_location (bl);
4930   /* If the condition is false, etc., don't do the commands.  */
4931   bs->commands = NULL;
4932   bs->old_val = NULL;
4933   bs->print_it = print_it_normal;
4934   return bs;
4935 }
4936 \f
4937 /* The target has stopped with waitstatus WS.  Check if any hardware
4938    watchpoints have triggered, according to the target.  */
4939
4940 int
4941 watchpoints_triggered (struct target_waitstatus *ws)
4942 {
4943   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4944   CORE_ADDR addr;
4945   struct breakpoint *b;
4946
4947   if (!stopped_by_watchpoint)
4948     {
4949       /* We were not stopped by a watchpoint.  Mark all watchpoints
4950          as not triggered.  */
4951       ALL_BREAKPOINTS (b)
4952         if (is_hardware_watchpoint (b))
4953           {
4954             struct watchpoint *w = (struct watchpoint *) b;
4955
4956             w->watchpoint_triggered = watch_triggered_no;
4957           }
4958
4959       return 0;
4960     }
4961
4962   if (!target_stopped_data_address (&current_target, &addr))
4963     {
4964       /* We were stopped by a watchpoint, but we don't know where.
4965          Mark all watchpoints as unknown.  */
4966       ALL_BREAKPOINTS (b)
4967         if (is_hardware_watchpoint (b))
4968           {
4969             struct watchpoint *w = (struct watchpoint *) b;
4970
4971             w->watchpoint_triggered = watch_triggered_unknown;
4972           }
4973
4974       return 1;
4975     }
4976
4977   /* The target could report the data address.  Mark watchpoints
4978      affected by this data address as triggered, and all others as not
4979      triggered.  */
4980
4981   ALL_BREAKPOINTS (b)
4982     if (is_hardware_watchpoint (b))
4983       {
4984         struct watchpoint *w = (struct watchpoint *) b;
4985         struct bp_location *loc;
4986
4987         w->watchpoint_triggered = watch_triggered_no;
4988         for (loc = b->loc; loc; loc = loc->next)
4989           {
4990             if (is_masked_watchpoint (b))
4991               {
4992                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4993                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4994
4995                 if (newaddr == start)
4996                   {
4997                     w->watchpoint_triggered = watch_triggered_yes;
4998                     break;
4999                   }
5000               }
5001             /* Exact match not required.  Within range is sufficient.  */
5002             else if (target_watchpoint_addr_within_range (&current_target,
5003                                                          addr, loc->address,
5004                                                          loc->length))
5005               {
5006                 w->watchpoint_triggered = watch_triggered_yes;
5007                 break;
5008               }
5009           }
5010       }
5011
5012   return 1;
5013 }
5014
5015 /* Possible return values for watchpoint_check (this can't be an enum
5016    because of check_errors).  */
5017 /* The watchpoint has been deleted.  */
5018 #define WP_DELETED 1
5019 /* The value has changed.  */
5020 #define WP_VALUE_CHANGED 2
5021 /* The value has not changed.  */
5022 #define WP_VALUE_NOT_CHANGED 3
5023 /* Ignore this watchpoint, no matter if the value changed or not.  */
5024 #define WP_IGNORE 4
5025
5026 #define BP_TEMPFLAG 1
5027 #define BP_HARDWAREFLAG 2
5028
5029 /* Evaluate watchpoint condition expression and check if its value
5030    changed.
5031
5032    P should be a pointer to struct bpstat, but is defined as a void *
5033    in order for this function to be usable with catch_errors.  */
5034
5035 static int
5036 watchpoint_check (void *p)
5037 {
5038   bpstat bs = (bpstat) p;
5039   struct watchpoint *b;
5040   struct frame_info *fr;
5041   int within_current_scope;
5042
5043   /* BS is built from an existing struct breakpoint.  */
5044   gdb_assert (bs->breakpoint_at != NULL);
5045   b = (struct watchpoint *) bs->breakpoint_at;
5046
5047   /* If this is a local watchpoint, we only want to check if the
5048      watchpoint frame is in scope if the current thread is the thread
5049      that was used to create the watchpoint.  */
5050   if (!watchpoint_in_thread_scope (b))
5051     return WP_IGNORE;
5052
5053   if (b->exp_valid_block == NULL)
5054     within_current_scope = 1;
5055   else
5056     {
5057       struct frame_info *frame = get_current_frame ();
5058       struct gdbarch *frame_arch = get_frame_arch (frame);
5059       CORE_ADDR frame_pc = get_frame_pc (frame);
5060
5061       /* stack_frame_destroyed_p() returns a non-zero value if we're
5062          still in the function but the stack frame has already been
5063          invalidated.  Since we can't rely on the values of local
5064          variables after the stack has been destroyed, we are treating
5065          the watchpoint in that state as `not changed' without further
5066          checking.  Don't mark watchpoints as changed if the current
5067          frame is in an epilogue - even if they are in some other
5068          frame, our view of the stack is likely to be wrong and
5069          frame_find_by_id could error out.  */
5070       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5071         return WP_IGNORE;
5072
5073       fr = frame_find_by_id (b->watchpoint_frame);
5074       within_current_scope = (fr != NULL);
5075
5076       /* If we've gotten confused in the unwinder, we might have
5077          returned a frame that can't describe this variable.  */
5078       if (within_current_scope)
5079         {
5080           struct symbol *function;
5081
5082           function = get_frame_function (fr);
5083           if (function == NULL
5084               || !contained_in (b->exp_valid_block,
5085                                 SYMBOL_BLOCK_VALUE (function)))
5086             within_current_scope = 0;
5087         }
5088
5089       if (within_current_scope)
5090         /* If we end up stopping, the current frame will get selected
5091            in normal_stop.  So this call to select_frame won't affect
5092            the user.  */
5093         select_frame (fr);
5094     }
5095
5096   if (within_current_scope)
5097     {
5098       /* We use value_{,free_to_}mark because it could be a *long*
5099          time before we return to the command level and call
5100          free_all_values.  We can't call free_all_values because we
5101          might be in the middle of evaluating a function call.  */
5102
5103       int pc = 0;
5104       struct value *mark;
5105       struct value *new_val;
5106
5107       if (is_masked_watchpoint (&b->base))
5108         /* Since we don't know the exact trigger address (from
5109            stopped_data_address), just tell the user we've triggered
5110            a mask watchpoint.  */
5111         return WP_VALUE_CHANGED;
5112
5113       mark = value_mark ();
5114       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5115
5116       if (b->val_bitsize != 0)
5117         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5118
5119       /* We use value_equal_contents instead of value_equal because
5120          the latter coerces an array to a pointer, thus comparing just
5121          the address of the array instead of its contents.  This is
5122          not what we want.  */
5123       if ((b->val != NULL) != (new_val != NULL)
5124           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5125         {
5126           if (new_val != NULL)
5127             {
5128               release_value (new_val);
5129               value_free_to_mark (mark);
5130             }
5131           bs->old_val = b->val;
5132           b->val = new_val;
5133           b->val_valid = 1;
5134           return WP_VALUE_CHANGED;
5135         }
5136       else
5137         {
5138           /* Nothing changed.  */
5139           value_free_to_mark (mark);
5140           return WP_VALUE_NOT_CHANGED;
5141         }
5142     }
5143   else
5144     {
5145       struct ui_out *uiout = current_uiout;
5146
5147       /* This seems like the only logical thing to do because
5148          if we temporarily ignored the watchpoint, then when
5149          we reenter the block in which it is valid it contains
5150          garbage (in the case of a function, it may have two
5151          garbage values, one before and one after the prologue).
5152          So we can't even detect the first assignment to it and
5153          watch after that (since the garbage may or may not equal
5154          the first value assigned).  */
5155       /* We print all the stop information in
5156          breakpoint_ops->print_it, but in this case, by the time we
5157          call breakpoint_ops->print_it this bp will be deleted
5158          already.  So we have no choice but print the information
5159          here.  */
5160       if (ui_out_is_mi_like_p (uiout))
5161         ui_out_field_string
5162           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5163       ui_out_text (uiout, "\nWatchpoint ");
5164       ui_out_field_int (uiout, "wpnum", b->base.number);
5165       ui_out_text (uiout,
5166                    " deleted because the program has left the block in\n\
5167 which its expression is valid.\n");     
5168
5169       /* Make sure the watchpoint's commands aren't executed.  */
5170       decref_counted_command_line (&b->base.commands);
5171       watchpoint_del_at_next_stop (b);
5172
5173       return WP_DELETED;
5174     }
5175 }
5176
5177 /* Return true if it looks like target has stopped due to hitting
5178    breakpoint location BL.  This function does not check if we should
5179    stop, only if BL explains the stop.  */
5180
5181 static int
5182 bpstat_check_location (const struct bp_location *bl,
5183                        struct address_space *aspace, CORE_ADDR bp_addr,
5184                        const struct target_waitstatus *ws)
5185 {
5186   struct breakpoint *b = bl->owner;
5187
5188   /* BL is from an existing breakpoint.  */
5189   gdb_assert (b != NULL);
5190
5191   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5192 }
5193
5194 /* Determine if the watched values have actually changed, and we
5195    should stop.  If not, set BS->stop to 0.  */
5196
5197 static void
5198 bpstat_check_watchpoint (bpstat bs)
5199 {
5200   const struct bp_location *bl;
5201   struct watchpoint *b;
5202
5203   /* BS is built for existing struct breakpoint.  */
5204   bl = bs->bp_location_at;
5205   gdb_assert (bl != NULL);
5206   b = (struct watchpoint *) bs->breakpoint_at;
5207   gdb_assert (b != NULL);
5208
5209     {
5210       int must_check_value = 0;
5211       
5212       if (b->base.type == bp_watchpoint)
5213         /* For a software watchpoint, we must always check the
5214            watched value.  */
5215         must_check_value = 1;
5216       else if (b->watchpoint_triggered == watch_triggered_yes)
5217         /* We have a hardware watchpoint (read, write, or access)
5218            and the target earlier reported an address watched by
5219            this watchpoint.  */
5220         must_check_value = 1;
5221       else if (b->watchpoint_triggered == watch_triggered_unknown
5222                && b->base.type == bp_hardware_watchpoint)
5223         /* We were stopped by a hardware watchpoint, but the target could
5224            not report the data address.  We must check the watchpoint's
5225            value.  Access and read watchpoints are out of luck; without
5226            a data address, we can't figure it out.  */
5227         must_check_value = 1;
5228
5229       if (must_check_value)
5230         {
5231           char *message
5232             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5233                           b->base.number);
5234           struct cleanup *cleanups = make_cleanup (xfree, message);
5235           int e = catch_errors (watchpoint_check, bs, message,
5236                                 RETURN_MASK_ALL);
5237           do_cleanups (cleanups);
5238           switch (e)
5239             {
5240             case WP_DELETED:
5241               /* We've already printed what needs to be printed.  */
5242               bs->print_it = print_it_done;
5243               /* Stop.  */
5244               break;
5245             case WP_IGNORE:
5246               bs->print_it = print_it_noop;
5247               bs->stop = 0;
5248               break;
5249             case WP_VALUE_CHANGED:
5250               if (b->base.type == bp_read_watchpoint)
5251                 {
5252                   /* There are two cases to consider here:
5253
5254                      1. We're watching the triggered memory for reads.
5255                      In that case, trust the target, and always report
5256                      the watchpoint hit to the user.  Even though
5257                      reads don't cause value changes, the value may
5258                      have changed since the last time it was read, and
5259                      since we're not trapping writes, we will not see
5260                      those, and as such we should ignore our notion of
5261                      old value.
5262
5263                      2. We're watching the triggered memory for both
5264                      reads and writes.  There are two ways this may
5265                      happen:
5266
5267                      2.1. This is a target that can't break on data
5268                      reads only, but can break on accesses (reads or
5269                      writes), such as e.g., x86.  We detect this case
5270                      at the time we try to insert read watchpoints.
5271
5272                      2.2. Otherwise, the target supports read
5273                      watchpoints, but, the user set an access or write
5274                      watchpoint watching the same memory as this read
5275                      watchpoint.
5276
5277                      If we're watching memory writes as well as reads,
5278                      ignore watchpoint hits when we find that the
5279                      value hasn't changed, as reads don't cause
5280                      changes.  This still gives false positives when
5281                      the program writes the same value to memory as
5282                      what there was already in memory (we will confuse
5283                      it for a read), but it's much better than
5284                      nothing.  */
5285
5286                   int other_write_watchpoint = 0;
5287
5288                   if (bl->watchpoint_type == hw_read)
5289                     {
5290                       struct breakpoint *other_b;
5291
5292                       ALL_BREAKPOINTS (other_b)
5293                         if (other_b->type == bp_hardware_watchpoint
5294                             || other_b->type == bp_access_watchpoint)
5295                           {
5296                             struct watchpoint *other_w =
5297                               (struct watchpoint *) other_b;
5298
5299                             if (other_w->watchpoint_triggered
5300                                 == watch_triggered_yes)
5301                               {
5302                                 other_write_watchpoint = 1;
5303                                 break;
5304                               }
5305                           }
5306                     }
5307
5308                   if (other_write_watchpoint
5309                       || bl->watchpoint_type == hw_access)
5310                     {
5311                       /* We're watching the same memory for writes,
5312                          and the value changed since the last time we
5313                          updated it, so this trap must be for a write.
5314                          Ignore it.  */
5315                       bs->print_it = print_it_noop;
5316                       bs->stop = 0;
5317                     }
5318                 }
5319               break;
5320             case WP_VALUE_NOT_CHANGED:
5321               if (b->base.type == bp_hardware_watchpoint
5322                   || b->base.type == bp_watchpoint)
5323                 {
5324                   /* Don't stop: write watchpoints shouldn't fire if
5325                      the value hasn't changed.  */
5326                   bs->print_it = print_it_noop;
5327                   bs->stop = 0;
5328                 }
5329               /* Stop.  */
5330               break;
5331             default:
5332               /* Can't happen.  */
5333             case 0:
5334               /* Error from catch_errors.  */
5335               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5336               watchpoint_del_at_next_stop (b);
5337               /* We've already printed what needs to be printed.  */
5338               bs->print_it = print_it_done;
5339               break;
5340             }
5341         }
5342       else      /* must_check_value == 0 */
5343         {
5344           /* This is a case where some watchpoint(s) triggered, but
5345              not at the address of this watchpoint, or else no
5346              watchpoint triggered after all.  So don't print
5347              anything for this watchpoint.  */
5348           bs->print_it = print_it_noop;
5349           bs->stop = 0;
5350         }
5351     }
5352 }
5353
5354 /* For breakpoints that are currently marked as telling gdb to stop,
5355    check conditions (condition proper, frame, thread and ignore count)
5356    of breakpoint referred to by BS.  If we should not stop for this
5357    breakpoint, set BS->stop to 0.  */
5358
5359 static void
5360 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5361 {
5362   const struct bp_location *bl;
5363   struct breakpoint *b;
5364   int value_is_zero = 0;
5365   struct expression *cond;
5366
5367   gdb_assert (bs->stop);
5368
5369   /* BS is built for existing struct breakpoint.  */
5370   bl = bs->bp_location_at;
5371   gdb_assert (bl != NULL);
5372   b = bs->breakpoint_at;
5373   gdb_assert (b != NULL);
5374
5375   /* Even if the target evaluated the condition on its end and notified GDB, we
5376      need to do so again since GDB does not know if we stopped due to a
5377      breakpoint or a single step breakpoint.  */
5378
5379   if (frame_id_p (b->frame_id)
5380       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5381     {
5382       bs->stop = 0;
5383       return;
5384     }
5385
5386   /* If this is a thread/task-specific breakpoint, don't waste cpu
5387      evaluating the condition if this isn't the specified
5388      thread/task.  */
5389   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5390       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5391
5392     {
5393       bs->stop = 0;
5394       return;
5395     }
5396
5397   /* Evaluate extension language breakpoints that have a "stop" method
5398      implemented.  */
5399   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5400
5401   if (is_watchpoint (b))
5402     {
5403       struct watchpoint *w = (struct watchpoint *) b;
5404
5405       cond = w->cond_exp;
5406     }
5407   else
5408     cond = bl->cond;
5409
5410   if (cond && b->disposition != disp_del_at_next_stop)
5411     {
5412       int within_current_scope = 1;
5413       struct watchpoint * w;
5414
5415       /* We use value_mark and value_free_to_mark because it could
5416          be a long time before we return to the command level and
5417          call free_all_values.  We can't call free_all_values
5418          because we might be in the middle of evaluating a
5419          function call.  */
5420       struct value *mark = value_mark ();
5421
5422       if (is_watchpoint (b))
5423         w = (struct watchpoint *) b;
5424       else
5425         w = NULL;
5426
5427       /* Need to select the frame, with all that implies so that
5428          the conditions will have the right context.  Because we
5429          use the frame, we will not see an inlined function's
5430          variables when we arrive at a breakpoint at the start
5431          of the inlined function; the current frame will be the
5432          call site.  */
5433       if (w == NULL || w->cond_exp_valid_block == NULL)
5434         select_frame (get_current_frame ());
5435       else
5436         {
5437           struct frame_info *frame;
5438
5439           /* For local watchpoint expressions, which particular
5440              instance of a local is being watched matters, so we
5441              keep track of the frame to evaluate the expression
5442              in.  To evaluate the condition however, it doesn't
5443              really matter which instantiation of the function
5444              where the condition makes sense triggers the
5445              watchpoint.  This allows an expression like "watch
5446              global if q > 10" set in `func', catch writes to
5447              global on all threads that call `func', or catch
5448              writes on all recursive calls of `func' by a single
5449              thread.  We simply always evaluate the condition in
5450              the innermost frame that's executing where it makes
5451              sense to evaluate the condition.  It seems
5452              intuitive.  */
5453           frame = block_innermost_frame (w->cond_exp_valid_block);
5454           if (frame != NULL)
5455             select_frame (frame);
5456           else
5457             within_current_scope = 0;
5458         }
5459       if (within_current_scope)
5460         value_is_zero
5461           = catch_errors (breakpoint_cond_eval, cond,
5462                           "Error in testing breakpoint condition:\n",
5463                           RETURN_MASK_ALL);
5464       else
5465         {
5466           warning (_("Watchpoint condition cannot be tested "
5467                      "in the current scope"));
5468           /* If we failed to set the right context for this
5469              watchpoint, unconditionally report it.  */
5470           value_is_zero = 0;
5471         }
5472       /* FIXME-someday, should give breakpoint #.  */
5473       value_free_to_mark (mark);
5474     }
5475
5476   if (cond && value_is_zero)
5477     {
5478       bs->stop = 0;
5479     }
5480   else if (b->ignore_count > 0)
5481     {
5482       b->ignore_count--;
5483       bs->stop = 0;
5484       /* Increase the hit count even though we don't stop.  */
5485       ++(b->hit_count);
5486       observer_notify_breakpoint_modified (b);
5487     }   
5488 }
5489
5490 /* Returns true if we need to track moribund locations of LOC's type
5491    on the current target.  */
5492
5493 static int
5494 need_moribund_for_location_type (struct bp_location *loc)
5495 {
5496   return ((loc->loc_type == bp_loc_software_breakpoint
5497            && !target_supports_stopped_by_sw_breakpoint ())
5498           || (loc->loc_type == bp_loc_hardware_breakpoint
5499               && !target_supports_stopped_by_hw_breakpoint ()));
5500 }
5501
5502
5503 /* Get a bpstat associated with having just stopped at address
5504    BP_ADDR in thread PTID.
5505
5506    Determine whether we stopped at a breakpoint, etc, or whether we
5507    don't understand this stop.  Result is a chain of bpstat's such
5508    that:
5509
5510    if we don't understand the stop, the result is a null pointer.
5511
5512    if we understand why we stopped, the result is not null.
5513
5514    Each element of the chain refers to a particular breakpoint or
5515    watchpoint at which we have stopped.  (We may have stopped for
5516    several reasons concurrently.)
5517
5518    Each element of the chain has valid next, breakpoint_at,
5519    commands, FIXME??? fields.  */
5520
5521 bpstat
5522 bpstat_stop_status (struct address_space *aspace,
5523                     CORE_ADDR bp_addr, ptid_t ptid,
5524                     const struct target_waitstatus *ws)
5525 {
5526   struct breakpoint *b = NULL;
5527   struct bp_location *bl;
5528   struct bp_location *loc;
5529   /* First item of allocated bpstat's.  */
5530   bpstat bs_head = NULL, *bs_link = &bs_head;
5531   /* Pointer to the last thing in the chain currently.  */
5532   bpstat bs;
5533   int ix;
5534   int need_remove_insert;
5535   int removed_any;
5536
5537   /* First, build the bpstat chain with locations that explain a
5538      target stop, while being careful to not set the target running,
5539      as that may invalidate locations (in particular watchpoint
5540      locations are recreated).  Resuming will happen here with
5541      breakpoint conditions or watchpoint expressions that include
5542      inferior function calls.  */
5543
5544   ALL_BREAKPOINTS (b)
5545     {
5546       if (!breakpoint_enabled (b))
5547         continue;
5548
5549       for (bl = b->loc; bl != NULL; bl = bl->next)
5550         {
5551           /* For hardware watchpoints, we look only at the first
5552              location.  The watchpoint_check function will work on the
5553              entire expression, not the individual locations.  For
5554              read watchpoints, the watchpoints_triggered function has
5555              checked all locations already.  */
5556           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5557             break;
5558
5559           if (!bl->enabled || bl->shlib_disabled)
5560             continue;
5561
5562           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5563             continue;
5564
5565           /* Come here if it's a watchpoint, or if the break address
5566              matches.  */
5567
5568           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5569                                                    explain stop.  */
5570
5571           /* Assume we stop.  Should we find a watchpoint that is not
5572              actually triggered, or if the condition of the breakpoint
5573              evaluates as false, we'll reset 'stop' to 0.  */
5574           bs->stop = 1;
5575           bs->print = 1;
5576
5577           /* If this is a scope breakpoint, mark the associated
5578              watchpoint as triggered so that we will handle the
5579              out-of-scope event.  We'll get to the watchpoint next
5580              iteration.  */
5581           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5582             {
5583               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5584
5585               w->watchpoint_triggered = watch_triggered_yes;
5586             }
5587         }
5588     }
5589
5590   /* Check if a moribund breakpoint explains the stop.  */
5591   if (!target_supports_stopped_by_sw_breakpoint ()
5592       || !target_supports_stopped_by_hw_breakpoint ())
5593     {
5594       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5595         {
5596           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5597               && need_moribund_for_location_type (loc))
5598             {
5599               bs = bpstat_alloc (loc, &bs_link);
5600               /* For hits of moribund locations, we should just proceed.  */
5601               bs->stop = 0;
5602               bs->print = 0;
5603               bs->print_it = print_it_noop;
5604             }
5605         }
5606     }
5607
5608   /* A bit of special processing for shlib breakpoints.  We need to
5609      process solib loading here, so that the lists of loaded and
5610      unloaded libraries are correct before we handle "catch load" and
5611      "catch unload".  */
5612   for (bs = bs_head; bs != NULL; bs = bs->next)
5613     {
5614       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5615         {
5616           handle_solib_event ();
5617           break;
5618         }
5619     }
5620
5621   /* Now go through the locations that caused the target to stop, and
5622      check whether we're interested in reporting this stop to higher
5623      layers, or whether we should resume the target transparently.  */
5624
5625   removed_any = 0;
5626
5627   for (bs = bs_head; bs != NULL; bs = bs->next)
5628     {
5629       if (!bs->stop)
5630         continue;
5631
5632       b = bs->breakpoint_at;
5633       b->ops->check_status (bs);
5634       if (bs->stop)
5635         {
5636           bpstat_check_breakpoint_conditions (bs, ptid);
5637
5638           if (bs->stop)
5639             {
5640               ++(b->hit_count);
5641               observer_notify_breakpoint_modified (b);
5642
5643               /* We will stop here.  */
5644               if (b->disposition == disp_disable)
5645                 {
5646                   --(b->enable_count);
5647                   if (b->enable_count <= 0)
5648                     b->enable_state = bp_disabled;
5649                   removed_any = 1;
5650                 }
5651               if (b->silent)
5652                 bs->print = 0;
5653               bs->commands = b->commands;
5654               incref_counted_command_line (bs->commands);
5655               if (command_line_is_silent (bs->commands
5656                                           ? bs->commands->commands : NULL))
5657                 bs->print = 0;
5658
5659               b->ops->after_condition_true (bs);
5660             }
5661
5662         }
5663
5664       /* Print nothing for this entry if we don't stop or don't
5665          print.  */
5666       if (!bs->stop || !bs->print)
5667         bs->print_it = print_it_noop;
5668     }
5669
5670   /* If we aren't stopping, the value of some hardware watchpoint may
5671      not have changed, but the intermediate memory locations we are
5672      watching may have.  Don't bother if we're stopping; this will get
5673      done later.  */
5674   need_remove_insert = 0;
5675   if (! bpstat_causes_stop (bs_head))
5676     for (bs = bs_head; bs != NULL; bs = bs->next)
5677       if (!bs->stop
5678           && bs->breakpoint_at
5679           && is_hardware_watchpoint (bs->breakpoint_at))
5680         {
5681           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5682
5683           update_watchpoint (w, 0 /* don't reparse.  */);
5684           need_remove_insert = 1;
5685         }
5686
5687   if (need_remove_insert)
5688     update_global_location_list (UGLL_MAY_INSERT);
5689   else if (removed_any)
5690     update_global_location_list (UGLL_DONT_INSERT);
5691
5692   return bs_head;
5693 }
5694
5695 static void
5696 handle_jit_event (void)
5697 {
5698   struct frame_info *frame;
5699   struct gdbarch *gdbarch;
5700
5701   if (debug_infrun)
5702     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5703
5704   /* Switch terminal for any messages produced by
5705      breakpoint_re_set.  */
5706   target_terminal_ours_for_output ();
5707
5708   frame = get_current_frame ();
5709   gdbarch = get_frame_arch (frame);
5710
5711   jit_event_handler (gdbarch);
5712
5713   target_terminal_inferior ();
5714 }
5715
5716 /* Prepare WHAT final decision for infrun.  */
5717
5718 /* Decide what infrun needs to do with this bpstat.  */
5719
5720 struct bpstat_what
5721 bpstat_what (bpstat bs_head)
5722 {
5723   struct bpstat_what retval;
5724   int jit_event = 0;
5725   bpstat bs;
5726
5727   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5728   retval.call_dummy = STOP_NONE;
5729   retval.is_longjmp = 0;
5730
5731   for (bs = bs_head; bs != NULL; bs = bs->next)
5732     {
5733       /* Extract this BS's action.  After processing each BS, we check
5734          if its action overrides all we've seem so far.  */
5735       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5736       enum bptype bptype;
5737
5738       if (bs->breakpoint_at == NULL)
5739         {
5740           /* I suspect this can happen if it was a momentary
5741              breakpoint which has since been deleted.  */
5742           bptype = bp_none;
5743         }
5744       else
5745         bptype = bs->breakpoint_at->type;
5746
5747       switch (bptype)
5748         {
5749         case bp_none:
5750           break;
5751         case bp_breakpoint:
5752         case bp_hardware_breakpoint:
5753         case bp_single_step:
5754         case bp_until:
5755         case bp_finish:
5756         case bp_shlib_event:
5757           if (bs->stop)
5758             {
5759               if (bs->print)
5760                 this_action = BPSTAT_WHAT_STOP_NOISY;
5761               else
5762                 this_action = BPSTAT_WHAT_STOP_SILENT;
5763             }
5764           else
5765             this_action = BPSTAT_WHAT_SINGLE;
5766           break;
5767         case bp_watchpoint:
5768         case bp_hardware_watchpoint:
5769         case bp_read_watchpoint:
5770         case bp_access_watchpoint:
5771           if (bs->stop)
5772             {
5773               if (bs->print)
5774                 this_action = BPSTAT_WHAT_STOP_NOISY;
5775               else
5776                 this_action = BPSTAT_WHAT_STOP_SILENT;
5777             }
5778           else
5779             {
5780               /* There was a watchpoint, but we're not stopping.
5781                  This requires no further action.  */
5782             }
5783           break;
5784         case bp_longjmp:
5785         case bp_longjmp_call_dummy:
5786         case bp_exception:
5787           if (bs->stop)
5788             {
5789               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5790               retval.is_longjmp = bptype != bp_exception;
5791             }
5792           else
5793             this_action = BPSTAT_WHAT_SINGLE;
5794           break;
5795         case bp_longjmp_resume:
5796         case bp_exception_resume:
5797           if (bs->stop)
5798             {
5799               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5800               retval.is_longjmp = bptype == bp_longjmp_resume;
5801             }
5802           else
5803             this_action = BPSTAT_WHAT_SINGLE;
5804           break;
5805         case bp_step_resume:
5806           if (bs->stop)
5807             this_action = BPSTAT_WHAT_STEP_RESUME;
5808           else
5809             {
5810               /* It is for the wrong frame.  */
5811               this_action = BPSTAT_WHAT_SINGLE;
5812             }
5813           break;
5814         case bp_hp_step_resume:
5815           if (bs->stop)
5816             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5817           else
5818             {
5819               /* It is for the wrong frame.  */
5820               this_action = BPSTAT_WHAT_SINGLE;
5821             }
5822           break;
5823         case bp_watchpoint_scope:
5824         case bp_thread_event:
5825         case bp_overlay_event:
5826         case bp_longjmp_master:
5827         case bp_std_terminate_master:
5828         case bp_exception_master:
5829           this_action = BPSTAT_WHAT_SINGLE;
5830           break;
5831         case bp_catchpoint:
5832           if (bs->stop)
5833             {
5834               if (bs->print)
5835                 this_action = BPSTAT_WHAT_STOP_NOISY;
5836               else
5837                 this_action = BPSTAT_WHAT_STOP_SILENT;
5838             }
5839           else
5840             {
5841               /* There was a catchpoint, but we're not stopping.
5842                  This requires no further action.  */
5843             }
5844           break;
5845         case bp_jit_event:
5846           jit_event = 1;
5847           this_action = BPSTAT_WHAT_SINGLE;
5848           break;
5849         case bp_call_dummy:
5850           /* Make sure the action is stop (silent or noisy),
5851              so infrun.c pops the dummy frame.  */
5852           retval.call_dummy = STOP_STACK_DUMMY;
5853           this_action = BPSTAT_WHAT_STOP_SILENT;
5854           break;
5855         case bp_std_terminate:
5856           /* Make sure the action is stop (silent or noisy),
5857              so infrun.c pops the dummy frame.  */
5858           retval.call_dummy = STOP_STD_TERMINATE;
5859           this_action = BPSTAT_WHAT_STOP_SILENT;
5860           break;
5861         case bp_tracepoint:
5862         case bp_fast_tracepoint:
5863         case bp_static_tracepoint:
5864           /* Tracepoint hits should not be reported back to GDB, and
5865              if one got through somehow, it should have been filtered
5866              out already.  */
5867           internal_error (__FILE__, __LINE__,
5868                           _("bpstat_what: tracepoint encountered"));
5869           break;
5870         case bp_gnu_ifunc_resolver:
5871           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5872           this_action = BPSTAT_WHAT_SINGLE;
5873           break;
5874         case bp_gnu_ifunc_resolver_return:
5875           /* The breakpoint will be removed, execution will restart from the
5876              PC of the former breakpoint.  */
5877           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5878           break;
5879
5880         case bp_dprintf:
5881           if (bs->stop)
5882             this_action = BPSTAT_WHAT_STOP_SILENT;
5883           else
5884             this_action = BPSTAT_WHAT_SINGLE;
5885           break;
5886
5887         default:
5888           internal_error (__FILE__, __LINE__,
5889                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5890         }
5891
5892       retval.main_action = max (retval.main_action, this_action);
5893     }
5894
5895   return retval;
5896 }
5897
5898 void
5899 bpstat_run_callbacks (bpstat bs_head)
5900 {
5901   bpstat bs;
5902
5903   for (bs = bs_head; bs != NULL; bs = bs->next)
5904     {
5905       struct breakpoint *b = bs->breakpoint_at;
5906
5907       if (b == NULL)
5908         continue;
5909       switch (b->type)
5910         {
5911         case bp_jit_event:
5912           handle_jit_event ();
5913           break;
5914         case bp_gnu_ifunc_resolver:
5915           gnu_ifunc_resolver_stop (b);
5916           break;
5917         case bp_gnu_ifunc_resolver_return:
5918           gnu_ifunc_resolver_return_stop (b);
5919           break;
5920         }
5921     }
5922 }
5923
5924 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5925    without hardware support).  This isn't related to a specific bpstat,
5926    just to things like whether watchpoints are set.  */
5927
5928 int
5929 bpstat_should_step (void)
5930 {
5931   struct breakpoint *b;
5932
5933   ALL_BREAKPOINTS (b)
5934     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5935       return 1;
5936   return 0;
5937 }
5938
5939 int
5940 bpstat_causes_stop (bpstat bs)
5941 {
5942   for (; bs != NULL; bs = bs->next)
5943     if (bs->stop)
5944       return 1;
5945
5946   return 0;
5947 }
5948
5949 \f
5950
5951 /* Compute a string of spaces suitable to indent the next line
5952    so it starts at the position corresponding to the table column
5953    named COL_NAME in the currently active table of UIOUT.  */
5954
5955 static char *
5956 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5957 {
5958   static char wrap_indent[80];
5959   int i, total_width, width, align;
5960   char *text;
5961
5962   total_width = 0;
5963   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5964     {
5965       if (strcmp (text, col_name) == 0)
5966         {
5967           gdb_assert (total_width < sizeof wrap_indent);
5968           memset (wrap_indent, ' ', total_width);
5969           wrap_indent[total_width] = 0;
5970
5971           return wrap_indent;
5972         }
5973
5974       total_width += width + 1;
5975     }
5976
5977   return NULL;
5978 }
5979
5980 /* Determine if the locations of this breakpoint will have their conditions
5981    evaluated by the target, host or a mix of both.  Returns the following:
5982
5983     "host": Host evals condition.
5984     "host or target": Host or Target evals condition.
5985     "target": Target evals condition.
5986 */
5987
5988 static const char *
5989 bp_condition_evaluator (struct breakpoint *b)
5990 {
5991   struct bp_location *bl;
5992   char host_evals = 0;
5993   char target_evals = 0;
5994
5995   if (!b)
5996     return NULL;
5997
5998   if (!is_breakpoint (b))
5999     return NULL;
6000
6001   if (gdb_evaluates_breakpoint_condition_p ()
6002       || !target_supports_evaluation_of_breakpoint_conditions ())
6003     return condition_evaluation_host;
6004
6005   for (bl = b->loc; bl; bl = bl->next)
6006     {
6007       if (bl->cond_bytecode)
6008         target_evals++;
6009       else
6010         host_evals++;
6011     }
6012
6013   if (host_evals && target_evals)
6014     return condition_evaluation_both;
6015   else if (target_evals)
6016     return condition_evaluation_target;
6017   else
6018     return condition_evaluation_host;
6019 }
6020
6021 /* Determine the breakpoint location's condition evaluator.  This is
6022    similar to bp_condition_evaluator, but for locations.  */
6023
6024 static const char *
6025 bp_location_condition_evaluator (struct bp_location *bl)
6026 {
6027   if (bl && !is_breakpoint (bl->owner))
6028     return NULL;
6029
6030   if (gdb_evaluates_breakpoint_condition_p ()
6031       || !target_supports_evaluation_of_breakpoint_conditions ())
6032     return condition_evaluation_host;
6033
6034   if (bl && bl->cond_bytecode)
6035     return condition_evaluation_target;
6036   else
6037     return condition_evaluation_host;
6038 }
6039
6040 /* Print the LOC location out of the list of B->LOC locations.  */
6041
6042 static void
6043 print_breakpoint_location (struct breakpoint *b,
6044                            struct bp_location *loc)
6045 {
6046   struct ui_out *uiout = current_uiout;
6047   struct cleanup *old_chain = save_current_program_space ();
6048
6049   if (loc != NULL && loc->shlib_disabled)
6050     loc = NULL;
6051
6052   if (loc != NULL)
6053     set_current_program_space (loc->pspace);
6054
6055   if (b->display_canonical)
6056     ui_out_field_string (uiout, "what",
6057                          event_location_to_string (b->location));
6058   else if (loc && loc->symtab)
6059     {
6060       struct symbol *sym 
6061         = find_pc_sect_function (loc->address, loc->section);
6062       if (sym)
6063         {
6064           ui_out_text (uiout, "in ");
6065           ui_out_field_string (uiout, "func",
6066                                SYMBOL_PRINT_NAME (sym));
6067           ui_out_text (uiout, " ");
6068           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6069           ui_out_text (uiout, "at ");
6070         }
6071       ui_out_field_string (uiout, "file",
6072                            symtab_to_filename_for_display (loc->symtab));
6073       ui_out_text (uiout, ":");
6074
6075       if (ui_out_is_mi_like_p (uiout))
6076         ui_out_field_string (uiout, "fullname",
6077                              symtab_to_fullname (loc->symtab));
6078       
6079       ui_out_field_int (uiout, "line", loc->line_number);
6080     }
6081   else if (loc)
6082     {
6083       struct ui_file *stb = mem_fileopen ();
6084       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6085
6086       print_address_symbolic (loc->gdbarch, loc->address, stb,
6087                               demangle, "");
6088       ui_out_field_stream (uiout, "at", stb);
6089
6090       do_cleanups (stb_chain);
6091     }
6092   else
6093     {
6094       ui_out_field_string (uiout, "pending",
6095                            event_location_to_string (b->location));
6096       /* If extra_string is available, it could be holding a condition
6097          or dprintf arguments.  In either case, make sure it is printed,
6098          too, but only for non-MI streams.  */
6099       if (!ui_out_is_mi_like_p (uiout) && b->extra_string != NULL)
6100         {
6101           if (b->type == bp_dprintf)
6102             ui_out_text (uiout, ",");
6103           else
6104             ui_out_text (uiout, " ");
6105           ui_out_text (uiout, b->extra_string);
6106         }
6107     }
6108
6109   if (loc && is_breakpoint (b)
6110       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6111       && bp_condition_evaluator (b) == condition_evaluation_both)
6112     {
6113       ui_out_text (uiout, " (");
6114       ui_out_field_string (uiout, "evaluated-by",
6115                            bp_location_condition_evaluator (loc));
6116       ui_out_text (uiout, ")");
6117     }
6118
6119   do_cleanups (old_chain);
6120 }
6121
6122 static const char *
6123 bptype_string (enum bptype type)
6124 {
6125   struct ep_type_description
6126     {
6127       enum bptype type;
6128       char *description;
6129     };
6130   static struct ep_type_description bptypes[] =
6131   {
6132     {bp_none, "?deleted?"},
6133     {bp_breakpoint, "breakpoint"},
6134     {bp_hardware_breakpoint, "hw breakpoint"},
6135     {bp_single_step, "sw single-step"},
6136     {bp_until, "until"},
6137     {bp_finish, "finish"},
6138     {bp_watchpoint, "watchpoint"},
6139     {bp_hardware_watchpoint, "hw watchpoint"},
6140     {bp_read_watchpoint, "read watchpoint"},
6141     {bp_access_watchpoint, "acc watchpoint"},
6142     {bp_longjmp, "longjmp"},
6143     {bp_longjmp_resume, "longjmp resume"},
6144     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6145     {bp_exception, "exception"},
6146     {bp_exception_resume, "exception resume"},
6147     {bp_step_resume, "step resume"},
6148     {bp_hp_step_resume, "high-priority step resume"},
6149     {bp_watchpoint_scope, "watchpoint scope"},
6150     {bp_call_dummy, "call dummy"},
6151     {bp_std_terminate, "std::terminate"},
6152     {bp_shlib_event, "shlib events"},
6153     {bp_thread_event, "thread events"},
6154     {bp_overlay_event, "overlay events"},
6155     {bp_longjmp_master, "longjmp master"},
6156     {bp_std_terminate_master, "std::terminate master"},
6157     {bp_exception_master, "exception master"},
6158     {bp_catchpoint, "catchpoint"},
6159     {bp_tracepoint, "tracepoint"},
6160     {bp_fast_tracepoint, "fast tracepoint"},
6161     {bp_static_tracepoint, "static tracepoint"},
6162     {bp_dprintf, "dprintf"},
6163     {bp_jit_event, "jit events"},
6164     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6165     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6166   };
6167
6168   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6169       || ((int) type != bptypes[(int) type].type))
6170     internal_error (__FILE__, __LINE__,
6171                     _("bptypes table does not describe type #%d."),
6172                     (int) type);
6173
6174   return bptypes[(int) type].description;
6175 }
6176
6177 /* For MI, output a field named 'thread-groups' with a list as the value.
6178    For CLI, prefix the list with the string 'inf'. */
6179
6180 static void
6181 output_thread_groups (struct ui_out *uiout,
6182                       const char *field_name,
6183                       VEC(int) *inf_num,
6184                       int mi_only)
6185 {
6186   struct cleanup *back_to;
6187   int is_mi = ui_out_is_mi_like_p (uiout);
6188   int inf;
6189   int i;
6190
6191   /* For backward compatibility, don't display inferiors in CLI unless
6192      there are several.  Always display them for MI. */
6193   if (!is_mi && mi_only)
6194     return;
6195
6196   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6197
6198   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6199     {
6200       if (is_mi)
6201         {
6202           char mi_group[10];
6203
6204           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6205           ui_out_field_string (uiout, NULL, mi_group);
6206         }
6207       else
6208         {
6209           if (i == 0)
6210             ui_out_text (uiout, " inf ");
6211           else
6212             ui_out_text (uiout, ", ");
6213         
6214           ui_out_text (uiout, plongest (inf));
6215         }
6216     }
6217
6218   do_cleanups (back_to);
6219 }
6220
6221 /* Print B to gdb_stdout.  */
6222
6223 static void
6224 print_one_breakpoint_location (struct breakpoint *b,
6225                                struct bp_location *loc,
6226                                int loc_number,
6227                                struct bp_location **last_loc,
6228                                int allflag)
6229 {
6230   struct command_line *l;
6231   static char bpenables[] = "nynny";
6232
6233   struct ui_out *uiout = current_uiout;
6234   int header_of_multiple = 0;
6235   int part_of_multiple = (loc != NULL);
6236   struct value_print_options opts;
6237
6238   get_user_print_options (&opts);
6239
6240   gdb_assert (!loc || loc_number != 0);
6241   /* See comment in print_one_breakpoint concerning treatment of
6242      breakpoints with single disabled location.  */
6243   if (loc == NULL 
6244       && (b->loc != NULL 
6245           && (b->loc->next != NULL || !b->loc->enabled)))
6246     header_of_multiple = 1;
6247   if (loc == NULL)
6248     loc = b->loc;
6249
6250   annotate_record ();
6251
6252   /* 1 */
6253   annotate_field (0);
6254   if (part_of_multiple)
6255     {
6256       char *formatted;
6257       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6258       ui_out_field_string (uiout, "number", formatted);
6259       xfree (formatted);
6260     }
6261   else
6262     {
6263       ui_out_field_int (uiout, "number", b->number);
6264     }
6265
6266   /* 2 */
6267   annotate_field (1);
6268   if (part_of_multiple)
6269     ui_out_field_skip (uiout, "type");
6270   else
6271     ui_out_field_string (uiout, "type", bptype_string (b->type));
6272
6273   /* 3 */
6274   annotate_field (2);
6275   if (part_of_multiple)
6276     ui_out_field_skip (uiout, "disp");
6277   else
6278     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6279
6280
6281   /* 4 */
6282   annotate_field (3);
6283   if (part_of_multiple)
6284     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6285   else
6286     ui_out_field_fmt (uiout, "enabled", "%c", 
6287                       bpenables[(int) b->enable_state]);
6288   ui_out_spaces (uiout, 2);
6289
6290   
6291   /* 5 and 6 */
6292   if (b->ops != NULL && b->ops->print_one != NULL)
6293     {
6294       /* Although the print_one can possibly print all locations,
6295          calling it here is not likely to get any nice result.  So,
6296          make sure there's just one location.  */
6297       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6298       b->ops->print_one (b, last_loc);
6299     }
6300   else
6301     switch (b->type)
6302       {
6303       case bp_none:
6304         internal_error (__FILE__, __LINE__,
6305                         _("print_one_breakpoint: bp_none encountered\n"));
6306         break;
6307
6308       case bp_watchpoint:
6309       case bp_hardware_watchpoint:
6310       case bp_read_watchpoint:
6311       case bp_access_watchpoint:
6312         {
6313           struct watchpoint *w = (struct watchpoint *) b;
6314
6315           /* Field 4, the address, is omitted (which makes the columns
6316              not line up too nicely with the headers, but the effect
6317              is relatively readable).  */
6318           if (opts.addressprint)
6319             ui_out_field_skip (uiout, "addr");
6320           annotate_field (5);
6321           ui_out_field_string (uiout, "what", w->exp_string);
6322         }
6323         break;
6324
6325       case bp_breakpoint:
6326       case bp_hardware_breakpoint:
6327       case bp_single_step:
6328       case bp_until:
6329       case bp_finish:
6330       case bp_longjmp:
6331       case bp_longjmp_resume:
6332       case bp_longjmp_call_dummy:
6333       case bp_exception:
6334       case bp_exception_resume:
6335       case bp_step_resume:
6336       case bp_hp_step_resume:
6337       case bp_watchpoint_scope:
6338       case bp_call_dummy:
6339       case bp_std_terminate:
6340       case bp_shlib_event:
6341       case bp_thread_event:
6342       case bp_overlay_event:
6343       case bp_longjmp_master:
6344       case bp_std_terminate_master:
6345       case bp_exception_master:
6346       case bp_tracepoint:
6347       case bp_fast_tracepoint:
6348       case bp_static_tracepoint:
6349       case bp_dprintf:
6350       case bp_jit_event:
6351       case bp_gnu_ifunc_resolver:
6352       case bp_gnu_ifunc_resolver_return:
6353         if (opts.addressprint)
6354           {
6355             annotate_field (4);
6356             if (header_of_multiple)
6357               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6358             else if (b->loc == NULL || loc->shlib_disabled)
6359               ui_out_field_string (uiout, "addr", "<PENDING>");
6360             else
6361               ui_out_field_core_addr (uiout, "addr",
6362                                       loc->gdbarch, loc->address);
6363           }
6364         annotate_field (5);
6365         if (!header_of_multiple)
6366           print_breakpoint_location (b, loc);
6367         if (b->loc)
6368           *last_loc = b->loc;
6369         break;
6370       }
6371
6372
6373   if (loc != NULL && !header_of_multiple)
6374     {
6375       struct inferior *inf;
6376       VEC(int) *inf_num = NULL;
6377       int mi_only = 1;
6378
6379       ALL_INFERIORS (inf)
6380         {
6381           if (inf->pspace == loc->pspace)
6382             VEC_safe_push (int, inf_num, inf->num);
6383         }
6384
6385         /* For backward compatibility, don't display inferiors in CLI unless
6386            there are several.  Always display for MI. */
6387         if (allflag
6388             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6389                 && (number_of_program_spaces () > 1
6390                     || number_of_inferiors () > 1)
6391                 /* LOC is for existing B, it cannot be in
6392                    moribund_locations and thus having NULL OWNER.  */
6393                 && loc->owner->type != bp_catchpoint))
6394         mi_only = 0;
6395       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6396       VEC_free (int, inf_num);
6397     }
6398
6399   if (!part_of_multiple)
6400     {
6401       if (b->thread != -1)
6402         {
6403           /* FIXME: This seems to be redundant and lost here; see the
6404              "stop only in" line a little further down.  */
6405           ui_out_text (uiout, " thread ");
6406           ui_out_field_int (uiout, "thread", b->thread);
6407         }
6408       else if (b->task != 0)
6409         {
6410           ui_out_text (uiout, " task ");
6411           ui_out_field_int (uiout, "task", b->task);
6412         }
6413     }
6414
6415   ui_out_text (uiout, "\n");
6416
6417   if (!part_of_multiple)
6418     b->ops->print_one_detail (b, uiout);
6419
6420   if (part_of_multiple && frame_id_p (b->frame_id))
6421     {
6422       annotate_field (6);
6423       ui_out_text (uiout, "\tstop only in stack frame at ");
6424       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6425          the frame ID.  */
6426       ui_out_field_core_addr (uiout, "frame",
6427                               b->gdbarch, b->frame_id.stack_addr);
6428       ui_out_text (uiout, "\n");
6429     }
6430   
6431   if (!part_of_multiple && b->cond_string)
6432     {
6433       annotate_field (7);
6434       if (is_tracepoint (b))
6435         ui_out_text (uiout, "\ttrace only if ");
6436       else
6437         ui_out_text (uiout, "\tstop only if ");
6438       ui_out_field_string (uiout, "cond", b->cond_string);
6439
6440       /* Print whether the target is doing the breakpoint's condition
6441          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6442       if (is_breakpoint (b)
6443           && breakpoint_condition_evaluation_mode ()
6444           == condition_evaluation_target)
6445         {
6446           ui_out_text (uiout, " (");
6447           ui_out_field_string (uiout, "evaluated-by",
6448                                bp_condition_evaluator (b));
6449           ui_out_text (uiout, " evals)");
6450         }
6451       ui_out_text (uiout, "\n");
6452     }
6453
6454   if (!part_of_multiple && b->thread != -1)
6455     {
6456       /* FIXME should make an annotation for this.  */
6457       ui_out_text (uiout, "\tstop only in thread ");
6458       ui_out_field_int (uiout, "thread", b->thread);
6459       ui_out_text (uiout, "\n");
6460     }
6461   
6462   if (!part_of_multiple)
6463     {
6464       if (b->hit_count)
6465         {
6466           /* FIXME should make an annotation for this.  */
6467           if (is_catchpoint (b))
6468             ui_out_text (uiout, "\tcatchpoint");
6469           else if (is_tracepoint (b))
6470             ui_out_text (uiout, "\ttracepoint");
6471           else
6472             ui_out_text (uiout, "\tbreakpoint");
6473           ui_out_text (uiout, " already hit ");
6474           ui_out_field_int (uiout, "times", b->hit_count);
6475           if (b->hit_count == 1)
6476             ui_out_text (uiout, " time\n");
6477           else
6478             ui_out_text (uiout, " times\n");
6479         }
6480       else
6481         {
6482           /* Output the count also if it is zero, but only if this is mi.  */
6483           if (ui_out_is_mi_like_p (uiout))
6484             ui_out_field_int (uiout, "times", b->hit_count);
6485         }
6486     }
6487
6488   if (!part_of_multiple && b->ignore_count)
6489     {
6490       annotate_field (8);
6491       ui_out_text (uiout, "\tignore next ");
6492       ui_out_field_int (uiout, "ignore", b->ignore_count);
6493       ui_out_text (uiout, " hits\n");
6494     }
6495
6496   /* Note that an enable count of 1 corresponds to "enable once"
6497      behavior, which is reported by the combination of enablement and
6498      disposition, so we don't need to mention it here.  */
6499   if (!part_of_multiple && b->enable_count > 1)
6500     {
6501       annotate_field (8);
6502       ui_out_text (uiout, "\tdisable after ");
6503       /* Tweak the wording to clarify that ignore and enable counts
6504          are distinct, and have additive effect.  */
6505       if (b->ignore_count)
6506         ui_out_text (uiout, "additional ");
6507       else
6508         ui_out_text (uiout, "next ");
6509       ui_out_field_int (uiout, "enable", b->enable_count);
6510       ui_out_text (uiout, " hits\n");
6511     }
6512
6513   if (!part_of_multiple && is_tracepoint (b))
6514     {
6515       struct tracepoint *tp = (struct tracepoint *) b;
6516
6517       if (tp->traceframe_usage)
6518         {
6519           ui_out_text (uiout, "\ttrace buffer usage ");
6520           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6521           ui_out_text (uiout, " bytes\n");
6522         }
6523     }
6524
6525   l = b->commands ? b->commands->commands : NULL;
6526   if (!part_of_multiple && l)
6527     {
6528       struct cleanup *script_chain;
6529
6530       annotate_field (9);
6531       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6532       print_command_lines (uiout, l, 4);
6533       do_cleanups (script_chain);
6534     }
6535
6536   if (is_tracepoint (b))
6537     {
6538       struct tracepoint *t = (struct tracepoint *) b;
6539
6540       if (!part_of_multiple && t->pass_count)
6541         {
6542           annotate_field (10);
6543           ui_out_text (uiout, "\tpass count ");
6544           ui_out_field_int (uiout, "pass", t->pass_count);
6545           ui_out_text (uiout, " \n");
6546         }
6547
6548       /* Don't display it when tracepoint or tracepoint location is
6549          pending.   */
6550       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6551         {
6552           annotate_field (11);
6553
6554           if (ui_out_is_mi_like_p (uiout))
6555             ui_out_field_string (uiout, "installed",
6556                                  loc->inserted ? "y" : "n");
6557           else
6558             {
6559               if (loc->inserted)
6560                 ui_out_text (uiout, "\t");
6561               else
6562                 ui_out_text (uiout, "\tnot ");
6563               ui_out_text (uiout, "installed on target\n");
6564             }
6565         }
6566     }
6567
6568   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6569     {
6570       if (is_watchpoint (b))
6571         {
6572           struct watchpoint *w = (struct watchpoint *) b;
6573
6574           ui_out_field_string (uiout, "original-location", w->exp_string);
6575         }
6576       else if (b->location != NULL
6577                && event_location_to_string (b->location) != NULL)
6578         ui_out_field_string (uiout, "original-location",
6579                              event_location_to_string (b->location));
6580     }
6581 }
6582
6583 static void
6584 print_one_breakpoint (struct breakpoint *b,
6585                       struct bp_location **last_loc, 
6586                       int allflag)
6587 {
6588   struct cleanup *bkpt_chain;
6589   struct ui_out *uiout = current_uiout;
6590
6591   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6592
6593   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6594   do_cleanups (bkpt_chain);
6595
6596   /* If this breakpoint has custom print function,
6597      it's already printed.  Otherwise, print individual
6598      locations, if any.  */
6599   if (b->ops == NULL || b->ops->print_one == NULL)
6600     {
6601       /* If breakpoint has a single location that is disabled, we
6602          print it as if it had several locations, since otherwise it's
6603          hard to represent "breakpoint enabled, location disabled"
6604          situation.
6605
6606          Note that while hardware watchpoints have several locations
6607          internally, that's not a property exposed to user.  */
6608       if (b->loc 
6609           && !is_hardware_watchpoint (b)
6610           && (b->loc->next || !b->loc->enabled))
6611         {
6612           struct bp_location *loc;
6613           int n = 1;
6614
6615           for (loc = b->loc; loc; loc = loc->next, ++n)
6616             {
6617               struct cleanup *inner2 =
6618                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6619               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6620               do_cleanups (inner2);
6621             }
6622         }
6623     }
6624 }
6625
6626 static int
6627 breakpoint_address_bits (struct breakpoint *b)
6628 {
6629   int print_address_bits = 0;
6630   struct bp_location *loc;
6631
6632   for (loc = b->loc; loc; loc = loc->next)
6633     {
6634       int addr_bit;
6635
6636       /* Software watchpoints that aren't watching memory don't have
6637          an address to print.  */
6638       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6639         continue;
6640
6641       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6642       if (addr_bit > print_address_bits)
6643         print_address_bits = addr_bit;
6644     }
6645
6646   return print_address_bits;
6647 }
6648
6649 struct captured_breakpoint_query_args
6650   {
6651     int bnum;
6652   };
6653
6654 static int
6655 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6656 {
6657   struct captured_breakpoint_query_args *args
6658     = (struct captured_breakpoint_query_args *) data;
6659   struct breakpoint *b;
6660   struct bp_location *dummy_loc = NULL;
6661
6662   ALL_BREAKPOINTS (b)
6663     {
6664       if (args->bnum == b->number)
6665         {
6666           print_one_breakpoint (b, &dummy_loc, 0);
6667           return GDB_RC_OK;
6668         }
6669     }
6670   return GDB_RC_NONE;
6671 }
6672
6673 enum gdb_rc
6674 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6675                       char **error_message)
6676 {
6677   struct captured_breakpoint_query_args args;
6678
6679   args.bnum = bnum;
6680   /* For the moment we don't trust print_one_breakpoint() to not throw
6681      an error.  */
6682   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6683                                  error_message, RETURN_MASK_ALL) < 0)
6684     return GDB_RC_FAIL;
6685   else
6686     return GDB_RC_OK;
6687 }
6688
6689 /* Return true if this breakpoint was set by the user, false if it is
6690    internal or momentary.  */
6691
6692 int
6693 user_breakpoint_p (struct breakpoint *b)
6694 {
6695   return b->number > 0;
6696 }
6697
6698 /* Print information on user settable breakpoint (watchpoint, etc)
6699    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6700    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6701    FILTER is non-NULL, call it on each breakpoint and only include the
6702    ones for which it returns non-zero.  Return the total number of
6703    breakpoints listed.  */
6704
6705 static int
6706 breakpoint_1 (char *args, int allflag, 
6707               int (*filter) (const struct breakpoint *))
6708 {
6709   struct breakpoint *b;
6710   struct bp_location *last_loc = NULL;
6711   int nr_printable_breakpoints;
6712   struct cleanup *bkpttbl_chain;
6713   struct value_print_options opts;
6714   int print_address_bits = 0;
6715   int print_type_col_width = 14;
6716   struct ui_out *uiout = current_uiout;
6717
6718   get_user_print_options (&opts);
6719
6720   /* Compute the number of rows in the table, as well as the size
6721      required for address fields.  */
6722   nr_printable_breakpoints = 0;
6723   ALL_BREAKPOINTS (b)
6724     {
6725       /* If we have a filter, only list the breakpoints it accepts.  */
6726       if (filter && !filter (b))
6727         continue;
6728
6729       /* If we have an "args" string, it is a list of breakpoints to 
6730          accept.  Skip the others.  */
6731       if (args != NULL && *args != '\0')
6732         {
6733           if (allflag && parse_and_eval_long (args) != b->number)
6734             continue;
6735           if (!allflag && !number_is_in_list (args, b->number))
6736             continue;
6737         }
6738
6739       if (allflag || user_breakpoint_p (b))
6740         {
6741           int addr_bit, type_len;
6742
6743           addr_bit = breakpoint_address_bits (b);
6744           if (addr_bit > print_address_bits)
6745             print_address_bits = addr_bit;
6746
6747           type_len = strlen (bptype_string (b->type));
6748           if (type_len > print_type_col_width)
6749             print_type_col_width = type_len;
6750
6751           nr_printable_breakpoints++;
6752         }
6753     }
6754
6755   if (opts.addressprint)
6756     bkpttbl_chain 
6757       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6758                                              nr_printable_breakpoints,
6759                                              "BreakpointTable");
6760   else
6761     bkpttbl_chain 
6762       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6763                                              nr_printable_breakpoints,
6764                                              "BreakpointTable");
6765
6766   if (nr_printable_breakpoints > 0)
6767     annotate_breakpoints_headers ();
6768   if (nr_printable_breakpoints > 0)
6769     annotate_field (0);
6770   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6771   if (nr_printable_breakpoints > 0)
6772     annotate_field (1);
6773   ui_out_table_header (uiout, print_type_col_width, ui_left,
6774                        "type", "Type");                         /* 2 */
6775   if (nr_printable_breakpoints > 0)
6776     annotate_field (2);
6777   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6778   if (nr_printable_breakpoints > 0)
6779     annotate_field (3);
6780   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6781   if (opts.addressprint)
6782     {
6783       if (nr_printable_breakpoints > 0)
6784         annotate_field (4);
6785       if (print_address_bits <= 32)
6786         ui_out_table_header (uiout, 10, ui_left, 
6787                              "addr", "Address");                /* 5 */
6788       else
6789         ui_out_table_header (uiout, 18, ui_left, 
6790                              "addr", "Address");                /* 5 */
6791     }
6792   if (nr_printable_breakpoints > 0)
6793     annotate_field (5);
6794   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6795   ui_out_table_body (uiout);
6796   if (nr_printable_breakpoints > 0)
6797     annotate_breakpoints_table ();
6798
6799   ALL_BREAKPOINTS (b)
6800     {
6801       QUIT;
6802       /* If we have a filter, only list the breakpoints it accepts.  */
6803       if (filter && !filter (b))
6804         continue;
6805
6806       /* If we have an "args" string, it is a list of breakpoints to 
6807          accept.  Skip the others.  */
6808
6809       if (args != NULL && *args != '\0')
6810         {
6811           if (allflag)  /* maintenance info breakpoint */
6812             {
6813               if (parse_and_eval_long (args) != b->number)
6814                 continue;
6815             }
6816           else          /* all others */
6817             {
6818               if (!number_is_in_list (args, b->number))
6819                 continue;
6820             }
6821         }
6822       /* We only print out user settable breakpoints unless the
6823          allflag is set.  */
6824       if (allflag || user_breakpoint_p (b))
6825         print_one_breakpoint (b, &last_loc, allflag);
6826     }
6827
6828   do_cleanups (bkpttbl_chain);
6829
6830   if (nr_printable_breakpoints == 0)
6831     {
6832       /* If there's a filter, let the caller decide how to report
6833          empty list.  */
6834       if (!filter)
6835         {
6836           if (args == NULL || *args == '\0')
6837             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6838           else
6839             ui_out_message (uiout, 0, 
6840                             "No breakpoint or watchpoint matching '%s'.\n",
6841                             args);
6842         }
6843     }
6844   else
6845     {
6846       if (last_loc && !server_command)
6847         set_next_address (last_loc->gdbarch, last_loc->address);
6848     }
6849
6850   /* FIXME?  Should this be moved up so that it is only called when
6851      there have been breakpoints? */
6852   annotate_breakpoints_table_end ();
6853
6854   return nr_printable_breakpoints;
6855 }
6856
6857 /* Display the value of default-collect in a way that is generally
6858    compatible with the breakpoint list.  */
6859
6860 static void
6861 default_collect_info (void)
6862 {
6863   struct ui_out *uiout = current_uiout;
6864
6865   /* If it has no value (which is frequently the case), say nothing; a
6866      message like "No default-collect." gets in user's face when it's
6867      not wanted.  */
6868   if (!*default_collect)
6869     return;
6870
6871   /* The following phrase lines up nicely with per-tracepoint collect
6872      actions.  */
6873   ui_out_text (uiout, "default collect ");
6874   ui_out_field_string (uiout, "default-collect", default_collect);
6875   ui_out_text (uiout, " \n");
6876 }
6877   
6878 static void
6879 breakpoints_info (char *args, int from_tty)
6880 {
6881   breakpoint_1 (args, 0, NULL);
6882
6883   default_collect_info ();
6884 }
6885
6886 static void
6887 watchpoints_info (char *args, int from_tty)
6888 {
6889   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6890   struct ui_out *uiout = current_uiout;
6891
6892   if (num_printed == 0)
6893     {
6894       if (args == NULL || *args == '\0')
6895         ui_out_message (uiout, 0, "No watchpoints.\n");
6896       else
6897         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6898     }
6899 }
6900
6901 static void
6902 maintenance_info_breakpoints (char *args, int from_tty)
6903 {
6904   breakpoint_1 (args, 1, NULL);
6905
6906   default_collect_info ();
6907 }
6908
6909 static int
6910 breakpoint_has_pc (struct breakpoint *b,
6911                    struct program_space *pspace,
6912                    CORE_ADDR pc, struct obj_section *section)
6913 {
6914   struct bp_location *bl = b->loc;
6915
6916   for (; bl; bl = bl->next)
6917     {
6918       if (bl->pspace == pspace
6919           && bl->address == pc
6920           && (!overlay_debugging || bl->section == section))
6921         return 1;         
6922     }
6923   return 0;
6924 }
6925
6926 /* Print a message describing any user-breakpoints set at PC.  This
6927    concerns with logical breakpoints, so we match program spaces, not
6928    address spaces.  */
6929
6930 static void
6931 describe_other_breakpoints (struct gdbarch *gdbarch,
6932                             struct program_space *pspace, CORE_ADDR pc,
6933                             struct obj_section *section, int thread)
6934 {
6935   int others = 0;
6936   struct breakpoint *b;
6937
6938   ALL_BREAKPOINTS (b)
6939     others += (user_breakpoint_p (b)
6940                && breakpoint_has_pc (b, pspace, pc, section));
6941   if (others > 0)
6942     {
6943       if (others == 1)
6944         printf_filtered (_("Note: breakpoint "));
6945       else /* if (others == ???) */
6946         printf_filtered (_("Note: breakpoints "));
6947       ALL_BREAKPOINTS (b)
6948         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6949           {
6950             others--;
6951             printf_filtered ("%d", b->number);
6952             if (b->thread == -1 && thread != -1)
6953               printf_filtered (" (all threads)");
6954             else if (b->thread != -1)
6955               printf_filtered (" (thread %d)", b->thread);
6956             printf_filtered ("%s%s ",
6957                              ((b->enable_state == bp_disabled
6958                                || b->enable_state == bp_call_disabled)
6959                               ? " (disabled)"
6960                               : ""),
6961                              (others > 1) ? "," 
6962                              : ((others == 1) ? " and" : ""));
6963           }
6964       printf_filtered (_("also set at pc "));
6965       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6966       printf_filtered (".\n");
6967     }
6968 }
6969 \f
6970
6971 /* Return true iff it is meaningful to use the address member of
6972    BPT locations.  For some breakpoint types, the locations' address members
6973    are irrelevant and it makes no sense to attempt to compare them to other
6974    addresses (or use them for any other purpose either).
6975
6976    More specifically, each of the following breakpoint types will
6977    always have a zero valued location address and we don't want to mark
6978    breakpoints of any of these types to be a duplicate of an actual
6979    breakpoint location at address zero:
6980
6981       bp_watchpoint
6982       bp_catchpoint
6983
6984 */
6985
6986 static int
6987 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6988 {
6989   enum bptype type = bpt->type;
6990
6991   return (type != bp_watchpoint && type != bp_catchpoint);
6992 }
6993
6994 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6995    true if LOC1 and LOC2 represent the same watchpoint location.  */
6996
6997 static int
6998 watchpoint_locations_match (struct bp_location *loc1, 
6999                             struct bp_location *loc2)
7000 {
7001   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7002   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7003
7004   /* Both of them must exist.  */
7005   gdb_assert (w1 != NULL);
7006   gdb_assert (w2 != NULL);
7007
7008   /* If the target can evaluate the condition expression in hardware,
7009      then we we need to insert both watchpoints even if they are at
7010      the same place.  Otherwise the watchpoint will only trigger when
7011      the condition of whichever watchpoint was inserted evaluates to
7012      true, not giving a chance for GDB to check the condition of the
7013      other watchpoint.  */
7014   if ((w1->cond_exp
7015        && target_can_accel_watchpoint_condition (loc1->address, 
7016                                                  loc1->length,
7017                                                  loc1->watchpoint_type,
7018                                                  w1->cond_exp))
7019       || (w2->cond_exp
7020           && target_can_accel_watchpoint_condition (loc2->address, 
7021                                                     loc2->length,
7022                                                     loc2->watchpoint_type,
7023                                                     w2->cond_exp)))
7024     return 0;
7025
7026   /* Note that this checks the owner's type, not the location's.  In
7027      case the target does not support read watchpoints, but does
7028      support access watchpoints, we'll have bp_read_watchpoint
7029      watchpoints with hw_access locations.  Those should be considered
7030      duplicates of hw_read locations.  The hw_read locations will
7031      become hw_access locations later.  */
7032   return (loc1->owner->type == loc2->owner->type
7033           && loc1->pspace->aspace == loc2->pspace->aspace
7034           && loc1->address == loc2->address
7035           && loc1->length == loc2->length);
7036 }
7037
7038 /* See breakpoint.h.  */
7039
7040 int
7041 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7042                           struct address_space *aspace2, CORE_ADDR addr2)
7043 {
7044   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7045            || aspace1 == aspace2)
7046           && addr1 == addr2);
7047 }
7048
7049 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7050    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7051    matches ASPACE2.  On targets that have global breakpoints, the address
7052    space doesn't really matter.  */
7053
7054 static int
7055 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7056                                 int len1, struct address_space *aspace2,
7057                                 CORE_ADDR addr2)
7058 {
7059   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7060            || aspace1 == aspace2)
7061           && addr2 >= addr1 && addr2 < addr1 + len1);
7062 }
7063
7064 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7065    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7066    matches the breakpoint's address space.  On targets that have global
7067    breakpoints, the address space doesn't really matter.  */
7068
7069 static int
7070 breakpoint_location_address_match (struct bp_location *bl,
7071                                    struct address_space *aspace,
7072                                    CORE_ADDR addr)
7073 {
7074   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7075                                     aspace, addr)
7076           || (bl->length
7077               && breakpoint_address_match_range (bl->pspace->aspace,
7078                                                  bl->address, bl->length,
7079                                                  aspace, addr)));
7080 }
7081
7082 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7083    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7084    true, otherwise returns false.  */
7085
7086 static int
7087 tracepoint_locations_match (struct bp_location *loc1,
7088                             struct bp_location *loc2)
7089 {
7090   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7091     /* Since tracepoint locations are never duplicated with others', tracepoint
7092        locations at the same address of different tracepoints are regarded as
7093        different locations.  */
7094     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7095   else
7096     return 0;
7097 }
7098
7099 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7100    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7101    represent the same location.  */
7102
7103 static int
7104 breakpoint_locations_match (struct bp_location *loc1, 
7105                             struct bp_location *loc2)
7106 {
7107   int hw_point1, hw_point2;
7108
7109   /* Both of them must not be in moribund_locations.  */
7110   gdb_assert (loc1->owner != NULL);
7111   gdb_assert (loc2->owner != NULL);
7112
7113   hw_point1 = is_hardware_watchpoint (loc1->owner);
7114   hw_point2 = is_hardware_watchpoint (loc2->owner);
7115
7116   if (hw_point1 != hw_point2)
7117     return 0;
7118   else if (hw_point1)
7119     return watchpoint_locations_match (loc1, loc2);
7120   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7121     return tracepoint_locations_match (loc1, loc2);
7122   else
7123     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7124     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7125                                      loc2->pspace->aspace, loc2->address)
7126             && loc1->length == loc2->length);
7127 }
7128
7129 static void
7130 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7131                                int bnum, int have_bnum)
7132 {
7133   /* The longest string possibly returned by hex_string_custom
7134      is 50 chars.  These must be at least that big for safety.  */
7135   char astr1[64];
7136   char astr2[64];
7137
7138   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7139   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7140   if (have_bnum)
7141     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7142              bnum, astr1, astr2);
7143   else
7144     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7145 }
7146
7147 /* Adjust a breakpoint's address to account for architectural
7148    constraints on breakpoint placement.  Return the adjusted address.
7149    Note: Very few targets require this kind of adjustment.  For most
7150    targets, this function is simply the identity function.  */
7151
7152 static CORE_ADDR
7153 adjust_breakpoint_address (struct gdbarch *gdbarch,
7154                            CORE_ADDR bpaddr, enum bptype bptype)
7155 {
7156   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7157     {
7158       /* Very few targets need any kind of breakpoint adjustment.  */
7159       return bpaddr;
7160     }
7161   else if (bptype == bp_watchpoint
7162            || bptype == bp_hardware_watchpoint
7163            || bptype == bp_read_watchpoint
7164            || bptype == bp_access_watchpoint
7165            || bptype == bp_catchpoint)
7166     {
7167       /* Watchpoints and the various bp_catch_* eventpoints should not
7168          have their addresses modified.  */
7169       return bpaddr;
7170     }
7171   else if (bptype == bp_single_step)
7172     {
7173       /* Single-step breakpoints should not have their addresses
7174          modified.  If there's any architectural constrain that
7175          applies to this address, then it should have already been
7176          taken into account when the breakpoint was created in the
7177          first place.  If we didn't do this, stepping through e.g.,
7178          Thumb-2 IT blocks would break.  */
7179       return bpaddr;
7180     }
7181   else
7182     {
7183       CORE_ADDR adjusted_bpaddr;
7184
7185       /* Some targets have architectural constraints on the placement
7186          of breakpoint instructions.  Obtain the adjusted address.  */
7187       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7188
7189       /* An adjusted breakpoint address can significantly alter
7190          a user's expectations.  Print a warning if an adjustment
7191          is required.  */
7192       if (adjusted_bpaddr != bpaddr)
7193         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7194
7195       return adjusted_bpaddr;
7196     }
7197 }
7198
7199 void
7200 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7201                   struct breakpoint *owner)
7202 {
7203   memset (loc, 0, sizeof (*loc));
7204
7205   gdb_assert (ops != NULL);
7206
7207   loc->ops = ops;
7208   loc->owner = owner;
7209   loc->cond = NULL;
7210   loc->cond_bytecode = NULL;
7211   loc->shlib_disabled = 0;
7212   loc->enabled = 1;
7213
7214   switch (owner->type)
7215     {
7216     case bp_breakpoint:
7217     case bp_single_step:
7218     case bp_until:
7219     case bp_finish:
7220     case bp_longjmp:
7221     case bp_longjmp_resume:
7222     case bp_longjmp_call_dummy:
7223     case bp_exception:
7224     case bp_exception_resume:
7225     case bp_step_resume:
7226     case bp_hp_step_resume:
7227     case bp_watchpoint_scope:
7228     case bp_call_dummy:
7229     case bp_std_terminate:
7230     case bp_shlib_event:
7231     case bp_thread_event:
7232     case bp_overlay_event:
7233     case bp_jit_event:
7234     case bp_longjmp_master:
7235     case bp_std_terminate_master:
7236     case bp_exception_master:
7237     case bp_gnu_ifunc_resolver:
7238     case bp_gnu_ifunc_resolver_return:
7239     case bp_dprintf:
7240       loc->loc_type = bp_loc_software_breakpoint;
7241       mark_breakpoint_location_modified (loc);
7242       break;
7243     case bp_hardware_breakpoint:
7244       loc->loc_type = bp_loc_hardware_breakpoint;
7245       mark_breakpoint_location_modified (loc);
7246       break;
7247     case bp_hardware_watchpoint:
7248     case bp_read_watchpoint:
7249     case bp_access_watchpoint:
7250       loc->loc_type = bp_loc_hardware_watchpoint;
7251       break;
7252     case bp_watchpoint:
7253     case bp_catchpoint:
7254     case bp_tracepoint:
7255     case bp_fast_tracepoint:
7256     case bp_static_tracepoint:
7257       loc->loc_type = bp_loc_other;
7258       break;
7259     default:
7260       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7261     }
7262
7263   loc->refc = 1;
7264 }
7265
7266 /* Allocate a struct bp_location.  */
7267
7268 static struct bp_location *
7269 allocate_bp_location (struct breakpoint *bpt)
7270 {
7271   return bpt->ops->allocate_location (bpt);
7272 }
7273
7274 static void
7275 free_bp_location (struct bp_location *loc)
7276 {
7277   loc->ops->dtor (loc);
7278   xfree (loc);
7279 }
7280
7281 /* Increment reference count.  */
7282
7283 static void
7284 incref_bp_location (struct bp_location *bl)
7285 {
7286   ++bl->refc;
7287 }
7288
7289 /* Decrement reference count.  If the reference count reaches 0,
7290    destroy the bp_location.  Sets *BLP to NULL.  */
7291
7292 static void
7293 decref_bp_location (struct bp_location **blp)
7294 {
7295   gdb_assert ((*blp)->refc > 0);
7296
7297   if (--(*blp)->refc == 0)
7298     free_bp_location (*blp);
7299   *blp = NULL;
7300 }
7301
7302 /* Add breakpoint B at the end of the global breakpoint chain.  */
7303
7304 static void
7305 add_to_breakpoint_chain (struct breakpoint *b)
7306 {
7307   struct breakpoint *b1;
7308
7309   /* Add this breakpoint to the end of the chain so that a list of
7310      breakpoints will come out in order of increasing numbers.  */
7311
7312   b1 = breakpoint_chain;
7313   if (b1 == 0)
7314     breakpoint_chain = b;
7315   else
7316     {
7317       while (b1->next)
7318         b1 = b1->next;
7319       b1->next = b;
7320     }
7321 }
7322
7323 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7324
7325 static void
7326 init_raw_breakpoint_without_location (struct breakpoint *b,
7327                                       struct gdbarch *gdbarch,
7328                                       enum bptype bptype,
7329                                       const struct breakpoint_ops *ops)
7330 {
7331   memset (b, 0, sizeof (*b));
7332
7333   gdb_assert (ops != NULL);
7334
7335   b->ops = ops;
7336   b->type = bptype;
7337   b->gdbarch = gdbarch;
7338   b->language = current_language->la_language;
7339   b->input_radix = input_radix;
7340   b->thread = -1;
7341   b->enable_state = bp_enabled;
7342   b->next = 0;
7343   b->silent = 0;
7344   b->ignore_count = 0;
7345   b->commands = NULL;
7346   b->frame_id = null_frame_id;
7347   b->condition_not_parsed = 0;
7348   b->py_bp_object = NULL;
7349   b->related_breakpoint = b;
7350   b->location = NULL;
7351 }
7352
7353 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7354    that has type BPTYPE and has no locations as yet.  */
7355
7356 static struct breakpoint *
7357 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7358                                      enum bptype bptype,
7359                                      const struct breakpoint_ops *ops)
7360 {
7361   struct breakpoint *b = XNEW (struct breakpoint);
7362
7363   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7364   add_to_breakpoint_chain (b);
7365   return b;
7366 }
7367
7368 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7369    resolutions should be made as the user specified the location explicitly
7370    enough.  */
7371
7372 static void
7373 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7374 {
7375   gdb_assert (loc->owner != NULL);
7376
7377   if (loc->owner->type == bp_breakpoint
7378       || loc->owner->type == bp_hardware_breakpoint
7379       || is_tracepoint (loc->owner))
7380     {
7381       int is_gnu_ifunc;
7382       const char *function_name;
7383       CORE_ADDR func_addr;
7384
7385       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7386                                           &func_addr, NULL, &is_gnu_ifunc);
7387
7388       if (is_gnu_ifunc && !explicit_loc)
7389         {
7390           struct breakpoint *b = loc->owner;
7391
7392           gdb_assert (loc->pspace == current_program_space);
7393           if (gnu_ifunc_resolve_name (function_name,
7394                                       &loc->requested_address))
7395             {
7396               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7397               loc->address = adjust_breakpoint_address (loc->gdbarch,
7398                                                         loc->requested_address,
7399                                                         b->type);
7400             }
7401           else if (b->type == bp_breakpoint && b->loc == loc
7402                    && loc->next == NULL && b->related_breakpoint == b)
7403             {
7404               /* Create only the whole new breakpoint of this type but do not
7405                  mess more complicated breakpoints with multiple locations.  */
7406               b->type = bp_gnu_ifunc_resolver;
7407               /* Remember the resolver's address for use by the return
7408                  breakpoint.  */
7409               loc->related_address = func_addr;
7410             }
7411         }
7412
7413       if (function_name)
7414         loc->function_name = xstrdup (function_name);
7415     }
7416 }
7417
7418 /* Attempt to determine architecture of location identified by SAL.  */
7419 struct gdbarch *
7420 get_sal_arch (struct symtab_and_line sal)
7421 {
7422   if (sal.section)
7423     return get_objfile_arch (sal.section->objfile);
7424   if (sal.symtab)
7425     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7426
7427   return NULL;
7428 }
7429
7430 /* Low level routine for partially initializing a breakpoint of type
7431    BPTYPE.  The newly created breakpoint's address, section, source
7432    file name, and line number are provided by SAL.
7433
7434    It is expected that the caller will complete the initialization of
7435    the newly created breakpoint struct as well as output any status
7436    information regarding the creation of a new breakpoint.  */
7437
7438 static void
7439 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7440                      struct symtab_and_line sal, enum bptype bptype,
7441                      const struct breakpoint_ops *ops)
7442 {
7443   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7444
7445   add_location_to_breakpoint (b, &sal);
7446
7447   if (bptype != bp_catchpoint)
7448     gdb_assert (sal.pspace != NULL);
7449
7450   /* Store the program space that was used to set the breakpoint,
7451      except for ordinary breakpoints, which are independent of the
7452      program space.  */
7453   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7454     b->pspace = sal.pspace;
7455 }
7456
7457 /* set_raw_breakpoint is a low level routine for allocating and
7458    partially initializing a breakpoint of type BPTYPE.  The newly
7459    created breakpoint's address, section, source file name, and line
7460    number are provided by SAL.  The newly created and partially
7461    initialized breakpoint is added to the breakpoint chain and
7462    is also returned as the value of this function.
7463
7464    It is expected that the caller will complete the initialization of
7465    the newly created breakpoint struct as well as output any status
7466    information regarding the creation of a new breakpoint.  In
7467    particular, set_raw_breakpoint does NOT set the breakpoint
7468    number!  Care should be taken to not allow an error to occur
7469    prior to completing the initialization of the breakpoint.  If this
7470    should happen, a bogus breakpoint will be left on the chain.  */
7471
7472 struct breakpoint *
7473 set_raw_breakpoint (struct gdbarch *gdbarch,
7474                     struct symtab_and_line sal, enum bptype bptype,
7475                     const struct breakpoint_ops *ops)
7476 {
7477   struct breakpoint *b = XNEW (struct breakpoint);
7478
7479   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7480   add_to_breakpoint_chain (b);
7481   return b;
7482 }
7483
7484 /* Call this routine when stepping and nexting to enable a breakpoint
7485    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7486    initiated the operation.  */
7487
7488 void
7489 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7490 {
7491   struct breakpoint *b, *b_tmp;
7492   int thread = tp->num;
7493
7494   /* To avoid having to rescan all objfile symbols at every step,
7495      we maintain a list of continually-inserted but always disabled
7496      longjmp "master" breakpoints.  Here, we simply create momentary
7497      clones of those and enable them for the requested thread.  */
7498   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7499     if (b->pspace == current_program_space
7500         && (b->type == bp_longjmp_master
7501             || b->type == bp_exception_master))
7502       {
7503         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7504         struct breakpoint *clone;
7505
7506         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7507            after their removal.  */
7508         clone = momentary_breakpoint_from_master (b, type,
7509                                                   &longjmp_breakpoint_ops, 1);
7510         clone->thread = thread;
7511       }
7512
7513   tp->initiating_frame = frame;
7514 }
7515
7516 /* Delete all longjmp breakpoints from THREAD.  */
7517 void
7518 delete_longjmp_breakpoint (int thread)
7519 {
7520   struct breakpoint *b, *b_tmp;
7521
7522   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7523     if (b->type == bp_longjmp || b->type == bp_exception)
7524       {
7525         if (b->thread == thread)
7526           delete_breakpoint (b);
7527       }
7528 }
7529
7530 void
7531 delete_longjmp_breakpoint_at_next_stop (int thread)
7532 {
7533   struct breakpoint *b, *b_tmp;
7534
7535   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7536     if (b->type == bp_longjmp || b->type == bp_exception)
7537       {
7538         if (b->thread == thread)
7539           b->disposition = disp_del_at_next_stop;
7540       }
7541 }
7542
7543 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7544    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7545    pointer to any of them.  Return NULL if this system cannot place longjmp
7546    breakpoints.  */
7547
7548 struct breakpoint *
7549 set_longjmp_breakpoint_for_call_dummy (void)
7550 {
7551   struct breakpoint *b, *retval = NULL;
7552
7553   ALL_BREAKPOINTS (b)
7554     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7555       {
7556         struct breakpoint *new_b;
7557
7558         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7559                                                   &momentary_breakpoint_ops,
7560                                                   1);
7561         new_b->thread = pid_to_thread_id (inferior_ptid);
7562
7563         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7564
7565         gdb_assert (new_b->related_breakpoint == new_b);
7566         if (retval == NULL)
7567           retval = new_b;
7568         new_b->related_breakpoint = retval;
7569         while (retval->related_breakpoint != new_b->related_breakpoint)
7570           retval = retval->related_breakpoint;
7571         retval->related_breakpoint = new_b;
7572       }
7573
7574   return retval;
7575 }
7576
7577 /* Verify all existing dummy frames and their associated breakpoints for
7578    TP.  Remove those which can no longer be found in the current frame
7579    stack.
7580
7581    You should call this function only at places where it is safe to currently
7582    unwind the whole stack.  Failed stack unwind would discard live dummy
7583    frames.  */
7584
7585 void
7586 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7587 {
7588   struct breakpoint *b, *b_tmp;
7589
7590   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7591     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7592       {
7593         struct breakpoint *dummy_b = b->related_breakpoint;
7594
7595         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7596           dummy_b = dummy_b->related_breakpoint;
7597         if (dummy_b->type != bp_call_dummy
7598             || frame_find_by_id (dummy_b->frame_id) != NULL)
7599           continue;
7600         
7601         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7602
7603         while (b->related_breakpoint != b)
7604           {
7605             if (b_tmp == b->related_breakpoint)
7606               b_tmp = b->related_breakpoint->next;
7607             delete_breakpoint (b->related_breakpoint);
7608           }
7609         delete_breakpoint (b);
7610       }
7611 }
7612
7613 void
7614 enable_overlay_breakpoints (void)
7615 {
7616   struct breakpoint *b;
7617
7618   ALL_BREAKPOINTS (b)
7619     if (b->type == bp_overlay_event)
7620     {
7621       b->enable_state = bp_enabled;
7622       update_global_location_list (UGLL_MAY_INSERT);
7623       overlay_events_enabled = 1;
7624     }
7625 }
7626
7627 void
7628 disable_overlay_breakpoints (void)
7629 {
7630   struct breakpoint *b;
7631
7632   ALL_BREAKPOINTS (b)
7633     if (b->type == bp_overlay_event)
7634     {
7635       b->enable_state = bp_disabled;
7636       update_global_location_list (UGLL_DONT_INSERT);
7637       overlay_events_enabled = 0;
7638     }
7639 }
7640
7641 /* Set an active std::terminate breakpoint for each std::terminate
7642    master breakpoint.  */
7643 void
7644 set_std_terminate_breakpoint (void)
7645 {
7646   struct breakpoint *b, *b_tmp;
7647
7648   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7649     if (b->pspace == current_program_space
7650         && b->type == bp_std_terminate_master)
7651       {
7652         momentary_breakpoint_from_master (b, bp_std_terminate,
7653                                           &momentary_breakpoint_ops, 1);
7654       }
7655 }
7656
7657 /* Delete all the std::terminate breakpoints.  */
7658 void
7659 delete_std_terminate_breakpoint (void)
7660 {
7661   struct breakpoint *b, *b_tmp;
7662
7663   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7664     if (b->type == bp_std_terminate)
7665       delete_breakpoint (b);
7666 }
7667
7668 struct breakpoint *
7669 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7670 {
7671   struct breakpoint *b;
7672
7673   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7674                                   &internal_breakpoint_ops);
7675
7676   b->enable_state = bp_enabled;
7677   /* location has to be used or breakpoint_re_set will delete me.  */
7678   b->location = new_address_location (b->loc->address);
7679
7680   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7681
7682   return b;
7683 }
7684
7685 void
7686 remove_thread_event_breakpoints (void)
7687 {
7688   struct breakpoint *b, *b_tmp;
7689
7690   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7691     if (b->type == bp_thread_event
7692         && b->loc->pspace == current_program_space)
7693       delete_breakpoint (b);
7694 }
7695
7696 struct lang_and_radix
7697   {
7698     enum language lang;
7699     int radix;
7700   };
7701
7702 /* Create a breakpoint for JIT code registration and unregistration.  */
7703
7704 struct breakpoint *
7705 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7706 {
7707   struct breakpoint *b;
7708
7709   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7710                                   &internal_breakpoint_ops);
7711   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7712   return b;
7713 }
7714
7715 /* Remove JIT code registration and unregistration breakpoint(s).  */
7716
7717 void
7718 remove_jit_event_breakpoints (void)
7719 {
7720   struct breakpoint *b, *b_tmp;
7721
7722   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7723     if (b->type == bp_jit_event
7724         && b->loc->pspace == current_program_space)
7725       delete_breakpoint (b);
7726 }
7727
7728 void
7729 remove_solib_event_breakpoints (void)
7730 {
7731   struct breakpoint *b, *b_tmp;
7732
7733   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7734     if (b->type == bp_shlib_event
7735         && b->loc->pspace == current_program_space)
7736       delete_breakpoint (b);
7737 }
7738
7739 /* See breakpoint.h.  */
7740
7741 void
7742 remove_solib_event_breakpoints_at_next_stop (void)
7743 {
7744   struct breakpoint *b, *b_tmp;
7745
7746   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7747     if (b->type == bp_shlib_event
7748         && b->loc->pspace == current_program_space)
7749       b->disposition = disp_del_at_next_stop;
7750 }
7751
7752 /* Helper for create_solib_event_breakpoint /
7753    create_and_insert_solib_event_breakpoint.  Allows specifying which
7754    INSERT_MODE to pass through to update_global_location_list.  */
7755
7756 static struct breakpoint *
7757 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7758                                  enum ugll_insert_mode insert_mode)
7759 {
7760   struct breakpoint *b;
7761
7762   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7763                                   &internal_breakpoint_ops);
7764   update_global_location_list_nothrow (insert_mode);
7765   return b;
7766 }
7767
7768 struct breakpoint *
7769 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7770 {
7771   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7772 }
7773
7774 /* See breakpoint.h.  */
7775
7776 struct breakpoint *
7777 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7778 {
7779   struct breakpoint *b;
7780
7781   /* Explicitly tell update_global_location_list to insert
7782      locations.  */
7783   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7784   if (!b->loc->inserted)
7785     {
7786       delete_breakpoint (b);
7787       return NULL;
7788     }
7789   return b;
7790 }
7791
7792 /* Disable any breakpoints that are on code in shared libraries.  Only
7793    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7794
7795 void
7796 disable_breakpoints_in_shlibs (void)
7797 {
7798   struct bp_location *loc, **locp_tmp;
7799
7800   ALL_BP_LOCATIONS (loc, locp_tmp)
7801   {
7802     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7803     struct breakpoint *b = loc->owner;
7804
7805     /* We apply the check to all breakpoints, including disabled for
7806        those with loc->duplicate set.  This is so that when breakpoint
7807        becomes enabled, or the duplicate is removed, gdb will try to
7808        insert all breakpoints.  If we don't set shlib_disabled here,
7809        we'll try to insert those breakpoints and fail.  */
7810     if (((b->type == bp_breakpoint)
7811          || (b->type == bp_jit_event)
7812          || (b->type == bp_hardware_breakpoint)
7813          || (is_tracepoint (b)))
7814         && loc->pspace == current_program_space
7815         && !loc->shlib_disabled
7816         && solib_name_from_address (loc->pspace, loc->address)
7817         )
7818       {
7819         loc->shlib_disabled = 1;
7820       }
7821   }
7822 }
7823
7824 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7825    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7826    disabled ones can just stay disabled.  */
7827
7828 static void
7829 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7830 {
7831   struct bp_location *loc, **locp_tmp;
7832   int disabled_shlib_breaks = 0;
7833
7834   /* SunOS a.out shared libraries are always mapped, so do not
7835      disable breakpoints; they will only be reported as unloaded
7836      through clear_solib when GDB discards its shared library
7837      list.  See clear_solib for more information.  */
7838   if (exec_bfd != NULL
7839       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7840     return;
7841
7842   ALL_BP_LOCATIONS (loc, locp_tmp)
7843   {
7844     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7845     struct breakpoint *b = loc->owner;
7846
7847     if (solib->pspace == loc->pspace
7848         && !loc->shlib_disabled
7849         && (((b->type == bp_breakpoint
7850               || b->type == bp_jit_event
7851               || b->type == bp_hardware_breakpoint)
7852              && (loc->loc_type == bp_loc_hardware_breakpoint
7853                  || loc->loc_type == bp_loc_software_breakpoint))
7854             || is_tracepoint (b))
7855         && solib_contains_address_p (solib, loc->address))
7856       {
7857         loc->shlib_disabled = 1;
7858         /* At this point, we cannot rely on remove_breakpoint
7859            succeeding so we must mark the breakpoint as not inserted
7860            to prevent future errors occurring in remove_breakpoints.  */
7861         loc->inserted = 0;
7862
7863         /* This may cause duplicate notifications for the same breakpoint.  */
7864         observer_notify_breakpoint_modified (b);
7865
7866         if (!disabled_shlib_breaks)
7867           {
7868             target_terminal_ours_for_output ();
7869             warning (_("Temporarily disabling breakpoints "
7870                        "for unloaded shared library \"%s\""),
7871                      solib->so_name);
7872           }
7873         disabled_shlib_breaks = 1;
7874       }
7875   }
7876 }
7877
7878 /* Disable any breakpoints and tracepoints in OBJFILE upon
7879    notification of free_objfile.  Only apply to enabled breakpoints,
7880    disabled ones can just stay disabled.  */
7881
7882 static void
7883 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7884 {
7885   struct breakpoint *b;
7886
7887   if (objfile == NULL)
7888     return;
7889
7890   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7891      managed by the user with add-symbol-file/remove-symbol-file.
7892      Similarly to how breakpoints in shared libraries are handled in
7893      response to "nosharedlibrary", mark breakpoints in such modules
7894      shlib_disabled so they end up uninserted on the next global
7895      location list update.  Shared libraries not loaded by the user
7896      aren't handled here -- they're already handled in
7897      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7898      solib_unloaded observer.  We skip objfiles that are not
7899      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7900      main objfile).  */
7901   if ((objfile->flags & OBJF_SHARED) == 0
7902       || (objfile->flags & OBJF_USERLOADED) == 0)
7903     return;
7904
7905   ALL_BREAKPOINTS (b)
7906     {
7907       struct bp_location *loc;
7908       int bp_modified = 0;
7909
7910       if (!is_breakpoint (b) && !is_tracepoint (b))
7911         continue;
7912
7913       for (loc = b->loc; loc != NULL; loc = loc->next)
7914         {
7915           CORE_ADDR loc_addr = loc->address;
7916
7917           if (loc->loc_type != bp_loc_hardware_breakpoint
7918               && loc->loc_type != bp_loc_software_breakpoint)
7919             continue;
7920
7921           if (loc->shlib_disabled != 0)
7922             continue;
7923
7924           if (objfile->pspace != loc->pspace)
7925             continue;
7926
7927           if (loc->loc_type != bp_loc_hardware_breakpoint
7928               && loc->loc_type != bp_loc_software_breakpoint)
7929             continue;
7930
7931           if (is_addr_in_objfile (loc_addr, objfile))
7932             {
7933               loc->shlib_disabled = 1;
7934               /* At this point, we don't know whether the object was
7935                  unmapped from the inferior or not, so leave the
7936                  inserted flag alone.  We'll handle failure to
7937                  uninsert quietly, in case the object was indeed
7938                  unmapped.  */
7939
7940               mark_breakpoint_location_modified (loc);
7941
7942               bp_modified = 1;
7943             }
7944         }
7945
7946       if (bp_modified)
7947         observer_notify_breakpoint_modified (b);
7948     }
7949 }
7950
7951 /* FORK & VFORK catchpoints.  */
7952
7953 /* An instance of this type is used to represent a fork or vfork
7954    catchpoint.  It includes a "struct breakpoint" as a kind of base
7955    class; users downcast to "struct breakpoint *" when needed.  A
7956    breakpoint is really of this type iff its ops pointer points to
7957    CATCH_FORK_BREAKPOINT_OPS.  */
7958
7959 struct fork_catchpoint
7960 {
7961   /* The base class.  */
7962   struct breakpoint base;
7963
7964   /* Process id of a child process whose forking triggered this
7965      catchpoint.  This field is only valid immediately after this
7966      catchpoint has triggered.  */
7967   ptid_t forked_inferior_pid;
7968 };
7969
7970 /* Implement the "insert" breakpoint_ops method for fork
7971    catchpoints.  */
7972
7973 static int
7974 insert_catch_fork (struct bp_location *bl)
7975 {
7976   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7977 }
7978
7979 /* Implement the "remove" breakpoint_ops method for fork
7980    catchpoints.  */
7981
7982 static int
7983 remove_catch_fork (struct bp_location *bl)
7984 {
7985   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7986 }
7987
7988 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7989    catchpoints.  */
7990
7991 static int
7992 breakpoint_hit_catch_fork (const struct bp_location *bl,
7993                            struct address_space *aspace, CORE_ADDR bp_addr,
7994                            const struct target_waitstatus *ws)
7995 {
7996   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7997
7998   if (ws->kind != TARGET_WAITKIND_FORKED)
7999     return 0;
8000
8001   c->forked_inferior_pid = ws->value.related_pid;
8002   return 1;
8003 }
8004
8005 /* Implement the "print_it" breakpoint_ops method for fork
8006    catchpoints.  */
8007
8008 static enum print_stop_action
8009 print_it_catch_fork (bpstat bs)
8010 {
8011   struct ui_out *uiout = current_uiout;
8012   struct breakpoint *b = bs->breakpoint_at;
8013   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8014
8015   annotate_catchpoint (b->number);
8016   if (b->disposition == disp_del)
8017     ui_out_text (uiout, "\nTemporary catchpoint ");
8018   else
8019     ui_out_text (uiout, "\nCatchpoint ");
8020   if (ui_out_is_mi_like_p (uiout))
8021     {
8022       ui_out_field_string (uiout, "reason",
8023                            async_reason_lookup (EXEC_ASYNC_FORK));
8024       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8025     }
8026   ui_out_field_int (uiout, "bkptno", b->number);
8027   ui_out_text (uiout, " (forked process ");
8028   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8029   ui_out_text (uiout, "), ");
8030   return PRINT_SRC_AND_LOC;
8031 }
8032
8033 /* Implement the "print_one" breakpoint_ops method for fork
8034    catchpoints.  */
8035
8036 static void
8037 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8038 {
8039   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8040   struct value_print_options opts;
8041   struct ui_out *uiout = current_uiout;
8042
8043   get_user_print_options (&opts);
8044
8045   /* Field 4, the address, is omitted (which makes the columns not
8046      line up too nicely with the headers, but the effect is relatively
8047      readable).  */
8048   if (opts.addressprint)
8049     ui_out_field_skip (uiout, "addr");
8050   annotate_field (5);
8051   ui_out_text (uiout, "fork");
8052   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8053     {
8054       ui_out_text (uiout, ", process ");
8055       ui_out_field_int (uiout, "what",
8056                         ptid_get_pid (c->forked_inferior_pid));
8057       ui_out_spaces (uiout, 1);
8058     }
8059
8060   if (ui_out_is_mi_like_p (uiout))
8061     ui_out_field_string (uiout, "catch-type", "fork");
8062 }
8063
8064 /* Implement the "print_mention" breakpoint_ops method for fork
8065    catchpoints.  */
8066
8067 static void
8068 print_mention_catch_fork (struct breakpoint *b)
8069 {
8070   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8071 }
8072
8073 /* Implement the "print_recreate" breakpoint_ops method for fork
8074    catchpoints.  */
8075
8076 static void
8077 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8078 {
8079   fprintf_unfiltered (fp, "catch fork");
8080   print_recreate_thread (b, fp);
8081 }
8082
8083 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8084
8085 static struct breakpoint_ops catch_fork_breakpoint_ops;
8086
8087 /* Implement the "insert" breakpoint_ops method for vfork
8088    catchpoints.  */
8089
8090 static int
8091 insert_catch_vfork (struct bp_location *bl)
8092 {
8093   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8094 }
8095
8096 /* Implement the "remove" breakpoint_ops method for vfork
8097    catchpoints.  */
8098
8099 static int
8100 remove_catch_vfork (struct bp_location *bl)
8101 {
8102   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8103 }
8104
8105 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8106    catchpoints.  */
8107
8108 static int
8109 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8110                             struct address_space *aspace, CORE_ADDR bp_addr,
8111                             const struct target_waitstatus *ws)
8112 {
8113   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8114
8115   if (ws->kind != TARGET_WAITKIND_VFORKED)
8116     return 0;
8117
8118   c->forked_inferior_pid = ws->value.related_pid;
8119   return 1;
8120 }
8121
8122 /* Implement the "print_it" breakpoint_ops method for vfork
8123    catchpoints.  */
8124
8125 static enum print_stop_action
8126 print_it_catch_vfork (bpstat bs)
8127 {
8128   struct ui_out *uiout = current_uiout;
8129   struct breakpoint *b = bs->breakpoint_at;
8130   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8131
8132   annotate_catchpoint (b->number);
8133   if (b->disposition == disp_del)
8134     ui_out_text (uiout, "\nTemporary catchpoint ");
8135   else
8136     ui_out_text (uiout, "\nCatchpoint ");
8137   if (ui_out_is_mi_like_p (uiout))
8138     {
8139       ui_out_field_string (uiout, "reason",
8140                            async_reason_lookup (EXEC_ASYNC_VFORK));
8141       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8142     }
8143   ui_out_field_int (uiout, "bkptno", b->number);
8144   ui_out_text (uiout, " (vforked process ");
8145   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8146   ui_out_text (uiout, "), ");
8147   return PRINT_SRC_AND_LOC;
8148 }
8149
8150 /* Implement the "print_one" breakpoint_ops method for vfork
8151    catchpoints.  */
8152
8153 static void
8154 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8155 {
8156   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8157   struct value_print_options opts;
8158   struct ui_out *uiout = current_uiout;
8159
8160   get_user_print_options (&opts);
8161   /* Field 4, the address, is omitted (which makes the columns not
8162      line up too nicely with the headers, but the effect is relatively
8163      readable).  */
8164   if (opts.addressprint)
8165     ui_out_field_skip (uiout, "addr");
8166   annotate_field (5);
8167   ui_out_text (uiout, "vfork");
8168   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8169     {
8170       ui_out_text (uiout, ", process ");
8171       ui_out_field_int (uiout, "what",
8172                         ptid_get_pid (c->forked_inferior_pid));
8173       ui_out_spaces (uiout, 1);
8174     }
8175
8176   if (ui_out_is_mi_like_p (uiout))
8177     ui_out_field_string (uiout, "catch-type", "vfork");
8178 }
8179
8180 /* Implement the "print_mention" breakpoint_ops method for vfork
8181    catchpoints.  */
8182
8183 static void
8184 print_mention_catch_vfork (struct breakpoint *b)
8185 {
8186   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8187 }
8188
8189 /* Implement the "print_recreate" breakpoint_ops method for vfork
8190    catchpoints.  */
8191
8192 static void
8193 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8194 {
8195   fprintf_unfiltered (fp, "catch vfork");
8196   print_recreate_thread (b, fp);
8197 }
8198
8199 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8200
8201 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8202
8203 /* An instance of this type is used to represent an solib catchpoint.
8204    It includes a "struct breakpoint" as a kind of base class; users
8205    downcast to "struct breakpoint *" when needed.  A breakpoint is
8206    really of this type iff its ops pointer points to
8207    CATCH_SOLIB_BREAKPOINT_OPS.  */
8208
8209 struct solib_catchpoint
8210 {
8211   /* The base class.  */
8212   struct breakpoint base;
8213
8214   /* True for "catch load", false for "catch unload".  */
8215   unsigned char is_load;
8216
8217   /* Regular expression to match, if any.  COMPILED is only valid when
8218      REGEX is non-NULL.  */
8219   char *regex;
8220   regex_t compiled;
8221 };
8222
8223 static void
8224 dtor_catch_solib (struct breakpoint *b)
8225 {
8226   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8227
8228   if (self->regex)
8229     regfree (&self->compiled);
8230   xfree (self->regex);
8231
8232   base_breakpoint_ops.dtor (b);
8233 }
8234
8235 static int
8236 insert_catch_solib (struct bp_location *ignore)
8237 {
8238   return 0;
8239 }
8240
8241 static int
8242 remove_catch_solib (struct bp_location *ignore)
8243 {
8244   return 0;
8245 }
8246
8247 static int
8248 breakpoint_hit_catch_solib (const struct bp_location *bl,
8249                             struct address_space *aspace,
8250                             CORE_ADDR bp_addr,
8251                             const struct target_waitstatus *ws)
8252 {
8253   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8254   struct breakpoint *other;
8255
8256   if (ws->kind == TARGET_WAITKIND_LOADED)
8257     return 1;
8258
8259   ALL_BREAKPOINTS (other)
8260   {
8261     struct bp_location *other_bl;
8262
8263     if (other == bl->owner)
8264       continue;
8265
8266     if (other->type != bp_shlib_event)
8267       continue;
8268
8269     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8270       continue;
8271
8272     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8273       {
8274         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8275           return 1;
8276       }
8277   }
8278
8279   return 0;
8280 }
8281
8282 static void
8283 check_status_catch_solib (struct bpstats *bs)
8284 {
8285   struct solib_catchpoint *self
8286     = (struct solib_catchpoint *) bs->breakpoint_at;
8287   int ix;
8288
8289   if (self->is_load)
8290     {
8291       struct so_list *iter;
8292
8293       for (ix = 0;
8294            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8295                         ix, iter);
8296            ++ix)
8297         {
8298           if (!self->regex
8299               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8300             return;
8301         }
8302     }
8303   else
8304     {
8305       char *iter;
8306
8307       for (ix = 0;
8308            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8309                         ix, iter);
8310            ++ix)
8311         {
8312           if (!self->regex
8313               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8314             return;
8315         }
8316     }
8317
8318   bs->stop = 0;
8319   bs->print_it = print_it_noop;
8320 }
8321
8322 static enum print_stop_action
8323 print_it_catch_solib (bpstat bs)
8324 {
8325   struct breakpoint *b = bs->breakpoint_at;
8326   struct ui_out *uiout = current_uiout;
8327
8328   annotate_catchpoint (b->number);
8329   if (b->disposition == disp_del)
8330     ui_out_text (uiout, "\nTemporary catchpoint ");
8331   else
8332     ui_out_text (uiout, "\nCatchpoint ");
8333   ui_out_field_int (uiout, "bkptno", b->number);
8334   ui_out_text (uiout, "\n");
8335   if (ui_out_is_mi_like_p (uiout))
8336     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8337   print_solib_event (1);
8338   return PRINT_SRC_AND_LOC;
8339 }
8340
8341 static void
8342 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8343 {
8344   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8345   struct value_print_options opts;
8346   struct ui_out *uiout = current_uiout;
8347   char *msg;
8348
8349   get_user_print_options (&opts);
8350   /* Field 4, the address, is omitted (which makes the columns not
8351      line up too nicely with the headers, but the effect is relatively
8352      readable).  */
8353   if (opts.addressprint)
8354     {
8355       annotate_field (4);
8356       ui_out_field_skip (uiout, "addr");
8357     }
8358
8359   annotate_field (5);
8360   if (self->is_load)
8361     {
8362       if (self->regex)
8363         msg = xstrprintf (_("load of library matching %s"), self->regex);
8364       else
8365         msg = xstrdup (_("load of library"));
8366     }
8367   else
8368     {
8369       if (self->regex)
8370         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8371       else
8372         msg = xstrdup (_("unload of library"));
8373     }
8374   ui_out_field_string (uiout, "what", msg);
8375   xfree (msg);
8376
8377   if (ui_out_is_mi_like_p (uiout))
8378     ui_out_field_string (uiout, "catch-type",
8379                          self->is_load ? "load" : "unload");
8380 }
8381
8382 static void
8383 print_mention_catch_solib (struct breakpoint *b)
8384 {
8385   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8386
8387   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8388                    self->is_load ? "load" : "unload");
8389 }
8390
8391 static void
8392 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8393 {
8394   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8395
8396   fprintf_unfiltered (fp, "%s %s",
8397                       b->disposition == disp_del ? "tcatch" : "catch",
8398                       self->is_load ? "load" : "unload");
8399   if (self->regex)
8400     fprintf_unfiltered (fp, " %s", self->regex);
8401   fprintf_unfiltered (fp, "\n");
8402 }
8403
8404 static struct breakpoint_ops catch_solib_breakpoint_ops;
8405
8406 /* Shared helper function (MI and CLI) for creating and installing
8407    a shared object event catchpoint.  If IS_LOAD is non-zero then
8408    the events to be caught are load events, otherwise they are
8409    unload events.  If IS_TEMP is non-zero the catchpoint is a
8410    temporary one.  If ENABLED is non-zero the catchpoint is
8411    created in an enabled state.  */
8412
8413 void
8414 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8415 {
8416   struct solib_catchpoint *c;
8417   struct gdbarch *gdbarch = get_current_arch ();
8418   struct cleanup *cleanup;
8419
8420   if (!arg)
8421     arg = "";
8422   arg = skip_spaces (arg);
8423
8424   c = XCNEW (struct solib_catchpoint);
8425   cleanup = make_cleanup (xfree, c);
8426
8427   if (*arg != '\0')
8428     {
8429       int errcode;
8430
8431       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8432       if (errcode != 0)
8433         {
8434           char *err = get_regcomp_error (errcode, &c->compiled);
8435
8436           make_cleanup (xfree, err);
8437           error (_("Invalid regexp (%s): %s"), err, arg);
8438         }
8439       c->regex = xstrdup (arg);
8440     }
8441
8442   c->is_load = is_load;
8443   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8444                    &catch_solib_breakpoint_ops);
8445
8446   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8447
8448   discard_cleanups (cleanup);
8449   install_breakpoint (0, &c->base, 1);
8450 }
8451
8452 /* A helper function that does all the work for "catch load" and
8453    "catch unload".  */
8454
8455 static void
8456 catch_load_or_unload (char *arg, int from_tty, int is_load,
8457                       struct cmd_list_element *command)
8458 {
8459   int tempflag;
8460   const int enabled = 1;
8461
8462   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8463
8464   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8465 }
8466
8467 static void
8468 catch_load_command_1 (char *arg, int from_tty,
8469                       struct cmd_list_element *command)
8470 {
8471   catch_load_or_unload (arg, from_tty, 1, command);
8472 }
8473
8474 static void
8475 catch_unload_command_1 (char *arg, int from_tty,
8476                         struct cmd_list_element *command)
8477 {
8478   catch_load_or_unload (arg, from_tty, 0, command);
8479 }
8480
8481 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8482    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8483    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8484    the breakpoint_ops structure associated to the catchpoint.  */
8485
8486 void
8487 init_catchpoint (struct breakpoint *b,
8488                  struct gdbarch *gdbarch, int tempflag,
8489                  char *cond_string,
8490                  const struct breakpoint_ops *ops)
8491 {
8492   struct symtab_and_line sal;
8493
8494   init_sal (&sal);
8495   sal.pspace = current_program_space;
8496
8497   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8498
8499   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8500   b->disposition = tempflag ? disp_del : disp_donttouch;
8501 }
8502
8503 void
8504 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8505 {
8506   add_to_breakpoint_chain (b);
8507   set_breakpoint_number (internal, b);
8508   if (is_tracepoint (b))
8509     set_tracepoint_count (breakpoint_count);
8510   if (!internal)
8511     mention (b);
8512   observer_notify_breakpoint_created (b);
8513
8514   if (update_gll)
8515     update_global_location_list (UGLL_MAY_INSERT);
8516 }
8517
8518 static void
8519 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8520                                     int tempflag, char *cond_string,
8521                                     const struct breakpoint_ops *ops)
8522 {
8523   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8524
8525   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8526
8527   c->forked_inferior_pid = null_ptid;
8528
8529   install_breakpoint (0, &c->base, 1);
8530 }
8531
8532 /* Exec catchpoints.  */
8533
8534 /* An instance of this type is used to represent an exec catchpoint.
8535    It includes a "struct breakpoint" as a kind of base class; users
8536    downcast to "struct breakpoint *" when needed.  A breakpoint is
8537    really of this type iff its ops pointer points to
8538    CATCH_EXEC_BREAKPOINT_OPS.  */
8539
8540 struct exec_catchpoint
8541 {
8542   /* The base class.  */
8543   struct breakpoint base;
8544
8545   /* Filename of a program whose exec triggered this catchpoint.
8546      This field is only valid immediately after this catchpoint has
8547      triggered.  */
8548   char *exec_pathname;
8549 };
8550
8551 /* Implement the "dtor" breakpoint_ops method for exec
8552    catchpoints.  */
8553
8554 static void
8555 dtor_catch_exec (struct breakpoint *b)
8556 {
8557   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8558
8559   xfree (c->exec_pathname);
8560
8561   base_breakpoint_ops.dtor (b);
8562 }
8563
8564 static int
8565 insert_catch_exec (struct bp_location *bl)
8566 {
8567   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8568 }
8569
8570 static int
8571 remove_catch_exec (struct bp_location *bl)
8572 {
8573   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8574 }
8575
8576 static int
8577 breakpoint_hit_catch_exec (const struct bp_location *bl,
8578                            struct address_space *aspace, CORE_ADDR bp_addr,
8579                            const struct target_waitstatus *ws)
8580 {
8581   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8582
8583   if (ws->kind != TARGET_WAITKIND_EXECD)
8584     return 0;
8585
8586   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8587   return 1;
8588 }
8589
8590 static enum print_stop_action
8591 print_it_catch_exec (bpstat bs)
8592 {
8593   struct ui_out *uiout = current_uiout;
8594   struct breakpoint *b = bs->breakpoint_at;
8595   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8596
8597   annotate_catchpoint (b->number);
8598   if (b->disposition == disp_del)
8599     ui_out_text (uiout, "\nTemporary catchpoint ");
8600   else
8601     ui_out_text (uiout, "\nCatchpoint ");
8602   if (ui_out_is_mi_like_p (uiout))
8603     {
8604       ui_out_field_string (uiout, "reason",
8605                            async_reason_lookup (EXEC_ASYNC_EXEC));
8606       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8607     }
8608   ui_out_field_int (uiout, "bkptno", b->number);
8609   ui_out_text (uiout, " (exec'd ");
8610   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8611   ui_out_text (uiout, "), ");
8612
8613   return PRINT_SRC_AND_LOC;
8614 }
8615
8616 static void
8617 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8618 {
8619   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8620   struct value_print_options opts;
8621   struct ui_out *uiout = current_uiout;
8622
8623   get_user_print_options (&opts);
8624
8625   /* Field 4, the address, is omitted (which makes the columns
8626      not line up too nicely with the headers, but the effect
8627      is relatively readable).  */
8628   if (opts.addressprint)
8629     ui_out_field_skip (uiout, "addr");
8630   annotate_field (5);
8631   ui_out_text (uiout, "exec");
8632   if (c->exec_pathname != NULL)
8633     {
8634       ui_out_text (uiout, ", program \"");
8635       ui_out_field_string (uiout, "what", c->exec_pathname);
8636       ui_out_text (uiout, "\" ");
8637     }
8638
8639   if (ui_out_is_mi_like_p (uiout))
8640     ui_out_field_string (uiout, "catch-type", "exec");
8641 }
8642
8643 static void
8644 print_mention_catch_exec (struct breakpoint *b)
8645 {
8646   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8647 }
8648
8649 /* Implement the "print_recreate" breakpoint_ops method for exec
8650    catchpoints.  */
8651
8652 static void
8653 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8654 {
8655   fprintf_unfiltered (fp, "catch exec");
8656   print_recreate_thread (b, fp);
8657 }
8658
8659 static struct breakpoint_ops catch_exec_breakpoint_ops;
8660
8661 static int
8662 hw_breakpoint_used_count (void)
8663 {
8664   int i = 0;
8665   struct breakpoint *b;
8666   struct bp_location *bl;
8667
8668   ALL_BREAKPOINTS (b)
8669   {
8670     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8671       for (bl = b->loc; bl; bl = bl->next)
8672         {
8673           /* Special types of hardware breakpoints may use more than
8674              one register.  */
8675           i += b->ops->resources_needed (bl);
8676         }
8677   }
8678
8679   return i;
8680 }
8681
8682 /* Returns the resources B would use if it were a hardware
8683    watchpoint.  */
8684
8685 static int
8686 hw_watchpoint_use_count (struct breakpoint *b)
8687 {
8688   int i = 0;
8689   struct bp_location *bl;
8690
8691   if (!breakpoint_enabled (b))
8692     return 0;
8693
8694   for (bl = b->loc; bl; bl = bl->next)
8695     {
8696       /* Special types of hardware watchpoints may use more than
8697          one register.  */
8698       i += b->ops->resources_needed (bl);
8699     }
8700
8701   return i;
8702 }
8703
8704 /* Returns the sum the used resources of all hardware watchpoints of
8705    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8706    the sum of the used resources of all hardware watchpoints of other
8707    types _not_ TYPE.  */
8708
8709 static int
8710 hw_watchpoint_used_count_others (struct breakpoint *except,
8711                                  enum bptype type, int *other_type_used)
8712 {
8713   int i = 0;
8714   struct breakpoint *b;
8715
8716   *other_type_used = 0;
8717   ALL_BREAKPOINTS (b)
8718     {
8719       if (b == except)
8720         continue;
8721       if (!breakpoint_enabled (b))
8722         continue;
8723
8724       if (b->type == type)
8725         i += hw_watchpoint_use_count (b);
8726       else if (is_hardware_watchpoint (b))
8727         *other_type_used = 1;
8728     }
8729
8730   return i;
8731 }
8732
8733 void
8734 disable_watchpoints_before_interactive_call_start (void)
8735 {
8736   struct breakpoint *b;
8737
8738   ALL_BREAKPOINTS (b)
8739   {
8740     if (is_watchpoint (b) && breakpoint_enabled (b))
8741       {
8742         b->enable_state = bp_call_disabled;
8743         update_global_location_list (UGLL_DONT_INSERT);
8744       }
8745   }
8746 }
8747
8748 void
8749 enable_watchpoints_after_interactive_call_stop (void)
8750 {
8751   struct breakpoint *b;
8752
8753   ALL_BREAKPOINTS (b)
8754   {
8755     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8756       {
8757         b->enable_state = bp_enabled;
8758         update_global_location_list (UGLL_MAY_INSERT);
8759       }
8760   }
8761 }
8762
8763 void
8764 disable_breakpoints_before_startup (void)
8765 {
8766   current_program_space->executing_startup = 1;
8767   update_global_location_list (UGLL_DONT_INSERT);
8768 }
8769
8770 void
8771 enable_breakpoints_after_startup (void)
8772 {
8773   current_program_space->executing_startup = 0;
8774   breakpoint_re_set ();
8775 }
8776
8777 /* Create a new single-step breakpoint for thread THREAD, with no
8778    locations.  */
8779
8780 static struct breakpoint *
8781 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8782 {
8783   struct breakpoint *b = XNEW (struct breakpoint);
8784
8785   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8786                                         &momentary_breakpoint_ops);
8787
8788   b->disposition = disp_donttouch;
8789   b->frame_id = null_frame_id;
8790
8791   b->thread = thread;
8792   gdb_assert (b->thread != 0);
8793
8794   add_to_breakpoint_chain (b);
8795
8796   return b;
8797 }
8798
8799 /* Set a momentary breakpoint of type TYPE at address specified by
8800    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8801    frame.  */
8802
8803 struct breakpoint *
8804 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8805                           struct frame_id frame_id, enum bptype type)
8806 {
8807   struct breakpoint *b;
8808
8809   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8810      tail-called one.  */
8811   gdb_assert (!frame_id_artificial_p (frame_id));
8812
8813   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8814   b->enable_state = bp_enabled;
8815   b->disposition = disp_donttouch;
8816   b->frame_id = frame_id;
8817
8818   /* If we're debugging a multi-threaded program, then we want
8819      momentary breakpoints to be active in only a single thread of
8820      control.  */
8821   if (in_thread_list (inferior_ptid))
8822     b->thread = pid_to_thread_id (inferior_ptid);
8823
8824   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8825
8826   return b;
8827 }
8828
8829 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8830    The new breakpoint will have type TYPE, use OPS as its
8831    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8832
8833 static struct breakpoint *
8834 momentary_breakpoint_from_master (struct breakpoint *orig,
8835                                   enum bptype type,
8836                                   const struct breakpoint_ops *ops,
8837                                   int loc_enabled)
8838 {
8839   struct breakpoint *copy;
8840
8841   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8842   copy->loc = allocate_bp_location (copy);
8843   set_breakpoint_location_function (copy->loc, 1);
8844
8845   copy->loc->gdbarch = orig->loc->gdbarch;
8846   copy->loc->requested_address = orig->loc->requested_address;
8847   copy->loc->address = orig->loc->address;
8848   copy->loc->section = orig->loc->section;
8849   copy->loc->pspace = orig->loc->pspace;
8850   copy->loc->probe = orig->loc->probe;
8851   copy->loc->line_number = orig->loc->line_number;
8852   copy->loc->symtab = orig->loc->symtab;
8853   copy->loc->enabled = loc_enabled;
8854   copy->frame_id = orig->frame_id;
8855   copy->thread = orig->thread;
8856   copy->pspace = orig->pspace;
8857
8858   copy->enable_state = bp_enabled;
8859   copy->disposition = disp_donttouch;
8860   copy->number = internal_breakpoint_number--;
8861
8862   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8863   return copy;
8864 }
8865
8866 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8867    ORIG is NULL.  */
8868
8869 struct breakpoint *
8870 clone_momentary_breakpoint (struct breakpoint *orig)
8871 {
8872   /* If there's nothing to clone, then return nothing.  */
8873   if (orig == NULL)
8874     return NULL;
8875
8876   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8877 }
8878
8879 struct breakpoint *
8880 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8881                                 enum bptype type)
8882 {
8883   struct symtab_and_line sal;
8884
8885   sal = find_pc_line (pc, 0);
8886   sal.pc = pc;
8887   sal.section = find_pc_overlay (pc);
8888   sal.explicit_pc = 1;
8889
8890   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8891 }
8892 \f
8893
8894 /* Tell the user we have just set a breakpoint B.  */
8895
8896 static void
8897 mention (struct breakpoint *b)
8898 {
8899   b->ops->print_mention (b);
8900   if (ui_out_is_mi_like_p (current_uiout))
8901     return;
8902   printf_filtered ("\n");
8903 }
8904 \f
8905
8906 static int bp_loc_is_permanent (struct bp_location *loc);
8907
8908 static struct bp_location *
8909 add_location_to_breakpoint (struct breakpoint *b,
8910                             const struct symtab_and_line *sal)
8911 {
8912   struct bp_location *loc, **tmp;
8913   CORE_ADDR adjusted_address;
8914   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8915
8916   if (loc_gdbarch == NULL)
8917     loc_gdbarch = b->gdbarch;
8918
8919   /* Adjust the breakpoint's address prior to allocating a location.
8920      Once we call allocate_bp_location(), that mostly uninitialized
8921      location will be placed on the location chain.  Adjustment of the
8922      breakpoint may cause target_read_memory() to be called and we do
8923      not want its scan of the location chain to find a breakpoint and
8924      location that's only been partially initialized.  */
8925   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8926                                                 sal->pc, b->type);
8927
8928   /* Sort the locations by their ADDRESS.  */
8929   loc = allocate_bp_location (b);
8930   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8931        tmp = &((*tmp)->next))
8932     ;
8933   loc->next = *tmp;
8934   *tmp = loc;
8935
8936   loc->requested_address = sal->pc;
8937   loc->address = adjusted_address;
8938   loc->pspace = sal->pspace;
8939   loc->probe.probe = sal->probe;
8940   loc->probe.objfile = sal->objfile;
8941   gdb_assert (loc->pspace != NULL);
8942   loc->section = sal->section;
8943   loc->gdbarch = loc_gdbarch;
8944   loc->line_number = sal->line;
8945   loc->symtab = sal->symtab;
8946
8947   set_breakpoint_location_function (loc,
8948                                     sal->explicit_pc || sal->explicit_line);
8949
8950   /* While by definition, permanent breakpoints are already present in the
8951      code, we don't mark the location as inserted.  Normally one would expect
8952      that GDB could rely on that breakpoint instruction to stop the program,
8953      thus removing the need to insert its own breakpoint, except that executing
8954      the breakpoint instruction can kill the target instead of reporting a
8955      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8956      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8957      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8958      breakpoint be inserted normally results in QEMU knowing about the GDB
8959      breakpoint, and thus trap before the breakpoint instruction is executed.
8960      (If GDB later needs to continue execution past the permanent breakpoint,
8961      it manually increments the PC, thus avoiding executing the breakpoint
8962      instruction.)  */
8963   if (bp_loc_is_permanent (loc))
8964     loc->permanent = 1;
8965
8966   return loc;
8967 }
8968 \f
8969
8970 /* See breakpoint.h.  */
8971
8972 int
8973 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8974 {
8975   int len;
8976   CORE_ADDR addr;
8977   const gdb_byte *bpoint;
8978   gdb_byte *target_mem;
8979   struct cleanup *cleanup;
8980   int retval = 0;
8981
8982   addr = address;
8983   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8984
8985   /* Software breakpoints unsupported?  */
8986   if (bpoint == NULL)
8987     return 0;
8988
8989   target_mem = (gdb_byte *) alloca (len);
8990
8991   /* Enable the automatic memory restoration from breakpoints while
8992      we read the memory.  Otherwise we could say about our temporary
8993      breakpoints they are permanent.  */
8994   cleanup = make_show_memory_breakpoints_cleanup (0);
8995
8996   if (target_read_memory (address, target_mem, len) == 0
8997       && memcmp (target_mem, bpoint, len) == 0)
8998     retval = 1;
8999
9000   do_cleanups (cleanup);
9001
9002   return retval;
9003 }
9004
9005 /* Return 1 if LOC is pointing to a permanent breakpoint,
9006    return 0 otherwise.  */
9007
9008 static int
9009 bp_loc_is_permanent (struct bp_location *loc)
9010 {
9011   struct cleanup *cleanup;
9012   int retval;
9013
9014   gdb_assert (loc != NULL);
9015
9016   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9017      attempt to read from the addresses the locations of these breakpoint types
9018      point to.  program_breakpoint_here_p, below, will attempt to read
9019      memory.  */
9020   if (!breakpoint_address_is_meaningful (loc->owner))
9021     return 0;
9022
9023   cleanup = save_current_space_and_thread ();
9024   switch_to_program_space_and_thread (loc->pspace);
9025
9026   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9027
9028   do_cleanups (cleanup);
9029
9030   return retval;
9031 }
9032
9033 /* Build a command list for the dprintf corresponding to the current
9034    settings of the dprintf style options.  */
9035
9036 static void
9037 update_dprintf_command_list (struct breakpoint *b)
9038 {
9039   char *dprintf_args = b->extra_string;
9040   char *printf_line = NULL;
9041
9042   if (!dprintf_args)
9043     return;
9044
9045   dprintf_args = skip_spaces (dprintf_args);
9046
9047   /* Allow a comma, as it may have terminated a location, but don't
9048      insist on it.  */
9049   if (*dprintf_args == ',')
9050     ++dprintf_args;
9051   dprintf_args = skip_spaces (dprintf_args);
9052
9053   if (*dprintf_args != '"')
9054     error (_("Bad format string, missing '\"'."));
9055
9056   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9057     printf_line = xstrprintf ("printf %s", dprintf_args);
9058   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9059     {
9060       if (!dprintf_function)
9061         error (_("No function supplied for dprintf call"));
9062
9063       if (dprintf_channel && strlen (dprintf_channel) > 0)
9064         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9065                                   dprintf_function,
9066                                   dprintf_channel,
9067                                   dprintf_args);
9068       else
9069         printf_line = xstrprintf ("call (void) %s (%s)",
9070                                   dprintf_function,
9071                                   dprintf_args);
9072     }
9073   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9074     {
9075       if (target_can_run_breakpoint_commands ())
9076         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9077       else
9078         {
9079           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9080           printf_line = xstrprintf ("printf %s", dprintf_args);
9081         }
9082     }
9083   else
9084     internal_error (__FILE__, __LINE__,
9085                     _("Invalid dprintf style."));
9086
9087   gdb_assert (printf_line != NULL);
9088   /* Manufacture a printf sequence.  */
9089   {
9090     struct command_line *printf_cmd_line = XNEW (struct command_line);
9091
9092     printf_cmd_line->control_type = simple_control;
9093     printf_cmd_line->body_count = 0;
9094     printf_cmd_line->body_list = NULL;
9095     printf_cmd_line->next = NULL;
9096     printf_cmd_line->line = printf_line;
9097
9098     breakpoint_set_commands (b, printf_cmd_line);
9099   }
9100 }
9101
9102 /* Update all dprintf commands, making their command lists reflect
9103    current style settings.  */
9104
9105 static void
9106 update_dprintf_commands (char *args, int from_tty,
9107                          struct cmd_list_element *c)
9108 {
9109   struct breakpoint *b;
9110
9111   ALL_BREAKPOINTS (b)
9112     {
9113       if (b->type == bp_dprintf)
9114         update_dprintf_command_list (b);
9115     }
9116 }
9117
9118 /* Create a breakpoint with SAL as location.  Use LOCATION
9119    as a description of the location, and COND_STRING
9120    as condition expression.  */
9121
9122 static void
9123 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9124                      struct symtabs_and_lines sals,
9125                      struct event_location *location,
9126                      char *filter, char *cond_string,
9127                      char *extra_string,
9128                      enum bptype type, enum bpdisp disposition,
9129                      int thread, int task, int ignore_count,
9130                      const struct breakpoint_ops *ops, int from_tty,
9131                      int enabled, int internal, unsigned flags,
9132                      int display_canonical)
9133 {
9134   int i;
9135
9136   if (type == bp_hardware_breakpoint)
9137     {
9138       int target_resources_ok;
9139
9140       i = hw_breakpoint_used_count ();
9141       target_resources_ok =
9142         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9143                                             i + 1, 0);
9144       if (target_resources_ok == 0)
9145         error (_("No hardware breakpoint support in the target."));
9146       else if (target_resources_ok < 0)
9147         error (_("Hardware breakpoints used exceeds limit."));
9148     }
9149
9150   gdb_assert (sals.nelts > 0);
9151
9152   for (i = 0; i < sals.nelts; ++i)
9153     {
9154       struct symtab_and_line sal = sals.sals[i];
9155       struct bp_location *loc;
9156
9157       if (from_tty)
9158         {
9159           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9160           if (!loc_gdbarch)
9161             loc_gdbarch = gdbarch;
9162
9163           describe_other_breakpoints (loc_gdbarch,
9164                                       sal.pspace, sal.pc, sal.section, thread);
9165         }
9166
9167       if (i == 0)
9168         {
9169           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9170           b->thread = thread;
9171           b->task = task;
9172
9173           b->cond_string = cond_string;
9174           b->extra_string = extra_string;
9175           b->ignore_count = ignore_count;
9176           b->enable_state = enabled ? bp_enabled : bp_disabled;
9177           b->disposition = disposition;
9178
9179           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9180             b->loc->inserted = 1;
9181
9182           if (type == bp_static_tracepoint)
9183             {
9184               struct tracepoint *t = (struct tracepoint *) b;
9185               struct static_tracepoint_marker marker;
9186
9187               if (strace_marker_p (b))
9188                 {
9189                   /* We already know the marker exists, otherwise, we
9190                      wouldn't see a sal for it.  */
9191                   const char *p = &event_location_to_string (b->location)[3];
9192                   const char *endp;
9193                   char *marker_str;
9194
9195                   p = skip_spaces_const (p);
9196
9197                   endp = skip_to_space_const (p);
9198
9199                   marker_str = savestring (p, endp - p);
9200                   t->static_trace_marker_id = marker_str;
9201
9202                   printf_filtered (_("Probed static tracepoint "
9203                                      "marker \"%s\"\n"),
9204                                    t->static_trace_marker_id);
9205                 }
9206               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9207                 {
9208                   t->static_trace_marker_id = xstrdup (marker.str_id);
9209                   release_static_tracepoint_marker (&marker);
9210
9211                   printf_filtered (_("Probed static tracepoint "
9212                                      "marker \"%s\"\n"),
9213                                    t->static_trace_marker_id);
9214                 }
9215               else
9216                 warning (_("Couldn't determine the static "
9217                            "tracepoint marker to probe"));
9218             }
9219
9220           loc = b->loc;
9221         }
9222       else
9223         {
9224           loc = add_location_to_breakpoint (b, &sal);
9225           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9226             loc->inserted = 1;
9227         }
9228
9229       if (b->cond_string)
9230         {
9231           const char *arg = b->cond_string;
9232
9233           loc->cond = parse_exp_1 (&arg, loc->address,
9234                                    block_for_pc (loc->address), 0);
9235           if (*arg)
9236               error (_("Garbage '%s' follows condition"), arg);
9237         }
9238
9239       /* Dynamic printf requires and uses additional arguments on the
9240          command line, otherwise it's an error.  */
9241       if (type == bp_dprintf)
9242         {
9243           if (b->extra_string)
9244             update_dprintf_command_list (b);
9245           else
9246             error (_("Format string required"));
9247         }
9248       else if (b->extra_string)
9249         error (_("Garbage '%s' at end of command"), b->extra_string);
9250     }
9251
9252   b->display_canonical = display_canonical;
9253   if (location != NULL)
9254     b->location = location;
9255   else
9256     b->location = new_address_location (b->loc->address);
9257   b->filter = filter;
9258 }
9259
9260 static void
9261 create_breakpoint_sal (struct gdbarch *gdbarch,
9262                        struct symtabs_and_lines sals,
9263                        struct event_location *location,
9264                        char *filter, char *cond_string,
9265                        char *extra_string,
9266                        enum bptype type, enum bpdisp disposition,
9267                        int thread, int task, int ignore_count,
9268                        const struct breakpoint_ops *ops, int from_tty,
9269                        int enabled, int internal, unsigned flags,
9270                        int display_canonical)
9271 {
9272   struct breakpoint *b;
9273   struct cleanup *old_chain;
9274
9275   if (is_tracepoint_type (type))
9276     {
9277       struct tracepoint *t;
9278
9279       t = XCNEW (struct tracepoint);
9280       b = &t->base;
9281     }
9282   else
9283     b = XNEW (struct breakpoint);
9284
9285   old_chain = make_cleanup (xfree, b);
9286
9287   init_breakpoint_sal (b, gdbarch,
9288                        sals, location,
9289                        filter, cond_string, extra_string,
9290                        type, disposition,
9291                        thread, task, ignore_count,
9292                        ops, from_tty,
9293                        enabled, internal, flags,
9294                        display_canonical);
9295   discard_cleanups (old_chain);
9296
9297   install_breakpoint (internal, b, 0);
9298 }
9299
9300 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9301    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9302    value.  COND_STRING, if not NULL, specified the condition to be
9303    used for all breakpoints.  Essentially the only case where
9304    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9305    function.  In that case, it's still not possible to specify
9306    separate conditions for different overloaded functions, so
9307    we take just a single condition string.
9308    
9309    NOTE: If the function succeeds, the caller is expected to cleanup
9310    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9311    array contents).  If the function fails (error() is called), the
9312    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9313    COND and SALS arrays and each of those arrays contents.  */
9314
9315 static void
9316 create_breakpoints_sal (struct gdbarch *gdbarch,
9317                         struct linespec_result *canonical,
9318                         char *cond_string, char *extra_string,
9319                         enum bptype type, enum bpdisp disposition,
9320                         int thread, int task, int ignore_count,
9321                         const struct breakpoint_ops *ops, int from_tty,
9322                         int enabled, int internal, unsigned flags)
9323 {
9324   int i;
9325   struct linespec_sals *lsal;
9326
9327   if (canonical->pre_expanded)
9328     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9329
9330   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9331     {
9332       /* Note that 'location' can be NULL in the case of a plain
9333          'break', without arguments.  */
9334       struct event_location *location
9335         = (canonical->location != NULL
9336            ? copy_event_location (canonical->location) : NULL);
9337       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9338       struct cleanup *inner = make_cleanup_delete_event_location (location);
9339
9340       make_cleanup (xfree, filter_string);
9341       create_breakpoint_sal (gdbarch, lsal->sals,
9342                              location,
9343                              filter_string,
9344                              cond_string, extra_string,
9345                              type, disposition,
9346                              thread, task, ignore_count, ops,
9347                              from_tty, enabled, internal, flags,
9348                              canonical->special_display);
9349       discard_cleanups (inner);
9350     }
9351 }
9352
9353 /* Parse LOCATION which is assumed to be a SAL specification possibly
9354    followed by conditionals.  On return, SALS contains an array of SAL
9355    addresses found.  LOCATION points to the end of the SAL (for
9356    linespec locations).
9357
9358    The array and the line spec strings are allocated on the heap, it is
9359    the caller's responsibility to free them.  */
9360
9361 static void
9362 parse_breakpoint_sals (const struct event_location *location,
9363                        struct linespec_result *canonical)
9364 {
9365   struct symtab_and_line cursal;
9366
9367   if (event_location_type (location) == LINESPEC_LOCATION)
9368     {
9369       const char *address = get_linespec_location (location);
9370
9371       if (address == NULL)
9372         {
9373           /* The last displayed codepoint, if it's valid, is our default
9374              breakpoint address.  */
9375           if (last_displayed_sal_is_valid ())
9376             {
9377               struct linespec_sals lsal;
9378               struct symtab_and_line sal;
9379               CORE_ADDR pc;
9380
9381               init_sal (&sal);          /* Initialize to zeroes.  */
9382               lsal.sals.sals = XNEW (struct symtab_and_line);
9383
9384               /* Set sal's pspace, pc, symtab, and line to the values
9385                  corresponding to the last call to print_frame_info.
9386                  Be sure to reinitialize LINE with NOTCURRENT == 0
9387                  as the breakpoint line number is inappropriate otherwise.
9388                  find_pc_line would adjust PC, re-set it back.  */
9389               get_last_displayed_sal (&sal);
9390               pc = sal.pc;
9391               sal = find_pc_line (pc, 0);
9392
9393               /* "break" without arguments is equivalent to "break *PC"
9394                  where PC is the last displayed codepoint's address.  So
9395                  make sure to set sal.explicit_pc to prevent GDB from
9396                  trying to expand the list of sals to include all other
9397                  instances with the same symtab and line.  */
9398               sal.pc = pc;
9399               sal.explicit_pc = 1;
9400
9401               lsal.sals.sals[0] = sal;
9402               lsal.sals.nelts = 1;
9403               lsal.canonical = NULL;
9404
9405               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9406               return;
9407             }
9408           else
9409             error (_("No default breakpoint address now."));
9410         }
9411     }
9412
9413   /* Force almost all breakpoints to be in terms of the
9414      current_source_symtab (which is decode_line_1's default).
9415      This should produce the results we want almost all of the
9416      time while leaving default_breakpoint_* alone.
9417
9418      ObjC: However, don't match an Objective-C method name which
9419      may have a '+' or '-' succeeded by a '['.  */
9420   cursal = get_current_source_symtab_and_line ();
9421   if (last_displayed_sal_is_valid ())
9422     {
9423       const char *address = NULL;
9424
9425       if (event_location_type (location) == LINESPEC_LOCATION)
9426         address = get_linespec_location (location);
9427
9428       if (!cursal.symtab
9429           || (address != NULL
9430               && strchr ("+-", address[0]) != NULL
9431               && address[1] != '['))
9432         {
9433           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
9434                             get_last_displayed_symtab (),
9435                             get_last_displayed_line (),
9436                             canonical, NULL, NULL);
9437           return;
9438         }
9439     }
9440
9441   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
9442                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9443 }
9444
9445
9446 /* Convert each SAL into a real PC.  Verify that the PC can be
9447    inserted as a breakpoint.  If it can't throw an error.  */
9448
9449 static void
9450 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9451 {    
9452   int i;
9453
9454   for (i = 0; i < sals->nelts; i++)
9455     resolve_sal_pc (&sals->sals[i]);
9456 }
9457
9458 /* Fast tracepoints may have restrictions on valid locations.  For
9459    instance, a fast tracepoint using a jump instead of a trap will
9460    likely have to overwrite more bytes than a trap would, and so can
9461    only be placed where the instruction is longer than the jump, or a
9462    multi-instruction sequence does not have a jump into the middle of
9463    it, etc.  */
9464
9465 static void
9466 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9467                             struct symtabs_and_lines *sals)
9468 {
9469   int i, rslt;
9470   struct symtab_and_line *sal;
9471   char *msg;
9472   struct cleanup *old_chain;
9473
9474   for (i = 0; i < sals->nelts; i++)
9475     {
9476       struct gdbarch *sarch;
9477
9478       sal = &sals->sals[i];
9479
9480       sarch = get_sal_arch (*sal);
9481       /* We fall back to GDBARCH if there is no architecture
9482          associated with SAL.  */
9483       if (sarch == NULL)
9484         sarch = gdbarch;
9485       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9486       old_chain = make_cleanup (xfree, msg);
9487
9488       if (!rslt)
9489         error (_("May not have a fast tracepoint at 0x%s%s"),
9490                paddress (sarch, sal->pc), (msg ? msg : ""));
9491
9492       do_cleanups (old_chain);
9493     }
9494 }
9495
9496 /* Issue an invalid thread ID error.  */
9497
9498 static void ATTRIBUTE_NORETURN
9499 invalid_thread_id_error (int id)
9500 {
9501   error (_("Unknown thread %d."), id);
9502 }
9503
9504 /* Given TOK, a string specification of condition and thread, as
9505    accepted by the 'break' command, extract the condition
9506    string and thread number and set *COND_STRING and *THREAD.
9507    PC identifies the context at which the condition should be parsed.
9508    If no condition is found, *COND_STRING is set to NULL.
9509    If no thread is found, *THREAD is set to -1.  */
9510
9511 static void
9512 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9513                            char **cond_string, int *thread, int *task,
9514                            char **rest)
9515 {
9516   *cond_string = NULL;
9517   *thread = -1;
9518   *task = 0;
9519   *rest = NULL;
9520
9521   while (tok && *tok)
9522     {
9523       const char *end_tok;
9524       int toklen;
9525       const char *cond_start = NULL;
9526       const char *cond_end = NULL;
9527
9528       tok = skip_spaces_const (tok);
9529
9530       if ((*tok == '"' || *tok == ',') && rest)
9531         {
9532           *rest = savestring (tok, strlen (tok));
9533           return;
9534         }
9535
9536       end_tok = skip_to_space_const (tok);
9537
9538       toklen = end_tok - tok;
9539
9540       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9541         {
9542           struct expression *expr;
9543
9544           tok = cond_start = end_tok + 1;
9545           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9546           xfree (expr);
9547           cond_end = tok;
9548           *cond_string = savestring (cond_start, cond_end - cond_start);
9549         }
9550       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9551         {
9552           char *tmptok;
9553
9554           tok = end_tok + 1;
9555           *thread = strtol (tok, &tmptok, 0);
9556           if (tok == tmptok)
9557             error (_("Junk after thread keyword."));
9558           if (!valid_thread_id (*thread))
9559             invalid_thread_id_error (*thread);
9560           tok = tmptok;
9561         }
9562       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9563         {
9564           char *tmptok;
9565
9566           tok = end_tok + 1;
9567           *task = strtol (tok, &tmptok, 0);
9568           if (tok == tmptok)
9569             error (_("Junk after task keyword."));
9570           if (!valid_task_id (*task))
9571             error (_("Unknown task %d."), *task);
9572           tok = tmptok;
9573         }
9574       else if (rest)
9575         {
9576           *rest = savestring (tok, strlen (tok));
9577           return;
9578         }
9579       else
9580         error (_("Junk at end of arguments."));
9581     }
9582 }
9583
9584 /* Decode a static tracepoint marker spec.  */
9585
9586 static struct symtabs_and_lines
9587 decode_static_tracepoint_spec (const char **arg_p)
9588 {
9589   VEC(static_tracepoint_marker_p) *markers = NULL;
9590   struct symtabs_and_lines sals;
9591   struct cleanup *old_chain;
9592   const char *p = &(*arg_p)[3];
9593   const char *endp;
9594   char *marker_str;
9595   int i;
9596
9597   p = skip_spaces_const (p);
9598
9599   endp = skip_to_space_const (p);
9600
9601   marker_str = savestring (p, endp - p);
9602   old_chain = make_cleanup (xfree, marker_str);
9603
9604   markers = target_static_tracepoint_markers_by_strid (marker_str);
9605   if (VEC_empty(static_tracepoint_marker_p, markers))
9606     error (_("No known static tracepoint marker named %s"), marker_str);
9607
9608   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9609   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9610
9611   for (i = 0; i < sals.nelts; i++)
9612     {
9613       struct static_tracepoint_marker *marker;
9614
9615       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9616
9617       init_sal (&sals.sals[i]);
9618
9619       sals.sals[i] = find_pc_line (marker->address, 0);
9620       sals.sals[i].pc = marker->address;
9621
9622       release_static_tracepoint_marker (marker);
9623     }
9624
9625   do_cleanups (old_chain);
9626
9627   *arg_p = endp;
9628   return sals;
9629 }
9630
9631 /* See breakpoint.h.  */
9632
9633 int
9634 create_breakpoint (struct gdbarch *gdbarch,
9635                    const struct event_location *location, char *cond_string,
9636                    int thread, char *extra_string,
9637                    int parse_extra,
9638                    int tempflag, enum bptype type_wanted,
9639                    int ignore_count,
9640                    enum auto_boolean pending_break_support,
9641                    const struct breakpoint_ops *ops,
9642                    int from_tty, int enabled, int internal,
9643                    unsigned flags)
9644 {
9645   struct linespec_result canonical;
9646   struct cleanup *old_chain;
9647   struct cleanup *bkpt_chain = NULL;
9648   int pending = 0;
9649   int task = 0;
9650   int prev_bkpt_count = breakpoint_count;
9651
9652   gdb_assert (ops != NULL);
9653
9654   /* If extra_string isn't useful, set it to NULL.  */
9655   if (extra_string != NULL && *extra_string == '\0')
9656     extra_string = NULL;
9657
9658   init_linespec_result (&canonical);
9659
9660   TRY
9661     {
9662       ops->create_sals_from_location (location, &canonical, type_wanted);
9663     }
9664   CATCH (e, RETURN_MASK_ERROR)
9665     {
9666       /* If caller is interested in rc value from parse, set
9667          value.  */
9668       if (e.error == NOT_FOUND_ERROR)
9669         {
9670           /* If pending breakpoint support is turned off, throw
9671              error.  */
9672
9673           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9674             throw_exception (e);
9675
9676           exception_print (gdb_stderr, e);
9677
9678           /* If pending breakpoint support is auto query and the user
9679              selects no, then simply return the error code.  */
9680           if (pending_break_support == AUTO_BOOLEAN_AUTO
9681               && !nquery (_("Make %s pending on future shared library load? "),
9682                           bptype_string (type_wanted)))
9683             return 0;
9684
9685           /* At this point, either the user was queried about setting
9686              a pending breakpoint and selected yes, or pending
9687              breakpoint behavior is on and thus a pending breakpoint
9688              is defaulted on behalf of the user.  */
9689           pending = 1;
9690         }
9691       else
9692         throw_exception (e);
9693     }
9694   END_CATCH
9695
9696   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9697     return 0;
9698
9699   /* Create a chain of things that always need to be cleaned up.  */
9700   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9701
9702   /* ----------------------------- SNIP -----------------------------
9703      Anything added to the cleanup chain beyond this point is assumed
9704      to be part of a breakpoint.  If the breakpoint create succeeds
9705      then the memory is not reclaimed.  */
9706   bkpt_chain = make_cleanup (null_cleanup, 0);
9707
9708   /* Resolve all line numbers to PC's and verify that the addresses
9709      are ok for the target.  */
9710   if (!pending)
9711     {
9712       int ix;
9713       struct linespec_sals *iter;
9714
9715       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9716         breakpoint_sals_to_pc (&iter->sals);
9717     }
9718
9719   /* Fast tracepoints may have additional restrictions on location.  */
9720   if (!pending && type_wanted == bp_fast_tracepoint)
9721     {
9722       int ix;
9723       struct linespec_sals *iter;
9724
9725       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9726         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9727     }
9728
9729   /* Verify that condition can be parsed, before setting any
9730      breakpoints.  Allocate a separate condition expression for each
9731      breakpoint.  */
9732   if (!pending)
9733     {
9734       if (parse_extra)
9735         {
9736           char *rest;
9737           struct linespec_sals *lsal;
9738
9739           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9740
9741           /* Here we only parse 'arg' to separate condition
9742              from thread number, so parsing in context of first
9743              sal is OK.  When setting the breakpoint we'll
9744              re-parse it in context of each sal.  */
9745
9746           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9747                                      &cond_string, &thread, &task, &rest);
9748           if (cond_string)
9749             make_cleanup (xfree, cond_string);
9750           if (rest)
9751             make_cleanup (xfree, rest);
9752           if (rest)
9753             extra_string = rest;
9754           else
9755             extra_string = NULL;
9756         }
9757       else
9758         {
9759           if (type_wanted != bp_dprintf
9760               && extra_string != NULL && *extra_string != '\0')
9761                 error (_("Garbage '%s' at end of location"), extra_string);
9762
9763           /* Create a private copy of condition string.  */
9764           if (cond_string)
9765             {
9766               cond_string = xstrdup (cond_string);
9767               make_cleanup (xfree, cond_string);
9768             }
9769           /* Create a private copy of any extra string.  */
9770           if (extra_string)
9771             {
9772               extra_string = xstrdup (extra_string);
9773               make_cleanup (xfree, extra_string);
9774             }
9775         }
9776
9777       ops->create_breakpoints_sal (gdbarch, &canonical,
9778                                    cond_string, extra_string, type_wanted,
9779                                    tempflag ? disp_del : disp_donttouch,
9780                                    thread, task, ignore_count, ops,
9781                                    from_tty, enabled, internal, flags);
9782     }
9783   else
9784     {
9785       struct breakpoint *b;
9786
9787       if (is_tracepoint_type (type_wanted))
9788         {
9789           struct tracepoint *t;
9790
9791           t = XCNEW (struct tracepoint);
9792           b = &t->base;
9793         }
9794       else
9795         b = XNEW (struct breakpoint);
9796
9797       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9798       b->location = copy_event_location (location);
9799
9800       if (parse_extra)
9801         b->cond_string = NULL;
9802       else
9803         {
9804           /* Create a private copy of condition string.  */
9805           if (cond_string)
9806             {
9807               cond_string = xstrdup (cond_string);
9808               make_cleanup (xfree, cond_string);
9809             }
9810           b->cond_string = cond_string;
9811           b->thread = thread;
9812         }
9813
9814       /* Create a private copy of any extra string.  */
9815       if (extra_string != NULL)
9816         {
9817           extra_string = xstrdup (extra_string);
9818           make_cleanup (xfree, extra_string);
9819         }
9820       b->extra_string = extra_string;
9821       b->ignore_count = ignore_count;
9822       b->disposition = tempflag ? disp_del : disp_donttouch;
9823       b->condition_not_parsed = 1;
9824       b->enable_state = enabled ? bp_enabled : bp_disabled;
9825       if ((type_wanted != bp_breakpoint
9826            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9827         b->pspace = current_program_space;
9828
9829       install_breakpoint (internal, b, 0);
9830     }
9831   
9832   if (VEC_length (linespec_sals, canonical.sals) > 1)
9833     {
9834       warning (_("Multiple breakpoints were set.\nUse the "
9835                  "\"delete\" command to delete unwanted breakpoints."));
9836       prev_breakpoint_count = prev_bkpt_count;
9837     }
9838
9839   /* That's it.  Discard the cleanups for data inserted into the
9840      breakpoint.  */
9841   discard_cleanups (bkpt_chain);
9842   /* But cleanup everything else.  */
9843   do_cleanups (old_chain);
9844
9845   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9846   update_global_location_list (UGLL_MAY_INSERT);
9847
9848   return 1;
9849 }
9850
9851 /* Set a breakpoint.
9852    ARG is a string describing breakpoint address,
9853    condition, and thread.
9854    FLAG specifies if a breakpoint is hardware on,
9855    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9856    and BP_TEMPFLAG.  */
9857
9858 static void
9859 break_command_1 (char *arg, int flag, int from_tty)
9860 {
9861   int tempflag = flag & BP_TEMPFLAG;
9862   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9863                              ? bp_hardware_breakpoint
9864                              : bp_breakpoint);
9865   struct breakpoint_ops *ops;
9866   struct event_location *location;
9867   struct cleanup *cleanup;
9868
9869   location = string_to_event_location (&arg, current_language);
9870   cleanup = make_cleanup_delete_event_location (location);
9871
9872   /* Matching breakpoints on probes.  */
9873   if (location != NULL
9874       && event_location_type (location) == PROBE_LOCATION)
9875     ops = &bkpt_probe_breakpoint_ops;
9876   else
9877     ops = &bkpt_breakpoint_ops;
9878
9879   create_breakpoint (get_current_arch (),
9880                      location,
9881                      NULL, 0, arg, 1 /* parse arg */,
9882                      tempflag, type_wanted,
9883                      0 /* Ignore count */,
9884                      pending_break_support,
9885                      ops,
9886                      from_tty,
9887                      1 /* enabled */,
9888                      0 /* internal */,
9889                      0);
9890   do_cleanups (cleanup);
9891 }
9892
9893 /* Helper function for break_command_1 and disassemble_command.  */
9894
9895 void
9896 resolve_sal_pc (struct symtab_and_line *sal)
9897 {
9898   CORE_ADDR pc;
9899
9900   if (sal->pc == 0 && sal->symtab != NULL)
9901     {
9902       if (!find_line_pc (sal->symtab, sal->line, &pc))
9903         error (_("No line %d in file \"%s\"."),
9904                sal->line, symtab_to_filename_for_display (sal->symtab));
9905       sal->pc = pc;
9906
9907       /* If this SAL corresponds to a breakpoint inserted using a line
9908          number, then skip the function prologue if necessary.  */
9909       if (sal->explicit_line)
9910         skip_prologue_sal (sal);
9911     }
9912
9913   if (sal->section == 0 && sal->symtab != NULL)
9914     {
9915       const struct blockvector *bv;
9916       const struct block *b;
9917       struct symbol *sym;
9918
9919       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9920                                     SYMTAB_COMPUNIT (sal->symtab));
9921       if (bv != NULL)
9922         {
9923           sym = block_linkage_function (b);
9924           if (sym != NULL)
9925             {
9926               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9927               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9928                                                  sym);
9929             }
9930           else
9931             {
9932               /* It really is worthwhile to have the section, so we'll
9933                  just have to look harder. This case can be executed
9934                  if we have line numbers but no functions (as can
9935                  happen in assembly source).  */
9936
9937               struct bound_minimal_symbol msym;
9938               struct cleanup *old_chain = save_current_space_and_thread ();
9939
9940               switch_to_program_space_and_thread (sal->pspace);
9941
9942               msym = lookup_minimal_symbol_by_pc (sal->pc);
9943               if (msym.minsym)
9944                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9945
9946               do_cleanups (old_chain);
9947             }
9948         }
9949     }
9950 }
9951
9952 void
9953 break_command (char *arg, int from_tty)
9954 {
9955   break_command_1 (arg, 0, from_tty);
9956 }
9957
9958 void
9959 tbreak_command (char *arg, int from_tty)
9960 {
9961   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9962 }
9963
9964 static void
9965 hbreak_command (char *arg, int from_tty)
9966 {
9967   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9968 }
9969
9970 static void
9971 thbreak_command (char *arg, int from_tty)
9972 {
9973   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9974 }
9975
9976 static void
9977 stop_command (char *arg, int from_tty)
9978 {
9979   printf_filtered (_("Specify the type of breakpoint to set.\n\
9980 Usage: stop in <function | address>\n\
9981        stop at <line>\n"));
9982 }
9983
9984 static void
9985 stopin_command (char *arg, int from_tty)
9986 {
9987   int badInput = 0;
9988
9989   if (arg == (char *) NULL)
9990     badInput = 1;
9991   else if (*arg != '*')
9992     {
9993       char *argptr = arg;
9994       int hasColon = 0;
9995
9996       /* Look for a ':'.  If this is a line number specification, then
9997          say it is bad, otherwise, it should be an address or
9998          function/method name.  */
9999       while (*argptr && !hasColon)
10000         {
10001           hasColon = (*argptr == ':');
10002           argptr++;
10003         }
10004
10005       if (hasColon)
10006         badInput = (*argptr != ':');    /* Not a class::method */
10007       else
10008         badInput = isdigit (*arg);      /* a simple line number */
10009     }
10010
10011   if (badInput)
10012     printf_filtered (_("Usage: stop in <function | address>\n"));
10013   else
10014     break_command_1 (arg, 0, from_tty);
10015 }
10016
10017 static void
10018 stopat_command (char *arg, int from_tty)
10019 {
10020   int badInput = 0;
10021
10022   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10023     badInput = 1;
10024   else
10025     {
10026       char *argptr = arg;
10027       int hasColon = 0;
10028
10029       /* Look for a ':'.  If there is a '::' then get out, otherwise
10030          it is probably a line number.  */
10031       while (*argptr && !hasColon)
10032         {
10033           hasColon = (*argptr == ':');
10034           argptr++;
10035         }
10036
10037       if (hasColon)
10038         badInput = (*argptr == ':');    /* we have class::method */
10039       else
10040         badInput = !isdigit (*arg);     /* not a line number */
10041     }
10042
10043   if (badInput)
10044     printf_filtered (_("Usage: stop at <line>\n"));
10045   else
10046     break_command_1 (arg, 0, from_tty);
10047 }
10048
10049 /* The dynamic printf command is mostly like a regular breakpoint, but
10050    with a prewired command list consisting of a single output command,
10051    built from extra arguments supplied on the dprintf command
10052    line.  */
10053
10054 static void
10055 dprintf_command (char *arg, int from_tty)
10056 {
10057   struct event_location *location;
10058   struct cleanup *cleanup;
10059
10060   location = string_to_event_location (&arg, current_language);
10061   cleanup = make_cleanup_delete_event_location (location);
10062
10063   /* If non-NULL, ARG should have been advanced past the location;
10064      the next character must be ','.  */
10065   if (arg != NULL)
10066     {
10067       if (arg[0] != ',' || arg[1] == '\0')
10068         error (_("Format string required"));
10069       else
10070         {
10071           /* Skip the comma.  */
10072           ++arg;
10073         }
10074     }
10075
10076   create_breakpoint (get_current_arch (),
10077                      location,
10078                      NULL, 0, arg, 1 /* parse arg */,
10079                      0, bp_dprintf,
10080                      0 /* Ignore count */,
10081                      pending_break_support,
10082                      &dprintf_breakpoint_ops,
10083                      from_tty,
10084                      1 /* enabled */,
10085                      0 /* internal */,
10086                      0);
10087   do_cleanups (cleanup);
10088 }
10089
10090 static void
10091 agent_printf_command (char *arg, int from_tty)
10092 {
10093   error (_("May only run agent-printf on the target"));
10094 }
10095
10096 /* Implement the "breakpoint_hit" breakpoint_ops method for
10097    ranged breakpoints.  */
10098
10099 static int
10100 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10101                                   struct address_space *aspace,
10102                                   CORE_ADDR bp_addr,
10103                                   const struct target_waitstatus *ws)
10104 {
10105   if (ws->kind != TARGET_WAITKIND_STOPPED
10106       || ws->value.sig != GDB_SIGNAL_TRAP)
10107     return 0;
10108
10109   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10110                                          bl->length, aspace, bp_addr);
10111 }
10112
10113 /* Implement the "resources_needed" breakpoint_ops method for
10114    ranged breakpoints.  */
10115
10116 static int
10117 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10118 {
10119   return target_ranged_break_num_registers ();
10120 }
10121
10122 /* Implement the "print_it" breakpoint_ops method for
10123    ranged breakpoints.  */
10124
10125 static enum print_stop_action
10126 print_it_ranged_breakpoint (bpstat bs)
10127 {
10128   struct breakpoint *b = bs->breakpoint_at;
10129   struct bp_location *bl = b->loc;
10130   struct ui_out *uiout = current_uiout;
10131
10132   gdb_assert (b->type == bp_hardware_breakpoint);
10133
10134   /* Ranged breakpoints have only one location.  */
10135   gdb_assert (bl && bl->next == NULL);
10136
10137   annotate_breakpoint (b->number);
10138   if (b->disposition == disp_del)
10139     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10140   else
10141     ui_out_text (uiout, "\nRanged breakpoint ");
10142   if (ui_out_is_mi_like_p (uiout))
10143     {
10144       ui_out_field_string (uiout, "reason",
10145                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10146       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10147     }
10148   ui_out_field_int (uiout, "bkptno", b->number);
10149   ui_out_text (uiout, ", ");
10150
10151   return PRINT_SRC_AND_LOC;
10152 }
10153
10154 /* Implement the "print_one" breakpoint_ops method for
10155    ranged breakpoints.  */
10156
10157 static void
10158 print_one_ranged_breakpoint (struct breakpoint *b,
10159                              struct bp_location **last_loc)
10160 {
10161   struct bp_location *bl = b->loc;
10162   struct value_print_options opts;
10163   struct ui_out *uiout = current_uiout;
10164
10165   /* Ranged breakpoints have only one location.  */
10166   gdb_assert (bl && bl->next == NULL);
10167
10168   get_user_print_options (&opts);
10169
10170   if (opts.addressprint)
10171     /* We don't print the address range here, it will be printed later
10172        by print_one_detail_ranged_breakpoint.  */
10173     ui_out_field_skip (uiout, "addr");
10174   annotate_field (5);
10175   print_breakpoint_location (b, bl);
10176   *last_loc = bl;
10177 }
10178
10179 /* Implement the "print_one_detail" breakpoint_ops method for
10180    ranged breakpoints.  */
10181
10182 static void
10183 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10184                                     struct ui_out *uiout)
10185 {
10186   CORE_ADDR address_start, address_end;
10187   struct bp_location *bl = b->loc;
10188   struct ui_file *stb = mem_fileopen ();
10189   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10190
10191   gdb_assert (bl);
10192
10193   address_start = bl->address;
10194   address_end = address_start + bl->length - 1;
10195
10196   ui_out_text (uiout, "\taddress range: ");
10197   fprintf_unfiltered (stb, "[%s, %s]",
10198                       print_core_address (bl->gdbarch, address_start),
10199                       print_core_address (bl->gdbarch, address_end));
10200   ui_out_field_stream (uiout, "addr", stb);
10201   ui_out_text (uiout, "\n");
10202
10203   do_cleanups (cleanup);
10204 }
10205
10206 /* Implement the "print_mention" breakpoint_ops method for
10207    ranged breakpoints.  */
10208
10209 static void
10210 print_mention_ranged_breakpoint (struct breakpoint *b)
10211 {
10212   struct bp_location *bl = b->loc;
10213   struct ui_out *uiout = current_uiout;
10214
10215   gdb_assert (bl);
10216   gdb_assert (b->type == bp_hardware_breakpoint);
10217
10218   if (ui_out_is_mi_like_p (uiout))
10219     return;
10220
10221   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10222                    b->number, paddress (bl->gdbarch, bl->address),
10223                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10224 }
10225
10226 /* Implement the "print_recreate" breakpoint_ops method for
10227    ranged breakpoints.  */
10228
10229 static void
10230 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10231 {
10232   fprintf_unfiltered (fp, "break-range %s, %s",
10233                       event_location_to_string (b->location),
10234                       event_location_to_string (b->location_range_end));
10235   print_recreate_thread (b, fp);
10236 }
10237
10238 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10239
10240 static struct breakpoint_ops ranged_breakpoint_ops;
10241
10242 /* Find the address where the end of the breakpoint range should be
10243    placed, given the SAL of the end of the range.  This is so that if
10244    the user provides a line number, the end of the range is set to the
10245    last instruction of the given line.  */
10246
10247 static CORE_ADDR
10248 find_breakpoint_range_end (struct symtab_and_line sal)
10249 {
10250   CORE_ADDR end;
10251
10252   /* If the user provided a PC value, use it.  Otherwise,
10253      find the address of the end of the given location.  */
10254   if (sal.explicit_pc)
10255     end = sal.pc;
10256   else
10257     {
10258       int ret;
10259       CORE_ADDR start;
10260
10261       ret = find_line_pc_range (sal, &start, &end);
10262       if (!ret)
10263         error (_("Could not find location of the end of the range."));
10264
10265       /* find_line_pc_range returns the start of the next line.  */
10266       end--;
10267     }
10268
10269   return end;
10270 }
10271
10272 /* Implement the "break-range" CLI command.  */
10273
10274 static void
10275 break_range_command (char *arg, int from_tty)
10276 {
10277   char *arg_start, *addr_string_start, *addr_string_end;
10278   struct linespec_result canonical_start, canonical_end;
10279   int bp_count, can_use_bp, length;
10280   CORE_ADDR end;
10281   struct breakpoint *b;
10282   struct symtab_and_line sal_start, sal_end;
10283   struct cleanup *cleanup_bkpt;
10284   struct linespec_sals *lsal_start, *lsal_end;
10285   struct event_location *start_location, *end_location;
10286
10287   /* We don't support software ranged breakpoints.  */
10288   if (target_ranged_break_num_registers () < 0)
10289     error (_("This target does not support hardware ranged breakpoints."));
10290
10291   bp_count = hw_breakpoint_used_count ();
10292   bp_count += target_ranged_break_num_registers ();
10293   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10294                                                    bp_count, 0);
10295   if (can_use_bp < 0)
10296     error (_("Hardware breakpoints used exceeds limit."));
10297
10298   arg = skip_spaces (arg);
10299   if (arg == NULL || arg[0] == '\0')
10300     error(_("No address range specified."));
10301
10302   init_linespec_result (&canonical_start);
10303
10304   arg_start = arg;
10305   start_location = string_to_event_location (&arg, current_language);
10306   cleanup_bkpt = make_cleanup_delete_event_location (start_location);
10307   parse_breakpoint_sals (start_location, &canonical_start);
10308   make_cleanup_destroy_linespec_result (&canonical_start);
10309
10310   if (arg[0] != ',')
10311     error (_("Too few arguments."));
10312   else if (VEC_empty (linespec_sals, canonical_start.sals))
10313     error (_("Could not find location of the beginning of the range."));
10314
10315   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10316
10317   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10318       || lsal_start->sals.nelts != 1)
10319     error (_("Cannot create a ranged breakpoint with multiple locations."));
10320
10321   sal_start = lsal_start->sals.sals[0];
10322   addr_string_start = savestring (arg_start, arg - arg_start);
10323   make_cleanup (xfree, addr_string_start);
10324
10325   arg++;        /* Skip the comma.  */
10326   arg = skip_spaces (arg);
10327
10328   /* Parse the end location.  */
10329
10330   init_linespec_result (&canonical_end);
10331   arg_start = arg;
10332
10333   /* We call decode_line_full directly here instead of using
10334      parse_breakpoint_sals because we need to specify the start location's
10335      symtab and line as the default symtab and line for the end of the
10336      range.  This makes it possible to have ranges like "foo.c:27, +14",
10337      where +14 means 14 lines from the start location.  */
10338   end_location = string_to_event_location (&arg, current_language);
10339   make_cleanup_delete_event_location (end_location);
10340   decode_line_full (end_location, DECODE_LINE_FUNFIRSTLINE,
10341                     sal_start.symtab, sal_start.line,
10342                     &canonical_end, NULL, NULL);
10343
10344   make_cleanup_destroy_linespec_result (&canonical_end);
10345
10346   if (VEC_empty (linespec_sals, canonical_end.sals))
10347     error (_("Could not find location of the end of the range."));
10348
10349   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10350   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10351       || lsal_end->sals.nelts != 1)
10352     error (_("Cannot create a ranged breakpoint with multiple locations."));
10353
10354   sal_end = lsal_end->sals.sals[0];
10355
10356   end = find_breakpoint_range_end (sal_end);
10357   if (sal_start.pc > end)
10358     error (_("Invalid address range, end precedes start."));
10359
10360   length = end - sal_start.pc + 1;
10361   if (length < 0)
10362     /* Length overflowed.  */
10363     error (_("Address range too large."));
10364   else if (length == 1)
10365     {
10366       /* This range is simple enough to be handled by
10367          the `hbreak' command.  */
10368       hbreak_command (addr_string_start, 1);
10369
10370       do_cleanups (cleanup_bkpt);
10371
10372       return;
10373     }
10374
10375   /* Now set up the breakpoint.  */
10376   b = set_raw_breakpoint (get_current_arch (), sal_start,
10377                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10378   set_breakpoint_count (breakpoint_count + 1);
10379   b->number = breakpoint_count;
10380   b->disposition = disp_donttouch;
10381   b->location = copy_event_location (start_location);
10382   b->location_range_end = copy_event_location (end_location);
10383   b->loc->length = length;
10384
10385   do_cleanups (cleanup_bkpt);
10386
10387   mention (b);
10388   observer_notify_breakpoint_created (b);
10389   update_global_location_list (UGLL_MAY_INSERT);
10390 }
10391
10392 /*  Return non-zero if EXP is verified as constant.  Returned zero
10393     means EXP is variable.  Also the constant detection may fail for
10394     some constant expressions and in such case still falsely return
10395     zero.  */
10396
10397 static int
10398 watchpoint_exp_is_const (const struct expression *exp)
10399 {
10400   int i = exp->nelts;
10401
10402   while (i > 0)
10403     {
10404       int oplenp, argsp;
10405
10406       /* We are only interested in the descriptor of each element.  */
10407       operator_length (exp, i, &oplenp, &argsp);
10408       i -= oplenp;
10409
10410       switch (exp->elts[i].opcode)
10411         {
10412         case BINOP_ADD:
10413         case BINOP_SUB:
10414         case BINOP_MUL:
10415         case BINOP_DIV:
10416         case BINOP_REM:
10417         case BINOP_MOD:
10418         case BINOP_LSH:
10419         case BINOP_RSH:
10420         case BINOP_LOGICAL_AND:
10421         case BINOP_LOGICAL_OR:
10422         case BINOP_BITWISE_AND:
10423         case BINOP_BITWISE_IOR:
10424         case BINOP_BITWISE_XOR:
10425         case BINOP_EQUAL:
10426         case BINOP_NOTEQUAL:
10427         case BINOP_LESS:
10428         case BINOP_GTR:
10429         case BINOP_LEQ:
10430         case BINOP_GEQ:
10431         case BINOP_REPEAT:
10432         case BINOP_COMMA:
10433         case BINOP_EXP:
10434         case BINOP_MIN:
10435         case BINOP_MAX:
10436         case BINOP_INTDIV:
10437         case BINOP_CONCAT:
10438         case TERNOP_COND:
10439         case TERNOP_SLICE:
10440
10441         case OP_LONG:
10442         case OP_DOUBLE:
10443         case OP_DECFLOAT:
10444         case OP_LAST:
10445         case OP_COMPLEX:
10446         case OP_STRING:
10447         case OP_ARRAY:
10448         case OP_TYPE:
10449         case OP_TYPEOF:
10450         case OP_DECLTYPE:
10451         case OP_TYPEID:
10452         case OP_NAME:
10453         case OP_OBJC_NSSTRING:
10454
10455         case UNOP_NEG:
10456         case UNOP_LOGICAL_NOT:
10457         case UNOP_COMPLEMENT:
10458         case UNOP_ADDR:
10459         case UNOP_HIGH:
10460         case UNOP_CAST:
10461
10462         case UNOP_CAST_TYPE:
10463         case UNOP_REINTERPRET_CAST:
10464         case UNOP_DYNAMIC_CAST:
10465           /* Unary, binary and ternary operators: We have to check
10466              their operands.  If they are constant, then so is the
10467              result of that operation.  For instance, if A and B are
10468              determined to be constants, then so is "A + B".
10469
10470              UNOP_IND is one exception to the rule above, because the
10471              value of *ADDR is not necessarily a constant, even when
10472              ADDR is.  */
10473           break;
10474
10475         case OP_VAR_VALUE:
10476           /* Check whether the associated symbol is a constant.
10477
10478              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10479              possible that a buggy compiler could mark a variable as
10480              constant even when it is not, and TYPE_CONST would return
10481              true in this case, while SYMBOL_CLASS wouldn't.
10482
10483              We also have to check for function symbols because they
10484              are always constant.  */
10485           {
10486             struct symbol *s = exp->elts[i + 2].symbol;
10487
10488             if (SYMBOL_CLASS (s) != LOC_BLOCK
10489                 && SYMBOL_CLASS (s) != LOC_CONST
10490                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10491               return 0;
10492             break;
10493           }
10494
10495         /* The default action is to return 0 because we are using
10496            the optimistic approach here: If we don't know something,
10497            then it is not a constant.  */
10498         default:
10499           return 0;
10500         }
10501     }
10502
10503   return 1;
10504 }
10505
10506 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10507
10508 static void
10509 dtor_watchpoint (struct breakpoint *self)
10510 {
10511   struct watchpoint *w = (struct watchpoint *) self;
10512
10513   xfree (w->cond_exp);
10514   xfree (w->exp);
10515   xfree (w->exp_string);
10516   xfree (w->exp_string_reparse);
10517   value_free (w->val);
10518
10519   base_breakpoint_ops.dtor (self);
10520 }
10521
10522 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10523
10524 static void
10525 re_set_watchpoint (struct breakpoint *b)
10526 {
10527   struct watchpoint *w = (struct watchpoint *) b;
10528
10529   /* Watchpoint can be either on expression using entirely global
10530      variables, or it can be on local variables.
10531
10532      Watchpoints of the first kind are never auto-deleted, and even
10533      persist across program restarts.  Since they can use variables
10534      from shared libraries, we need to reparse expression as libraries
10535      are loaded and unloaded.
10536
10537      Watchpoints on local variables can also change meaning as result
10538      of solib event.  For example, if a watchpoint uses both a local
10539      and a global variables in expression, it's a local watchpoint,
10540      but unloading of a shared library will make the expression
10541      invalid.  This is not a very common use case, but we still
10542      re-evaluate expression, to avoid surprises to the user.
10543
10544      Note that for local watchpoints, we re-evaluate it only if
10545      watchpoints frame id is still valid.  If it's not, it means the
10546      watchpoint is out of scope and will be deleted soon.  In fact,
10547      I'm not sure we'll ever be called in this case.
10548
10549      If a local watchpoint's frame id is still valid, then
10550      w->exp_valid_block is likewise valid, and we can safely use it.
10551
10552      Don't do anything about disabled watchpoints, since they will be
10553      reevaluated again when enabled.  */
10554   update_watchpoint (w, 1 /* reparse */);
10555 }
10556
10557 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10558
10559 static int
10560 insert_watchpoint (struct bp_location *bl)
10561 {
10562   struct watchpoint *w = (struct watchpoint *) bl->owner;
10563   int length = w->exact ? 1 : bl->length;
10564
10565   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10566                                    w->cond_exp);
10567 }
10568
10569 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10570
10571 static int
10572 remove_watchpoint (struct bp_location *bl)
10573 {
10574   struct watchpoint *w = (struct watchpoint *) bl->owner;
10575   int length = w->exact ? 1 : bl->length;
10576
10577   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10578                                    w->cond_exp);
10579 }
10580
10581 static int
10582 breakpoint_hit_watchpoint (const struct bp_location *bl,
10583                            struct address_space *aspace, CORE_ADDR bp_addr,
10584                            const struct target_waitstatus *ws)
10585 {
10586   struct breakpoint *b = bl->owner;
10587   struct watchpoint *w = (struct watchpoint *) b;
10588
10589   /* Continuable hardware watchpoints are treated as non-existent if the
10590      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10591      some data address).  Otherwise gdb won't stop on a break instruction
10592      in the code (not from a breakpoint) when a hardware watchpoint has
10593      been defined.  Also skip watchpoints which we know did not trigger
10594      (did not match the data address).  */
10595   if (is_hardware_watchpoint (b)
10596       && w->watchpoint_triggered == watch_triggered_no)
10597     return 0;
10598
10599   return 1;
10600 }
10601
10602 static void
10603 check_status_watchpoint (bpstat bs)
10604 {
10605   gdb_assert (is_watchpoint (bs->breakpoint_at));
10606
10607   bpstat_check_watchpoint (bs);
10608 }
10609
10610 /* Implement the "resources_needed" breakpoint_ops method for
10611    hardware watchpoints.  */
10612
10613 static int
10614 resources_needed_watchpoint (const struct bp_location *bl)
10615 {
10616   struct watchpoint *w = (struct watchpoint *) bl->owner;
10617   int length = w->exact? 1 : bl->length;
10618
10619   return target_region_ok_for_hw_watchpoint (bl->address, length);
10620 }
10621
10622 /* Implement the "works_in_software_mode" breakpoint_ops method for
10623    hardware watchpoints.  */
10624
10625 static int
10626 works_in_software_mode_watchpoint (const struct breakpoint *b)
10627 {
10628   /* Read and access watchpoints only work with hardware support.  */
10629   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10630 }
10631
10632 static enum print_stop_action
10633 print_it_watchpoint (bpstat bs)
10634 {
10635   struct cleanup *old_chain;
10636   struct breakpoint *b;
10637   struct ui_file *stb;
10638   enum print_stop_action result;
10639   struct watchpoint *w;
10640   struct ui_out *uiout = current_uiout;
10641
10642   gdb_assert (bs->bp_location_at != NULL);
10643
10644   b = bs->breakpoint_at;
10645   w = (struct watchpoint *) b;
10646
10647   stb = mem_fileopen ();
10648   old_chain = make_cleanup_ui_file_delete (stb);
10649
10650   switch (b->type)
10651     {
10652     case bp_watchpoint:
10653     case bp_hardware_watchpoint:
10654       annotate_watchpoint (b->number);
10655       if (ui_out_is_mi_like_p (uiout))
10656         ui_out_field_string
10657           (uiout, "reason",
10658            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10659       mention (b);
10660       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10661       ui_out_text (uiout, "\nOld value = ");
10662       watchpoint_value_print (bs->old_val, stb);
10663       ui_out_field_stream (uiout, "old", stb);
10664       ui_out_text (uiout, "\nNew value = ");
10665       watchpoint_value_print (w->val, stb);
10666       ui_out_field_stream (uiout, "new", stb);
10667       ui_out_text (uiout, "\n");
10668       /* More than one watchpoint may have been triggered.  */
10669       result = PRINT_UNKNOWN;
10670       break;
10671
10672     case bp_read_watchpoint:
10673       if (ui_out_is_mi_like_p (uiout))
10674         ui_out_field_string
10675           (uiout, "reason",
10676            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10677       mention (b);
10678       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10679       ui_out_text (uiout, "\nValue = ");
10680       watchpoint_value_print (w->val, stb);
10681       ui_out_field_stream (uiout, "value", stb);
10682       ui_out_text (uiout, "\n");
10683       result = PRINT_UNKNOWN;
10684       break;
10685
10686     case bp_access_watchpoint:
10687       if (bs->old_val != NULL)
10688         {
10689           annotate_watchpoint (b->number);
10690           if (ui_out_is_mi_like_p (uiout))
10691             ui_out_field_string
10692               (uiout, "reason",
10693                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10694           mention (b);
10695           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10696           ui_out_text (uiout, "\nOld value = ");
10697           watchpoint_value_print (bs->old_val, stb);
10698           ui_out_field_stream (uiout, "old", stb);
10699           ui_out_text (uiout, "\nNew value = ");
10700         }
10701       else
10702         {
10703           mention (b);
10704           if (ui_out_is_mi_like_p (uiout))
10705             ui_out_field_string
10706               (uiout, "reason",
10707                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10708           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10709           ui_out_text (uiout, "\nValue = ");
10710         }
10711       watchpoint_value_print (w->val, stb);
10712       ui_out_field_stream (uiout, "new", stb);
10713       ui_out_text (uiout, "\n");
10714       result = PRINT_UNKNOWN;
10715       break;
10716     default:
10717       result = PRINT_UNKNOWN;
10718     }
10719
10720   do_cleanups (old_chain);
10721   return result;
10722 }
10723
10724 /* Implement the "print_mention" breakpoint_ops method for hardware
10725    watchpoints.  */
10726
10727 static void
10728 print_mention_watchpoint (struct breakpoint *b)
10729 {
10730   struct cleanup *ui_out_chain;
10731   struct watchpoint *w = (struct watchpoint *) b;
10732   struct ui_out *uiout = current_uiout;
10733
10734   switch (b->type)
10735     {
10736     case bp_watchpoint:
10737       ui_out_text (uiout, "Watchpoint ");
10738       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10739       break;
10740     case bp_hardware_watchpoint:
10741       ui_out_text (uiout, "Hardware watchpoint ");
10742       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10743       break;
10744     case bp_read_watchpoint:
10745       ui_out_text (uiout, "Hardware read watchpoint ");
10746       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10747       break;
10748     case bp_access_watchpoint:
10749       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10750       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10751       break;
10752     default:
10753       internal_error (__FILE__, __LINE__,
10754                       _("Invalid hardware watchpoint type."));
10755     }
10756
10757   ui_out_field_int (uiout, "number", b->number);
10758   ui_out_text (uiout, ": ");
10759   ui_out_field_string (uiout, "exp", w->exp_string);
10760   do_cleanups (ui_out_chain);
10761 }
10762
10763 /* Implement the "print_recreate" breakpoint_ops method for
10764    watchpoints.  */
10765
10766 static void
10767 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10768 {
10769   struct watchpoint *w = (struct watchpoint *) b;
10770
10771   switch (b->type)
10772     {
10773     case bp_watchpoint:
10774     case bp_hardware_watchpoint:
10775       fprintf_unfiltered (fp, "watch");
10776       break;
10777     case bp_read_watchpoint:
10778       fprintf_unfiltered (fp, "rwatch");
10779       break;
10780     case bp_access_watchpoint:
10781       fprintf_unfiltered (fp, "awatch");
10782       break;
10783     default:
10784       internal_error (__FILE__, __LINE__,
10785                       _("Invalid watchpoint type."));
10786     }
10787
10788   fprintf_unfiltered (fp, " %s", w->exp_string);
10789   print_recreate_thread (b, fp);
10790 }
10791
10792 /* Implement the "explains_signal" breakpoint_ops method for
10793    watchpoints.  */
10794
10795 static int
10796 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10797 {
10798   /* A software watchpoint cannot cause a signal other than
10799      GDB_SIGNAL_TRAP.  */
10800   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10801     return 0;
10802
10803   return 1;
10804 }
10805
10806 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10807
10808 static struct breakpoint_ops watchpoint_breakpoint_ops;
10809
10810 /* Implement the "insert" breakpoint_ops method for
10811    masked hardware watchpoints.  */
10812
10813 static int
10814 insert_masked_watchpoint (struct bp_location *bl)
10815 {
10816   struct watchpoint *w = (struct watchpoint *) bl->owner;
10817
10818   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10819                                         bl->watchpoint_type);
10820 }
10821
10822 /* Implement the "remove" breakpoint_ops method for
10823    masked hardware watchpoints.  */
10824
10825 static int
10826 remove_masked_watchpoint (struct bp_location *bl)
10827 {
10828   struct watchpoint *w = (struct watchpoint *) bl->owner;
10829
10830   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10831                                         bl->watchpoint_type);
10832 }
10833
10834 /* Implement the "resources_needed" breakpoint_ops method for
10835    masked hardware watchpoints.  */
10836
10837 static int
10838 resources_needed_masked_watchpoint (const struct bp_location *bl)
10839 {
10840   struct watchpoint *w = (struct watchpoint *) bl->owner;
10841
10842   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10843 }
10844
10845 /* Implement the "works_in_software_mode" breakpoint_ops method for
10846    masked hardware watchpoints.  */
10847
10848 static int
10849 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10850 {
10851   return 0;
10852 }
10853
10854 /* Implement the "print_it" breakpoint_ops method for
10855    masked hardware watchpoints.  */
10856
10857 static enum print_stop_action
10858 print_it_masked_watchpoint (bpstat bs)
10859 {
10860   struct breakpoint *b = bs->breakpoint_at;
10861   struct ui_out *uiout = current_uiout;
10862
10863   /* Masked watchpoints have only one location.  */
10864   gdb_assert (b->loc && b->loc->next == NULL);
10865
10866   switch (b->type)
10867     {
10868     case bp_hardware_watchpoint:
10869       annotate_watchpoint (b->number);
10870       if (ui_out_is_mi_like_p (uiout))
10871         ui_out_field_string
10872           (uiout, "reason",
10873            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10874       break;
10875
10876     case bp_read_watchpoint:
10877       if (ui_out_is_mi_like_p (uiout))
10878         ui_out_field_string
10879           (uiout, "reason",
10880            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10881       break;
10882
10883     case bp_access_watchpoint:
10884       if (ui_out_is_mi_like_p (uiout))
10885         ui_out_field_string
10886           (uiout, "reason",
10887            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10888       break;
10889     default:
10890       internal_error (__FILE__, __LINE__,
10891                       _("Invalid hardware watchpoint type."));
10892     }
10893
10894   mention (b);
10895   ui_out_text (uiout, _("\n\
10896 Check the underlying instruction at PC for the memory\n\
10897 address and value which triggered this watchpoint.\n"));
10898   ui_out_text (uiout, "\n");
10899
10900   /* More than one watchpoint may have been triggered.  */
10901   return PRINT_UNKNOWN;
10902 }
10903
10904 /* Implement the "print_one_detail" breakpoint_ops method for
10905    masked hardware watchpoints.  */
10906
10907 static void
10908 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10909                                     struct ui_out *uiout)
10910 {
10911   struct watchpoint *w = (struct watchpoint *) b;
10912
10913   /* Masked watchpoints have only one location.  */
10914   gdb_assert (b->loc && b->loc->next == NULL);
10915
10916   ui_out_text (uiout, "\tmask ");
10917   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10918   ui_out_text (uiout, "\n");
10919 }
10920
10921 /* Implement the "print_mention" breakpoint_ops method for
10922    masked hardware watchpoints.  */
10923
10924 static void
10925 print_mention_masked_watchpoint (struct breakpoint *b)
10926 {
10927   struct watchpoint *w = (struct watchpoint *) b;
10928   struct ui_out *uiout = current_uiout;
10929   struct cleanup *ui_out_chain;
10930
10931   switch (b->type)
10932     {
10933     case bp_hardware_watchpoint:
10934       ui_out_text (uiout, "Masked hardware watchpoint ");
10935       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10936       break;
10937     case bp_read_watchpoint:
10938       ui_out_text (uiout, "Masked hardware read watchpoint ");
10939       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10940       break;
10941     case bp_access_watchpoint:
10942       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10943       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10944       break;
10945     default:
10946       internal_error (__FILE__, __LINE__,
10947                       _("Invalid hardware watchpoint type."));
10948     }
10949
10950   ui_out_field_int (uiout, "number", b->number);
10951   ui_out_text (uiout, ": ");
10952   ui_out_field_string (uiout, "exp", w->exp_string);
10953   do_cleanups (ui_out_chain);
10954 }
10955
10956 /* Implement the "print_recreate" breakpoint_ops method for
10957    masked hardware watchpoints.  */
10958
10959 static void
10960 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10961 {
10962   struct watchpoint *w = (struct watchpoint *) b;
10963   char tmp[40];
10964
10965   switch (b->type)
10966     {
10967     case bp_hardware_watchpoint:
10968       fprintf_unfiltered (fp, "watch");
10969       break;
10970     case bp_read_watchpoint:
10971       fprintf_unfiltered (fp, "rwatch");
10972       break;
10973     case bp_access_watchpoint:
10974       fprintf_unfiltered (fp, "awatch");
10975       break;
10976     default:
10977       internal_error (__FILE__, __LINE__,
10978                       _("Invalid hardware watchpoint type."));
10979     }
10980
10981   sprintf_vma (tmp, w->hw_wp_mask);
10982   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10983   print_recreate_thread (b, fp);
10984 }
10985
10986 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10987
10988 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10989
10990 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10991
10992 static int
10993 is_masked_watchpoint (const struct breakpoint *b)
10994 {
10995   return b->ops == &masked_watchpoint_breakpoint_ops;
10996 }
10997
10998 /* accessflag:  hw_write:  watch write, 
10999                 hw_read:   watch read, 
11000                 hw_access: watch access (read or write) */
11001 static void
11002 watch_command_1 (const char *arg, int accessflag, int from_tty,
11003                  int just_location, int internal)
11004 {
11005   struct breakpoint *b, *scope_breakpoint = NULL;
11006   struct expression *exp;
11007   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11008   struct value *val, *mark, *result;
11009   int saved_bitpos = 0, saved_bitsize = 0;
11010   struct frame_info *frame;
11011   const char *exp_start = NULL;
11012   const char *exp_end = NULL;
11013   const char *tok, *end_tok;
11014   int toklen = -1;
11015   const char *cond_start = NULL;
11016   const char *cond_end = NULL;
11017   enum bptype bp_type;
11018   int thread = -1;
11019   int pc = 0;
11020   /* Flag to indicate whether we are going to use masks for
11021      the hardware watchpoint.  */
11022   int use_mask = 0;
11023   CORE_ADDR mask = 0;
11024   struct watchpoint *w;
11025   char *expression;
11026   struct cleanup *back_to;
11027
11028   /* Make sure that we actually have parameters to parse.  */
11029   if (arg != NULL && arg[0] != '\0')
11030     {
11031       const char *value_start;
11032
11033       exp_end = arg + strlen (arg);
11034
11035       /* Look for "parameter value" pairs at the end
11036          of the arguments string.  */
11037       for (tok = exp_end - 1; tok > arg; tok--)
11038         {
11039           /* Skip whitespace at the end of the argument list.  */
11040           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11041             tok--;
11042
11043           /* Find the beginning of the last token.
11044              This is the value of the parameter.  */
11045           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11046             tok--;
11047           value_start = tok + 1;
11048
11049           /* Skip whitespace.  */
11050           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11051             tok--;
11052
11053           end_tok = tok;
11054
11055           /* Find the beginning of the second to last token.
11056              This is the parameter itself.  */
11057           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11058             tok--;
11059           tok++;
11060           toklen = end_tok - tok + 1;
11061
11062           if (toklen == 6 && startswith (tok, "thread"))
11063             {
11064               /* At this point we've found a "thread" token, which means
11065                  the user is trying to set a watchpoint that triggers
11066                  only in a specific thread.  */
11067               char *endp;
11068
11069               if (thread != -1)
11070                 error(_("You can specify only one thread."));
11071
11072               /* Extract the thread ID from the next token.  */
11073               thread = strtol (value_start, &endp, 0);
11074
11075               /* Check if the user provided a valid numeric value for the
11076                  thread ID.  */
11077               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11078                 error (_("Invalid thread ID specification %s."), value_start);
11079
11080               /* Check if the thread actually exists.  */
11081               if (!valid_thread_id (thread))
11082                 invalid_thread_id_error (thread);
11083             }
11084           else if (toklen == 4 && startswith (tok, "mask"))
11085             {
11086               /* We've found a "mask" token, which means the user wants to
11087                  create a hardware watchpoint that is going to have the mask
11088                  facility.  */
11089               struct value *mask_value, *mark;
11090
11091               if (use_mask)
11092                 error(_("You can specify only one mask."));
11093
11094               use_mask = just_location = 1;
11095
11096               mark = value_mark ();
11097               mask_value = parse_to_comma_and_eval (&value_start);
11098               mask = value_as_address (mask_value);
11099               value_free_to_mark (mark);
11100             }
11101           else
11102             /* We didn't recognize what we found.  We should stop here.  */
11103             break;
11104
11105           /* Truncate the string and get rid of the "parameter value" pair before
11106              the arguments string is parsed by the parse_exp_1 function.  */
11107           exp_end = tok;
11108         }
11109     }
11110   else
11111     exp_end = arg;
11112
11113   /* Parse the rest of the arguments.  From here on out, everything
11114      is in terms of a newly allocated string instead of the original
11115      ARG.  */
11116   innermost_block = NULL;
11117   expression = savestring (arg, exp_end - arg);
11118   back_to = make_cleanup (xfree, expression);
11119   exp_start = arg = expression;
11120   exp = parse_exp_1 (&arg, 0, 0, 0);
11121   exp_end = arg;
11122   /* Remove trailing whitespace from the expression before saving it.
11123      This makes the eventual display of the expression string a bit
11124      prettier.  */
11125   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11126     --exp_end;
11127
11128   /* Checking if the expression is not constant.  */
11129   if (watchpoint_exp_is_const (exp))
11130     {
11131       int len;
11132
11133       len = exp_end - exp_start;
11134       while (len > 0 && isspace (exp_start[len - 1]))
11135         len--;
11136       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11137     }
11138
11139   exp_valid_block = innermost_block;
11140   mark = value_mark ();
11141   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11142
11143   if (val != NULL && just_location)
11144     {
11145       saved_bitpos = value_bitpos (val);
11146       saved_bitsize = value_bitsize (val);
11147     }
11148
11149   if (just_location)
11150     {
11151       int ret;
11152
11153       exp_valid_block = NULL;
11154       val = value_addr (result);
11155       release_value (val);
11156       value_free_to_mark (mark);
11157
11158       if (use_mask)
11159         {
11160           ret = target_masked_watch_num_registers (value_as_address (val),
11161                                                    mask);
11162           if (ret == -1)
11163             error (_("This target does not support masked watchpoints."));
11164           else if (ret == -2)
11165             error (_("Invalid mask or memory region."));
11166         }
11167     }
11168   else if (val != NULL)
11169     release_value (val);
11170
11171   tok = skip_spaces_const (arg);
11172   end_tok = skip_to_space_const (tok);
11173
11174   toklen = end_tok - tok;
11175   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11176     {
11177       struct expression *cond;
11178
11179       innermost_block = NULL;
11180       tok = cond_start = end_tok + 1;
11181       cond = parse_exp_1 (&tok, 0, 0, 0);
11182
11183       /* The watchpoint expression may not be local, but the condition
11184          may still be.  E.g.: `watch global if local > 0'.  */
11185       cond_exp_valid_block = innermost_block;
11186
11187       xfree (cond);
11188       cond_end = tok;
11189     }
11190   if (*tok)
11191     error (_("Junk at end of command."));
11192
11193   frame = block_innermost_frame (exp_valid_block);
11194
11195   /* If the expression is "local", then set up a "watchpoint scope"
11196      breakpoint at the point where we've left the scope of the watchpoint
11197      expression.  Create the scope breakpoint before the watchpoint, so
11198      that we will encounter it first in bpstat_stop_status.  */
11199   if (exp_valid_block && frame)
11200     {
11201       if (frame_id_p (frame_unwind_caller_id (frame)))
11202         {
11203           scope_breakpoint
11204             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11205                                           frame_unwind_caller_pc (frame),
11206                                           bp_watchpoint_scope,
11207                                           &momentary_breakpoint_ops);
11208
11209           scope_breakpoint->enable_state = bp_enabled;
11210
11211           /* Automatically delete the breakpoint when it hits.  */
11212           scope_breakpoint->disposition = disp_del;
11213
11214           /* Only break in the proper frame (help with recursion).  */
11215           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11216
11217           /* Set the address at which we will stop.  */
11218           scope_breakpoint->loc->gdbarch
11219             = frame_unwind_caller_arch (frame);
11220           scope_breakpoint->loc->requested_address
11221             = frame_unwind_caller_pc (frame);
11222           scope_breakpoint->loc->address
11223             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11224                                          scope_breakpoint->loc->requested_address,
11225                                          scope_breakpoint->type);
11226         }
11227     }
11228
11229   /* Now set up the breakpoint.  We create all watchpoints as hardware
11230      watchpoints here even if hardware watchpoints are turned off, a call
11231      to update_watchpoint later in this function will cause the type to
11232      drop back to bp_watchpoint (software watchpoint) if required.  */
11233
11234   if (accessflag == hw_read)
11235     bp_type = bp_read_watchpoint;
11236   else if (accessflag == hw_access)
11237     bp_type = bp_access_watchpoint;
11238   else
11239     bp_type = bp_hardware_watchpoint;
11240
11241   w = XCNEW (struct watchpoint);
11242   b = &w->base;
11243   if (use_mask)
11244     init_raw_breakpoint_without_location (b, NULL, bp_type,
11245                                           &masked_watchpoint_breakpoint_ops);
11246   else
11247     init_raw_breakpoint_without_location (b, NULL, bp_type,
11248                                           &watchpoint_breakpoint_ops);
11249   b->thread = thread;
11250   b->disposition = disp_donttouch;
11251   b->pspace = current_program_space;
11252   w->exp = exp;
11253   w->exp_valid_block = exp_valid_block;
11254   w->cond_exp_valid_block = cond_exp_valid_block;
11255   if (just_location)
11256     {
11257       struct type *t = value_type (val);
11258       CORE_ADDR addr = value_as_address (val);
11259       char *name;
11260
11261       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11262       name = type_to_string (t);
11263
11264       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11265                                           core_addr_to_string (addr));
11266       xfree (name);
11267
11268       w->exp_string = xstrprintf ("-location %.*s",
11269                                   (int) (exp_end - exp_start), exp_start);
11270
11271       /* The above expression is in C.  */
11272       b->language = language_c;
11273     }
11274   else
11275     w->exp_string = savestring (exp_start, exp_end - exp_start);
11276
11277   if (use_mask)
11278     {
11279       w->hw_wp_mask = mask;
11280     }
11281   else
11282     {
11283       w->val = val;
11284       w->val_bitpos = saved_bitpos;
11285       w->val_bitsize = saved_bitsize;
11286       w->val_valid = 1;
11287     }
11288
11289   if (cond_start)
11290     b->cond_string = savestring (cond_start, cond_end - cond_start);
11291   else
11292     b->cond_string = 0;
11293
11294   if (frame)
11295     {
11296       w->watchpoint_frame = get_frame_id (frame);
11297       w->watchpoint_thread = inferior_ptid;
11298     }
11299   else
11300     {
11301       w->watchpoint_frame = null_frame_id;
11302       w->watchpoint_thread = null_ptid;
11303     }
11304
11305   if (scope_breakpoint != NULL)
11306     {
11307       /* The scope breakpoint is related to the watchpoint.  We will
11308          need to act on them together.  */
11309       b->related_breakpoint = scope_breakpoint;
11310       scope_breakpoint->related_breakpoint = b;
11311     }
11312
11313   if (!just_location)
11314     value_free_to_mark (mark);
11315
11316   TRY
11317     {
11318       /* Finally update the new watchpoint.  This creates the locations
11319          that should be inserted.  */
11320       update_watchpoint (w, 1);
11321     }
11322   CATCH (e, RETURN_MASK_ALL)
11323     {
11324       delete_breakpoint (b);
11325       throw_exception (e);
11326     }
11327   END_CATCH
11328
11329   install_breakpoint (internal, b, 1);
11330   do_cleanups (back_to);
11331 }
11332
11333 /* Return count of debug registers needed to watch the given expression.
11334    If the watchpoint cannot be handled in hardware return zero.  */
11335
11336 static int
11337 can_use_hardware_watchpoint (struct value *v)
11338 {
11339   int found_memory_cnt = 0;
11340   struct value *head = v;
11341
11342   /* Did the user specifically forbid us to use hardware watchpoints? */
11343   if (!can_use_hw_watchpoints)
11344     return 0;
11345
11346   /* Make sure that the value of the expression depends only upon
11347      memory contents, and values computed from them within GDB.  If we
11348      find any register references or function calls, we can't use a
11349      hardware watchpoint.
11350
11351      The idea here is that evaluating an expression generates a series
11352      of values, one holding the value of every subexpression.  (The
11353      expression a*b+c has five subexpressions: a, b, a*b, c, and
11354      a*b+c.)  GDB's values hold almost enough information to establish
11355      the criteria given above --- they identify memory lvalues,
11356      register lvalues, computed values, etcetera.  So we can evaluate
11357      the expression, and then scan the chain of values that leaves
11358      behind to decide whether we can detect any possible change to the
11359      expression's final value using only hardware watchpoints.
11360
11361      However, I don't think that the values returned by inferior
11362      function calls are special in any way.  So this function may not
11363      notice that an expression involving an inferior function call
11364      can't be watched with hardware watchpoints.  FIXME.  */
11365   for (; v; v = value_next (v))
11366     {
11367       if (VALUE_LVAL (v) == lval_memory)
11368         {
11369           if (v != head && value_lazy (v))
11370             /* A lazy memory lvalue in the chain is one that GDB never
11371                needed to fetch; we either just used its address (e.g.,
11372                `a' in `a.b') or we never needed it at all (e.g., `a'
11373                in `a,b').  This doesn't apply to HEAD; if that is
11374                lazy then it was not readable, but watch it anyway.  */
11375             ;
11376           else
11377             {
11378               /* Ahh, memory we actually used!  Check if we can cover
11379                  it with hardware watchpoints.  */
11380               struct type *vtype = check_typedef (value_type (v));
11381
11382               /* We only watch structs and arrays if user asked for it
11383                  explicitly, never if they just happen to appear in a
11384                  middle of some value chain.  */
11385               if (v == head
11386                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11387                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11388                 {
11389                   CORE_ADDR vaddr = value_address (v);
11390                   int len;
11391                   int num_regs;
11392
11393                   len = (target_exact_watchpoints
11394                          && is_scalar_type_recursive (vtype))?
11395                     1 : TYPE_LENGTH (value_type (v));
11396
11397                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11398                   if (!num_regs)
11399                     return 0;
11400                   else
11401                     found_memory_cnt += num_regs;
11402                 }
11403             }
11404         }
11405       else if (VALUE_LVAL (v) != not_lval
11406                && deprecated_value_modifiable (v) == 0)
11407         return 0;       /* These are values from the history (e.g., $1).  */
11408       else if (VALUE_LVAL (v) == lval_register)
11409         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11410     }
11411
11412   /* The expression itself looks suitable for using a hardware
11413      watchpoint, but give the target machine a chance to reject it.  */
11414   return found_memory_cnt;
11415 }
11416
11417 void
11418 watch_command_wrapper (char *arg, int from_tty, int internal)
11419 {
11420   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11421 }
11422
11423 /* A helper function that looks for the "-location" argument and then
11424    calls watch_command_1.  */
11425
11426 static void
11427 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11428 {
11429   int just_location = 0;
11430
11431   if (arg
11432       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11433           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11434     {
11435       arg = skip_spaces (arg);
11436       just_location = 1;
11437     }
11438
11439   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11440 }
11441
11442 static void
11443 watch_command (char *arg, int from_tty)
11444 {
11445   watch_maybe_just_location (arg, hw_write, from_tty);
11446 }
11447
11448 void
11449 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11450 {
11451   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11452 }
11453
11454 static void
11455 rwatch_command (char *arg, int from_tty)
11456 {
11457   watch_maybe_just_location (arg, hw_read, from_tty);
11458 }
11459
11460 void
11461 awatch_command_wrapper (char *arg, int from_tty, int internal)
11462 {
11463   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11464 }
11465
11466 static void
11467 awatch_command (char *arg, int from_tty)
11468 {
11469   watch_maybe_just_location (arg, hw_access, from_tty);
11470 }
11471 \f
11472
11473 /* Data for the FSM that manages the until(location)/advance commands
11474    in infcmd.c.  Here because it uses the mechanisms of
11475    breakpoints.  */
11476
11477 struct until_break_fsm
11478 {
11479   /* The base class.  */
11480   struct thread_fsm thread_fsm;
11481
11482   /* The thread that as current when the command was executed.  */
11483   int thread;
11484
11485   /* The breakpoint set at the destination location.  */
11486   struct breakpoint *location_breakpoint;
11487
11488   /* Breakpoint set at the return address in the caller frame.  May be
11489      NULL.  */
11490   struct breakpoint *caller_breakpoint;
11491 };
11492
11493 static void until_break_fsm_clean_up (struct thread_fsm *self);
11494 static int until_break_fsm_should_stop (struct thread_fsm *self);
11495 static enum async_reply_reason
11496   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11497
11498 /* until_break_fsm's vtable.  */
11499
11500 static struct thread_fsm_ops until_break_fsm_ops =
11501 {
11502   NULL, /* dtor */
11503   until_break_fsm_clean_up,
11504   until_break_fsm_should_stop,
11505   NULL, /* return_value */
11506   until_break_fsm_async_reply_reason,
11507 };
11508
11509 /* Allocate a new until_break_command_fsm.  */
11510
11511 static struct until_break_fsm *
11512 new_until_break_fsm (int thread,
11513                      struct breakpoint *location_breakpoint,
11514                      struct breakpoint *caller_breakpoint)
11515 {
11516   struct until_break_fsm *sm;
11517
11518   sm = XCNEW (struct until_break_fsm);
11519   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops);
11520
11521   sm->thread = thread;
11522   sm->location_breakpoint = location_breakpoint;
11523   sm->caller_breakpoint = caller_breakpoint;
11524
11525   return sm;
11526 }
11527
11528 /* Implementation of the 'should_stop' FSM method for the
11529    until(location)/advance commands.  */
11530
11531 static int
11532 until_break_fsm_should_stop (struct thread_fsm *self)
11533 {
11534   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11535   struct thread_info *tp = inferior_thread ();
11536
11537   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11538                               sm->location_breakpoint) != NULL
11539       || (sm->caller_breakpoint != NULL
11540           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11541                                      sm->caller_breakpoint) != NULL))
11542     thread_fsm_set_finished (self);
11543
11544   return 1;
11545 }
11546
11547 /* Implementation of the 'clean_up' FSM method for the
11548    until(location)/advance commands.  */
11549
11550 static void
11551 until_break_fsm_clean_up (struct thread_fsm *self)
11552 {
11553   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11554
11555   /* Clean up our temporary breakpoints.  */
11556   if (sm->location_breakpoint != NULL)
11557     {
11558       delete_breakpoint (sm->location_breakpoint);
11559       sm->location_breakpoint = NULL;
11560     }
11561   if (sm->caller_breakpoint != NULL)
11562     {
11563       delete_breakpoint (sm->caller_breakpoint);
11564       sm->caller_breakpoint = NULL;
11565     }
11566   delete_longjmp_breakpoint (sm->thread);
11567 }
11568
11569 /* Implementation of the 'async_reply_reason' FSM method for the
11570    until(location)/advance commands.  */
11571
11572 static enum async_reply_reason
11573 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11574 {
11575   return EXEC_ASYNC_LOCATION_REACHED;
11576 }
11577
11578 void
11579 until_break_command (char *arg, int from_tty, int anywhere)
11580 {
11581   struct symtabs_and_lines sals;
11582   struct symtab_and_line sal;
11583   struct frame_info *frame;
11584   struct gdbarch *frame_gdbarch;
11585   struct frame_id stack_frame_id;
11586   struct frame_id caller_frame_id;
11587   struct breakpoint *location_breakpoint;
11588   struct breakpoint *caller_breakpoint = NULL;
11589   struct cleanup *old_chain, *cleanup;
11590   int thread;
11591   struct thread_info *tp;
11592   struct event_location *location;
11593   struct until_break_fsm *sm;
11594
11595   clear_proceed_status (0);
11596
11597   /* Set a breakpoint where the user wants it and at return from
11598      this function.  */
11599
11600   location = string_to_event_location (&arg, current_language);
11601   cleanup = make_cleanup_delete_event_location (location);
11602
11603   if (last_displayed_sal_is_valid ())
11604     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11605                           get_last_displayed_symtab (),
11606                           get_last_displayed_line ());
11607   else
11608     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11609                           (struct symtab *) NULL, 0);
11610
11611   if (sals.nelts != 1)
11612     error (_("Couldn't get information on specified line."));
11613
11614   sal = sals.sals[0];
11615   xfree (sals.sals);    /* malloc'd, so freed.  */
11616
11617   if (*arg)
11618     error (_("Junk at end of arguments."));
11619
11620   resolve_sal_pc (&sal);
11621
11622   tp = inferior_thread ();
11623   thread = tp->num;
11624
11625   old_chain = make_cleanup (null_cleanup, NULL);
11626
11627   /* Note linespec handling above invalidates the frame chain.
11628      Installing a breakpoint also invalidates the frame chain (as it
11629      may need to switch threads), so do any frame handling before
11630      that.  */
11631
11632   frame = get_selected_frame (NULL);
11633   frame_gdbarch = get_frame_arch (frame);
11634   stack_frame_id = get_stack_frame_id (frame);
11635   caller_frame_id = frame_unwind_caller_id (frame);
11636
11637   /* Keep within the current frame, or in frames called by the current
11638      one.  */
11639
11640   if (frame_id_p (caller_frame_id))
11641     {
11642       struct symtab_and_line sal2;
11643       struct gdbarch *caller_gdbarch;
11644
11645       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11646       sal2.pc = frame_unwind_caller_pc (frame);
11647       caller_gdbarch = frame_unwind_caller_arch (frame);
11648       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11649                                                     sal2,
11650                                                     caller_frame_id,
11651                                                     bp_until);
11652       make_cleanup_delete_breakpoint (caller_breakpoint);
11653
11654       set_longjmp_breakpoint (tp, caller_frame_id);
11655       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11656     }
11657
11658   /* set_momentary_breakpoint could invalidate FRAME.  */
11659   frame = NULL;
11660
11661   if (anywhere)
11662     /* If the user told us to continue until a specified location,
11663        we don't specify a frame at which we need to stop.  */
11664     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11665                                                     null_frame_id, bp_until);
11666   else
11667     /* Otherwise, specify the selected frame, because we want to stop
11668        only at the very same frame.  */
11669     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11670                                                     stack_frame_id, bp_until);
11671   make_cleanup_delete_breakpoint (location_breakpoint);
11672
11673   sm = new_until_break_fsm (tp->num, location_breakpoint, caller_breakpoint);
11674   tp->thread_fsm = &sm->thread_fsm;
11675
11676   discard_cleanups (old_chain);
11677
11678   proceed (-1, GDB_SIGNAL_DEFAULT);
11679
11680   do_cleanups (cleanup);
11681 }
11682
11683 /* This function attempts to parse an optional "if <cond>" clause
11684    from the arg string.  If one is not found, it returns NULL.
11685
11686    Else, it returns a pointer to the condition string.  (It does not
11687    attempt to evaluate the string against a particular block.)  And,
11688    it updates arg to point to the first character following the parsed
11689    if clause in the arg string.  */
11690
11691 char *
11692 ep_parse_optional_if_clause (char **arg)
11693 {
11694   char *cond_string;
11695
11696   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11697     return NULL;
11698
11699   /* Skip the "if" keyword.  */
11700   (*arg) += 2;
11701
11702   /* Skip any extra leading whitespace, and record the start of the
11703      condition string.  */
11704   *arg = skip_spaces (*arg);
11705   cond_string = *arg;
11706
11707   /* Assume that the condition occupies the remainder of the arg
11708      string.  */
11709   (*arg) += strlen (cond_string);
11710
11711   return cond_string;
11712 }
11713
11714 /* Commands to deal with catching events, such as signals, exceptions,
11715    process start/exit, etc.  */
11716
11717 typedef enum
11718 {
11719   catch_fork_temporary, catch_vfork_temporary,
11720   catch_fork_permanent, catch_vfork_permanent
11721 }
11722 catch_fork_kind;
11723
11724 static void
11725 catch_fork_command_1 (char *arg, int from_tty, 
11726                       struct cmd_list_element *command)
11727 {
11728   struct gdbarch *gdbarch = get_current_arch ();
11729   char *cond_string = NULL;
11730   catch_fork_kind fork_kind;
11731   int tempflag;
11732
11733   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11734   tempflag = (fork_kind == catch_fork_temporary
11735               || fork_kind == catch_vfork_temporary);
11736
11737   if (!arg)
11738     arg = "";
11739   arg = skip_spaces (arg);
11740
11741   /* The allowed syntax is:
11742      catch [v]fork
11743      catch [v]fork if <cond>
11744
11745      First, check if there's an if clause.  */
11746   cond_string = ep_parse_optional_if_clause (&arg);
11747
11748   if ((*arg != '\0') && !isspace (*arg))
11749     error (_("Junk at end of arguments."));
11750
11751   /* If this target supports it, create a fork or vfork catchpoint
11752      and enable reporting of such events.  */
11753   switch (fork_kind)
11754     {
11755     case catch_fork_temporary:
11756     case catch_fork_permanent:
11757       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11758                                           &catch_fork_breakpoint_ops);
11759       break;
11760     case catch_vfork_temporary:
11761     case catch_vfork_permanent:
11762       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11763                                           &catch_vfork_breakpoint_ops);
11764       break;
11765     default:
11766       error (_("unsupported or unknown fork kind; cannot catch it"));
11767       break;
11768     }
11769 }
11770
11771 static void
11772 catch_exec_command_1 (char *arg, int from_tty, 
11773                       struct cmd_list_element *command)
11774 {
11775   struct exec_catchpoint *c;
11776   struct gdbarch *gdbarch = get_current_arch ();
11777   int tempflag;
11778   char *cond_string = NULL;
11779
11780   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11781
11782   if (!arg)
11783     arg = "";
11784   arg = skip_spaces (arg);
11785
11786   /* The allowed syntax is:
11787      catch exec
11788      catch exec if <cond>
11789
11790      First, check if there's an if clause.  */
11791   cond_string = ep_parse_optional_if_clause (&arg);
11792
11793   if ((*arg != '\0') && !isspace (*arg))
11794     error (_("Junk at end of arguments."));
11795
11796   c = XNEW (struct exec_catchpoint);
11797   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11798                    &catch_exec_breakpoint_ops);
11799   c->exec_pathname = NULL;
11800
11801   install_breakpoint (0, &c->base, 1);
11802 }
11803
11804 void
11805 init_ada_exception_breakpoint (struct breakpoint *b,
11806                                struct gdbarch *gdbarch,
11807                                struct symtab_and_line sal,
11808                                char *addr_string,
11809                                const struct breakpoint_ops *ops,
11810                                int tempflag,
11811                                int enabled,
11812                                int from_tty)
11813 {
11814   if (from_tty)
11815     {
11816       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11817       if (!loc_gdbarch)
11818         loc_gdbarch = gdbarch;
11819
11820       describe_other_breakpoints (loc_gdbarch,
11821                                   sal.pspace, sal.pc, sal.section, -1);
11822       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11823          version for exception catchpoints, because two catchpoints
11824          used for different exception names will use the same address.
11825          In this case, a "breakpoint ... also set at..." warning is
11826          unproductive.  Besides, the warning phrasing is also a bit
11827          inappropriate, we should use the word catchpoint, and tell
11828          the user what type of catchpoint it is.  The above is good
11829          enough for now, though.  */
11830     }
11831
11832   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11833
11834   b->enable_state = enabled ? bp_enabled : bp_disabled;
11835   b->disposition = tempflag ? disp_del : disp_donttouch;
11836   b->location = string_to_event_location (&addr_string,
11837                                           language_def (language_ada));
11838   b->language = language_ada;
11839 }
11840
11841 static void
11842 catch_command (char *arg, int from_tty)
11843 {
11844   error (_("Catch requires an event name."));
11845 }
11846 \f
11847
11848 static void
11849 tcatch_command (char *arg, int from_tty)
11850 {
11851   error (_("Catch requires an event name."));
11852 }
11853
11854 /* A qsort comparison function that sorts breakpoints in order.  */
11855
11856 static int
11857 compare_breakpoints (const void *a, const void *b)
11858 {
11859   const breakpoint_p *ba = (const breakpoint_p *) a;
11860   uintptr_t ua = (uintptr_t) *ba;
11861   const breakpoint_p *bb = (const breakpoint_p *) b;
11862   uintptr_t ub = (uintptr_t) *bb;
11863
11864   if ((*ba)->number < (*bb)->number)
11865     return -1;
11866   else if ((*ba)->number > (*bb)->number)
11867     return 1;
11868
11869   /* Now sort by address, in case we see, e..g, two breakpoints with
11870      the number 0.  */
11871   if (ua < ub)
11872     return -1;
11873   return ua > ub ? 1 : 0;
11874 }
11875
11876 /* Delete breakpoints by address or line.  */
11877
11878 static void
11879 clear_command (char *arg, int from_tty)
11880 {
11881   struct breakpoint *b, *prev;
11882   VEC(breakpoint_p) *found = 0;
11883   int ix;
11884   int default_match;
11885   struct symtabs_and_lines sals;
11886   struct symtab_and_line sal;
11887   int i;
11888   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11889
11890   if (arg)
11891     {
11892       sals = decode_line_with_current_source (arg,
11893                                               (DECODE_LINE_FUNFIRSTLINE
11894                                                | DECODE_LINE_LIST_MODE));
11895       make_cleanup (xfree, sals.sals);
11896       default_match = 0;
11897     }
11898   else
11899     {
11900       sals.sals = XNEW (struct symtab_and_line);
11901       make_cleanup (xfree, sals.sals);
11902       init_sal (&sal);          /* Initialize to zeroes.  */
11903
11904       /* Set sal's line, symtab, pc, and pspace to the values
11905          corresponding to the last call to print_frame_info.  If the
11906          codepoint is not valid, this will set all the fields to 0.  */
11907       get_last_displayed_sal (&sal);
11908       if (sal.symtab == 0)
11909         error (_("No source file specified."));
11910
11911       sals.sals[0] = sal;
11912       sals.nelts = 1;
11913
11914       default_match = 1;
11915     }
11916
11917   /* We don't call resolve_sal_pc here.  That's not as bad as it
11918      seems, because all existing breakpoints typically have both
11919      file/line and pc set.  So, if clear is given file/line, we can
11920      match this to existing breakpoint without obtaining pc at all.
11921
11922      We only support clearing given the address explicitly 
11923      present in breakpoint table.  Say, we've set breakpoint 
11924      at file:line.  There were several PC values for that file:line,
11925      due to optimization, all in one block.
11926
11927      We've picked one PC value.  If "clear" is issued with another
11928      PC corresponding to the same file:line, the breakpoint won't
11929      be cleared.  We probably can still clear the breakpoint, but 
11930      since the other PC value is never presented to user, user
11931      can only find it by guessing, and it does not seem important
11932      to support that.  */
11933
11934   /* For each line spec given, delete bps which correspond to it.  Do
11935      it in two passes, solely to preserve the current behavior that
11936      from_tty is forced true if we delete more than one
11937      breakpoint.  */
11938
11939   found = NULL;
11940   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11941   for (i = 0; i < sals.nelts; i++)
11942     {
11943       const char *sal_fullname;
11944
11945       /* If exact pc given, clear bpts at that pc.
11946          If line given (pc == 0), clear all bpts on specified line.
11947          If defaulting, clear all bpts on default line
11948          or at default pc.
11949
11950          defaulting    sal.pc != 0    tests to do
11951
11952          0              1             pc
11953          1              1             pc _and_ line
11954          0              0             line
11955          1              0             <can't happen> */
11956
11957       sal = sals.sals[i];
11958       sal_fullname = (sal.symtab == NULL
11959                       ? NULL : symtab_to_fullname (sal.symtab));
11960
11961       /* Find all matching breakpoints and add them to 'found'.  */
11962       ALL_BREAKPOINTS (b)
11963         {
11964           int match = 0;
11965           /* Are we going to delete b?  */
11966           if (b->type != bp_none && !is_watchpoint (b))
11967             {
11968               struct bp_location *loc = b->loc;
11969               for (; loc; loc = loc->next)
11970                 {
11971                   /* If the user specified file:line, don't allow a PC
11972                      match.  This matches historical gdb behavior.  */
11973                   int pc_match = (!sal.explicit_line
11974                                   && sal.pc
11975                                   && (loc->pspace == sal.pspace)
11976                                   && (loc->address == sal.pc)
11977                                   && (!section_is_overlay (loc->section)
11978                                       || loc->section == sal.section));
11979                   int line_match = 0;
11980
11981                   if ((default_match || sal.explicit_line)
11982                       && loc->symtab != NULL
11983                       && sal_fullname != NULL
11984                       && sal.pspace == loc->pspace
11985                       && loc->line_number == sal.line
11986                       && filename_cmp (symtab_to_fullname (loc->symtab),
11987                                        sal_fullname) == 0)
11988                     line_match = 1;
11989
11990                   if (pc_match || line_match)
11991                     {
11992                       match = 1;
11993                       break;
11994                     }
11995                 }
11996             }
11997
11998           if (match)
11999             VEC_safe_push(breakpoint_p, found, b);
12000         }
12001     }
12002
12003   /* Now go thru the 'found' chain and delete them.  */
12004   if (VEC_empty(breakpoint_p, found))
12005     {
12006       if (arg)
12007         error (_("No breakpoint at %s."), arg);
12008       else
12009         error (_("No breakpoint at this line."));
12010     }
12011
12012   /* Remove duplicates from the vec.  */
12013   qsort (VEC_address (breakpoint_p, found),
12014          VEC_length (breakpoint_p, found),
12015          sizeof (breakpoint_p),
12016          compare_breakpoints);
12017   prev = VEC_index (breakpoint_p, found, 0);
12018   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12019     {
12020       if (b == prev)
12021         {
12022           VEC_ordered_remove (breakpoint_p, found, ix);
12023           --ix;
12024         }
12025     }
12026
12027   if (VEC_length(breakpoint_p, found) > 1)
12028     from_tty = 1;       /* Always report if deleted more than one.  */
12029   if (from_tty)
12030     {
12031       if (VEC_length(breakpoint_p, found) == 1)
12032         printf_unfiltered (_("Deleted breakpoint "));
12033       else
12034         printf_unfiltered (_("Deleted breakpoints "));
12035     }
12036
12037   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12038     {
12039       if (from_tty)
12040         printf_unfiltered ("%d ", b->number);
12041       delete_breakpoint (b);
12042     }
12043   if (from_tty)
12044     putchar_unfiltered ('\n');
12045
12046   do_cleanups (cleanups);
12047 }
12048 \f
12049 /* Delete breakpoint in BS if they are `delete' breakpoints and
12050    all breakpoints that are marked for deletion, whether hit or not.
12051    This is called after any breakpoint is hit, or after errors.  */
12052
12053 void
12054 breakpoint_auto_delete (bpstat bs)
12055 {
12056   struct breakpoint *b, *b_tmp;
12057
12058   for (; bs; bs = bs->next)
12059     if (bs->breakpoint_at
12060         && bs->breakpoint_at->disposition == disp_del
12061         && bs->stop)
12062       delete_breakpoint (bs->breakpoint_at);
12063
12064   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12065   {
12066     if (b->disposition == disp_del_at_next_stop)
12067       delete_breakpoint (b);
12068   }
12069 }
12070
12071 /* A comparison function for bp_location AP and BP being interfaced to
12072    qsort.  Sort elements primarily by their ADDRESS (no matter what
12073    does breakpoint_address_is_meaningful say for its OWNER),
12074    secondarily by ordering first permanent elements and
12075    terciarily just ensuring the array is sorted stable way despite
12076    qsort being an unstable algorithm.  */
12077
12078 static int
12079 bp_location_compare (const void *ap, const void *bp)
12080 {
12081   const struct bp_location *a = *(const struct bp_location **) ap;
12082   const struct bp_location *b = *(const struct bp_location **) bp;
12083
12084   if (a->address != b->address)
12085     return (a->address > b->address) - (a->address < b->address);
12086
12087   /* Sort locations at the same address by their pspace number, keeping
12088      locations of the same inferior (in a multi-inferior environment)
12089      grouped.  */
12090
12091   if (a->pspace->num != b->pspace->num)
12092     return ((a->pspace->num > b->pspace->num)
12093             - (a->pspace->num < b->pspace->num));
12094
12095   /* Sort permanent breakpoints first.  */
12096   if (a->permanent != b->permanent)
12097     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12098
12099   /* Make the internal GDB representation stable across GDB runs
12100      where A and B memory inside GDB can differ.  Breakpoint locations of
12101      the same type at the same address can be sorted in arbitrary order.  */
12102
12103   if (a->owner->number != b->owner->number)
12104     return ((a->owner->number > b->owner->number)
12105             - (a->owner->number < b->owner->number));
12106
12107   return (a > b) - (a < b);
12108 }
12109
12110 /* Set bp_location_placed_address_before_address_max and
12111    bp_location_shadow_len_after_address_max according to the current
12112    content of the bp_location array.  */
12113
12114 static void
12115 bp_location_target_extensions_update (void)
12116 {
12117   struct bp_location *bl, **blp_tmp;
12118
12119   bp_location_placed_address_before_address_max = 0;
12120   bp_location_shadow_len_after_address_max = 0;
12121
12122   ALL_BP_LOCATIONS (bl, blp_tmp)
12123     {
12124       CORE_ADDR start, end, addr;
12125
12126       if (!bp_location_has_shadow (bl))
12127         continue;
12128
12129       start = bl->target_info.placed_address;
12130       end = start + bl->target_info.shadow_len;
12131
12132       gdb_assert (bl->address >= start);
12133       addr = bl->address - start;
12134       if (addr > bp_location_placed_address_before_address_max)
12135         bp_location_placed_address_before_address_max = addr;
12136
12137       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12138
12139       gdb_assert (bl->address < end);
12140       addr = end - bl->address;
12141       if (addr > bp_location_shadow_len_after_address_max)
12142         bp_location_shadow_len_after_address_max = addr;
12143     }
12144 }
12145
12146 /* Download tracepoint locations if they haven't been.  */
12147
12148 static void
12149 download_tracepoint_locations (void)
12150 {
12151   struct breakpoint *b;
12152   struct cleanup *old_chain;
12153   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12154
12155   old_chain = save_current_space_and_thread ();
12156
12157   ALL_TRACEPOINTS (b)
12158     {
12159       struct bp_location *bl;
12160       struct tracepoint *t;
12161       int bp_location_downloaded = 0;
12162
12163       if ((b->type == bp_fast_tracepoint
12164            ? !may_insert_fast_tracepoints
12165            : !may_insert_tracepoints))
12166         continue;
12167
12168       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12169         {
12170           if (target_can_download_tracepoint ())
12171             can_download_tracepoint = TRIBOOL_TRUE;
12172           else
12173             can_download_tracepoint = TRIBOOL_FALSE;
12174         }
12175
12176       if (can_download_tracepoint == TRIBOOL_FALSE)
12177         break;
12178
12179       for (bl = b->loc; bl; bl = bl->next)
12180         {
12181           /* In tracepoint, locations are _never_ duplicated, so
12182              should_be_inserted is equivalent to
12183              unduplicated_should_be_inserted.  */
12184           if (!should_be_inserted (bl) || bl->inserted)
12185             continue;
12186
12187           switch_to_program_space_and_thread (bl->pspace);
12188
12189           target_download_tracepoint (bl);
12190
12191           bl->inserted = 1;
12192           bp_location_downloaded = 1;
12193         }
12194       t = (struct tracepoint *) b;
12195       t->number_on_target = b->number;
12196       if (bp_location_downloaded)
12197         observer_notify_breakpoint_modified (b);
12198     }
12199
12200   do_cleanups (old_chain);
12201 }
12202
12203 /* Swap the insertion/duplication state between two locations.  */
12204
12205 static void
12206 swap_insertion (struct bp_location *left, struct bp_location *right)
12207 {
12208   const int left_inserted = left->inserted;
12209   const int left_duplicate = left->duplicate;
12210   const int left_needs_update = left->needs_update;
12211   const struct bp_target_info left_target_info = left->target_info;
12212
12213   /* Locations of tracepoints can never be duplicated.  */
12214   if (is_tracepoint (left->owner))
12215     gdb_assert (!left->duplicate);
12216   if (is_tracepoint (right->owner))
12217     gdb_assert (!right->duplicate);
12218
12219   left->inserted = right->inserted;
12220   left->duplicate = right->duplicate;
12221   left->needs_update = right->needs_update;
12222   left->target_info = right->target_info;
12223   right->inserted = left_inserted;
12224   right->duplicate = left_duplicate;
12225   right->needs_update = left_needs_update;
12226   right->target_info = left_target_info;
12227 }
12228
12229 /* Force the re-insertion of the locations at ADDRESS.  This is called
12230    once a new/deleted/modified duplicate location is found and we are evaluating
12231    conditions on the target's side.  Such conditions need to be updated on
12232    the target.  */
12233
12234 static void
12235 force_breakpoint_reinsertion (struct bp_location *bl)
12236 {
12237   struct bp_location **locp = NULL, **loc2p;
12238   struct bp_location *loc;
12239   CORE_ADDR address = 0;
12240   int pspace_num;
12241
12242   address = bl->address;
12243   pspace_num = bl->pspace->num;
12244
12245   /* This is only meaningful if the target is
12246      evaluating conditions and if the user has
12247      opted for condition evaluation on the target's
12248      side.  */
12249   if (gdb_evaluates_breakpoint_condition_p ()
12250       || !target_supports_evaluation_of_breakpoint_conditions ())
12251     return;
12252
12253   /* Flag all breakpoint locations with this address and
12254      the same program space as the location
12255      as "its condition has changed".  We need to
12256      update the conditions on the target's side.  */
12257   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12258     {
12259       loc = *loc2p;
12260
12261       if (!is_breakpoint (loc->owner)
12262           || pspace_num != loc->pspace->num)
12263         continue;
12264
12265       /* Flag the location appropriately.  We use a different state to
12266          let everyone know that we already updated the set of locations
12267          with addr bl->address and program space bl->pspace.  This is so
12268          we don't have to keep calling these functions just to mark locations
12269          that have already been marked.  */
12270       loc->condition_changed = condition_updated;
12271
12272       /* Free the agent expression bytecode as well.  We will compute
12273          it later on.  */
12274       if (loc->cond_bytecode)
12275         {
12276           free_agent_expr (loc->cond_bytecode);
12277           loc->cond_bytecode = NULL;
12278         }
12279     }
12280 }
12281 /* Called whether new breakpoints are created, or existing breakpoints
12282    deleted, to update the global location list and recompute which
12283    locations are duplicate of which.
12284
12285    The INSERT_MODE flag determines whether locations may not, may, or
12286    shall be inserted now.  See 'enum ugll_insert_mode' for more
12287    info.  */
12288
12289 static void
12290 update_global_location_list (enum ugll_insert_mode insert_mode)
12291 {
12292   struct breakpoint *b;
12293   struct bp_location **locp, *loc;
12294   struct cleanup *cleanups;
12295   /* Last breakpoint location address that was marked for update.  */
12296   CORE_ADDR last_addr = 0;
12297   /* Last breakpoint location program space that was marked for update.  */
12298   int last_pspace_num = -1;
12299
12300   /* Used in the duplicates detection below.  When iterating over all
12301      bp_locations, points to the first bp_location of a given address.
12302      Breakpoints and watchpoints of different types are never
12303      duplicates of each other.  Keep one pointer for each type of
12304      breakpoint/watchpoint, so we only need to loop over all locations
12305      once.  */
12306   struct bp_location *bp_loc_first;  /* breakpoint */
12307   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12308   struct bp_location *awp_loc_first; /* access watchpoint */
12309   struct bp_location *rwp_loc_first; /* read watchpoint */
12310
12311   /* Saved former bp_location array which we compare against the newly
12312      built bp_location from the current state of ALL_BREAKPOINTS.  */
12313   struct bp_location **old_location, **old_locp;
12314   unsigned old_location_count;
12315
12316   old_location = bp_location;
12317   old_location_count = bp_location_count;
12318   bp_location = NULL;
12319   bp_location_count = 0;
12320   cleanups = make_cleanup (xfree, old_location);
12321
12322   ALL_BREAKPOINTS (b)
12323     for (loc = b->loc; loc; loc = loc->next)
12324       bp_location_count++;
12325
12326   bp_location = XNEWVEC (struct bp_location *, bp_location_count);
12327   locp = bp_location;
12328   ALL_BREAKPOINTS (b)
12329     for (loc = b->loc; loc; loc = loc->next)
12330       *locp++ = loc;
12331   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12332          bp_location_compare);
12333
12334   bp_location_target_extensions_update ();
12335
12336   /* Identify bp_location instances that are no longer present in the
12337      new list, and therefore should be freed.  Note that it's not
12338      necessary that those locations should be removed from inferior --
12339      if there's another location at the same address (previously
12340      marked as duplicate), we don't need to remove/insert the
12341      location.
12342      
12343      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12344      and former bp_location array state respectively.  */
12345
12346   locp = bp_location;
12347   for (old_locp = old_location; old_locp < old_location + old_location_count;
12348        old_locp++)
12349     {
12350       struct bp_location *old_loc = *old_locp;
12351       struct bp_location **loc2p;
12352
12353       /* Tells if 'old_loc' is found among the new locations.  If
12354          not, we have to free it.  */
12355       int found_object = 0;
12356       /* Tells if the location should remain inserted in the target.  */
12357       int keep_in_target = 0;
12358       int removed = 0;
12359
12360       /* Skip LOCP entries which will definitely never be needed.
12361          Stop either at or being the one matching OLD_LOC.  */
12362       while (locp < bp_location + bp_location_count
12363              && (*locp)->address < old_loc->address)
12364         locp++;
12365
12366       for (loc2p = locp;
12367            (loc2p < bp_location + bp_location_count
12368             && (*loc2p)->address == old_loc->address);
12369            loc2p++)
12370         {
12371           /* Check if this is a new/duplicated location or a duplicated
12372              location that had its condition modified.  If so, we want to send
12373              its condition to the target if evaluation of conditions is taking
12374              place there.  */
12375           if ((*loc2p)->condition_changed == condition_modified
12376               && (last_addr != old_loc->address
12377                   || last_pspace_num != old_loc->pspace->num))
12378             {
12379               force_breakpoint_reinsertion (*loc2p);
12380               last_pspace_num = old_loc->pspace->num;
12381             }
12382
12383           if (*loc2p == old_loc)
12384             found_object = 1;
12385         }
12386
12387       /* We have already handled this address, update it so that we don't
12388          have to go through updates again.  */
12389       last_addr = old_loc->address;
12390
12391       /* Target-side condition evaluation: Handle deleted locations.  */
12392       if (!found_object)
12393         force_breakpoint_reinsertion (old_loc);
12394
12395       /* If this location is no longer present, and inserted, look if
12396          there's maybe a new location at the same address.  If so,
12397          mark that one inserted, and don't remove this one.  This is
12398          needed so that we don't have a time window where a breakpoint
12399          at certain location is not inserted.  */
12400
12401       if (old_loc->inserted)
12402         {
12403           /* If the location is inserted now, we might have to remove
12404              it.  */
12405
12406           if (found_object && should_be_inserted (old_loc))
12407             {
12408               /* The location is still present in the location list,
12409                  and still should be inserted.  Don't do anything.  */
12410               keep_in_target = 1;
12411             }
12412           else
12413             {
12414               /* This location still exists, but it won't be kept in the
12415                  target since it may have been disabled.  We proceed to
12416                  remove its target-side condition.  */
12417
12418               /* The location is either no longer present, or got
12419                  disabled.  See if there's another location at the
12420                  same address, in which case we don't need to remove
12421                  this one from the target.  */
12422
12423               /* OLD_LOC comes from existing struct breakpoint.  */
12424               if (breakpoint_address_is_meaningful (old_loc->owner))
12425                 {
12426                   for (loc2p = locp;
12427                        (loc2p < bp_location + bp_location_count
12428                         && (*loc2p)->address == old_loc->address);
12429                        loc2p++)
12430                     {
12431                       struct bp_location *loc2 = *loc2p;
12432
12433                       if (breakpoint_locations_match (loc2, old_loc))
12434                         {
12435                           /* Read watchpoint locations are switched to
12436                              access watchpoints, if the former are not
12437                              supported, but the latter are.  */
12438                           if (is_hardware_watchpoint (old_loc->owner))
12439                             {
12440                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12441                               loc2->watchpoint_type = old_loc->watchpoint_type;
12442                             }
12443
12444                           /* loc2 is a duplicated location. We need to check
12445                              if it should be inserted in case it will be
12446                              unduplicated.  */
12447                           if (loc2 != old_loc
12448                               && unduplicated_should_be_inserted (loc2))
12449                             {
12450                               swap_insertion (old_loc, loc2);
12451                               keep_in_target = 1;
12452                               break;
12453                             }
12454                         }
12455                     }
12456                 }
12457             }
12458
12459           if (!keep_in_target)
12460             {
12461               if (remove_breakpoint (old_loc, mark_uninserted))
12462                 {
12463                   /* This is just about all we can do.  We could keep
12464                      this location on the global list, and try to
12465                      remove it next time, but there's no particular
12466                      reason why we will succeed next time.
12467                      
12468                      Note that at this point, old_loc->owner is still
12469                      valid, as delete_breakpoint frees the breakpoint
12470                      only after calling us.  */
12471                   printf_filtered (_("warning: Error removing "
12472                                      "breakpoint %d\n"), 
12473                                    old_loc->owner->number);
12474                 }
12475               removed = 1;
12476             }
12477         }
12478
12479       if (!found_object)
12480         {
12481           if (removed && target_is_non_stop_p ()
12482               && need_moribund_for_location_type (old_loc))
12483             {
12484               /* This location was removed from the target.  In
12485                  non-stop mode, a race condition is possible where
12486                  we've removed a breakpoint, but stop events for that
12487                  breakpoint are already queued and will arrive later.
12488                  We apply an heuristic to be able to distinguish such
12489                  SIGTRAPs from other random SIGTRAPs: we keep this
12490                  breakpoint location for a bit, and will retire it
12491                  after we see some number of events.  The theory here
12492                  is that reporting of events should, "on the average",
12493                  be fair, so after a while we'll see events from all
12494                  threads that have anything of interest, and no longer
12495                  need to keep this breakpoint location around.  We
12496                  don't hold locations forever so to reduce chances of
12497                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12498                  SIGTRAP.
12499
12500                  The heuristic failing can be disastrous on
12501                  decr_pc_after_break targets.
12502
12503                  On decr_pc_after_break targets, like e.g., x86-linux,
12504                  if we fail to recognize a late breakpoint SIGTRAP,
12505                  because events_till_retirement has reached 0 too
12506                  soon, we'll fail to do the PC adjustment, and report
12507                  a random SIGTRAP to the user.  When the user resumes
12508                  the inferior, it will most likely immediately crash
12509                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12510                  corrupted, because of being resumed e.g., in the
12511                  middle of a multi-byte instruction, or skipped a
12512                  one-byte instruction.  This was actually seen happen
12513                  on native x86-linux, and should be less rare on
12514                  targets that do not support new thread events, like
12515                  remote, due to the heuristic depending on
12516                  thread_count.
12517
12518                  Mistaking a random SIGTRAP for a breakpoint trap
12519                  causes similar symptoms (PC adjustment applied when
12520                  it shouldn't), but then again, playing with SIGTRAPs
12521                  behind the debugger's back is asking for trouble.
12522
12523                  Since hardware watchpoint traps are always
12524                  distinguishable from other traps, so we don't need to
12525                  apply keep hardware watchpoint moribund locations
12526                  around.  We simply always ignore hardware watchpoint
12527                  traps we can no longer explain.  */
12528
12529               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12530               old_loc->owner = NULL;
12531
12532               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12533             }
12534           else
12535             {
12536               old_loc->owner = NULL;
12537               decref_bp_location (&old_loc);
12538             }
12539         }
12540     }
12541
12542   /* Rescan breakpoints at the same address and section, marking the
12543      first one as "first" and any others as "duplicates".  This is so
12544      that the bpt instruction is only inserted once.  If we have a
12545      permanent breakpoint at the same place as BPT, make that one the
12546      official one, and the rest as duplicates.  Permanent breakpoints
12547      are sorted first for the same address.
12548
12549      Do the same for hardware watchpoints, but also considering the
12550      watchpoint's type (regular/access/read) and length.  */
12551
12552   bp_loc_first = NULL;
12553   wp_loc_first = NULL;
12554   awp_loc_first = NULL;
12555   rwp_loc_first = NULL;
12556   ALL_BP_LOCATIONS (loc, locp)
12557     {
12558       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12559          non-NULL.  */
12560       struct bp_location **loc_first_p;
12561       b = loc->owner;
12562
12563       if (!unduplicated_should_be_inserted (loc)
12564           || !breakpoint_address_is_meaningful (b)
12565           /* Don't detect duplicate for tracepoint locations because they are
12566            never duplicated.  See the comments in field `duplicate' of
12567            `struct bp_location'.  */
12568           || is_tracepoint (b))
12569         {
12570           /* Clear the condition modification flag.  */
12571           loc->condition_changed = condition_unchanged;
12572           continue;
12573         }
12574
12575       if (b->type == bp_hardware_watchpoint)
12576         loc_first_p = &wp_loc_first;
12577       else if (b->type == bp_read_watchpoint)
12578         loc_first_p = &rwp_loc_first;
12579       else if (b->type == bp_access_watchpoint)
12580         loc_first_p = &awp_loc_first;
12581       else
12582         loc_first_p = &bp_loc_first;
12583
12584       if (*loc_first_p == NULL
12585           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12586           || !breakpoint_locations_match (loc, *loc_first_p))
12587         {
12588           *loc_first_p = loc;
12589           loc->duplicate = 0;
12590
12591           if (is_breakpoint (loc->owner) && loc->condition_changed)
12592             {
12593               loc->needs_update = 1;
12594               /* Clear the condition modification flag.  */
12595               loc->condition_changed = condition_unchanged;
12596             }
12597           continue;
12598         }
12599
12600
12601       /* This and the above ensure the invariant that the first location
12602          is not duplicated, and is the inserted one.
12603          All following are marked as duplicated, and are not inserted.  */
12604       if (loc->inserted)
12605         swap_insertion (loc, *loc_first_p);
12606       loc->duplicate = 1;
12607
12608       /* Clear the condition modification flag.  */
12609       loc->condition_changed = condition_unchanged;
12610     }
12611
12612   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12613     {
12614       if (insert_mode != UGLL_DONT_INSERT)
12615         insert_breakpoint_locations ();
12616       else
12617         {
12618           /* Even though the caller told us to not insert new
12619              locations, we may still need to update conditions on the
12620              target's side of breakpoints that were already inserted
12621              if the target is evaluating breakpoint conditions.  We
12622              only update conditions for locations that are marked
12623              "needs_update".  */
12624           update_inserted_breakpoint_locations ();
12625         }
12626     }
12627
12628   if (insert_mode != UGLL_DONT_INSERT)
12629     download_tracepoint_locations ();
12630
12631   do_cleanups (cleanups);
12632 }
12633
12634 void
12635 breakpoint_retire_moribund (void)
12636 {
12637   struct bp_location *loc;
12638   int ix;
12639
12640   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12641     if (--(loc->events_till_retirement) == 0)
12642       {
12643         decref_bp_location (&loc);
12644         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12645         --ix;
12646       }
12647 }
12648
12649 static void
12650 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12651 {
12652
12653   TRY
12654     {
12655       update_global_location_list (insert_mode);
12656     }
12657   CATCH (e, RETURN_MASK_ERROR)
12658     {
12659     }
12660   END_CATCH
12661 }
12662
12663 /* Clear BKP from a BPS.  */
12664
12665 static void
12666 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12667 {
12668   bpstat bs;
12669
12670   for (bs = bps; bs; bs = bs->next)
12671     if (bs->breakpoint_at == bpt)
12672       {
12673         bs->breakpoint_at = NULL;
12674         bs->old_val = NULL;
12675         /* bs->commands will be freed later.  */
12676       }
12677 }
12678
12679 /* Callback for iterate_over_threads.  */
12680 static int
12681 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12682 {
12683   struct breakpoint *bpt = (struct breakpoint *) data;
12684
12685   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12686   return 0;
12687 }
12688
12689 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12690    callbacks.  */
12691
12692 static void
12693 say_where (struct breakpoint *b)
12694 {
12695   struct value_print_options opts;
12696
12697   get_user_print_options (&opts);
12698
12699   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12700      single string.  */
12701   if (b->loc == NULL)
12702     {
12703       /* For pending locations, the output differs slightly based
12704          on b->extra_string.  If this is non-NULL, it contains either
12705          a condition or dprintf arguments.  */
12706       if (b->extra_string == NULL)
12707         {
12708           printf_filtered (_(" (%s) pending."),
12709                            event_location_to_string (b->location));
12710         }
12711       else if (b->type == bp_dprintf)
12712         {
12713           printf_filtered (_(" (%s,%s) pending."),
12714                            event_location_to_string (b->location),
12715                            b->extra_string);
12716         }
12717       else
12718         {
12719           printf_filtered (_(" (%s %s) pending."),
12720                            event_location_to_string (b->location),
12721                            b->extra_string);
12722         }
12723     }
12724   else
12725     {
12726       if (opts.addressprint || b->loc->symtab == NULL)
12727         {
12728           printf_filtered (" at ");
12729           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12730                           gdb_stdout);
12731         }
12732       if (b->loc->symtab != NULL)
12733         {
12734           /* If there is a single location, we can print the location
12735              more nicely.  */
12736           if (b->loc->next == NULL)
12737             printf_filtered (": file %s, line %d.",
12738                              symtab_to_filename_for_display (b->loc->symtab),
12739                              b->loc->line_number);
12740           else
12741             /* This is not ideal, but each location may have a
12742                different file name, and this at least reflects the
12743                real situation somewhat.  */
12744             printf_filtered (": %s.",
12745                              event_location_to_string (b->location));
12746         }
12747
12748       if (b->loc->next)
12749         {
12750           struct bp_location *loc = b->loc;
12751           int n = 0;
12752           for (; loc; loc = loc->next)
12753             ++n;
12754           printf_filtered (" (%d locations)", n);
12755         }
12756     }
12757 }
12758
12759 /* Default bp_location_ops methods.  */
12760
12761 static void
12762 bp_location_dtor (struct bp_location *self)
12763 {
12764   xfree (self->cond);
12765   if (self->cond_bytecode)
12766     free_agent_expr (self->cond_bytecode);
12767   xfree (self->function_name);
12768
12769   VEC_free (agent_expr_p, self->target_info.conditions);
12770   VEC_free (agent_expr_p, self->target_info.tcommands);
12771 }
12772
12773 static const struct bp_location_ops bp_location_ops =
12774 {
12775   bp_location_dtor
12776 };
12777
12778 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12779    inherit from.  */
12780
12781 static void
12782 base_breakpoint_dtor (struct breakpoint *self)
12783 {
12784   decref_counted_command_line (&self->commands);
12785   xfree (self->cond_string);
12786   xfree (self->extra_string);
12787   xfree (self->filter);
12788   delete_event_location (self->location);
12789   delete_event_location (self->location_range_end);
12790 }
12791
12792 static struct bp_location *
12793 base_breakpoint_allocate_location (struct breakpoint *self)
12794 {
12795   struct bp_location *loc;
12796
12797   loc = XNEW (struct bp_location);
12798   init_bp_location (loc, &bp_location_ops, self);
12799   return loc;
12800 }
12801
12802 static void
12803 base_breakpoint_re_set (struct breakpoint *b)
12804 {
12805   /* Nothing to re-set. */
12806 }
12807
12808 #define internal_error_pure_virtual_called() \
12809   gdb_assert_not_reached ("pure virtual function called")
12810
12811 static int
12812 base_breakpoint_insert_location (struct bp_location *bl)
12813 {
12814   internal_error_pure_virtual_called ();
12815 }
12816
12817 static int
12818 base_breakpoint_remove_location (struct bp_location *bl)
12819 {
12820   internal_error_pure_virtual_called ();
12821 }
12822
12823 static int
12824 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12825                                 struct address_space *aspace,
12826                                 CORE_ADDR bp_addr,
12827                                 const struct target_waitstatus *ws)
12828 {
12829   internal_error_pure_virtual_called ();
12830 }
12831
12832 static void
12833 base_breakpoint_check_status (bpstat bs)
12834 {
12835   /* Always stop.   */
12836 }
12837
12838 /* A "works_in_software_mode" breakpoint_ops method that just internal
12839    errors.  */
12840
12841 static int
12842 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12843 {
12844   internal_error_pure_virtual_called ();
12845 }
12846
12847 /* A "resources_needed" breakpoint_ops method that just internal
12848    errors.  */
12849
12850 static int
12851 base_breakpoint_resources_needed (const struct bp_location *bl)
12852 {
12853   internal_error_pure_virtual_called ();
12854 }
12855
12856 static enum print_stop_action
12857 base_breakpoint_print_it (bpstat bs)
12858 {
12859   internal_error_pure_virtual_called ();
12860 }
12861
12862 static void
12863 base_breakpoint_print_one_detail (const struct breakpoint *self,
12864                                   struct ui_out *uiout)
12865 {
12866   /* nothing */
12867 }
12868
12869 static void
12870 base_breakpoint_print_mention (struct breakpoint *b)
12871 {
12872   internal_error_pure_virtual_called ();
12873 }
12874
12875 static void
12876 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12877 {
12878   internal_error_pure_virtual_called ();
12879 }
12880
12881 static void
12882 base_breakpoint_create_sals_from_location
12883   (const struct event_location *location,
12884    struct linespec_result *canonical,
12885    enum bptype type_wanted)
12886 {
12887   internal_error_pure_virtual_called ();
12888 }
12889
12890 static void
12891 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12892                                         struct linespec_result *c,
12893                                         char *cond_string,
12894                                         char *extra_string,
12895                                         enum bptype type_wanted,
12896                                         enum bpdisp disposition,
12897                                         int thread,
12898                                         int task, int ignore_count,
12899                                         const struct breakpoint_ops *o,
12900                                         int from_tty, int enabled,
12901                                         int internal, unsigned flags)
12902 {
12903   internal_error_pure_virtual_called ();
12904 }
12905
12906 static void
12907 base_breakpoint_decode_location (struct breakpoint *b,
12908                                  const struct event_location *location,
12909                                  struct symtabs_and_lines *sals)
12910 {
12911   internal_error_pure_virtual_called ();
12912 }
12913
12914 /* The default 'explains_signal' method.  */
12915
12916 static int
12917 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12918 {
12919   return 1;
12920 }
12921
12922 /* The default "after_condition_true" method.  */
12923
12924 static void
12925 base_breakpoint_after_condition_true (struct bpstats *bs)
12926 {
12927   /* Nothing to do.   */
12928 }
12929
12930 struct breakpoint_ops base_breakpoint_ops =
12931 {
12932   base_breakpoint_dtor,
12933   base_breakpoint_allocate_location,
12934   base_breakpoint_re_set,
12935   base_breakpoint_insert_location,
12936   base_breakpoint_remove_location,
12937   base_breakpoint_breakpoint_hit,
12938   base_breakpoint_check_status,
12939   base_breakpoint_resources_needed,
12940   base_breakpoint_works_in_software_mode,
12941   base_breakpoint_print_it,
12942   NULL,
12943   base_breakpoint_print_one_detail,
12944   base_breakpoint_print_mention,
12945   base_breakpoint_print_recreate,
12946   base_breakpoint_create_sals_from_location,
12947   base_breakpoint_create_breakpoints_sal,
12948   base_breakpoint_decode_location,
12949   base_breakpoint_explains_signal,
12950   base_breakpoint_after_condition_true,
12951 };
12952
12953 /* Default breakpoint_ops methods.  */
12954
12955 static void
12956 bkpt_re_set (struct breakpoint *b)
12957 {
12958   /* FIXME: is this still reachable?  */
12959   if (event_location_empty_p (b->location))
12960     {
12961       /* Anything without a location can't be re-set.  */
12962       delete_breakpoint (b);
12963       return;
12964     }
12965
12966   breakpoint_re_set_default (b);
12967 }
12968
12969 static int
12970 bkpt_insert_location (struct bp_location *bl)
12971 {
12972   if (bl->loc_type == bp_loc_hardware_breakpoint)
12973     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12974   else
12975     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12976 }
12977
12978 static int
12979 bkpt_remove_location (struct bp_location *bl)
12980 {
12981   if (bl->loc_type == bp_loc_hardware_breakpoint)
12982     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12983   else
12984     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12985 }
12986
12987 static int
12988 bkpt_breakpoint_hit (const struct bp_location *bl,
12989                      struct address_space *aspace, CORE_ADDR bp_addr,
12990                      const struct target_waitstatus *ws)
12991 {
12992   if (ws->kind != TARGET_WAITKIND_STOPPED
12993       || ws->value.sig != GDB_SIGNAL_TRAP)
12994     return 0;
12995
12996   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12997                                  aspace, bp_addr))
12998     return 0;
12999
13000   if (overlay_debugging         /* unmapped overlay section */
13001       && section_is_overlay (bl->section)
13002       && !section_is_mapped (bl->section))
13003     return 0;
13004
13005   return 1;
13006 }
13007
13008 static int
13009 dprintf_breakpoint_hit (const struct bp_location *bl,
13010                         struct address_space *aspace, CORE_ADDR bp_addr,
13011                         const struct target_waitstatus *ws)
13012 {
13013   if (dprintf_style == dprintf_style_agent
13014       && target_can_run_breakpoint_commands ())
13015     {
13016       /* An agent-style dprintf never causes a stop.  If we see a trap
13017          for this address it must be for a breakpoint that happens to
13018          be set at the same address.  */
13019       return 0;
13020     }
13021
13022   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13023 }
13024
13025 static int
13026 bkpt_resources_needed (const struct bp_location *bl)
13027 {
13028   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13029
13030   return 1;
13031 }
13032
13033 static enum print_stop_action
13034 bkpt_print_it (bpstat bs)
13035 {
13036   struct breakpoint *b;
13037   const struct bp_location *bl;
13038   int bp_temp;
13039   struct ui_out *uiout = current_uiout;
13040
13041   gdb_assert (bs->bp_location_at != NULL);
13042
13043   bl = bs->bp_location_at;
13044   b = bs->breakpoint_at;
13045
13046   bp_temp = b->disposition == disp_del;
13047   if (bl->address != bl->requested_address)
13048     breakpoint_adjustment_warning (bl->requested_address,
13049                                    bl->address,
13050                                    b->number, 1);
13051   annotate_breakpoint (b->number);
13052   if (bp_temp)
13053     ui_out_text (uiout, "\nTemporary breakpoint ");
13054   else
13055     ui_out_text (uiout, "\nBreakpoint ");
13056   if (ui_out_is_mi_like_p (uiout))
13057     {
13058       ui_out_field_string (uiout, "reason",
13059                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13060       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13061     }
13062   ui_out_field_int (uiout, "bkptno", b->number);
13063   ui_out_text (uiout, ", ");
13064
13065   return PRINT_SRC_AND_LOC;
13066 }
13067
13068 static void
13069 bkpt_print_mention (struct breakpoint *b)
13070 {
13071   if (ui_out_is_mi_like_p (current_uiout))
13072     return;
13073
13074   switch (b->type)
13075     {
13076     case bp_breakpoint:
13077     case bp_gnu_ifunc_resolver:
13078       if (b->disposition == disp_del)
13079         printf_filtered (_("Temporary breakpoint"));
13080       else
13081         printf_filtered (_("Breakpoint"));
13082       printf_filtered (_(" %d"), b->number);
13083       if (b->type == bp_gnu_ifunc_resolver)
13084         printf_filtered (_(" at gnu-indirect-function resolver"));
13085       break;
13086     case bp_hardware_breakpoint:
13087       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13088       break;
13089     case bp_dprintf:
13090       printf_filtered (_("Dprintf %d"), b->number);
13091       break;
13092     }
13093
13094   say_where (b);
13095 }
13096
13097 static void
13098 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13099 {
13100   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13101     fprintf_unfiltered (fp, "tbreak");
13102   else if (tp->type == bp_breakpoint)
13103     fprintf_unfiltered (fp, "break");
13104   else if (tp->type == bp_hardware_breakpoint
13105            && tp->disposition == disp_del)
13106     fprintf_unfiltered (fp, "thbreak");
13107   else if (tp->type == bp_hardware_breakpoint)
13108     fprintf_unfiltered (fp, "hbreak");
13109   else
13110     internal_error (__FILE__, __LINE__,
13111                     _("unhandled breakpoint type %d"), (int) tp->type);
13112
13113   fprintf_unfiltered (fp, " %s",
13114                       event_location_to_string (tp->location));
13115
13116   /* Print out extra_string if this breakpoint is pending.  It might
13117      contain, for example, conditions that were set by the user.  */
13118   if (tp->loc == NULL && tp->extra_string != NULL)
13119     fprintf_unfiltered (fp, " %s", tp->extra_string);
13120
13121   print_recreate_thread (tp, fp);
13122 }
13123
13124 static void
13125 bkpt_create_sals_from_location (const struct event_location *location,
13126                                 struct linespec_result *canonical,
13127                                 enum bptype type_wanted)
13128 {
13129   create_sals_from_location_default (location, canonical, type_wanted);
13130 }
13131
13132 static void
13133 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13134                              struct linespec_result *canonical,
13135                              char *cond_string,
13136                              char *extra_string,
13137                              enum bptype type_wanted,
13138                              enum bpdisp disposition,
13139                              int thread,
13140                              int task, int ignore_count,
13141                              const struct breakpoint_ops *ops,
13142                              int from_tty, int enabled,
13143                              int internal, unsigned flags)
13144 {
13145   create_breakpoints_sal_default (gdbarch, canonical,
13146                                   cond_string, extra_string,
13147                                   type_wanted,
13148                                   disposition, thread, task,
13149                                   ignore_count, ops, from_tty,
13150                                   enabled, internal, flags);
13151 }
13152
13153 static void
13154 bkpt_decode_location (struct breakpoint *b,
13155                       const struct event_location *location,
13156                       struct symtabs_and_lines *sals)
13157 {
13158   decode_location_default (b, location, sals);
13159 }
13160
13161 /* Virtual table for internal breakpoints.  */
13162
13163 static void
13164 internal_bkpt_re_set (struct breakpoint *b)
13165 {
13166   switch (b->type)
13167     {
13168       /* Delete overlay event and longjmp master breakpoints; they
13169          will be reset later by breakpoint_re_set.  */
13170     case bp_overlay_event:
13171     case bp_longjmp_master:
13172     case bp_std_terminate_master:
13173     case bp_exception_master:
13174       delete_breakpoint (b);
13175       break;
13176
13177       /* This breakpoint is special, it's set up when the inferior
13178          starts and we really don't want to touch it.  */
13179     case bp_shlib_event:
13180
13181       /* Like bp_shlib_event, this breakpoint type is special.  Once
13182          it is set up, we do not want to touch it.  */
13183     case bp_thread_event:
13184       break;
13185     }
13186 }
13187
13188 static void
13189 internal_bkpt_check_status (bpstat bs)
13190 {
13191   if (bs->breakpoint_at->type == bp_shlib_event)
13192     {
13193       /* If requested, stop when the dynamic linker notifies GDB of
13194          events.  This allows the user to get control and place
13195          breakpoints in initializer routines for dynamically loaded
13196          objects (among other things).  */
13197       bs->stop = stop_on_solib_events;
13198       bs->print = stop_on_solib_events;
13199     }
13200   else
13201     bs->stop = 0;
13202 }
13203
13204 static enum print_stop_action
13205 internal_bkpt_print_it (bpstat bs)
13206 {
13207   struct breakpoint *b;
13208
13209   b = bs->breakpoint_at;
13210
13211   switch (b->type)
13212     {
13213     case bp_shlib_event:
13214       /* Did we stop because the user set the stop_on_solib_events
13215          variable?  (If so, we report this as a generic, "Stopped due
13216          to shlib event" message.) */
13217       print_solib_event (0);
13218       break;
13219
13220     case bp_thread_event:
13221       /* Not sure how we will get here.
13222          GDB should not stop for these breakpoints.  */
13223       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13224       break;
13225
13226     case bp_overlay_event:
13227       /* By analogy with the thread event, GDB should not stop for these.  */
13228       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13229       break;
13230
13231     case bp_longjmp_master:
13232       /* These should never be enabled.  */
13233       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13234       break;
13235
13236     case bp_std_terminate_master:
13237       /* These should never be enabled.  */
13238       printf_filtered (_("std::terminate Master Breakpoint: "
13239                          "gdb should not stop!\n"));
13240       break;
13241
13242     case bp_exception_master:
13243       /* These should never be enabled.  */
13244       printf_filtered (_("Exception Master Breakpoint: "
13245                          "gdb should not stop!\n"));
13246       break;
13247     }
13248
13249   return PRINT_NOTHING;
13250 }
13251
13252 static void
13253 internal_bkpt_print_mention (struct breakpoint *b)
13254 {
13255   /* Nothing to mention.  These breakpoints are internal.  */
13256 }
13257
13258 /* Virtual table for momentary breakpoints  */
13259
13260 static void
13261 momentary_bkpt_re_set (struct breakpoint *b)
13262 {
13263   /* Keep temporary breakpoints, which can be encountered when we step
13264      over a dlopen call and solib_add is resetting the breakpoints.
13265      Otherwise these should have been blown away via the cleanup chain
13266      or by breakpoint_init_inferior when we rerun the executable.  */
13267 }
13268
13269 static void
13270 momentary_bkpt_check_status (bpstat bs)
13271 {
13272   /* Nothing.  The point of these breakpoints is causing a stop.  */
13273 }
13274
13275 static enum print_stop_action
13276 momentary_bkpt_print_it (bpstat bs)
13277 {
13278   return PRINT_UNKNOWN;
13279 }
13280
13281 static void
13282 momentary_bkpt_print_mention (struct breakpoint *b)
13283 {
13284   /* Nothing to mention.  These breakpoints are internal.  */
13285 }
13286
13287 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13288
13289    It gets cleared already on the removal of the first one of such placed
13290    breakpoints.  This is OK as they get all removed altogether.  */
13291
13292 static void
13293 longjmp_bkpt_dtor (struct breakpoint *self)
13294 {
13295   struct thread_info *tp = find_thread_id (self->thread);
13296
13297   if (tp)
13298     tp->initiating_frame = null_frame_id;
13299
13300   momentary_breakpoint_ops.dtor (self);
13301 }
13302
13303 /* Specific methods for probe breakpoints.  */
13304
13305 static int
13306 bkpt_probe_insert_location (struct bp_location *bl)
13307 {
13308   int v = bkpt_insert_location (bl);
13309
13310   if (v == 0)
13311     {
13312       /* The insertion was successful, now let's set the probe's semaphore
13313          if needed.  */
13314       if (bl->probe.probe->pops->set_semaphore != NULL)
13315         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13316                                               bl->probe.objfile,
13317                                               bl->gdbarch);
13318     }
13319
13320   return v;
13321 }
13322
13323 static int
13324 bkpt_probe_remove_location (struct bp_location *bl)
13325 {
13326   /* Let's clear the semaphore before removing the location.  */
13327   if (bl->probe.probe->pops->clear_semaphore != NULL)
13328     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13329                                             bl->probe.objfile,
13330                                             bl->gdbarch);
13331
13332   return bkpt_remove_location (bl);
13333 }
13334
13335 static void
13336 bkpt_probe_create_sals_from_location (const struct event_location *location,
13337                                       struct linespec_result *canonical,
13338                                       enum bptype type_wanted)
13339 {
13340   struct linespec_sals lsal;
13341
13342   lsal.sals = parse_probes (location, canonical);
13343   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13344   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13345 }
13346
13347 static void
13348 bkpt_probe_decode_location (struct breakpoint *b,
13349                             const struct event_location *location,
13350                             struct symtabs_and_lines *sals)
13351 {
13352   *sals = parse_probes (location, NULL);
13353   if (!sals->sals)
13354     error (_("probe not found"));
13355 }
13356
13357 /* The breakpoint_ops structure to be used in tracepoints.  */
13358
13359 static void
13360 tracepoint_re_set (struct breakpoint *b)
13361 {
13362   breakpoint_re_set_default (b);
13363 }
13364
13365 static int
13366 tracepoint_breakpoint_hit (const struct bp_location *bl,
13367                            struct address_space *aspace, CORE_ADDR bp_addr,
13368                            const struct target_waitstatus *ws)
13369 {
13370   /* By definition, the inferior does not report stops at
13371      tracepoints.  */
13372   return 0;
13373 }
13374
13375 static void
13376 tracepoint_print_one_detail (const struct breakpoint *self,
13377                              struct ui_out *uiout)
13378 {
13379   struct tracepoint *tp = (struct tracepoint *) self;
13380   if (tp->static_trace_marker_id)
13381     {
13382       gdb_assert (self->type == bp_static_tracepoint);
13383
13384       ui_out_text (uiout, "\tmarker id is ");
13385       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13386                            tp->static_trace_marker_id);
13387       ui_out_text (uiout, "\n");
13388     }
13389 }
13390
13391 static void
13392 tracepoint_print_mention (struct breakpoint *b)
13393 {
13394   if (ui_out_is_mi_like_p (current_uiout))
13395     return;
13396
13397   switch (b->type)
13398     {
13399     case bp_tracepoint:
13400       printf_filtered (_("Tracepoint"));
13401       printf_filtered (_(" %d"), b->number);
13402       break;
13403     case bp_fast_tracepoint:
13404       printf_filtered (_("Fast tracepoint"));
13405       printf_filtered (_(" %d"), b->number);
13406       break;
13407     case bp_static_tracepoint:
13408       printf_filtered (_("Static tracepoint"));
13409       printf_filtered (_(" %d"), b->number);
13410       break;
13411     default:
13412       internal_error (__FILE__, __LINE__,
13413                       _("unhandled tracepoint type %d"), (int) b->type);
13414     }
13415
13416   say_where (b);
13417 }
13418
13419 static void
13420 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13421 {
13422   struct tracepoint *tp = (struct tracepoint *) self;
13423
13424   if (self->type == bp_fast_tracepoint)
13425     fprintf_unfiltered (fp, "ftrace");
13426   if (self->type == bp_static_tracepoint)
13427     fprintf_unfiltered (fp, "strace");
13428   else if (self->type == bp_tracepoint)
13429     fprintf_unfiltered (fp, "trace");
13430   else
13431     internal_error (__FILE__, __LINE__,
13432                     _("unhandled tracepoint type %d"), (int) self->type);
13433
13434   fprintf_unfiltered (fp, " %s",
13435                       event_location_to_string (self->location));
13436   print_recreate_thread (self, fp);
13437
13438   if (tp->pass_count)
13439     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13440 }
13441
13442 static void
13443 tracepoint_create_sals_from_location (const struct event_location *location,
13444                                       struct linespec_result *canonical,
13445                                       enum bptype type_wanted)
13446 {
13447   create_sals_from_location_default (location, canonical, type_wanted);
13448 }
13449
13450 static void
13451 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13452                                    struct linespec_result *canonical,
13453                                    char *cond_string,
13454                                    char *extra_string,
13455                                    enum bptype type_wanted,
13456                                    enum bpdisp disposition,
13457                                    int thread,
13458                                    int task, int ignore_count,
13459                                    const struct breakpoint_ops *ops,
13460                                    int from_tty, int enabled,
13461                                    int internal, unsigned flags)
13462 {
13463   create_breakpoints_sal_default (gdbarch, canonical,
13464                                   cond_string, extra_string,
13465                                   type_wanted,
13466                                   disposition, thread, task,
13467                                   ignore_count, ops, from_tty,
13468                                   enabled, internal, flags);
13469 }
13470
13471 static void
13472 tracepoint_decode_location (struct breakpoint *b,
13473                             const struct event_location *location,
13474                             struct symtabs_and_lines *sals)
13475 {
13476   decode_location_default (b, location, sals);
13477 }
13478
13479 struct breakpoint_ops tracepoint_breakpoint_ops;
13480
13481 /* The breakpoint_ops structure to be use on tracepoints placed in a
13482    static probe.  */
13483
13484 static void
13485 tracepoint_probe_create_sals_from_location
13486   (const struct event_location *location,
13487    struct linespec_result *canonical,
13488    enum bptype type_wanted)
13489 {
13490   /* We use the same method for breakpoint on probes.  */
13491   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13492 }
13493
13494 static void
13495 tracepoint_probe_decode_location (struct breakpoint *b,
13496                                   const struct event_location *location,
13497                                   struct symtabs_and_lines *sals)
13498 {
13499   /* We use the same method for breakpoint on probes.  */
13500   bkpt_probe_decode_location (b, location, sals);
13501 }
13502
13503 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13504
13505 /* Dprintf breakpoint_ops methods.  */
13506
13507 static void
13508 dprintf_re_set (struct breakpoint *b)
13509 {
13510   breakpoint_re_set_default (b);
13511
13512   /* extra_string should never be non-NULL for dprintf.  */
13513   gdb_assert (b->extra_string != NULL);
13514
13515   /* 1 - connect to target 1, that can run breakpoint commands.
13516      2 - create a dprintf, which resolves fine.
13517      3 - disconnect from target 1
13518      4 - connect to target 2, that can NOT run breakpoint commands.
13519
13520      After steps #3/#4, you'll want the dprintf command list to
13521      be updated, because target 1 and 2 may well return different
13522      answers for target_can_run_breakpoint_commands().
13523      Given absence of finer grained resetting, we get to do
13524      it all the time.  */
13525   if (b->extra_string != NULL)
13526     update_dprintf_command_list (b);
13527 }
13528
13529 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13530
13531 static void
13532 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13533 {
13534   fprintf_unfiltered (fp, "dprintf %s,%s",
13535                       event_location_to_string (tp->location),
13536                       tp->extra_string);
13537   print_recreate_thread (tp, fp);
13538 }
13539
13540 /* Implement the "after_condition_true" breakpoint_ops method for
13541    dprintf.
13542
13543    dprintf's are implemented with regular commands in their command
13544    list, but we run the commands here instead of before presenting the
13545    stop to the user, as dprintf's don't actually cause a stop.  This
13546    also makes it so that the commands of multiple dprintfs at the same
13547    address are all handled.  */
13548
13549 static void
13550 dprintf_after_condition_true (struct bpstats *bs)
13551 {
13552   struct cleanup *old_chain;
13553   struct bpstats tmp_bs = { NULL };
13554   struct bpstats *tmp_bs_p = &tmp_bs;
13555
13556   /* dprintf's never cause a stop.  This wasn't set in the
13557      check_status hook instead because that would make the dprintf's
13558      condition not be evaluated.  */
13559   bs->stop = 0;
13560
13561   /* Run the command list here.  Take ownership of it instead of
13562      copying.  We never want these commands to run later in
13563      bpstat_do_actions, if a breakpoint that causes a stop happens to
13564      be set at same address as this dprintf, or even if running the
13565      commands here throws.  */
13566   tmp_bs.commands = bs->commands;
13567   bs->commands = NULL;
13568   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13569
13570   bpstat_do_actions_1 (&tmp_bs_p);
13571
13572   /* 'tmp_bs.commands' will usually be NULL by now, but
13573      bpstat_do_actions_1 may return early without processing the whole
13574      list.  */
13575   do_cleanups (old_chain);
13576 }
13577
13578 /* The breakpoint_ops structure to be used on static tracepoints with
13579    markers (`-m').  */
13580
13581 static void
13582 strace_marker_create_sals_from_location (const struct event_location *location,
13583                                          struct linespec_result *canonical,
13584                                          enum bptype type_wanted)
13585 {
13586   struct linespec_sals lsal;
13587   const char *arg_start, *arg;
13588   char *str;
13589   struct cleanup *cleanup;
13590
13591   arg = arg_start = get_linespec_location (location);
13592   lsal.sals = decode_static_tracepoint_spec (&arg);
13593
13594   str = savestring (arg_start, arg - arg_start);
13595   cleanup = make_cleanup (xfree, str);
13596   canonical->location = new_linespec_location (&str);
13597   do_cleanups (cleanup);
13598
13599   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13600   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13601 }
13602
13603 static void
13604 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13605                                       struct linespec_result *canonical,
13606                                       char *cond_string,
13607                                       char *extra_string,
13608                                       enum bptype type_wanted,
13609                                       enum bpdisp disposition,
13610                                       int thread,
13611                                       int task, int ignore_count,
13612                                       const struct breakpoint_ops *ops,
13613                                       int from_tty, int enabled,
13614                                       int internal, unsigned flags)
13615 {
13616   int i;
13617   struct linespec_sals *lsal = VEC_index (linespec_sals,
13618                                           canonical->sals, 0);
13619
13620   /* If the user is creating a static tracepoint by marker id
13621      (strace -m MARKER_ID), then store the sals index, so that
13622      breakpoint_re_set can try to match up which of the newly
13623      found markers corresponds to this one, and, don't try to
13624      expand multiple locations for each sal, given than SALS
13625      already should contain all sals for MARKER_ID.  */
13626
13627   for (i = 0; i < lsal->sals.nelts; ++i)
13628     {
13629       struct symtabs_and_lines expanded;
13630       struct tracepoint *tp;
13631       struct cleanup *old_chain;
13632       struct event_location *location;
13633
13634       expanded.nelts = 1;
13635       expanded.sals = &lsal->sals.sals[i];
13636
13637       location = copy_event_location (canonical->location);
13638       old_chain = make_cleanup_delete_event_location (location);
13639
13640       tp = XCNEW (struct tracepoint);
13641       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13642                            location, NULL,
13643                            cond_string, extra_string,
13644                            type_wanted, disposition,
13645                            thread, task, ignore_count, ops,
13646                            from_tty, enabled, internal, flags,
13647                            canonical->special_display);
13648       /* Given that its possible to have multiple markers with
13649          the same string id, if the user is creating a static
13650          tracepoint by marker id ("strace -m MARKER_ID"), then
13651          store the sals index, so that breakpoint_re_set can
13652          try to match up which of the newly found markers
13653          corresponds to this one  */
13654       tp->static_trace_marker_id_idx = i;
13655
13656       install_breakpoint (internal, &tp->base, 0);
13657
13658       discard_cleanups (old_chain);
13659     }
13660 }
13661
13662 static void
13663 strace_marker_decode_location (struct breakpoint *b,
13664                                const struct event_location *location,
13665                                struct symtabs_and_lines *sals)
13666 {
13667   struct tracepoint *tp = (struct tracepoint *) b;
13668   const char *s = get_linespec_location (location);
13669
13670   *sals = decode_static_tracepoint_spec (&s);
13671   if (sals->nelts > tp->static_trace_marker_id_idx)
13672     {
13673       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13674       sals->nelts = 1;
13675     }
13676   else
13677     error (_("marker %s not found"), tp->static_trace_marker_id);
13678 }
13679
13680 static struct breakpoint_ops strace_marker_breakpoint_ops;
13681
13682 static int
13683 strace_marker_p (struct breakpoint *b)
13684 {
13685   return b->ops == &strace_marker_breakpoint_ops;
13686 }
13687
13688 /* Delete a breakpoint and clean up all traces of it in the data
13689    structures.  */
13690
13691 void
13692 delete_breakpoint (struct breakpoint *bpt)
13693 {
13694   struct breakpoint *b;
13695
13696   gdb_assert (bpt != NULL);
13697
13698   /* Has this bp already been deleted?  This can happen because
13699      multiple lists can hold pointers to bp's.  bpstat lists are
13700      especial culprits.
13701
13702      One example of this happening is a watchpoint's scope bp.  When
13703      the scope bp triggers, we notice that the watchpoint is out of
13704      scope, and delete it.  We also delete its scope bp.  But the
13705      scope bp is marked "auto-deleting", and is already on a bpstat.
13706      That bpstat is then checked for auto-deleting bp's, which are
13707      deleted.
13708
13709      A real solution to this problem might involve reference counts in
13710      bp's, and/or giving them pointers back to their referencing
13711      bpstat's, and teaching delete_breakpoint to only free a bp's
13712      storage when no more references were extent.  A cheaper bandaid
13713      was chosen.  */
13714   if (bpt->type == bp_none)
13715     return;
13716
13717   /* At least avoid this stale reference until the reference counting
13718      of breakpoints gets resolved.  */
13719   if (bpt->related_breakpoint != bpt)
13720     {
13721       struct breakpoint *related;
13722       struct watchpoint *w;
13723
13724       if (bpt->type == bp_watchpoint_scope)
13725         w = (struct watchpoint *) bpt->related_breakpoint;
13726       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13727         w = (struct watchpoint *) bpt;
13728       else
13729         w = NULL;
13730       if (w != NULL)
13731         watchpoint_del_at_next_stop (w);
13732
13733       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13734       for (related = bpt; related->related_breakpoint != bpt;
13735            related = related->related_breakpoint);
13736       related->related_breakpoint = bpt->related_breakpoint;
13737       bpt->related_breakpoint = bpt;
13738     }
13739
13740   /* watch_command_1 creates a watchpoint but only sets its number if
13741      update_watchpoint succeeds in creating its bp_locations.  If there's
13742      a problem in that process, we'll be asked to delete the half-created
13743      watchpoint.  In that case, don't announce the deletion.  */
13744   if (bpt->number)
13745     observer_notify_breakpoint_deleted (bpt);
13746
13747   if (breakpoint_chain == bpt)
13748     breakpoint_chain = bpt->next;
13749
13750   ALL_BREAKPOINTS (b)
13751     if (b->next == bpt)
13752     {
13753       b->next = bpt->next;
13754       break;
13755     }
13756
13757   /* Be sure no bpstat's are pointing at the breakpoint after it's
13758      been freed.  */
13759   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13760      in all threads for now.  Note that we cannot just remove bpstats
13761      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13762      commands are associated with the bpstat; if we remove it here,
13763      then the later call to bpstat_do_actions (&stop_bpstat); in
13764      event-top.c won't do anything, and temporary breakpoints with
13765      commands won't work.  */
13766
13767   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13768
13769   /* Now that breakpoint is removed from breakpoint list, update the
13770      global location list.  This will remove locations that used to
13771      belong to this breakpoint.  Do this before freeing the breakpoint
13772      itself, since remove_breakpoint looks at location's owner.  It
13773      might be better design to have location completely
13774      self-contained, but it's not the case now.  */
13775   update_global_location_list (UGLL_DONT_INSERT);
13776
13777   bpt->ops->dtor (bpt);
13778   /* On the chance that someone will soon try again to delete this
13779      same bp, we mark it as deleted before freeing its storage.  */
13780   bpt->type = bp_none;
13781   xfree (bpt);
13782 }
13783
13784 static void
13785 do_delete_breakpoint_cleanup (void *b)
13786 {
13787   delete_breakpoint ((struct breakpoint *) b);
13788 }
13789
13790 struct cleanup *
13791 make_cleanup_delete_breakpoint (struct breakpoint *b)
13792 {
13793   return make_cleanup (do_delete_breakpoint_cleanup, b);
13794 }
13795
13796 /* Iterator function to call a user-provided callback function once
13797    for each of B and its related breakpoints.  */
13798
13799 static void
13800 iterate_over_related_breakpoints (struct breakpoint *b,
13801                                   void (*function) (struct breakpoint *,
13802                                                     void *),
13803                                   void *data)
13804 {
13805   struct breakpoint *related;
13806
13807   related = b;
13808   do
13809     {
13810       struct breakpoint *next;
13811
13812       /* FUNCTION may delete RELATED.  */
13813       next = related->related_breakpoint;
13814
13815       if (next == related)
13816         {
13817           /* RELATED is the last ring entry.  */
13818           function (related, data);
13819
13820           /* FUNCTION may have deleted it, so we'd never reach back to
13821              B.  There's nothing left to do anyway, so just break
13822              out.  */
13823           break;
13824         }
13825       else
13826         function (related, data);
13827
13828       related = next;
13829     }
13830   while (related != b);
13831 }
13832
13833 static void
13834 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13835 {
13836   delete_breakpoint (b);
13837 }
13838
13839 /* A callback for map_breakpoint_numbers that calls
13840    delete_breakpoint.  */
13841
13842 static void
13843 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13844 {
13845   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13846 }
13847
13848 void
13849 delete_command (char *arg, int from_tty)
13850 {
13851   struct breakpoint *b, *b_tmp;
13852
13853   dont_repeat ();
13854
13855   if (arg == 0)
13856     {
13857       int breaks_to_delete = 0;
13858
13859       /* Delete all breakpoints if no argument.  Do not delete
13860          internal breakpoints, these have to be deleted with an
13861          explicit breakpoint number argument.  */
13862       ALL_BREAKPOINTS (b)
13863         if (user_breakpoint_p (b))
13864           {
13865             breaks_to_delete = 1;
13866             break;
13867           }
13868
13869       /* Ask user only if there are some breakpoints to delete.  */
13870       if (!from_tty
13871           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13872         {
13873           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13874             if (user_breakpoint_p (b))
13875               delete_breakpoint (b);
13876         }
13877     }
13878   else
13879     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13880 }
13881
13882 static int
13883 all_locations_are_pending (struct bp_location *loc)
13884 {
13885   for (; loc; loc = loc->next)
13886     if (!loc->shlib_disabled
13887         && !loc->pspace->executing_startup)
13888       return 0;
13889   return 1;
13890 }
13891
13892 /* Subroutine of update_breakpoint_locations to simplify it.
13893    Return non-zero if multiple fns in list LOC have the same name.
13894    Null names are ignored.  */
13895
13896 static int
13897 ambiguous_names_p (struct bp_location *loc)
13898 {
13899   struct bp_location *l;
13900   htab_t htab = htab_create_alloc (13, htab_hash_string,
13901                                    (int (*) (const void *, 
13902                                              const void *)) streq,
13903                                    NULL, xcalloc, xfree);
13904
13905   for (l = loc; l != NULL; l = l->next)
13906     {
13907       const char **slot;
13908       const char *name = l->function_name;
13909
13910       /* Allow for some names to be NULL, ignore them.  */
13911       if (name == NULL)
13912         continue;
13913
13914       slot = (const char **) htab_find_slot (htab, (const void *) name,
13915                                              INSERT);
13916       /* NOTE: We can assume slot != NULL here because xcalloc never
13917          returns NULL.  */
13918       if (*slot != NULL)
13919         {
13920           htab_delete (htab);
13921           return 1;
13922         }
13923       *slot = name;
13924     }
13925
13926   htab_delete (htab);
13927   return 0;
13928 }
13929
13930 /* When symbols change, it probably means the sources changed as well,
13931    and it might mean the static tracepoint markers are no longer at
13932    the same address or line numbers they used to be at last we
13933    checked.  Losing your static tracepoints whenever you rebuild is
13934    undesirable.  This function tries to resync/rematch gdb static
13935    tracepoints with the markers on the target, for static tracepoints
13936    that have not been set by marker id.  Static tracepoint that have
13937    been set by marker id are reset by marker id in breakpoint_re_set.
13938    The heuristic is:
13939
13940    1) For a tracepoint set at a specific address, look for a marker at
13941    the old PC.  If one is found there, assume to be the same marker.
13942    If the name / string id of the marker found is different from the
13943    previous known name, assume that means the user renamed the marker
13944    in the sources, and output a warning.
13945
13946    2) For a tracepoint set at a given line number, look for a marker
13947    at the new address of the old line number.  If one is found there,
13948    assume to be the same marker.  If the name / string id of the
13949    marker found is different from the previous known name, assume that
13950    means the user renamed the marker in the sources, and output a
13951    warning.
13952
13953    3) If a marker is no longer found at the same address or line, it
13954    may mean the marker no longer exists.  But it may also just mean
13955    the code changed a bit.  Maybe the user added a few lines of code
13956    that made the marker move up or down (in line number terms).  Ask
13957    the target for info about the marker with the string id as we knew
13958    it.  If found, update line number and address in the matching
13959    static tracepoint.  This will get confused if there's more than one
13960    marker with the same ID (possible in UST, although unadvised
13961    precisely because it confuses tools).  */
13962
13963 static struct symtab_and_line
13964 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13965 {
13966   struct tracepoint *tp = (struct tracepoint *) b;
13967   struct static_tracepoint_marker marker;
13968   CORE_ADDR pc;
13969
13970   pc = sal.pc;
13971   if (sal.line)
13972     find_line_pc (sal.symtab, sal.line, &pc);
13973
13974   if (target_static_tracepoint_marker_at (pc, &marker))
13975     {
13976       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13977         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13978                  b->number,
13979                  tp->static_trace_marker_id, marker.str_id);
13980
13981       xfree (tp->static_trace_marker_id);
13982       tp->static_trace_marker_id = xstrdup (marker.str_id);
13983       release_static_tracepoint_marker (&marker);
13984
13985       return sal;
13986     }
13987
13988   /* Old marker wasn't found on target at lineno.  Try looking it up
13989      by string ID.  */
13990   if (!sal.explicit_pc
13991       && sal.line != 0
13992       && sal.symtab != NULL
13993       && tp->static_trace_marker_id != NULL)
13994     {
13995       VEC(static_tracepoint_marker_p) *markers;
13996
13997       markers
13998         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13999
14000       if (!VEC_empty(static_tracepoint_marker_p, markers))
14001         {
14002           struct symtab_and_line sal2;
14003           struct symbol *sym;
14004           struct static_tracepoint_marker *tpmarker;
14005           struct ui_out *uiout = current_uiout;
14006           struct explicit_location explicit_loc;
14007
14008           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14009
14010           xfree (tp->static_trace_marker_id);
14011           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14012
14013           warning (_("marker for static tracepoint %d (%s) not "
14014                      "found at previous line number"),
14015                    b->number, tp->static_trace_marker_id);
14016
14017           init_sal (&sal2);
14018
14019           sal2.pc = tpmarker->address;
14020
14021           sal2 = find_pc_line (tpmarker->address, 0);
14022           sym = find_pc_sect_function (tpmarker->address, NULL);
14023           ui_out_text (uiout, "Now in ");
14024           if (sym)
14025             {
14026               ui_out_field_string (uiout, "func",
14027                                    SYMBOL_PRINT_NAME (sym));
14028               ui_out_text (uiout, " at ");
14029             }
14030           ui_out_field_string (uiout, "file",
14031                                symtab_to_filename_for_display (sal2.symtab));
14032           ui_out_text (uiout, ":");
14033
14034           if (ui_out_is_mi_like_p (uiout))
14035             {
14036               const char *fullname = symtab_to_fullname (sal2.symtab);
14037
14038               ui_out_field_string (uiout, "fullname", fullname);
14039             }
14040
14041           ui_out_field_int (uiout, "line", sal2.line);
14042           ui_out_text (uiout, "\n");
14043
14044           b->loc->line_number = sal2.line;
14045           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14046
14047           delete_event_location (b->location);
14048           initialize_explicit_location (&explicit_loc);
14049           explicit_loc.source_filename
14050             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14051           explicit_loc.line_offset.offset = b->loc->line_number;
14052           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14053           b->location = new_explicit_location (&explicit_loc);
14054
14055           /* Might be nice to check if function changed, and warn if
14056              so.  */
14057
14058           release_static_tracepoint_marker (tpmarker);
14059         }
14060     }
14061   return sal;
14062 }
14063
14064 /* Returns 1 iff locations A and B are sufficiently same that
14065    we don't need to report breakpoint as changed.  */
14066
14067 static int
14068 locations_are_equal (struct bp_location *a, struct bp_location *b)
14069 {
14070   while (a && b)
14071     {
14072       if (a->address != b->address)
14073         return 0;
14074
14075       if (a->shlib_disabled != b->shlib_disabled)
14076         return 0;
14077
14078       if (a->enabled != b->enabled)
14079         return 0;
14080
14081       a = a->next;
14082       b = b->next;
14083     }
14084
14085   if ((a == NULL) != (b == NULL))
14086     return 0;
14087
14088   return 1;
14089 }
14090
14091 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14092    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14093    a ranged breakpoint.  */
14094
14095 void
14096 update_breakpoint_locations (struct breakpoint *b,
14097                              struct symtabs_and_lines sals,
14098                              struct symtabs_and_lines sals_end)
14099 {
14100   int i;
14101   struct bp_location *existing_locations = b->loc;
14102
14103   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14104     {
14105       /* Ranged breakpoints have only one start location and one end
14106          location.  */
14107       b->enable_state = bp_disabled;
14108       update_global_location_list (UGLL_MAY_INSERT);
14109       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14110                            "multiple locations found\n"),
14111                          b->number);
14112       return;
14113     }
14114
14115   /* If there's no new locations, and all existing locations are
14116      pending, don't do anything.  This optimizes the common case where
14117      all locations are in the same shared library, that was unloaded.
14118      We'd like to retain the location, so that when the library is
14119      loaded again, we don't loose the enabled/disabled status of the
14120      individual locations.  */
14121   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14122     return;
14123
14124   b->loc = NULL;
14125
14126   for (i = 0; i < sals.nelts; ++i)
14127     {
14128       struct bp_location *new_loc;
14129
14130       switch_to_program_space_and_thread (sals.sals[i].pspace);
14131
14132       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14133
14134       /* Reparse conditions, they might contain references to the
14135          old symtab.  */
14136       if (b->cond_string != NULL)
14137         {
14138           const char *s;
14139
14140           s = b->cond_string;
14141           TRY
14142             {
14143               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14144                                            block_for_pc (sals.sals[i].pc), 
14145                                            0);
14146             }
14147           CATCH (e, RETURN_MASK_ERROR)
14148             {
14149               warning (_("failed to reevaluate condition "
14150                          "for breakpoint %d: %s"), 
14151                        b->number, e.message);
14152               new_loc->enabled = 0;
14153             }
14154           END_CATCH
14155         }
14156
14157       if (sals_end.nelts)
14158         {
14159           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14160
14161           new_loc->length = end - sals.sals[0].pc + 1;
14162         }
14163     }
14164
14165   /* If possible, carry over 'disable' status from existing
14166      breakpoints.  */
14167   {
14168     struct bp_location *e = existing_locations;
14169     /* If there are multiple breakpoints with the same function name,
14170        e.g. for inline functions, comparing function names won't work.
14171        Instead compare pc addresses; this is just a heuristic as things
14172        may have moved, but in practice it gives the correct answer
14173        often enough until a better solution is found.  */
14174     int have_ambiguous_names = ambiguous_names_p (b->loc);
14175
14176     for (; e; e = e->next)
14177       {
14178         if (!e->enabled && e->function_name)
14179           {
14180             struct bp_location *l = b->loc;
14181             if (have_ambiguous_names)
14182               {
14183                 for (; l; l = l->next)
14184                   if (breakpoint_locations_match (e, l))
14185                     {
14186                       l->enabled = 0;
14187                       break;
14188                     }
14189               }
14190             else
14191               {
14192                 for (; l; l = l->next)
14193                   if (l->function_name
14194                       && strcmp (e->function_name, l->function_name) == 0)
14195                     {
14196                       l->enabled = 0;
14197                       break;
14198                     }
14199               }
14200           }
14201       }
14202   }
14203
14204   if (!locations_are_equal (existing_locations, b->loc))
14205     observer_notify_breakpoint_modified (b);
14206
14207   update_global_location_list (UGLL_MAY_INSERT);
14208 }
14209
14210 /* Find the SaL locations corresponding to the given LOCATION.
14211    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14212
14213 static struct symtabs_and_lines
14214 location_to_sals (struct breakpoint *b, struct event_location *location,
14215                   int *found)
14216 {
14217   struct symtabs_and_lines sals = {0};
14218   struct gdb_exception exception = exception_none;
14219
14220   gdb_assert (b->ops != NULL);
14221
14222   TRY
14223     {
14224       b->ops->decode_location (b, location, &sals);
14225     }
14226   CATCH (e, RETURN_MASK_ERROR)
14227     {
14228       int not_found_and_ok = 0;
14229
14230       exception = e;
14231
14232       /* For pending breakpoints, it's expected that parsing will
14233          fail until the right shared library is loaded.  User has
14234          already told to create pending breakpoints and don't need
14235          extra messages.  If breakpoint is in bp_shlib_disabled
14236          state, then user already saw the message about that
14237          breakpoint being disabled, and don't want to see more
14238          errors.  */
14239       if (e.error == NOT_FOUND_ERROR
14240           && (b->condition_not_parsed 
14241               || (b->loc && b->loc->shlib_disabled)
14242               || (b->loc && b->loc->pspace->executing_startup)
14243               || b->enable_state == bp_disabled))
14244         not_found_and_ok = 1;
14245
14246       if (!not_found_and_ok)
14247         {
14248           /* We surely don't want to warn about the same breakpoint
14249              10 times.  One solution, implemented here, is disable
14250              the breakpoint on error.  Another solution would be to
14251              have separate 'warning emitted' flag.  Since this
14252              happens only when a binary has changed, I don't know
14253              which approach is better.  */
14254           b->enable_state = bp_disabled;
14255           throw_exception (e);
14256         }
14257     }
14258   END_CATCH
14259
14260   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14261     {
14262       int i;
14263
14264       for (i = 0; i < sals.nelts; ++i)
14265         resolve_sal_pc (&sals.sals[i]);
14266       if (b->condition_not_parsed && b->extra_string != NULL)
14267         {
14268           char *cond_string, *extra_string;
14269           int thread, task;
14270
14271           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14272                                      &cond_string, &thread, &task,
14273                                      &extra_string);
14274           gdb_assert (b->cond_string == NULL);
14275           if (cond_string)
14276             b->cond_string = cond_string;
14277           b->thread = thread;
14278           b->task = task;
14279           if (extra_string)
14280             {
14281               xfree (b->extra_string);
14282               b->extra_string = extra_string;
14283             }
14284           b->condition_not_parsed = 0;
14285         }
14286
14287       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14288         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14289
14290       *found = 1;
14291     }
14292   else
14293     *found = 0;
14294
14295   return sals;
14296 }
14297
14298 /* The default re_set method, for typical hardware or software
14299    breakpoints.  Reevaluate the breakpoint and recreate its
14300    locations.  */
14301
14302 static void
14303 breakpoint_re_set_default (struct breakpoint *b)
14304 {
14305   int found;
14306   struct symtabs_and_lines sals, sals_end;
14307   struct symtabs_and_lines expanded = {0};
14308   struct symtabs_and_lines expanded_end = {0};
14309
14310   sals = location_to_sals (b, b->location, &found);
14311   if (found)
14312     {
14313       make_cleanup (xfree, sals.sals);
14314       expanded = sals;
14315     }
14316
14317   if (b->location_range_end != NULL)
14318     {
14319       sals_end = location_to_sals (b, b->location_range_end, &found);
14320       if (found)
14321         {
14322           make_cleanup (xfree, sals_end.sals);
14323           expanded_end = sals_end;
14324         }
14325     }
14326
14327   update_breakpoint_locations (b, expanded, expanded_end);
14328 }
14329
14330 /* Default method for creating SALs from an address string.  It basically
14331    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14332
14333 static void
14334 create_sals_from_location_default (const struct event_location *location,
14335                                    struct linespec_result *canonical,
14336                                    enum bptype type_wanted)
14337 {
14338   parse_breakpoint_sals (location, canonical);
14339 }
14340
14341 /* Call create_breakpoints_sal for the given arguments.  This is the default
14342    function for the `create_breakpoints_sal' method of
14343    breakpoint_ops.  */
14344
14345 static void
14346 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14347                                 struct linespec_result *canonical,
14348                                 char *cond_string,
14349                                 char *extra_string,
14350                                 enum bptype type_wanted,
14351                                 enum bpdisp disposition,
14352                                 int thread,
14353                                 int task, int ignore_count,
14354                                 const struct breakpoint_ops *ops,
14355                                 int from_tty, int enabled,
14356                                 int internal, unsigned flags)
14357 {
14358   create_breakpoints_sal (gdbarch, canonical, cond_string,
14359                           extra_string,
14360                           type_wanted, disposition,
14361                           thread, task, ignore_count, ops, from_tty,
14362                           enabled, internal, flags);
14363 }
14364
14365 /* Decode the line represented by S by calling decode_line_full.  This is the
14366    default function for the `decode_location' method of breakpoint_ops.  */
14367
14368 static void
14369 decode_location_default (struct breakpoint *b,
14370                          const struct event_location *location,
14371                          struct symtabs_and_lines *sals)
14372 {
14373   struct linespec_result canonical;
14374
14375   init_linespec_result (&canonical);
14376   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
14377                     (struct symtab *) NULL, 0,
14378                     &canonical, multiple_symbols_all,
14379                     b->filter);
14380
14381   /* We should get 0 or 1 resulting SALs.  */
14382   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14383
14384   if (VEC_length (linespec_sals, canonical.sals) > 0)
14385     {
14386       struct linespec_sals *lsal;
14387
14388       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14389       *sals = lsal->sals;
14390       /* Arrange it so the destructor does not free the
14391          contents.  */
14392       lsal->sals.sals = NULL;
14393     }
14394
14395   destroy_linespec_result (&canonical);
14396 }
14397
14398 /* Prepare the global context for a re-set of breakpoint B.  */
14399
14400 static struct cleanup *
14401 prepare_re_set_context (struct breakpoint *b)
14402 {
14403   struct cleanup *cleanups;
14404
14405   input_radix = b->input_radix;
14406   cleanups = save_current_space_and_thread ();
14407   if (b->pspace != NULL)
14408     switch_to_program_space_and_thread (b->pspace);
14409   set_language (b->language);
14410
14411   return cleanups;
14412 }
14413
14414 /* Reset a breakpoint given it's struct breakpoint * BINT.
14415    The value we return ends up being the return value from catch_errors.
14416    Unused in this case.  */
14417
14418 static int
14419 breakpoint_re_set_one (void *bint)
14420 {
14421   /* Get past catch_errs.  */
14422   struct breakpoint *b = (struct breakpoint *) bint;
14423   struct cleanup *cleanups;
14424
14425   cleanups = prepare_re_set_context (b);
14426   b->ops->re_set (b);
14427   do_cleanups (cleanups);
14428   return 0;
14429 }
14430
14431 /* Re-set all breakpoints after symbols have been re-loaded.  */
14432 void
14433 breakpoint_re_set (void)
14434 {
14435   struct breakpoint *b, *b_tmp;
14436   enum language save_language;
14437   int save_input_radix;
14438   struct cleanup *old_chain;
14439
14440   save_language = current_language->la_language;
14441   save_input_radix = input_radix;
14442   old_chain = save_current_program_space ();
14443
14444   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14445   {
14446     /* Format possible error msg.  */
14447     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14448                                 b->number);
14449     struct cleanup *cleanups = make_cleanup (xfree, message);
14450     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14451     do_cleanups (cleanups);
14452   }
14453   set_language (save_language);
14454   input_radix = save_input_radix;
14455
14456   jit_breakpoint_re_set ();
14457
14458   do_cleanups (old_chain);
14459
14460   create_overlay_event_breakpoint ();
14461   create_longjmp_master_breakpoint ();
14462   create_std_terminate_master_breakpoint ();
14463   create_exception_master_breakpoint ();
14464 }
14465 \f
14466 /* Reset the thread number of this breakpoint:
14467
14468    - If the breakpoint is for all threads, leave it as-is.
14469    - Else, reset it to the current thread for inferior_ptid.  */
14470 void
14471 breakpoint_re_set_thread (struct breakpoint *b)
14472 {
14473   if (b->thread != -1)
14474     {
14475       if (in_thread_list (inferior_ptid))
14476         b->thread = pid_to_thread_id (inferior_ptid);
14477
14478       /* We're being called after following a fork.  The new fork is
14479          selected as current, and unless this was a vfork will have a
14480          different program space from the original thread.  Reset that
14481          as well.  */
14482       b->loc->pspace = current_program_space;
14483     }
14484 }
14485
14486 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14487    If from_tty is nonzero, it prints a message to that effect,
14488    which ends with a period (no newline).  */
14489
14490 void
14491 set_ignore_count (int bptnum, int count, int from_tty)
14492 {
14493   struct breakpoint *b;
14494
14495   if (count < 0)
14496     count = 0;
14497
14498   ALL_BREAKPOINTS (b)
14499     if (b->number == bptnum)
14500     {
14501       if (is_tracepoint (b))
14502         {
14503           if (from_tty && count != 0)
14504             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14505                              bptnum);
14506           return;
14507         }
14508       
14509       b->ignore_count = count;
14510       if (from_tty)
14511         {
14512           if (count == 0)
14513             printf_filtered (_("Will stop next time "
14514                                "breakpoint %d is reached."),
14515                              bptnum);
14516           else if (count == 1)
14517             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14518                              bptnum);
14519           else
14520             printf_filtered (_("Will ignore next %d "
14521                                "crossings of breakpoint %d."),
14522                              count, bptnum);
14523         }
14524       observer_notify_breakpoint_modified (b);
14525       return;
14526     }
14527
14528   error (_("No breakpoint number %d."), bptnum);
14529 }
14530
14531 /* Command to set ignore-count of breakpoint N to COUNT.  */
14532
14533 static void
14534 ignore_command (char *args, int from_tty)
14535 {
14536   char *p = args;
14537   int num;
14538
14539   if (p == 0)
14540     error_no_arg (_("a breakpoint number"));
14541
14542   num = get_number (&p);
14543   if (num == 0)
14544     error (_("bad breakpoint number: '%s'"), args);
14545   if (*p == 0)
14546     error (_("Second argument (specified ignore-count) is missing."));
14547
14548   set_ignore_count (num,
14549                     longest_to_int (value_as_long (parse_and_eval (p))),
14550                     from_tty);
14551   if (from_tty)
14552     printf_filtered ("\n");
14553 }
14554 \f
14555 /* Call FUNCTION on each of the breakpoints
14556    whose numbers are given in ARGS.  */
14557
14558 static void
14559 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14560                                                       void *),
14561                         void *data)
14562 {
14563   int num;
14564   struct breakpoint *b, *tmp;
14565   int match;
14566   struct get_number_or_range_state state;
14567
14568   if (args == 0 || *args == '\0')
14569     error_no_arg (_("one or more breakpoint numbers"));
14570
14571   init_number_or_range (&state, args);
14572
14573   while (!state.finished)
14574     {
14575       const char *p = state.string;
14576
14577       match = 0;
14578
14579       num = get_number_or_range (&state);
14580       if (num == 0)
14581         {
14582           warning (_("bad breakpoint number at or near '%s'"), p);
14583         }
14584       else
14585         {
14586           ALL_BREAKPOINTS_SAFE (b, tmp)
14587             if (b->number == num)
14588               {
14589                 match = 1;
14590                 function (b, data);
14591                 break;
14592               }
14593           if (match == 0)
14594             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14595         }
14596     }
14597 }
14598
14599 static struct bp_location *
14600 find_location_by_number (char *number)
14601 {
14602   char *dot = strchr (number, '.');
14603   char *p1;
14604   int bp_num;
14605   int loc_num;
14606   struct breakpoint *b;
14607   struct bp_location *loc;  
14608
14609   *dot = '\0';
14610
14611   p1 = number;
14612   bp_num = get_number (&p1);
14613   if (bp_num == 0)
14614     error (_("Bad breakpoint number '%s'"), number);
14615
14616   ALL_BREAKPOINTS (b)
14617     if (b->number == bp_num)
14618       {
14619         break;
14620       }
14621
14622   if (!b || b->number != bp_num)
14623     error (_("Bad breakpoint number '%s'"), number);
14624   
14625   p1 = dot+1;
14626   loc_num = get_number (&p1);
14627   if (loc_num == 0)
14628     error (_("Bad breakpoint location number '%s'"), number);
14629
14630   --loc_num;
14631   loc = b->loc;
14632   for (;loc_num && loc; --loc_num, loc = loc->next)
14633     ;
14634   if (!loc)
14635     error (_("Bad breakpoint location number '%s'"), dot+1);
14636     
14637   return loc;  
14638 }
14639
14640
14641 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14642    If from_tty is nonzero, it prints a message to that effect,
14643    which ends with a period (no newline).  */
14644
14645 void
14646 disable_breakpoint (struct breakpoint *bpt)
14647 {
14648   /* Never disable a watchpoint scope breakpoint; we want to
14649      hit them when we leave scope so we can delete both the
14650      watchpoint and its scope breakpoint at that time.  */
14651   if (bpt->type == bp_watchpoint_scope)
14652     return;
14653
14654   bpt->enable_state = bp_disabled;
14655
14656   /* Mark breakpoint locations modified.  */
14657   mark_breakpoint_modified (bpt);
14658
14659   if (target_supports_enable_disable_tracepoint ()
14660       && current_trace_status ()->running && is_tracepoint (bpt))
14661     {
14662       struct bp_location *location;
14663      
14664       for (location = bpt->loc; location; location = location->next)
14665         target_disable_tracepoint (location);
14666     }
14667
14668   update_global_location_list (UGLL_DONT_INSERT);
14669
14670   observer_notify_breakpoint_modified (bpt);
14671 }
14672
14673 /* A callback for iterate_over_related_breakpoints.  */
14674
14675 static void
14676 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14677 {
14678   disable_breakpoint (b);
14679 }
14680
14681 /* A callback for map_breakpoint_numbers that calls
14682    disable_breakpoint.  */
14683
14684 static void
14685 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14686 {
14687   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14688 }
14689
14690 static void
14691 disable_command (char *args, int from_tty)
14692 {
14693   if (args == 0)
14694     {
14695       struct breakpoint *bpt;
14696
14697       ALL_BREAKPOINTS (bpt)
14698         if (user_breakpoint_p (bpt))
14699           disable_breakpoint (bpt);
14700     }
14701   else
14702     {
14703       char *num = extract_arg (&args);
14704
14705       while (num)
14706         {
14707           if (strchr (num, '.'))
14708             {
14709               struct bp_location *loc = find_location_by_number (num);
14710
14711               if (loc)
14712                 {
14713                   if (loc->enabled)
14714                     {
14715                       loc->enabled = 0;
14716                       mark_breakpoint_location_modified (loc);
14717                     }
14718                   if (target_supports_enable_disable_tracepoint ()
14719                       && current_trace_status ()->running && loc->owner
14720                       && is_tracepoint (loc->owner))
14721                     target_disable_tracepoint (loc);
14722                 }
14723               update_global_location_list (UGLL_DONT_INSERT);
14724             }
14725           else
14726             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14727           num = extract_arg (&args);
14728         }
14729     }
14730 }
14731
14732 static void
14733 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14734                         int count)
14735 {
14736   int target_resources_ok;
14737
14738   if (bpt->type == bp_hardware_breakpoint)
14739     {
14740       int i;
14741       i = hw_breakpoint_used_count ();
14742       target_resources_ok = 
14743         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14744                                             i + 1, 0);
14745       if (target_resources_ok == 0)
14746         error (_("No hardware breakpoint support in the target."));
14747       else if (target_resources_ok < 0)
14748         error (_("Hardware breakpoints used exceeds limit."));
14749     }
14750
14751   if (is_watchpoint (bpt))
14752     {
14753       /* Initialize it just to avoid a GCC false warning.  */
14754       enum enable_state orig_enable_state = bp_disabled;
14755
14756       TRY
14757         {
14758           struct watchpoint *w = (struct watchpoint *) bpt;
14759
14760           orig_enable_state = bpt->enable_state;
14761           bpt->enable_state = bp_enabled;
14762           update_watchpoint (w, 1 /* reparse */);
14763         }
14764       CATCH (e, RETURN_MASK_ALL)
14765         {
14766           bpt->enable_state = orig_enable_state;
14767           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14768                              bpt->number);
14769           return;
14770         }
14771       END_CATCH
14772     }
14773
14774   bpt->enable_state = bp_enabled;
14775
14776   /* Mark breakpoint locations modified.  */
14777   mark_breakpoint_modified (bpt);
14778
14779   if (target_supports_enable_disable_tracepoint ()
14780       && current_trace_status ()->running && is_tracepoint (bpt))
14781     {
14782       struct bp_location *location;
14783
14784       for (location = bpt->loc; location; location = location->next)
14785         target_enable_tracepoint (location);
14786     }
14787
14788   bpt->disposition = disposition;
14789   bpt->enable_count = count;
14790   update_global_location_list (UGLL_MAY_INSERT);
14791
14792   observer_notify_breakpoint_modified (bpt);
14793 }
14794
14795
14796 void
14797 enable_breakpoint (struct breakpoint *bpt)
14798 {
14799   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14800 }
14801
14802 static void
14803 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14804 {
14805   enable_breakpoint (bpt);
14806 }
14807
14808 /* A callback for map_breakpoint_numbers that calls
14809    enable_breakpoint.  */
14810
14811 static void
14812 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14813 {
14814   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14815 }
14816
14817 /* The enable command enables the specified breakpoints (or all defined
14818    breakpoints) so they once again become (or continue to be) effective
14819    in stopping the inferior.  */
14820
14821 static void
14822 enable_command (char *args, int from_tty)
14823 {
14824   if (args == 0)
14825     {
14826       struct breakpoint *bpt;
14827
14828       ALL_BREAKPOINTS (bpt)
14829         if (user_breakpoint_p (bpt))
14830           enable_breakpoint (bpt);
14831     }
14832   else
14833     {
14834       char *num = extract_arg (&args);
14835
14836       while (num)
14837         {
14838           if (strchr (num, '.'))
14839             {
14840               struct bp_location *loc = find_location_by_number (num);
14841
14842               if (loc)
14843                 {
14844                   if (!loc->enabled)
14845                     {
14846                       loc->enabled = 1;
14847                       mark_breakpoint_location_modified (loc);
14848                     }
14849                   if (target_supports_enable_disable_tracepoint ()
14850                       && current_trace_status ()->running && loc->owner
14851                       && is_tracepoint (loc->owner))
14852                     target_enable_tracepoint (loc);
14853                 }
14854               update_global_location_list (UGLL_MAY_INSERT);
14855             }
14856           else
14857             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14858           num = extract_arg (&args);
14859         }
14860     }
14861 }
14862
14863 /* This struct packages up disposition data for application to multiple
14864    breakpoints.  */
14865
14866 struct disp_data
14867 {
14868   enum bpdisp disp;
14869   int count;
14870 };
14871
14872 static void
14873 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14874 {
14875   struct disp_data disp_data = *(struct disp_data *) arg;
14876
14877   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14878 }
14879
14880 static void
14881 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14882 {
14883   struct disp_data disp = { disp_disable, 1 };
14884
14885   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14886 }
14887
14888 static void
14889 enable_once_command (char *args, int from_tty)
14890 {
14891   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14892 }
14893
14894 static void
14895 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14896 {
14897   struct disp_data disp = { disp_disable, *(int *) countptr };
14898
14899   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14900 }
14901
14902 static void
14903 enable_count_command (char *args, int from_tty)
14904 {
14905   int count;
14906
14907   if (args == NULL)
14908     error_no_arg (_("hit count"));
14909
14910   count = get_number (&args);
14911
14912   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14913 }
14914
14915 static void
14916 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14917 {
14918   struct disp_data disp = { disp_del, 1 };
14919
14920   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14921 }
14922
14923 static void
14924 enable_delete_command (char *args, int from_tty)
14925 {
14926   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14927 }
14928 \f
14929 static void
14930 set_breakpoint_cmd (char *args, int from_tty)
14931 {
14932 }
14933
14934 static void
14935 show_breakpoint_cmd (char *args, int from_tty)
14936 {
14937 }
14938
14939 /* Invalidate last known value of any hardware watchpoint if
14940    the memory which that value represents has been written to by
14941    GDB itself.  */
14942
14943 static void
14944 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14945                                       CORE_ADDR addr, ssize_t len,
14946                                       const bfd_byte *data)
14947 {
14948   struct breakpoint *bp;
14949
14950   ALL_BREAKPOINTS (bp)
14951     if (bp->enable_state == bp_enabled
14952         && bp->type == bp_hardware_watchpoint)
14953       {
14954         struct watchpoint *wp = (struct watchpoint *) bp;
14955
14956         if (wp->val_valid && wp->val)
14957           {
14958             struct bp_location *loc;
14959
14960             for (loc = bp->loc; loc != NULL; loc = loc->next)
14961               if (loc->loc_type == bp_loc_hardware_watchpoint
14962                   && loc->address + loc->length > addr
14963                   && addr + len > loc->address)
14964                 {
14965                   value_free (wp->val);
14966                   wp->val = NULL;
14967                   wp->val_valid = 0;
14968                 }
14969           }
14970       }
14971 }
14972
14973 /* Create and insert a breakpoint for software single step.  */
14974
14975 void
14976 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14977                                struct address_space *aspace, 
14978                                CORE_ADDR next_pc)
14979 {
14980   struct thread_info *tp = inferior_thread ();
14981   struct symtab_and_line sal;
14982   CORE_ADDR pc = next_pc;
14983
14984   if (tp->control.single_step_breakpoints == NULL)
14985     {
14986       tp->control.single_step_breakpoints
14987         = new_single_step_breakpoint (tp->num, gdbarch);
14988     }
14989
14990   sal = find_pc_line (pc, 0);
14991   sal.pc = pc;
14992   sal.section = find_pc_overlay (pc);
14993   sal.explicit_pc = 1;
14994   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14995
14996   update_global_location_list (UGLL_INSERT);
14997 }
14998
14999 /* See breakpoint.h.  */
15000
15001 int
15002 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15003                                        struct address_space *aspace,
15004                                        CORE_ADDR pc)
15005 {
15006   struct bp_location *loc;
15007
15008   for (loc = bp->loc; loc != NULL; loc = loc->next)
15009     if (loc->inserted
15010         && breakpoint_location_address_match (loc, aspace, pc))
15011       return 1;
15012
15013   return 0;
15014 }
15015
15016 /* Check whether a software single-step breakpoint is inserted at
15017    PC.  */
15018
15019 int
15020 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15021                                         CORE_ADDR pc)
15022 {
15023   struct breakpoint *bpt;
15024
15025   ALL_BREAKPOINTS (bpt)
15026     {
15027       if (bpt->type == bp_single_step
15028           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15029         return 1;
15030     }
15031   return 0;
15032 }
15033
15034 /* Tracepoint-specific operations.  */
15035
15036 /* Set tracepoint count to NUM.  */
15037 static void
15038 set_tracepoint_count (int num)
15039 {
15040   tracepoint_count = num;
15041   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15042 }
15043
15044 static void
15045 trace_command (char *arg, int from_tty)
15046 {
15047   struct breakpoint_ops *ops;
15048   struct event_location *location;
15049   struct cleanup *back_to;
15050
15051   location = string_to_event_location (&arg, current_language);
15052   back_to = make_cleanup_delete_event_location (location);
15053   if (location != NULL
15054       && event_location_type (location) == PROBE_LOCATION)
15055     ops = &tracepoint_probe_breakpoint_ops;
15056   else
15057     ops = &tracepoint_breakpoint_ops;
15058
15059   create_breakpoint (get_current_arch (),
15060                      location,
15061                      NULL, 0, arg, 1 /* parse arg */,
15062                      0 /* tempflag */,
15063                      bp_tracepoint /* type_wanted */,
15064                      0 /* Ignore count */,
15065                      pending_break_support,
15066                      ops,
15067                      from_tty,
15068                      1 /* enabled */,
15069                      0 /* internal */, 0);
15070   do_cleanups (back_to);
15071 }
15072
15073 static void
15074 ftrace_command (char *arg, int from_tty)
15075 {
15076   struct event_location *location;
15077   struct cleanup *back_to;
15078
15079   location = string_to_event_location (&arg, current_language);
15080   back_to = make_cleanup_delete_event_location (location);
15081   create_breakpoint (get_current_arch (),
15082                      location,
15083                      NULL, 0, arg, 1 /* parse arg */,
15084                      0 /* tempflag */,
15085                      bp_fast_tracepoint /* type_wanted */,
15086                      0 /* Ignore count */,
15087                      pending_break_support,
15088                      &tracepoint_breakpoint_ops,
15089                      from_tty,
15090                      1 /* enabled */,
15091                      0 /* internal */, 0);
15092   do_cleanups (back_to);
15093 }
15094
15095 /* strace command implementation.  Creates a static tracepoint.  */
15096
15097 static void
15098 strace_command (char *arg, int from_tty)
15099 {
15100   struct breakpoint_ops *ops;
15101   struct event_location *location;
15102   struct cleanup *back_to;
15103
15104   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15105      or with a normal static tracepoint.  */
15106   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15107     {
15108       ops = &strace_marker_breakpoint_ops;
15109       location = new_linespec_location (&arg);
15110     }
15111   else
15112     {
15113       ops = &tracepoint_breakpoint_ops;
15114       location = string_to_event_location (&arg, current_language);
15115     }
15116
15117   back_to = make_cleanup_delete_event_location (location);
15118   create_breakpoint (get_current_arch (),
15119                      location,
15120                      NULL, 0, arg, 1 /* parse arg */,
15121                      0 /* tempflag */,
15122                      bp_static_tracepoint /* type_wanted */,
15123                      0 /* Ignore count */,
15124                      pending_break_support,
15125                      ops,
15126                      from_tty,
15127                      1 /* enabled */,
15128                      0 /* internal */, 0);
15129   do_cleanups (back_to);
15130 }
15131
15132 /* Set up a fake reader function that gets command lines from a linked
15133    list that was acquired during tracepoint uploading.  */
15134
15135 static struct uploaded_tp *this_utp;
15136 static int next_cmd;
15137
15138 static char *
15139 read_uploaded_action (void)
15140 {
15141   char *rslt;
15142
15143   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15144
15145   next_cmd++;
15146
15147   return rslt;
15148 }
15149
15150 /* Given information about a tracepoint as recorded on a target (which
15151    can be either a live system or a trace file), attempt to create an
15152    equivalent GDB tracepoint.  This is not a reliable process, since
15153    the target does not necessarily have all the information used when
15154    the tracepoint was originally defined.  */
15155   
15156 struct tracepoint *
15157 create_tracepoint_from_upload (struct uploaded_tp *utp)
15158 {
15159   char *addr_str, small_buf[100];
15160   struct tracepoint *tp;
15161   struct event_location *location;
15162   struct cleanup *cleanup;
15163
15164   if (utp->at_string)
15165     addr_str = utp->at_string;
15166   else
15167     {
15168       /* In the absence of a source location, fall back to raw
15169          address.  Since there is no way to confirm that the address
15170          means the same thing as when the trace was started, warn the
15171          user.  */
15172       warning (_("Uploaded tracepoint %d has no "
15173                  "source location, using raw address"),
15174                utp->number);
15175       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15176       addr_str = small_buf;
15177     }
15178
15179   /* There's not much we can do with a sequence of bytecodes.  */
15180   if (utp->cond && !utp->cond_string)
15181     warning (_("Uploaded tracepoint %d condition "
15182                "has no source form, ignoring it"),
15183              utp->number);
15184
15185   location = string_to_event_location (&addr_str, current_language);
15186   cleanup = make_cleanup_delete_event_location (location);
15187   if (!create_breakpoint (get_current_arch (),
15188                           location,
15189                           utp->cond_string, -1, addr_str,
15190                           0 /* parse cond/thread */,
15191                           0 /* tempflag */,
15192                           utp->type /* type_wanted */,
15193                           0 /* Ignore count */,
15194                           pending_break_support,
15195                           &tracepoint_breakpoint_ops,
15196                           0 /* from_tty */,
15197                           utp->enabled /* enabled */,
15198                           0 /* internal */,
15199                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15200     {
15201       do_cleanups (cleanup);
15202       return NULL;
15203     }
15204
15205   do_cleanups (cleanup);
15206
15207   /* Get the tracepoint we just created.  */
15208   tp = get_tracepoint (tracepoint_count);
15209   gdb_assert (tp != NULL);
15210
15211   if (utp->pass > 0)
15212     {
15213       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15214                  tp->base.number);
15215
15216       trace_pass_command (small_buf, 0);
15217     }
15218
15219   /* If we have uploaded versions of the original commands, set up a
15220      special-purpose "reader" function and call the usual command line
15221      reader, then pass the result to the breakpoint command-setting
15222      function.  */
15223   if (!VEC_empty (char_ptr, utp->cmd_strings))
15224     {
15225       struct command_line *cmd_list;
15226
15227       this_utp = utp;
15228       next_cmd = 0;
15229
15230       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15231
15232       breakpoint_set_commands (&tp->base, cmd_list);
15233     }
15234   else if (!VEC_empty (char_ptr, utp->actions)
15235            || !VEC_empty (char_ptr, utp->step_actions))
15236     warning (_("Uploaded tracepoint %d actions "
15237                "have no source form, ignoring them"),
15238              utp->number);
15239
15240   /* Copy any status information that might be available.  */
15241   tp->base.hit_count = utp->hit_count;
15242   tp->traceframe_usage = utp->traceframe_usage;
15243
15244   return tp;
15245 }
15246   
15247 /* Print information on tracepoint number TPNUM_EXP, or all if
15248    omitted.  */
15249
15250 static void
15251 tracepoints_info (char *args, int from_tty)
15252 {
15253   struct ui_out *uiout = current_uiout;
15254   int num_printed;
15255
15256   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15257
15258   if (num_printed == 0)
15259     {
15260       if (args == NULL || *args == '\0')
15261         ui_out_message (uiout, 0, "No tracepoints.\n");
15262       else
15263         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15264     }
15265
15266   default_collect_info ();
15267 }
15268
15269 /* The 'enable trace' command enables tracepoints.
15270    Not supported by all targets.  */
15271 static void
15272 enable_trace_command (char *args, int from_tty)
15273 {
15274   enable_command (args, from_tty);
15275 }
15276
15277 /* The 'disable trace' command disables tracepoints.
15278    Not supported by all targets.  */
15279 static void
15280 disable_trace_command (char *args, int from_tty)
15281 {
15282   disable_command (args, from_tty);
15283 }
15284
15285 /* Remove a tracepoint (or all if no argument).  */
15286 static void
15287 delete_trace_command (char *arg, int from_tty)
15288 {
15289   struct breakpoint *b, *b_tmp;
15290
15291   dont_repeat ();
15292
15293   if (arg == 0)
15294     {
15295       int breaks_to_delete = 0;
15296
15297       /* Delete all breakpoints if no argument.
15298          Do not delete internal or call-dummy breakpoints, these
15299          have to be deleted with an explicit breakpoint number 
15300          argument.  */
15301       ALL_TRACEPOINTS (b)
15302         if (is_tracepoint (b) && user_breakpoint_p (b))
15303           {
15304             breaks_to_delete = 1;
15305             break;
15306           }
15307
15308       /* Ask user only if there are some breakpoints to delete.  */
15309       if (!from_tty
15310           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15311         {
15312           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15313             if (is_tracepoint (b) && user_breakpoint_p (b))
15314               delete_breakpoint (b);
15315         }
15316     }
15317   else
15318     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15319 }
15320
15321 /* Helper function for trace_pass_command.  */
15322
15323 static void
15324 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15325 {
15326   tp->pass_count = count;
15327   observer_notify_breakpoint_modified (&tp->base);
15328   if (from_tty)
15329     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15330                      tp->base.number, count);
15331 }
15332
15333 /* Set passcount for tracepoint.
15334
15335    First command argument is passcount, second is tracepoint number.
15336    If tracepoint number omitted, apply to most recently defined.
15337    Also accepts special argument "all".  */
15338
15339 static void
15340 trace_pass_command (char *args, int from_tty)
15341 {
15342   struct tracepoint *t1;
15343   unsigned int count;
15344
15345   if (args == 0 || *args == 0)
15346     error (_("passcount command requires an "
15347              "argument (count + optional TP num)"));
15348
15349   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15350
15351   args = skip_spaces (args);
15352   if (*args && strncasecmp (args, "all", 3) == 0)
15353     {
15354       struct breakpoint *b;
15355
15356       args += 3;                        /* Skip special argument "all".  */
15357       if (*args)
15358         error (_("Junk at end of arguments."));
15359
15360       ALL_TRACEPOINTS (b)
15361       {
15362         t1 = (struct tracepoint *) b;
15363         trace_pass_set_count (t1, count, from_tty);
15364       }
15365     }
15366   else if (*args == '\0')
15367     {
15368       t1 = get_tracepoint_by_number (&args, NULL);
15369       if (t1)
15370         trace_pass_set_count (t1, count, from_tty);
15371     }
15372   else
15373     {
15374       struct get_number_or_range_state state;
15375
15376       init_number_or_range (&state, args);
15377       while (!state.finished)
15378         {
15379           t1 = get_tracepoint_by_number (&args, &state);
15380           if (t1)
15381             trace_pass_set_count (t1, count, from_tty);
15382         }
15383     }
15384 }
15385
15386 struct tracepoint *
15387 get_tracepoint (int num)
15388 {
15389   struct breakpoint *t;
15390
15391   ALL_TRACEPOINTS (t)
15392     if (t->number == num)
15393       return (struct tracepoint *) t;
15394
15395   return NULL;
15396 }
15397
15398 /* Find the tracepoint with the given target-side number (which may be
15399    different from the tracepoint number after disconnecting and
15400    reconnecting).  */
15401
15402 struct tracepoint *
15403 get_tracepoint_by_number_on_target (int num)
15404 {
15405   struct breakpoint *b;
15406
15407   ALL_TRACEPOINTS (b)
15408     {
15409       struct tracepoint *t = (struct tracepoint *) b;
15410
15411       if (t->number_on_target == num)
15412         return t;
15413     }
15414
15415   return NULL;
15416 }
15417
15418 /* Utility: parse a tracepoint number and look it up in the list.
15419    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15420    If the argument is missing, the most recent tracepoint
15421    (tracepoint_count) is returned.  */
15422
15423 struct tracepoint *
15424 get_tracepoint_by_number (char **arg,
15425                           struct get_number_or_range_state *state)
15426 {
15427   struct breakpoint *t;
15428   int tpnum;
15429   char *instring = arg == NULL ? NULL : *arg;
15430
15431   if (state)
15432     {
15433       gdb_assert (!state->finished);
15434       tpnum = get_number_or_range (state);
15435     }
15436   else if (arg == NULL || *arg == NULL || ! **arg)
15437     tpnum = tracepoint_count;
15438   else
15439     tpnum = get_number (arg);
15440
15441   if (tpnum <= 0)
15442     {
15443       if (instring && *instring)
15444         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15445                          instring);
15446       else
15447         printf_filtered (_("No previous tracepoint\n"));
15448       return NULL;
15449     }
15450
15451   ALL_TRACEPOINTS (t)
15452     if (t->number == tpnum)
15453     {
15454       return (struct tracepoint *) t;
15455     }
15456
15457   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15458   return NULL;
15459 }
15460
15461 void
15462 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15463 {
15464   if (b->thread != -1)
15465     fprintf_unfiltered (fp, " thread %d", b->thread);
15466
15467   if (b->task != 0)
15468     fprintf_unfiltered (fp, " task %d", b->task);
15469
15470   fprintf_unfiltered (fp, "\n");
15471 }
15472
15473 /* Save information on user settable breakpoints (watchpoints, etc) to
15474    a new script file named FILENAME.  If FILTER is non-NULL, call it
15475    on each breakpoint and only include the ones for which it returns
15476    non-zero.  */
15477
15478 static void
15479 save_breakpoints (char *filename, int from_tty,
15480                   int (*filter) (const struct breakpoint *))
15481 {
15482   struct breakpoint *tp;
15483   int any = 0;
15484   struct cleanup *cleanup;
15485   struct ui_file *fp;
15486   int extra_trace_bits = 0;
15487
15488   if (filename == 0 || *filename == 0)
15489     error (_("Argument required (file name in which to save)"));
15490
15491   /* See if we have anything to save.  */
15492   ALL_BREAKPOINTS (tp)
15493   {
15494     /* Skip internal and momentary breakpoints.  */
15495     if (!user_breakpoint_p (tp))
15496       continue;
15497
15498     /* If we have a filter, only save the breakpoints it accepts.  */
15499     if (filter && !filter (tp))
15500       continue;
15501
15502     any = 1;
15503
15504     if (is_tracepoint (tp))
15505       {
15506         extra_trace_bits = 1;
15507
15508         /* We can stop searching.  */
15509         break;
15510       }
15511   }
15512
15513   if (!any)
15514     {
15515       warning (_("Nothing to save."));
15516       return;
15517     }
15518
15519   filename = tilde_expand (filename);
15520   cleanup = make_cleanup (xfree, filename);
15521   fp = gdb_fopen (filename, "w");
15522   if (!fp)
15523     error (_("Unable to open file '%s' for saving (%s)"),
15524            filename, safe_strerror (errno));
15525   make_cleanup_ui_file_delete (fp);
15526
15527   if (extra_trace_bits)
15528     save_trace_state_variables (fp);
15529
15530   ALL_BREAKPOINTS (tp)
15531   {
15532     /* Skip internal and momentary breakpoints.  */
15533     if (!user_breakpoint_p (tp))
15534       continue;
15535
15536     /* If we have a filter, only save the breakpoints it accepts.  */
15537     if (filter && !filter (tp))
15538       continue;
15539
15540     tp->ops->print_recreate (tp, fp);
15541
15542     /* Note, we can't rely on tp->number for anything, as we can't
15543        assume the recreated breakpoint numbers will match.  Use $bpnum
15544        instead.  */
15545
15546     if (tp->cond_string)
15547       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15548
15549     if (tp->ignore_count)
15550       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15551
15552     if (tp->type != bp_dprintf && tp->commands)
15553       {
15554         struct gdb_exception exception;
15555
15556         fprintf_unfiltered (fp, "  commands\n");
15557         
15558         ui_out_redirect (current_uiout, fp);
15559         TRY
15560           {
15561             print_command_lines (current_uiout, tp->commands->commands, 2);
15562           }
15563         CATCH (ex, RETURN_MASK_ALL)
15564           {
15565             ui_out_redirect (current_uiout, NULL);
15566             throw_exception (ex);
15567           }
15568         END_CATCH
15569
15570         ui_out_redirect (current_uiout, NULL);
15571         fprintf_unfiltered (fp, "  end\n");
15572       }
15573
15574     if (tp->enable_state == bp_disabled)
15575       fprintf_unfiltered (fp, "disable $bpnum\n");
15576
15577     /* If this is a multi-location breakpoint, check if the locations
15578        should be individually disabled.  Watchpoint locations are
15579        special, and not user visible.  */
15580     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15581       {
15582         struct bp_location *loc;
15583         int n = 1;
15584
15585         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15586           if (!loc->enabled)
15587             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15588       }
15589   }
15590
15591   if (extra_trace_bits && *default_collect)
15592     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15593
15594   if (from_tty)
15595     printf_filtered (_("Saved to file '%s'.\n"), filename);
15596   do_cleanups (cleanup);
15597 }
15598
15599 /* The `save breakpoints' command.  */
15600
15601 static void
15602 save_breakpoints_command (char *args, int from_tty)
15603 {
15604   save_breakpoints (args, from_tty, NULL);
15605 }
15606
15607 /* The `save tracepoints' command.  */
15608
15609 static void
15610 save_tracepoints_command (char *args, int from_tty)
15611 {
15612   save_breakpoints (args, from_tty, is_tracepoint);
15613 }
15614
15615 /* Create a vector of all tracepoints.  */
15616
15617 VEC(breakpoint_p) *
15618 all_tracepoints (void)
15619 {
15620   VEC(breakpoint_p) *tp_vec = 0;
15621   struct breakpoint *tp;
15622
15623   ALL_TRACEPOINTS (tp)
15624   {
15625     VEC_safe_push (breakpoint_p, tp_vec, tp);
15626   }
15627
15628   return tp_vec;
15629 }
15630
15631 \f
15632 /* This help string is used to consolidate all the help string for specifying
15633    locations used by several commands.  */
15634
15635 #define LOCATION_HELP_STRING \
15636 "Linespecs are colon-separated lists of location parameters, such as\n\
15637 source filename, function name, label name, and line number.\n\
15638 Example: To specify the start of a label named \"the_top\" in the\n\
15639 function \"fact\" in the file \"factorial.c\", use\n\
15640 \"factorial.c:fact:the_top\".\n\
15641 \n\
15642 Address locations begin with \"*\" and specify an exact address in the\n\
15643 program.  Example: To specify the fourth byte past the start function\n\
15644 \"main\", use \"*main + 4\".\n\
15645 \n\
15646 Explicit locations are similar to linespecs but use an option/argument\n\
15647 syntax to specify location parameters.\n\
15648 Example: To specify the start of the label named \"the_top\" in the\n\
15649 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15650 -function fact -label the_top\".\n"
15651
15652 /* This help string is used for the break, hbreak, tbreak and thbreak
15653    commands.  It is defined as a macro to prevent duplication.
15654    COMMAND should be a string constant containing the name of the
15655    command.  */
15656
15657 #define BREAK_ARGS_HELP(command) \
15658 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15659 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15660 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15661 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15662 `-probe-dtrace' (for a DTrace probe).\n\
15663 LOCATION may be a linespec, address, or explicit location as described\n\
15664 below.\n\
15665 \n\
15666 With no LOCATION, uses current execution address of the selected\n\
15667 stack frame.  This is useful for breaking on return to a stack frame.\n\
15668 \n\
15669 THREADNUM is the number from \"info threads\".\n\
15670 CONDITION is a boolean expression.\n\
15671 \n" LOCATION_HELP_STRING "\n\
15672 Multiple breakpoints at one place are permitted, and useful if their\n\
15673 conditions are different.\n\
15674 \n\
15675 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15676
15677 /* List of subcommands for "catch".  */
15678 static struct cmd_list_element *catch_cmdlist;
15679
15680 /* List of subcommands for "tcatch".  */
15681 static struct cmd_list_element *tcatch_cmdlist;
15682
15683 void
15684 add_catch_command (char *name, char *docstring,
15685                    cmd_sfunc_ftype *sfunc,
15686                    completer_ftype *completer,
15687                    void *user_data_catch,
15688                    void *user_data_tcatch)
15689 {
15690   struct cmd_list_element *command;
15691
15692   command = add_cmd (name, class_breakpoint, NULL, docstring,
15693                      &catch_cmdlist);
15694   set_cmd_sfunc (command, sfunc);
15695   set_cmd_context (command, user_data_catch);
15696   set_cmd_completer (command, completer);
15697
15698   command = add_cmd (name, class_breakpoint, NULL, docstring,
15699                      &tcatch_cmdlist);
15700   set_cmd_sfunc (command, sfunc);
15701   set_cmd_context (command, user_data_tcatch);
15702   set_cmd_completer (command, completer);
15703 }
15704
15705 static void
15706 save_command (char *arg, int from_tty)
15707 {
15708   printf_unfiltered (_("\"save\" must be followed by "
15709                        "the name of a save subcommand.\n"));
15710   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15711 }
15712
15713 struct breakpoint *
15714 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15715                           void *data)
15716 {
15717   struct breakpoint *b, *b_tmp;
15718
15719   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15720     {
15721       if ((*callback) (b, data))
15722         return b;
15723     }
15724
15725   return NULL;
15726 }
15727
15728 /* Zero if any of the breakpoint's locations could be a location where
15729    functions have been inlined, nonzero otherwise.  */
15730
15731 static int
15732 is_non_inline_function (struct breakpoint *b)
15733 {
15734   /* The shared library event breakpoint is set on the address of a
15735      non-inline function.  */
15736   if (b->type == bp_shlib_event)
15737     return 1;
15738
15739   return 0;
15740 }
15741
15742 /* Nonzero if the specified PC cannot be a location where functions
15743    have been inlined.  */
15744
15745 int
15746 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15747                            const struct target_waitstatus *ws)
15748 {
15749   struct breakpoint *b;
15750   struct bp_location *bl;
15751
15752   ALL_BREAKPOINTS (b)
15753     {
15754       if (!is_non_inline_function (b))
15755         continue;
15756
15757       for (bl = b->loc; bl != NULL; bl = bl->next)
15758         {
15759           if (!bl->shlib_disabled
15760               && bpstat_check_location (bl, aspace, pc, ws))
15761             return 1;
15762         }
15763     }
15764
15765   return 0;
15766 }
15767
15768 /* Remove any references to OBJFILE which is going to be freed.  */
15769
15770 void
15771 breakpoint_free_objfile (struct objfile *objfile)
15772 {
15773   struct bp_location **locp, *loc;
15774
15775   ALL_BP_LOCATIONS (loc, locp)
15776     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15777       loc->symtab = NULL;
15778 }
15779
15780 void
15781 initialize_breakpoint_ops (void)
15782 {
15783   static int initialized = 0;
15784
15785   struct breakpoint_ops *ops;
15786
15787   if (initialized)
15788     return;
15789   initialized = 1;
15790
15791   /* The breakpoint_ops structure to be inherit by all kinds of
15792      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15793      internal and momentary breakpoints, etc.).  */
15794   ops = &bkpt_base_breakpoint_ops;
15795   *ops = base_breakpoint_ops;
15796   ops->re_set = bkpt_re_set;
15797   ops->insert_location = bkpt_insert_location;
15798   ops->remove_location = bkpt_remove_location;
15799   ops->breakpoint_hit = bkpt_breakpoint_hit;
15800   ops->create_sals_from_location = bkpt_create_sals_from_location;
15801   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15802   ops->decode_location = bkpt_decode_location;
15803
15804   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15805   ops = &bkpt_breakpoint_ops;
15806   *ops = bkpt_base_breakpoint_ops;
15807   ops->re_set = bkpt_re_set;
15808   ops->resources_needed = bkpt_resources_needed;
15809   ops->print_it = bkpt_print_it;
15810   ops->print_mention = bkpt_print_mention;
15811   ops->print_recreate = bkpt_print_recreate;
15812
15813   /* Ranged breakpoints.  */
15814   ops = &ranged_breakpoint_ops;
15815   *ops = bkpt_breakpoint_ops;
15816   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15817   ops->resources_needed = resources_needed_ranged_breakpoint;
15818   ops->print_it = print_it_ranged_breakpoint;
15819   ops->print_one = print_one_ranged_breakpoint;
15820   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15821   ops->print_mention = print_mention_ranged_breakpoint;
15822   ops->print_recreate = print_recreate_ranged_breakpoint;
15823
15824   /* Internal breakpoints.  */
15825   ops = &internal_breakpoint_ops;
15826   *ops = bkpt_base_breakpoint_ops;
15827   ops->re_set = internal_bkpt_re_set;
15828   ops->check_status = internal_bkpt_check_status;
15829   ops->print_it = internal_bkpt_print_it;
15830   ops->print_mention = internal_bkpt_print_mention;
15831
15832   /* Momentary breakpoints.  */
15833   ops = &momentary_breakpoint_ops;
15834   *ops = bkpt_base_breakpoint_ops;
15835   ops->re_set = momentary_bkpt_re_set;
15836   ops->check_status = momentary_bkpt_check_status;
15837   ops->print_it = momentary_bkpt_print_it;
15838   ops->print_mention = momentary_bkpt_print_mention;
15839
15840   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15841   ops = &longjmp_breakpoint_ops;
15842   *ops = momentary_breakpoint_ops;
15843   ops->dtor = longjmp_bkpt_dtor;
15844
15845   /* Probe breakpoints.  */
15846   ops = &bkpt_probe_breakpoint_ops;
15847   *ops = bkpt_breakpoint_ops;
15848   ops->insert_location = bkpt_probe_insert_location;
15849   ops->remove_location = bkpt_probe_remove_location;
15850   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15851   ops->decode_location = bkpt_probe_decode_location;
15852
15853   /* Watchpoints.  */
15854   ops = &watchpoint_breakpoint_ops;
15855   *ops = base_breakpoint_ops;
15856   ops->dtor = dtor_watchpoint;
15857   ops->re_set = re_set_watchpoint;
15858   ops->insert_location = insert_watchpoint;
15859   ops->remove_location = remove_watchpoint;
15860   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15861   ops->check_status = check_status_watchpoint;
15862   ops->resources_needed = resources_needed_watchpoint;
15863   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15864   ops->print_it = print_it_watchpoint;
15865   ops->print_mention = print_mention_watchpoint;
15866   ops->print_recreate = print_recreate_watchpoint;
15867   ops->explains_signal = explains_signal_watchpoint;
15868
15869   /* Masked watchpoints.  */
15870   ops = &masked_watchpoint_breakpoint_ops;
15871   *ops = watchpoint_breakpoint_ops;
15872   ops->insert_location = insert_masked_watchpoint;
15873   ops->remove_location = remove_masked_watchpoint;
15874   ops->resources_needed = resources_needed_masked_watchpoint;
15875   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15876   ops->print_it = print_it_masked_watchpoint;
15877   ops->print_one_detail = print_one_detail_masked_watchpoint;
15878   ops->print_mention = print_mention_masked_watchpoint;
15879   ops->print_recreate = print_recreate_masked_watchpoint;
15880
15881   /* Tracepoints.  */
15882   ops = &tracepoint_breakpoint_ops;
15883   *ops = base_breakpoint_ops;
15884   ops->re_set = tracepoint_re_set;
15885   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15886   ops->print_one_detail = tracepoint_print_one_detail;
15887   ops->print_mention = tracepoint_print_mention;
15888   ops->print_recreate = tracepoint_print_recreate;
15889   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15890   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15891   ops->decode_location = tracepoint_decode_location;
15892
15893   /* Probe tracepoints.  */
15894   ops = &tracepoint_probe_breakpoint_ops;
15895   *ops = tracepoint_breakpoint_ops;
15896   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15897   ops->decode_location = tracepoint_probe_decode_location;
15898
15899   /* Static tracepoints with marker (`-m').  */
15900   ops = &strace_marker_breakpoint_ops;
15901   *ops = tracepoint_breakpoint_ops;
15902   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15903   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15904   ops->decode_location = strace_marker_decode_location;
15905
15906   /* Fork catchpoints.  */
15907   ops = &catch_fork_breakpoint_ops;
15908   *ops = base_breakpoint_ops;
15909   ops->insert_location = insert_catch_fork;
15910   ops->remove_location = remove_catch_fork;
15911   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15912   ops->print_it = print_it_catch_fork;
15913   ops->print_one = print_one_catch_fork;
15914   ops->print_mention = print_mention_catch_fork;
15915   ops->print_recreate = print_recreate_catch_fork;
15916
15917   /* Vfork catchpoints.  */
15918   ops = &catch_vfork_breakpoint_ops;
15919   *ops = base_breakpoint_ops;
15920   ops->insert_location = insert_catch_vfork;
15921   ops->remove_location = remove_catch_vfork;
15922   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15923   ops->print_it = print_it_catch_vfork;
15924   ops->print_one = print_one_catch_vfork;
15925   ops->print_mention = print_mention_catch_vfork;
15926   ops->print_recreate = print_recreate_catch_vfork;
15927
15928   /* Exec catchpoints.  */
15929   ops = &catch_exec_breakpoint_ops;
15930   *ops = base_breakpoint_ops;
15931   ops->dtor = dtor_catch_exec;
15932   ops->insert_location = insert_catch_exec;
15933   ops->remove_location = remove_catch_exec;
15934   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15935   ops->print_it = print_it_catch_exec;
15936   ops->print_one = print_one_catch_exec;
15937   ops->print_mention = print_mention_catch_exec;
15938   ops->print_recreate = print_recreate_catch_exec;
15939
15940   /* Solib-related catchpoints.  */
15941   ops = &catch_solib_breakpoint_ops;
15942   *ops = base_breakpoint_ops;
15943   ops->dtor = dtor_catch_solib;
15944   ops->insert_location = insert_catch_solib;
15945   ops->remove_location = remove_catch_solib;
15946   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15947   ops->check_status = check_status_catch_solib;
15948   ops->print_it = print_it_catch_solib;
15949   ops->print_one = print_one_catch_solib;
15950   ops->print_mention = print_mention_catch_solib;
15951   ops->print_recreate = print_recreate_catch_solib;
15952
15953   ops = &dprintf_breakpoint_ops;
15954   *ops = bkpt_base_breakpoint_ops;
15955   ops->re_set = dprintf_re_set;
15956   ops->resources_needed = bkpt_resources_needed;
15957   ops->print_it = bkpt_print_it;
15958   ops->print_mention = bkpt_print_mention;
15959   ops->print_recreate = dprintf_print_recreate;
15960   ops->after_condition_true = dprintf_after_condition_true;
15961   ops->breakpoint_hit = dprintf_breakpoint_hit;
15962 }
15963
15964 /* Chain containing all defined "enable breakpoint" subcommands.  */
15965
15966 static struct cmd_list_element *enablebreaklist = NULL;
15967
15968 void
15969 _initialize_breakpoint (void)
15970 {
15971   struct cmd_list_element *c;
15972
15973   initialize_breakpoint_ops ();
15974
15975   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15976   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15977   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15978
15979   breakpoint_objfile_key
15980     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15981
15982   breakpoint_chain = 0;
15983   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15984      before a breakpoint is set.  */
15985   breakpoint_count = 0;
15986
15987   tracepoint_count = 0;
15988
15989   add_com ("ignore", class_breakpoint, ignore_command, _("\
15990 Set ignore-count of breakpoint number N to COUNT.\n\
15991 Usage is `ignore N COUNT'."));
15992
15993   add_com ("commands", class_breakpoint, commands_command, _("\
15994 Set commands to be executed when a breakpoint is hit.\n\
15995 Give breakpoint number as argument after \"commands\".\n\
15996 With no argument, the targeted breakpoint is the last one set.\n\
15997 The commands themselves follow starting on the next line.\n\
15998 Type a line containing \"end\" to indicate the end of them.\n\
15999 Give \"silent\" as the first line to make the breakpoint silent;\n\
16000 then no output is printed when it is hit, except what the commands print."));
16001
16002   c = add_com ("condition", class_breakpoint, condition_command, _("\
16003 Specify breakpoint number N to break only if COND is true.\n\
16004 Usage is `condition N COND', where N is an integer and COND is an\n\
16005 expression to be evaluated whenever breakpoint N is reached."));
16006   set_cmd_completer (c, condition_completer);
16007
16008   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16009 Set a temporary breakpoint.\n\
16010 Like \"break\" except the breakpoint is only temporary,\n\
16011 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16012 by using \"enable delete\" on the breakpoint number.\n\
16013 \n"
16014 BREAK_ARGS_HELP ("tbreak")));
16015   set_cmd_completer (c, location_completer);
16016
16017   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16018 Set a hardware assisted breakpoint.\n\
16019 Like \"break\" except the breakpoint requires hardware support,\n\
16020 some target hardware may not have this support.\n\
16021 \n"
16022 BREAK_ARGS_HELP ("hbreak")));
16023   set_cmd_completer (c, location_completer);
16024
16025   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16026 Set a temporary hardware assisted breakpoint.\n\
16027 Like \"hbreak\" except the breakpoint is only temporary,\n\
16028 so it will be deleted when hit.\n\
16029 \n"
16030 BREAK_ARGS_HELP ("thbreak")));
16031   set_cmd_completer (c, location_completer);
16032
16033   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16034 Enable some breakpoints.\n\
16035 Give breakpoint numbers (separated by spaces) as arguments.\n\
16036 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16037 This is used to cancel the effect of the \"disable\" command.\n\
16038 With a subcommand you can enable temporarily."),
16039                   &enablelist, "enable ", 1, &cmdlist);
16040
16041   add_com_alias ("en", "enable", class_breakpoint, 1);
16042
16043   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16044 Enable some breakpoints.\n\
16045 Give breakpoint numbers (separated by spaces) as arguments.\n\
16046 This is used to cancel the effect of the \"disable\" command.\n\
16047 May be abbreviated to simply \"enable\".\n"),
16048                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16049
16050   add_cmd ("once", no_class, enable_once_command, _("\
16051 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16052 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16053            &enablebreaklist);
16054
16055   add_cmd ("delete", no_class, enable_delete_command, _("\
16056 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16057 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16058            &enablebreaklist);
16059
16060   add_cmd ("count", no_class, enable_count_command, _("\
16061 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16062 If a breakpoint is hit while enabled in this fashion,\n\
16063 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16064            &enablebreaklist);
16065
16066   add_cmd ("delete", no_class, enable_delete_command, _("\
16067 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16068 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16069            &enablelist);
16070
16071   add_cmd ("once", no_class, enable_once_command, _("\
16072 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16073 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16074            &enablelist);
16075
16076   add_cmd ("count", no_class, enable_count_command, _("\
16077 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16078 If a breakpoint is hit while enabled in this fashion,\n\
16079 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16080            &enablelist);
16081
16082   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16083 Disable some breakpoints.\n\
16084 Arguments are breakpoint numbers with spaces in between.\n\
16085 To disable all breakpoints, give no argument.\n\
16086 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16087                   &disablelist, "disable ", 1, &cmdlist);
16088   add_com_alias ("dis", "disable", class_breakpoint, 1);
16089   add_com_alias ("disa", "disable", class_breakpoint, 1);
16090
16091   add_cmd ("breakpoints", class_alias, disable_command, _("\
16092 Disable some breakpoints.\n\
16093 Arguments are breakpoint numbers with spaces in between.\n\
16094 To disable all breakpoints, give no argument.\n\
16095 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16096 This command may be abbreviated \"disable\"."),
16097            &disablelist);
16098
16099   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16100 Delete some breakpoints or auto-display expressions.\n\
16101 Arguments are breakpoint numbers with spaces in between.\n\
16102 To delete all breakpoints, give no argument.\n\
16103 \n\
16104 Also a prefix command for deletion of other GDB objects.\n\
16105 The \"unset\" command is also an alias for \"delete\"."),
16106                   &deletelist, "delete ", 1, &cmdlist);
16107   add_com_alias ("d", "delete", class_breakpoint, 1);
16108   add_com_alias ("del", "delete", class_breakpoint, 1);
16109
16110   add_cmd ("breakpoints", class_alias, delete_command, _("\
16111 Delete some breakpoints or auto-display expressions.\n\
16112 Arguments are breakpoint numbers with spaces in between.\n\
16113 To delete all breakpoints, give no argument.\n\
16114 This command may be abbreviated \"delete\"."),
16115            &deletelist);
16116
16117   add_com ("clear", class_breakpoint, clear_command, _("\
16118 Clear breakpoint at specified location.\n\
16119 Argument may be a linespec, explicit, or address location as described below.\n\
16120 \n\
16121 With no argument, clears all breakpoints in the line that the selected frame\n\
16122 is executing in.\n"
16123 "\n" LOCATION_HELP_STRING "\n\
16124 See also the \"delete\" command which clears breakpoints by number."));
16125   add_com_alias ("cl", "clear", class_breakpoint, 1);
16126
16127   c = add_com ("break", class_breakpoint, break_command, _("\
16128 Set breakpoint at specified location.\n"
16129 BREAK_ARGS_HELP ("break")));
16130   set_cmd_completer (c, location_completer);
16131
16132   add_com_alias ("b", "break", class_run, 1);
16133   add_com_alias ("br", "break", class_run, 1);
16134   add_com_alias ("bre", "break", class_run, 1);
16135   add_com_alias ("brea", "break", class_run, 1);
16136
16137   if (dbx_commands)
16138     {
16139       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16140 Break in function/address or break at a line in the current file."),
16141                              &stoplist, "stop ", 1, &cmdlist);
16142       add_cmd ("in", class_breakpoint, stopin_command,
16143                _("Break in function or address."), &stoplist);
16144       add_cmd ("at", class_breakpoint, stopat_command,
16145                _("Break at a line in the current file."), &stoplist);
16146       add_com ("status", class_info, breakpoints_info, _("\
16147 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16148 The \"Type\" column indicates one of:\n\
16149 \tbreakpoint     - normal breakpoint\n\
16150 \twatchpoint     - watchpoint\n\
16151 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16152 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16153 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16154 address and file/line number respectively.\n\
16155 \n\
16156 Convenience variable \"$_\" and default examine address for \"x\"\n\
16157 are set to the address of the last breakpoint listed unless the command\n\
16158 is prefixed with \"server \".\n\n\
16159 Convenience variable \"$bpnum\" contains the number of the last\n\
16160 breakpoint set."));
16161     }
16162
16163   add_info ("breakpoints", breakpoints_info, _("\
16164 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16165 The \"Type\" column indicates one of:\n\
16166 \tbreakpoint     - normal breakpoint\n\
16167 \twatchpoint     - watchpoint\n\
16168 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16169 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16170 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16171 address and file/line number respectively.\n\
16172 \n\
16173 Convenience variable \"$_\" and default examine address for \"x\"\n\
16174 are set to the address of the last breakpoint listed unless the command\n\
16175 is prefixed with \"server \".\n\n\
16176 Convenience variable \"$bpnum\" contains the number of the last\n\
16177 breakpoint set."));
16178
16179   add_info_alias ("b", "breakpoints", 1);
16180
16181   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16182 Status of all breakpoints, or breakpoint number NUMBER.\n\
16183 The \"Type\" column indicates one of:\n\
16184 \tbreakpoint     - normal breakpoint\n\
16185 \twatchpoint     - watchpoint\n\
16186 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16187 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16188 \tuntil          - internal breakpoint used by the \"until\" command\n\
16189 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16190 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16191 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16192 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16193 address and file/line number respectively.\n\
16194 \n\
16195 Convenience variable \"$_\" and default examine address for \"x\"\n\
16196 are set to the address of the last breakpoint listed unless the command\n\
16197 is prefixed with \"server \".\n\n\
16198 Convenience variable \"$bpnum\" contains the number of the last\n\
16199 breakpoint set."),
16200            &maintenanceinfolist);
16201
16202   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16203 Set catchpoints to catch events."),
16204                   &catch_cmdlist, "catch ",
16205                   0/*allow-unknown*/, &cmdlist);
16206
16207   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16208 Set temporary catchpoints to catch events."),
16209                   &tcatch_cmdlist, "tcatch ",
16210                   0/*allow-unknown*/, &cmdlist);
16211
16212   add_catch_command ("fork", _("Catch calls to fork."),
16213                      catch_fork_command_1,
16214                      NULL,
16215                      (void *) (uintptr_t) catch_fork_permanent,
16216                      (void *) (uintptr_t) catch_fork_temporary);
16217   add_catch_command ("vfork", _("Catch calls to vfork."),
16218                      catch_fork_command_1,
16219                      NULL,
16220                      (void *) (uintptr_t) catch_vfork_permanent,
16221                      (void *) (uintptr_t) catch_vfork_temporary);
16222   add_catch_command ("exec", _("Catch calls to exec."),
16223                      catch_exec_command_1,
16224                      NULL,
16225                      CATCH_PERMANENT,
16226                      CATCH_TEMPORARY);
16227   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16228 Usage: catch load [REGEX]\n\
16229 If REGEX is given, only stop for libraries matching the regular expression."),
16230                      catch_load_command_1,
16231                      NULL,
16232                      CATCH_PERMANENT,
16233                      CATCH_TEMPORARY);
16234   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16235 Usage: catch unload [REGEX]\n\
16236 If REGEX is given, only stop for libraries matching the regular expression."),
16237                      catch_unload_command_1,
16238                      NULL,
16239                      CATCH_PERMANENT,
16240                      CATCH_TEMPORARY);
16241
16242   c = add_com ("watch", class_breakpoint, watch_command, _("\
16243 Set a watchpoint for an expression.\n\
16244 Usage: watch [-l|-location] EXPRESSION\n\
16245 A watchpoint stops execution of your program whenever the value of\n\
16246 an expression changes.\n\
16247 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16248 the memory to which it refers."));
16249   set_cmd_completer (c, expression_completer);
16250
16251   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16252 Set a read watchpoint for an expression.\n\
16253 Usage: rwatch [-l|-location] EXPRESSION\n\
16254 A watchpoint stops execution of your program whenever the value of\n\
16255 an expression is read.\n\
16256 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16257 the memory to which it refers."));
16258   set_cmd_completer (c, expression_completer);
16259
16260   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16261 Set a watchpoint for an expression.\n\
16262 Usage: awatch [-l|-location] EXPRESSION\n\
16263 A watchpoint stops execution of your program whenever the value of\n\
16264 an expression is either read or written.\n\
16265 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16266 the memory to which it refers."));
16267   set_cmd_completer (c, expression_completer);
16268
16269   add_info ("watchpoints", watchpoints_info, _("\
16270 Status of specified watchpoints (all watchpoints if no argument)."));
16271
16272   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16273      respond to changes - contrary to the description.  */
16274   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16275                             &can_use_hw_watchpoints, _("\
16276 Set debugger's willingness to use watchpoint hardware."), _("\
16277 Show debugger's willingness to use watchpoint hardware."), _("\
16278 If zero, gdb will not use hardware for new watchpoints, even if\n\
16279 such is available.  (However, any hardware watchpoints that were\n\
16280 created before setting this to nonzero, will continue to use watchpoint\n\
16281 hardware.)"),
16282                             NULL,
16283                             show_can_use_hw_watchpoints,
16284                             &setlist, &showlist);
16285
16286   can_use_hw_watchpoints = 1;
16287
16288   /* Tracepoint manipulation commands.  */
16289
16290   c = add_com ("trace", class_breakpoint, trace_command, _("\
16291 Set a tracepoint at specified location.\n\
16292 \n"
16293 BREAK_ARGS_HELP ("trace") "\n\
16294 Do \"help tracepoints\" for info on other tracepoint commands."));
16295   set_cmd_completer (c, location_completer);
16296
16297   add_com_alias ("tp", "trace", class_alias, 0);
16298   add_com_alias ("tr", "trace", class_alias, 1);
16299   add_com_alias ("tra", "trace", class_alias, 1);
16300   add_com_alias ("trac", "trace", class_alias, 1);
16301
16302   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16303 Set a fast tracepoint at specified location.\n\
16304 \n"
16305 BREAK_ARGS_HELP ("ftrace") "\n\
16306 Do \"help tracepoints\" for info on other tracepoint commands."));
16307   set_cmd_completer (c, location_completer);
16308
16309   c = add_com ("strace", class_breakpoint, strace_command, _("\
16310 Set a static tracepoint at location or marker.\n\
16311 \n\
16312 strace [LOCATION] [if CONDITION]\n\
16313 LOCATION may be a linespec, explicit, or address location (described below) \n\
16314 or -m MARKER_ID.\n\n\
16315 If a marker id is specified, probe the marker with that name.  With\n\
16316 no LOCATION, uses current execution address of the selected stack frame.\n\
16317 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16318 This collects arbitrary user data passed in the probe point call to the\n\
16319 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16320 by printing the $_sdata variable like any other convenience variable.\n\
16321 \n\
16322 CONDITION is a boolean expression.\n\
16323 \n" LOCATION_HELP_STRING "\n\
16324 Multiple tracepoints at one place are permitted, and useful if their\n\
16325 conditions are different.\n\
16326 \n\
16327 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16328 Do \"help tracepoints\" for info on other tracepoint commands."));
16329   set_cmd_completer (c, location_completer);
16330
16331   add_info ("tracepoints", tracepoints_info, _("\
16332 Status of specified tracepoints (all tracepoints if no argument).\n\
16333 Convenience variable \"$tpnum\" contains the number of the\n\
16334 last tracepoint set."));
16335
16336   add_info_alias ("tp", "tracepoints", 1);
16337
16338   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16339 Delete specified tracepoints.\n\
16340 Arguments are tracepoint numbers, separated by spaces.\n\
16341 No argument means delete all tracepoints."),
16342            &deletelist);
16343   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16344
16345   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16346 Disable specified tracepoints.\n\
16347 Arguments are tracepoint numbers, separated by spaces.\n\
16348 No argument means disable all tracepoints."),
16349            &disablelist);
16350   deprecate_cmd (c, "disable");
16351
16352   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16353 Enable specified tracepoints.\n\
16354 Arguments are tracepoint numbers, separated by spaces.\n\
16355 No argument means enable all tracepoints."),
16356            &enablelist);
16357   deprecate_cmd (c, "enable");
16358
16359   add_com ("passcount", class_trace, trace_pass_command, _("\
16360 Set the passcount for a tracepoint.\n\
16361 The trace will end when the tracepoint has been passed 'count' times.\n\
16362 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16363 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16364
16365   add_prefix_cmd ("save", class_breakpoint, save_command,
16366                   _("Save breakpoint definitions as a script."),
16367                   &save_cmdlist, "save ",
16368                   0/*allow-unknown*/, &cmdlist);
16369
16370   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16371 Save current breakpoint definitions as a script.\n\
16372 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16373 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16374 session to restore them."),
16375                &save_cmdlist);
16376   set_cmd_completer (c, filename_completer);
16377
16378   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16379 Save current tracepoint definitions as a script.\n\
16380 Use the 'source' command in another debug session to restore them."),
16381                &save_cmdlist);
16382   set_cmd_completer (c, filename_completer);
16383
16384   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16385   deprecate_cmd (c, "save tracepoints");
16386
16387   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16388 Breakpoint specific settings\n\
16389 Configure various breakpoint-specific variables such as\n\
16390 pending breakpoint behavior"),
16391                   &breakpoint_set_cmdlist, "set breakpoint ",
16392                   0/*allow-unknown*/, &setlist);
16393   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16394 Breakpoint specific settings\n\
16395 Configure various breakpoint-specific variables such as\n\
16396 pending breakpoint behavior"),
16397                   &breakpoint_show_cmdlist, "show breakpoint ",
16398                   0/*allow-unknown*/, &showlist);
16399
16400   add_setshow_auto_boolean_cmd ("pending", no_class,
16401                                 &pending_break_support, _("\
16402 Set debugger's behavior regarding pending breakpoints."), _("\
16403 Show debugger's behavior regarding pending breakpoints."), _("\
16404 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16405 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16406 an error.  If auto, an unrecognized breakpoint location results in a\n\
16407 user-query to see if a pending breakpoint should be created."),
16408                                 NULL,
16409                                 show_pending_break_support,
16410                                 &breakpoint_set_cmdlist,
16411                                 &breakpoint_show_cmdlist);
16412
16413   pending_break_support = AUTO_BOOLEAN_AUTO;
16414
16415   add_setshow_boolean_cmd ("auto-hw", no_class,
16416                            &automatic_hardware_breakpoints, _("\
16417 Set automatic usage of hardware breakpoints."), _("\
16418 Show automatic usage of hardware breakpoints."), _("\
16419 If set, the debugger will automatically use hardware breakpoints for\n\
16420 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16421 a warning will be emitted for such breakpoints."),
16422                            NULL,
16423                            show_automatic_hardware_breakpoints,
16424                            &breakpoint_set_cmdlist,
16425                            &breakpoint_show_cmdlist);
16426
16427   add_setshow_boolean_cmd ("always-inserted", class_support,
16428                            &always_inserted_mode, _("\
16429 Set mode for inserting breakpoints."), _("\
16430 Show mode for inserting breakpoints."), _("\
16431 When this mode is on, breakpoints are inserted immediately as soon as\n\
16432 they're created, kept inserted even when execution stops, and removed\n\
16433 only when the user deletes them.  When this mode is off (the default),\n\
16434 breakpoints are inserted only when execution continues, and removed\n\
16435 when execution stops."),
16436                                 NULL,
16437                                 &show_always_inserted_mode,
16438                                 &breakpoint_set_cmdlist,
16439                                 &breakpoint_show_cmdlist);
16440
16441   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16442                         condition_evaluation_enums,
16443                         &condition_evaluation_mode_1, _("\
16444 Set mode of breakpoint condition evaluation."), _("\
16445 Show mode of breakpoint condition evaluation."), _("\
16446 When this is set to \"host\", breakpoint conditions will be\n\
16447 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16448 breakpoint conditions will be downloaded to the target (if the target\n\
16449 supports such feature) and conditions will be evaluated on the target's side.\n\
16450 If this is set to \"auto\" (default), this will be automatically set to\n\
16451 \"target\" if it supports condition evaluation, otherwise it will\n\
16452 be set to \"gdb\""),
16453                            &set_condition_evaluation_mode,
16454                            &show_condition_evaluation_mode,
16455                            &breakpoint_set_cmdlist,
16456                            &breakpoint_show_cmdlist);
16457
16458   add_com ("break-range", class_breakpoint, break_range_command, _("\
16459 Set a breakpoint for an address range.\n\
16460 break-range START-LOCATION, END-LOCATION\n\
16461 where START-LOCATION and END-LOCATION can be one of the following:\n\
16462   LINENUM, for that line in the current file,\n\
16463   FILE:LINENUM, for that line in that file,\n\
16464   +OFFSET, for that number of lines after the current line\n\
16465            or the start of the range\n\
16466   FUNCTION, for the first line in that function,\n\
16467   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16468   *ADDRESS, for the instruction at that address.\n\
16469 \n\
16470 The breakpoint will stop execution of the inferior whenever it executes\n\
16471 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16472 range (including START-LOCATION and END-LOCATION)."));
16473
16474   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16475 Set a dynamic printf at specified location.\n\
16476 dprintf location,format string,arg1,arg2,...\n\
16477 location may be a linespec, explicit, or address location.\n"
16478 "\n" LOCATION_HELP_STRING));
16479   set_cmd_completer (c, location_completer);
16480
16481   add_setshow_enum_cmd ("dprintf-style", class_support,
16482                         dprintf_style_enums, &dprintf_style, _("\
16483 Set the style of usage for dynamic printf."), _("\
16484 Show the style of usage for dynamic printf."), _("\
16485 This setting chooses how GDB will do a dynamic printf.\n\
16486 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16487 console, as with the \"printf\" command.\n\
16488 If the value is \"call\", the print is done by calling a function in your\n\
16489 program; by default printf(), but you can choose a different function or\n\
16490 output stream by setting dprintf-function and dprintf-channel."),
16491                         update_dprintf_commands, NULL,
16492                         &setlist, &showlist);
16493
16494   dprintf_function = xstrdup ("printf");
16495   add_setshow_string_cmd ("dprintf-function", class_support,
16496                           &dprintf_function, _("\
16497 Set the function to use for dynamic printf"), _("\
16498 Show the function to use for dynamic printf"), NULL,
16499                           update_dprintf_commands, NULL,
16500                           &setlist, &showlist);
16501
16502   dprintf_channel = xstrdup ("");
16503   add_setshow_string_cmd ("dprintf-channel", class_support,
16504                           &dprintf_channel, _("\
16505 Set the channel to use for dynamic printf"), _("\
16506 Show the channel to use for dynamic printf"), NULL,
16507                           update_dprintf_commands, NULL,
16508                           &setlist, &showlist);
16509
16510   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16511                            &disconnected_dprintf, _("\
16512 Set whether dprintf continues after GDB disconnects."), _("\
16513 Show whether dprintf continues after GDB disconnects."), _("\
16514 Use this to let dprintf commands continue to hit and produce output\n\
16515 even if GDB disconnects or detaches from the target."),
16516                            NULL,
16517                            NULL,
16518                            &setlist, &showlist);
16519
16520   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16521 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16522 (target agent only) This is useful for formatted output in user-defined commands."));
16523
16524   automatic_hardware_breakpoints = 1;
16525
16526   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16527   observer_attach_thread_exit (remove_threaded_breakpoints);
16528 }