Call target_can_download_tracepoint if there are tracepoints to download
[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 (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   struct bp_location *a = *(void **) ap;
929   struct bp_location *b = *(void **) 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 = bsearch (&dummy_locp, bp_location, bp_location_count,
955                         sizeof (struct bp_location **),
956                         bp_location_compare_addrs);
957
958   /* Nothing was found, nothing left to do.  */
959   if (locp_found == NULL)
960     return NULL;
961
962   /* We may have found a location that is at ADDRESS but is not the first in the
963      location's list.  Go backwards (if possible) and locate the first one.  */
964   while ((locp_found - 1) >= bp_location
965          && (*(locp_found - 1))->address == address)
966     locp_found--;
967
968   return locp_found;
969 }
970
971 void
972 set_breakpoint_condition (struct breakpoint *b, const char *exp,
973                           int from_tty)
974 {
975   xfree (b->cond_string);
976   b->cond_string = NULL;
977
978   if (is_watchpoint (b))
979     {
980       struct watchpoint *w = (struct watchpoint *) b;
981
982       xfree (w->cond_exp);
983       w->cond_exp = NULL;
984     }
985   else
986     {
987       struct bp_location *loc;
988
989       for (loc = b->loc; loc; loc = loc->next)
990         {
991           xfree (loc->cond);
992           loc->cond = NULL;
993
994           /* No need to free the condition agent expression
995              bytecode (if we have one).  We will handle this
996              when we go through update_global_location_list.  */
997         }
998     }
999
1000   if (*exp == 0)
1001     {
1002       if (from_tty)
1003         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1004     }
1005   else
1006     {
1007       const char *arg = exp;
1008
1009       /* I don't know if it matters whether this is the string the user
1010          typed in or the decompiled expression.  */
1011       b->cond_string = xstrdup (arg);
1012       b->condition_not_parsed = 0;
1013
1014       if (is_watchpoint (b))
1015         {
1016           struct watchpoint *w = (struct watchpoint *) b;
1017
1018           innermost_block = NULL;
1019           arg = exp;
1020           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1021           if (*arg)
1022             error (_("Junk at end of expression"));
1023           w->cond_exp_valid_block = innermost_block;
1024         }
1025       else
1026         {
1027           struct bp_location *loc;
1028
1029           for (loc = b->loc; loc; loc = loc->next)
1030             {
1031               arg = exp;
1032               loc->cond =
1033                 parse_exp_1 (&arg, loc->address,
1034                              block_for_pc (loc->address), 0);
1035               if (*arg)
1036                 error (_("Junk at end of expression"));
1037             }
1038         }
1039     }
1040   mark_breakpoint_modified (b);
1041
1042   observer_notify_breakpoint_modified (b);
1043 }
1044
1045 /* Completion for the "condition" command.  */
1046
1047 static VEC (char_ptr) *
1048 condition_completer (struct cmd_list_element *cmd,
1049                      const char *text, const char *word)
1050 {
1051   const char *space;
1052
1053   text = skip_spaces_const (text);
1054   space = skip_to_space_const (text);
1055   if (*space == '\0')
1056     {
1057       int len;
1058       struct breakpoint *b;
1059       VEC (char_ptr) *result = NULL;
1060
1061       if (text[0] == '$')
1062         {
1063           /* We don't support completion of history indices.  */
1064           if (isdigit (text[1]))
1065             return NULL;
1066           return complete_internalvar (&text[1]);
1067         }
1068
1069       /* We're completing the breakpoint number.  */
1070       len = strlen (text);
1071
1072       ALL_BREAKPOINTS (b)
1073         {
1074           char number[50];
1075
1076           xsnprintf (number, sizeof (number), "%d", b->number);
1077
1078           if (strncmp (number, text, len) == 0)
1079             VEC_safe_push (char_ptr, result, xstrdup (number));
1080         }
1081
1082       return result;
1083     }
1084
1085   /* We're completing the expression part.  */
1086   text = skip_spaces_const (space);
1087   return expression_completer (cmd, text, word);
1088 }
1089
1090 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1091
1092 static void
1093 condition_command (char *arg, int from_tty)
1094 {
1095   struct breakpoint *b;
1096   char *p;
1097   int bnum;
1098
1099   if (arg == 0)
1100     error_no_arg (_("breakpoint number"));
1101
1102   p = arg;
1103   bnum = get_number (&p);
1104   if (bnum == 0)
1105     error (_("Bad breakpoint argument: '%s'"), arg);
1106
1107   ALL_BREAKPOINTS (b)
1108     if (b->number == bnum)
1109       {
1110         /* Check if this breakpoint has a "stop" method implemented in an
1111            extension language.  This method and conditions entered into GDB
1112            from the CLI are mutually exclusive.  */
1113         const struct extension_language_defn *extlang
1114           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1115
1116         if (extlang != NULL)
1117           {
1118             error (_("Only one stop condition allowed.  There is currently"
1119                      " a %s stop condition defined for this breakpoint."),
1120                    ext_lang_capitalized_name (extlang));
1121           }
1122         set_breakpoint_condition (b, p, from_tty);
1123
1124         if (is_breakpoint (b))
1125           update_global_location_list (UGLL_MAY_INSERT);
1126
1127         return;
1128       }
1129
1130   error (_("No breakpoint number %d."), bnum);
1131 }
1132
1133 /* Check that COMMAND do not contain commands that are suitable
1134    only for tracepoints and not suitable for ordinary breakpoints.
1135    Throw if any such commands is found.  */
1136
1137 static void
1138 check_no_tracepoint_commands (struct command_line *commands)
1139 {
1140   struct command_line *c;
1141
1142   for (c = commands; c; c = c->next)
1143     {
1144       int i;
1145
1146       if (c->control_type == while_stepping_control)
1147         error (_("The 'while-stepping' command can "
1148                  "only be used for tracepoints"));
1149
1150       for (i = 0; i < c->body_count; ++i)
1151         check_no_tracepoint_commands ((c->body_list)[i]);
1152
1153       /* Not that command parsing removes leading whitespace and comment
1154          lines and also empty lines.  So, we only need to check for
1155          command directly.  */
1156       if (strstr (c->line, "collect ") == c->line)
1157         error (_("The 'collect' command can only be used for tracepoints"));
1158
1159       if (strstr (c->line, "teval ") == c->line)
1160         error (_("The 'teval' command can only be used for tracepoints"));
1161     }
1162 }
1163
1164 /* Encapsulate tests for different types of tracepoints.  */
1165
1166 static int
1167 is_tracepoint_type (enum bptype type)
1168 {
1169   return (type == bp_tracepoint
1170           || type == bp_fast_tracepoint
1171           || type == bp_static_tracepoint);
1172 }
1173
1174 int
1175 is_tracepoint (const struct breakpoint *b)
1176 {
1177   return is_tracepoint_type (b->type);
1178 }
1179
1180 /* A helper function that validates that COMMANDS are valid for a
1181    breakpoint.  This function will throw an exception if a problem is
1182    found.  */
1183
1184 static void
1185 validate_commands_for_breakpoint (struct breakpoint *b,
1186                                   struct command_line *commands)
1187 {
1188   if (is_tracepoint (b))
1189     {
1190       struct tracepoint *t = (struct tracepoint *) b;
1191       struct command_line *c;
1192       struct command_line *while_stepping = 0;
1193
1194       /* Reset the while-stepping step count.  The previous commands
1195          might have included a while-stepping action, while the new
1196          ones might not.  */
1197       t->step_count = 0;
1198
1199       /* We need to verify that each top-level element of commands is
1200          valid for tracepoints, that there's at most one
1201          while-stepping element, and that the while-stepping's body
1202          has valid tracing commands excluding nested while-stepping.
1203          We also need to validate the tracepoint action line in the
1204          context of the tracepoint --- validate_actionline actually
1205          has side effects, like setting the tracepoint's
1206          while-stepping STEP_COUNT, in addition to checking if the
1207          collect/teval actions parse and make sense in the
1208          tracepoint's context.  */
1209       for (c = commands; c; c = c->next)
1210         {
1211           if (c->control_type == while_stepping_control)
1212             {
1213               if (b->type == bp_fast_tracepoint)
1214                 error (_("The 'while-stepping' command "
1215                          "cannot be used for fast tracepoint"));
1216               else if (b->type == bp_static_tracepoint)
1217                 error (_("The 'while-stepping' command "
1218                          "cannot be used for static tracepoint"));
1219
1220               if (while_stepping)
1221                 error (_("The 'while-stepping' command "
1222                          "can be used only once"));
1223               else
1224                 while_stepping = c;
1225             }
1226
1227           validate_actionline (c->line, b);
1228         }
1229       if (while_stepping)
1230         {
1231           struct command_line *c2;
1232
1233           gdb_assert (while_stepping->body_count == 1);
1234           c2 = while_stepping->body_list[0];
1235           for (; c2; c2 = c2->next)
1236             {
1237               if (c2->control_type == while_stepping_control)
1238                 error (_("The 'while-stepping' command cannot be nested"));
1239             }
1240         }
1241     }
1242   else
1243     {
1244       check_no_tracepoint_commands (commands);
1245     }
1246 }
1247
1248 /* Return a vector of all the static tracepoints set at ADDR.  The
1249    caller is responsible for releasing the vector.  */
1250
1251 VEC(breakpoint_p) *
1252 static_tracepoints_here (CORE_ADDR addr)
1253 {
1254   struct breakpoint *b;
1255   VEC(breakpoint_p) *found = 0;
1256   struct bp_location *loc;
1257
1258   ALL_BREAKPOINTS (b)
1259     if (b->type == bp_static_tracepoint)
1260       {
1261         for (loc = b->loc; loc; loc = loc->next)
1262           if (loc->address == addr)
1263             VEC_safe_push(breakpoint_p, found, b);
1264       }
1265
1266   return found;
1267 }
1268
1269 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1270    validate that only allowed commands are included.  */
1271
1272 void
1273 breakpoint_set_commands (struct breakpoint *b, 
1274                          struct command_line *commands)
1275 {
1276   validate_commands_for_breakpoint (b, commands);
1277
1278   decref_counted_command_line (&b->commands);
1279   b->commands = alloc_counted_command_line (commands);
1280   observer_notify_breakpoint_modified (b);
1281 }
1282
1283 /* Set the internal `silent' flag on the breakpoint.  Note that this
1284    is not the same as the "silent" that may appear in the breakpoint's
1285    commands.  */
1286
1287 void
1288 breakpoint_set_silent (struct breakpoint *b, int silent)
1289 {
1290   int old_silent = b->silent;
1291
1292   b->silent = silent;
1293   if (old_silent != silent)
1294     observer_notify_breakpoint_modified (b);
1295 }
1296
1297 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1298    breakpoint work for any thread.  */
1299
1300 void
1301 breakpoint_set_thread (struct breakpoint *b, int thread)
1302 {
1303   int old_thread = b->thread;
1304
1305   b->thread = thread;
1306   if (old_thread != thread)
1307     observer_notify_breakpoint_modified (b);
1308 }
1309
1310 /* Set the task for this breakpoint.  If TASK is 0, make the
1311    breakpoint work for any task.  */
1312
1313 void
1314 breakpoint_set_task (struct breakpoint *b, int task)
1315 {
1316   int old_task = b->task;
1317
1318   b->task = task;
1319   if (old_task != task)
1320     observer_notify_breakpoint_modified (b);
1321 }
1322
1323 void
1324 check_tracepoint_command (char *line, void *closure)
1325 {
1326   struct breakpoint *b = closure;
1327
1328   validate_actionline (line, b);
1329 }
1330
1331 /* A structure used to pass information through
1332    map_breakpoint_numbers.  */
1333
1334 struct commands_info
1335 {
1336   /* True if the command was typed at a tty.  */
1337   int from_tty;
1338
1339   /* The breakpoint range spec.  */
1340   char *arg;
1341
1342   /* Non-NULL if the body of the commands are being read from this
1343      already-parsed command.  */
1344   struct command_line *control;
1345
1346   /* The command lines read from the user, or NULL if they have not
1347      yet been read.  */
1348   struct counted_command_line *cmd;
1349 };
1350
1351 /* A callback for map_breakpoint_numbers that sets the commands for
1352    commands_command.  */
1353
1354 static void
1355 do_map_commands_command (struct breakpoint *b, void *data)
1356 {
1357   struct commands_info *info = data;
1358
1359   if (info->cmd == NULL)
1360     {
1361       struct command_line *l;
1362
1363       if (info->control != NULL)
1364         l = copy_command_lines (info->control->body_list[0]);
1365       else
1366         {
1367           struct cleanup *old_chain;
1368           char *str;
1369
1370           str = xstrprintf (_("Type commands for breakpoint(s) "
1371                               "%s, one per line."),
1372                             info->arg);
1373
1374           old_chain = make_cleanup (xfree, str);
1375
1376           l = read_command_lines (str,
1377                                   info->from_tty, 1,
1378                                   (is_tracepoint (b)
1379                                    ? check_tracepoint_command : 0),
1380                                   b);
1381
1382           do_cleanups (old_chain);
1383         }
1384
1385       info->cmd = alloc_counted_command_line (l);
1386     }
1387
1388   /* If a breakpoint was on the list more than once, we don't need to
1389      do anything.  */
1390   if (b->commands != info->cmd)
1391     {
1392       validate_commands_for_breakpoint (b, info->cmd->commands);
1393       incref_counted_command_line (info->cmd);
1394       decref_counted_command_line (&b->commands);
1395       b->commands = info->cmd;
1396       observer_notify_breakpoint_modified (b);
1397     }
1398 }
1399
1400 static void
1401 commands_command_1 (char *arg, int from_tty, 
1402                     struct command_line *control)
1403 {
1404   struct cleanup *cleanups;
1405   struct commands_info info;
1406
1407   info.from_tty = from_tty;
1408   info.control = control;
1409   info.cmd = NULL;
1410   /* If we read command lines from the user, then `info' will hold an
1411      extra reference to the commands that we must clean up.  */
1412   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1413
1414   if (arg == NULL || !*arg)
1415     {
1416       if (breakpoint_count - prev_breakpoint_count > 1)
1417         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1418                           breakpoint_count);
1419       else if (breakpoint_count > 0)
1420         arg = xstrprintf ("%d", breakpoint_count);
1421       else
1422         {
1423           /* So that we don't try to free the incoming non-NULL
1424              argument in the cleanup below.  Mapping breakpoint
1425              numbers will fail in this case.  */
1426           arg = NULL;
1427         }
1428     }
1429   else
1430     /* The command loop has some static state, so we need to preserve
1431        our argument.  */
1432     arg = xstrdup (arg);
1433
1434   if (arg != NULL)
1435     make_cleanup (xfree, arg);
1436
1437   info.arg = arg;
1438
1439   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1440
1441   if (info.cmd == NULL)
1442     error (_("No breakpoints specified."));
1443
1444   do_cleanups (cleanups);
1445 }
1446
1447 static void
1448 commands_command (char *arg, int from_tty)
1449 {
1450   commands_command_1 (arg, from_tty, NULL);
1451 }
1452
1453 /* Like commands_command, but instead of reading the commands from
1454    input stream, takes them from an already parsed command structure.
1455
1456    This is used by cli-script.c to DTRT with breakpoint commands
1457    that are part of if and while bodies.  */
1458 enum command_control_type
1459 commands_from_control_command (char *arg, struct command_line *cmd)
1460 {
1461   commands_command_1 (arg, 0, cmd);
1462   return simple_control;
1463 }
1464
1465 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1466
1467 static int
1468 bp_location_has_shadow (struct bp_location *bl)
1469 {
1470   if (bl->loc_type != bp_loc_software_breakpoint)
1471     return 0;
1472   if (!bl->inserted)
1473     return 0;
1474   if (bl->target_info.shadow_len == 0)
1475     /* BL isn't valid, or doesn't shadow memory.  */
1476     return 0;
1477   return 1;
1478 }
1479
1480 /* Update BUF, which is LEN bytes read from the target address
1481    MEMADDR, by replacing a memory breakpoint with its shadowed
1482    contents.
1483
1484    If READBUF is not NULL, this buffer must not overlap with the of
1485    the breakpoint location's shadow_contents buffer.  Otherwise, a
1486    failed assertion internal error will be raised.  */
1487
1488 static void
1489 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1490                             const gdb_byte *writebuf_org,
1491                             ULONGEST memaddr, LONGEST len,
1492                             struct bp_target_info *target_info,
1493                             struct gdbarch *gdbarch)
1494 {
1495   /* Now do full processing of the found relevant range of elements.  */
1496   CORE_ADDR bp_addr = 0;
1497   int bp_size = 0;
1498   int bptoffset = 0;
1499
1500   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1501                                  current_program_space->aspace, 0))
1502     {
1503       /* The breakpoint is inserted in a different address space.  */
1504       return;
1505     }
1506
1507   /* Addresses and length of the part of the breakpoint that
1508      we need to copy.  */
1509   bp_addr = target_info->placed_address;
1510   bp_size = target_info->shadow_len;
1511
1512   if (bp_addr + bp_size <= memaddr)
1513     {
1514       /* The breakpoint is entirely before the chunk of memory we are
1515          reading.  */
1516       return;
1517     }
1518
1519   if (bp_addr >= memaddr + len)
1520     {
1521       /* The breakpoint is entirely after the chunk of memory we are
1522          reading.  */
1523       return;
1524     }
1525
1526   /* Offset within shadow_contents.  */
1527   if (bp_addr < memaddr)
1528     {
1529       /* Only copy the second part of the breakpoint.  */
1530       bp_size -= memaddr - bp_addr;
1531       bptoffset = memaddr - bp_addr;
1532       bp_addr = memaddr;
1533     }
1534
1535   if (bp_addr + bp_size > memaddr + len)
1536     {
1537       /* Only copy the first part of the breakpoint.  */
1538       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1539     }
1540
1541   if (readbuf != NULL)
1542     {
1543       /* Verify that the readbuf buffer does not overlap with the
1544          shadow_contents buffer.  */
1545       gdb_assert (target_info->shadow_contents >= readbuf + len
1546                   || readbuf >= (target_info->shadow_contents
1547                                  + target_info->shadow_len));
1548
1549       /* Update the read buffer with this inserted breakpoint's
1550          shadow.  */
1551       memcpy (readbuf + bp_addr - memaddr,
1552               target_info->shadow_contents + bptoffset, bp_size);
1553     }
1554   else
1555     {
1556       const unsigned char *bp;
1557       CORE_ADDR addr = target_info->reqstd_address;
1558       int placed_size;
1559
1560       /* Update the shadow with what we want to write to memory.  */
1561       memcpy (target_info->shadow_contents + bptoffset,
1562               writebuf_org + bp_addr - memaddr, bp_size);
1563
1564       /* Determine appropriate breakpoint contents and size for this
1565          address.  */
1566       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1567
1568       /* Update the final write buffer with this inserted
1569          breakpoint's INSN.  */
1570       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1571     }
1572 }
1573
1574 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1575    by replacing any memory breakpoints with their shadowed contents.
1576
1577    If READBUF is not NULL, this buffer must not overlap with any of
1578    the breakpoint location's shadow_contents buffers.  Otherwise,
1579    a failed assertion internal error will be raised.
1580
1581    The range of shadowed area by each bp_location is:
1582      bl->address - bp_location_placed_address_before_address_max
1583      up to bl->address + bp_location_shadow_len_after_address_max
1584    The range we were requested to resolve shadows for is:
1585      memaddr ... memaddr + len
1586    Thus the safe cutoff boundaries for performance optimization are
1587      memaddr + len <= (bl->address
1588                        - bp_location_placed_address_before_address_max)
1589    and:
1590      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1591
1592 void
1593 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1594                         const gdb_byte *writebuf_org,
1595                         ULONGEST memaddr, LONGEST len)
1596 {
1597   /* Left boundary, right boundary and median element of our binary
1598      search.  */
1599   unsigned bc_l, bc_r, bc;
1600   size_t i;
1601
1602   /* Find BC_L which is a leftmost element which may affect BUF
1603      content.  It is safe to report lower value but a failure to
1604      report higher one.  */
1605
1606   bc_l = 0;
1607   bc_r = bp_location_count;
1608   while (bc_l + 1 < bc_r)
1609     {
1610       struct bp_location *bl;
1611
1612       bc = (bc_l + bc_r) / 2;
1613       bl = bp_location[bc];
1614
1615       /* Check first BL->ADDRESS will not overflow due to the added
1616          constant.  Then advance the left boundary only if we are sure
1617          the BC element can in no way affect the BUF content (MEMADDR
1618          to MEMADDR + LEN range).
1619
1620          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1621          offset so that we cannot miss a breakpoint with its shadow
1622          range tail still reaching MEMADDR.  */
1623
1624       if ((bl->address + bp_location_shadow_len_after_address_max
1625            >= bl->address)
1626           && (bl->address + bp_location_shadow_len_after_address_max
1627               <= memaddr))
1628         bc_l = bc;
1629       else
1630         bc_r = bc;
1631     }
1632
1633   /* Due to the binary search above, we need to make sure we pick the
1634      first location that's at BC_L's address.  E.g., if there are
1635      multiple locations at the same address, BC_L may end up pointing
1636      at a duplicate location, and miss the "master"/"inserted"
1637      location.  Say, given locations L1, L2 and L3 at addresses A and
1638      B:
1639
1640       L1@A, L2@A, L3@B, ...
1641
1642      BC_L could end up pointing at location L2, while the "master"
1643      location could be L1.  Since the `loc->inserted' flag is only set
1644      on "master" locations, we'd forget to restore the shadow of L1
1645      and L2.  */
1646   while (bc_l > 0
1647          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1648     bc_l--;
1649
1650   /* Now do full processing of the found relevant range of elements.  */
1651
1652   for (bc = bc_l; bc < bp_location_count; bc++)
1653   {
1654     struct bp_location *bl = bp_location[bc];
1655     CORE_ADDR bp_addr = 0;
1656     int bp_size = 0;
1657     int bptoffset = 0;
1658
1659     /* bp_location array has BL->OWNER always non-NULL.  */
1660     if (bl->owner->type == bp_none)
1661       warning (_("reading through apparently deleted breakpoint #%d?"),
1662                bl->owner->number);
1663
1664     /* Performance optimization: any further element can no longer affect BUF
1665        content.  */
1666
1667     if (bl->address >= bp_location_placed_address_before_address_max
1668         && memaddr + len <= (bl->address
1669                              - bp_location_placed_address_before_address_max))
1670       break;
1671
1672     if (!bp_location_has_shadow (bl))
1673       continue;
1674
1675     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1676                                 memaddr, len, &bl->target_info, bl->gdbarch);
1677   }
1678 }
1679
1680 \f
1681
1682 /* Return true if BPT is either a software breakpoint or a hardware
1683    breakpoint.  */
1684
1685 int
1686 is_breakpoint (const struct breakpoint *bpt)
1687 {
1688   return (bpt->type == bp_breakpoint
1689           || bpt->type == bp_hardware_breakpoint
1690           || bpt->type == bp_dprintf);
1691 }
1692
1693 /* Return true if BPT is of any hardware watchpoint kind.  */
1694
1695 static int
1696 is_hardware_watchpoint (const struct breakpoint *bpt)
1697 {
1698   return (bpt->type == bp_hardware_watchpoint
1699           || bpt->type == bp_read_watchpoint
1700           || bpt->type == bp_access_watchpoint);
1701 }
1702
1703 /* Return true if BPT is of any watchpoint kind, hardware or
1704    software.  */
1705
1706 int
1707 is_watchpoint (const struct breakpoint *bpt)
1708 {
1709   return (is_hardware_watchpoint (bpt)
1710           || bpt->type == bp_watchpoint);
1711 }
1712
1713 /* Returns true if the current thread and its running state are safe
1714    to evaluate or update watchpoint B.  Watchpoints on local
1715    expressions need to be evaluated in the context of the thread that
1716    was current when the watchpoint was created, and, that thread needs
1717    to be stopped to be able to select the correct frame context.
1718    Watchpoints on global expressions can be evaluated on any thread,
1719    and in any state.  It is presently left to the target allowing
1720    memory accesses when threads are running.  */
1721
1722 static int
1723 watchpoint_in_thread_scope (struct watchpoint *b)
1724 {
1725   return (b->base.pspace == current_program_space
1726           && (ptid_equal (b->watchpoint_thread, null_ptid)
1727               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1728                   && !is_executing (inferior_ptid))));
1729 }
1730
1731 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1732    associated bp_watchpoint_scope breakpoint.  */
1733
1734 static void
1735 watchpoint_del_at_next_stop (struct watchpoint *w)
1736 {
1737   struct breakpoint *b = &w->base;
1738
1739   if (b->related_breakpoint != b)
1740     {
1741       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1742       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1743       b->related_breakpoint->disposition = disp_del_at_next_stop;
1744       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1745       b->related_breakpoint = b;
1746     }
1747   b->disposition = disp_del_at_next_stop;
1748 }
1749
1750 /* Extract a bitfield value from value VAL using the bit parameters contained in
1751    watchpoint W.  */
1752
1753 static struct value *
1754 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1755 {
1756   struct value *bit_val;
1757
1758   if (val == NULL)
1759     return NULL;
1760
1761   bit_val = allocate_value (value_type (val));
1762
1763   unpack_value_bitfield (bit_val,
1764                          w->val_bitpos,
1765                          w->val_bitsize,
1766                          value_contents_for_printing (val),
1767                          value_offset (val),
1768                          val);
1769
1770   return bit_val;
1771 }
1772
1773 /* Assuming that B is a watchpoint:
1774    - Reparse watchpoint expression, if REPARSE is non-zero
1775    - Evaluate expression and store the result in B->val
1776    - Evaluate the condition if there is one, and store the result
1777      in b->loc->cond.
1778    - Update the list of values that must be watched in B->loc.
1779
1780    If the watchpoint disposition is disp_del_at_next_stop, then do
1781    nothing.  If this is local watchpoint that is out of scope, delete
1782    it.
1783
1784    Even with `set breakpoint always-inserted on' the watchpoints are
1785    removed + inserted on each stop here.  Normal breakpoints must
1786    never be removed because they might be missed by a running thread
1787    when debugging in non-stop mode.  On the other hand, hardware
1788    watchpoints (is_hardware_watchpoint; processed here) are specific
1789    to each LWP since they are stored in each LWP's hardware debug
1790    registers.  Therefore, such LWP must be stopped first in order to
1791    be able to modify its hardware watchpoints.
1792
1793    Hardware watchpoints must be reset exactly once after being
1794    presented to the user.  It cannot be done sooner, because it would
1795    reset the data used to present the watchpoint hit to the user.  And
1796    it must not be done later because it could display the same single
1797    watchpoint hit during multiple GDB stops.  Note that the latter is
1798    relevant only to the hardware watchpoint types bp_read_watchpoint
1799    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1800    not user-visible - its hit is suppressed if the memory content has
1801    not changed.
1802
1803    The following constraints influence the location where we can reset
1804    hardware watchpoints:
1805
1806    * target_stopped_by_watchpoint and target_stopped_data_address are
1807      called several times when GDB stops.
1808
1809    [linux] 
1810    * Multiple hardware watchpoints can be hit at the same time,
1811      causing GDB to stop.  GDB only presents one hardware watchpoint
1812      hit at a time as the reason for stopping, and all the other hits
1813      are presented later, one after the other, each time the user
1814      requests the execution to be resumed.  Execution is not resumed
1815      for the threads still having pending hit event stored in
1816      LWP_INFO->STATUS.  While the watchpoint is already removed from
1817      the inferior on the first stop the thread hit event is kept being
1818      reported from its cached value by linux_nat_stopped_data_address
1819      until the real thread resume happens after the watchpoint gets
1820      presented and thus its LWP_INFO->STATUS gets reset.
1821
1822    Therefore the hardware watchpoint hit can get safely reset on the
1823    watchpoint removal from inferior.  */
1824
1825 static void
1826 update_watchpoint (struct watchpoint *b, int reparse)
1827 {
1828   int within_current_scope;
1829   struct frame_id saved_frame_id;
1830   int frame_saved;
1831
1832   /* If this is a local watchpoint, we only want to check if the
1833      watchpoint frame is in scope if the current thread is the thread
1834      that was used to create the watchpoint.  */
1835   if (!watchpoint_in_thread_scope (b))
1836     return;
1837
1838   if (b->base.disposition == disp_del_at_next_stop)
1839     return;
1840  
1841   frame_saved = 0;
1842
1843   /* Determine if the watchpoint is within scope.  */
1844   if (b->exp_valid_block == NULL)
1845     within_current_scope = 1;
1846   else
1847     {
1848       struct frame_info *fi = get_current_frame ();
1849       struct gdbarch *frame_arch = get_frame_arch (fi);
1850       CORE_ADDR frame_pc = get_frame_pc (fi);
1851
1852       /* If we're at a point where the stack has been destroyed
1853          (e.g. in a function epilogue), unwinding may not work
1854          properly. Do not attempt to recreate locations at this
1855          point.  See similar comments in watchpoint_check.  */
1856       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1857         return;
1858
1859       /* Save the current frame's ID so we can restore it after
1860          evaluating the watchpoint expression on its own frame.  */
1861       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1862          took a frame parameter, so that we didn't have to change the
1863          selected frame.  */
1864       frame_saved = 1;
1865       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1866
1867       fi = frame_find_by_id (b->watchpoint_frame);
1868       within_current_scope = (fi != NULL);
1869       if (within_current_scope)
1870         select_frame (fi);
1871     }
1872
1873   /* We don't free locations.  They are stored in the bp_location array
1874      and update_global_location_list will eventually delete them and
1875      remove breakpoints if needed.  */
1876   b->base.loc = NULL;
1877
1878   if (within_current_scope && reparse)
1879     {
1880       const char *s;
1881
1882       if (b->exp)
1883         {
1884           xfree (b->exp);
1885           b->exp = NULL;
1886         }
1887       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1888       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1889       /* If the meaning of expression itself changed, the old value is
1890          no longer relevant.  We don't want to report a watchpoint hit
1891          to the user when the old value and the new value may actually
1892          be completely different objects.  */
1893       value_free (b->val);
1894       b->val = NULL;
1895       b->val_valid = 0;
1896
1897       /* Note that unlike with breakpoints, the watchpoint's condition
1898          expression is stored in the breakpoint object, not in the
1899          locations (re)created below.  */
1900       if (b->base.cond_string != NULL)
1901         {
1902           if (b->cond_exp != NULL)
1903             {
1904               xfree (b->cond_exp);
1905               b->cond_exp = NULL;
1906             }
1907
1908           s = b->base.cond_string;
1909           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1910         }
1911     }
1912
1913   /* If we failed to parse the expression, for example because
1914      it refers to a global variable in a not-yet-loaded shared library,
1915      don't try to insert watchpoint.  We don't automatically delete
1916      such watchpoint, though, since failure to parse expression
1917      is different from out-of-scope watchpoint.  */
1918   if (!target_has_execution)
1919     {
1920       /* Without execution, memory can't change.  No use to try and
1921          set watchpoint locations.  The watchpoint will be reset when
1922          the target gains execution, through breakpoint_re_set.  */
1923       if (!can_use_hw_watchpoints)
1924         {
1925           if (b->base.ops->works_in_software_mode (&b->base))
1926             b->base.type = bp_watchpoint;
1927           else
1928             error (_("Can't set read/access watchpoint when "
1929                      "hardware watchpoints are disabled."));
1930         }
1931     }
1932   else if (within_current_scope && b->exp)
1933     {
1934       int pc = 0;
1935       struct value *val_chain, *v, *result, *next;
1936       struct program_space *frame_pspace;
1937
1938       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1939
1940       /* Avoid setting b->val if it's already set.  The meaning of
1941          b->val is 'the last value' user saw, and we should update
1942          it only if we reported that last value to user.  As it
1943          happens, the code that reports it updates b->val directly.
1944          We don't keep track of the memory value for masked
1945          watchpoints.  */
1946       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1947         {
1948           if (b->val_bitsize != 0)
1949             {
1950               v = extract_bitfield_from_watchpoint_value (b, v);
1951               if (v != NULL)
1952                 release_value (v);
1953             }
1954           b->val = v;
1955           b->val_valid = 1;
1956         }
1957
1958       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1959
1960       /* Look at each value on the value chain.  */
1961       for (v = val_chain; v; v = value_next (v))
1962         {
1963           /* If it's a memory location, and GDB actually needed
1964              its contents to evaluate the expression, then we
1965              must watch it.  If the first value returned is
1966              still lazy, that means an error occurred reading it;
1967              watch it anyway in case it becomes readable.  */
1968           if (VALUE_LVAL (v) == lval_memory
1969               && (v == val_chain || ! value_lazy (v)))
1970             {
1971               struct type *vtype = check_typedef (value_type (v));
1972
1973               /* We only watch structs and arrays if user asked
1974                  for it explicitly, never if they just happen to
1975                  appear in the middle of some value chain.  */
1976               if (v == result
1977                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1978                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1979                 {
1980                   CORE_ADDR addr;
1981                   enum target_hw_bp_type type;
1982                   struct bp_location *loc, **tmp;
1983                   int bitpos = 0, bitsize = 0;
1984
1985                   if (value_bitsize (v) != 0)
1986                     {
1987                       /* Extract the bit parameters out from the bitfield
1988                          sub-expression.  */
1989                       bitpos = value_bitpos (v);
1990                       bitsize = value_bitsize (v);
1991                     }
1992                   else if (v == result && b->val_bitsize != 0)
1993                     {
1994                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1995                         lvalue whose bit parameters are saved in the fields
1996                         VAL_BITPOS and VAL_BITSIZE.  */
1997                       bitpos = b->val_bitpos;
1998                       bitsize = b->val_bitsize;
1999                     }
2000
2001                   addr = value_address (v);
2002                   if (bitsize != 0)
2003                     {
2004                       /* Skip the bytes that don't contain the bitfield.  */
2005                       addr += bitpos / 8;
2006                     }
2007
2008                   type = hw_write;
2009                   if (b->base.type == bp_read_watchpoint)
2010                     type = hw_read;
2011                   else if (b->base.type == bp_access_watchpoint)
2012                     type = hw_access;
2013
2014                   loc = allocate_bp_location (&b->base);
2015                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2016                     ;
2017                   *tmp = loc;
2018                   loc->gdbarch = get_type_arch (value_type (v));
2019
2020                   loc->pspace = frame_pspace;
2021                   loc->address = addr;
2022
2023                   if (bitsize != 0)
2024                     {
2025                       /* Just cover the bytes that make up the bitfield.  */
2026                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2027                     }
2028                   else
2029                     loc->length = TYPE_LENGTH (value_type (v));
2030
2031                   loc->watchpoint_type = type;
2032                 }
2033             }
2034         }
2035
2036       /* Change the type of breakpoint between hardware assisted or
2037          an ordinary watchpoint depending on the hardware support
2038          and free hardware slots.  REPARSE is set when the inferior
2039          is started.  */
2040       if (reparse)
2041         {
2042           int reg_cnt;
2043           enum bp_loc_type loc_type;
2044           struct bp_location *bl;
2045
2046           reg_cnt = can_use_hardware_watchpoint (val_chain);
2047
2048           if (reg_cnt)
2049             {
2050               int i, target_resources_ok, other_type_used;
2051               enum bptype type;
2052
2053               /* Use an exact watchpoint when there's only one memory region to be
2054                  watched, and only one debug register is needed to watch it.  */
2055               b->exact = target_exact_watchpoints && reg_cnt == 1;
2056
2057               /* We need to determine how many resources are already
2058                  used for all other hardware watchpoints plus this one
2059                  to see if we still have enough resources to also fit
2060                  this watchpoint in as well.  */
2061
2062               /* If this is a software watchpoint, we try to turn it
2063                  to a hardware one -- count resources as if B was of
2064                  hardware watchpoint type.  */
2065               type = b->base.type;
2066               if (type == bp_watchpoint)
2067                 type = bp_hardware_watchpoint;
2068
2069               /* This watchpoint may or may not have been placed on
2070                  the list yet at this point (it won't be in the list
2071                  if we're trying to create it for the first time,
2072                  through watch_command), so always account for it
2073                  manually.  */
2074
2075               /* Count resources used by all watchpoints except B.  */
2076               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2077
2078               /* Add in the resources needed for B.  */
2079               i += hw_watchpoint_use_count (&b->base);
2080
2081               target_resources_ok
2082                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2083               if (target_resources_ok <= 0)
2084                 {
2085                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2086
2087                   if (target_resources_ok == 0 && !sw_mode)
2088                     error (_("Target does not support this type of "
2089                              "hardware watchpoint."));
2090                   else if (target_resources_ok < 0 && !sw_mode)
2091                     error (_("There are not enough available hardware "
2092                              "resources for this watchpoint."));
2093
2094                   /* Downgrade to software watchpoint.  */
2095                   b->base.type = bp_watchpoint;
2096                 }
2097               else
2098                 {
2099                   /* If this was a software watchpoint, we've just
2100                      found we have enough resources to turn it to a
2101                      hardware watchpoint.  Otherwise, this is a
2102                      nop.  */
2103                   b->base.type = type;
2104                 }
2105             }
2106           else if (!b->base.ops->works_in_software_mode (&b->base))
2107             {
2108               if (!can_use_hw_watchpoints)
2109                 error (_("Can't set read/access watchpoint when "
2110                          "hardware watchpoints are disabled."));
2111               else
2112                 error (_("Expression cannot be implemented with "
2113                          "read/access watchpoint."));
2114             }
2115           else
2116             b->base.type = bp_watchpoint;
2117
2118           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2119                       : bp_loc_hardware_watchpoint);
2120           for (bl = b->base.loc; bl; bl = bl->next)
2121             bl->loc_type = loc_type;
2122         }
2123
2124       for (v = val_chain; v; v = next)
2125         {
2126           next = value_next (v);
2127           if (v != b->val)
2128             value_free (v);
2129         }
2130
2131       /* If a software watchpoint is not watching any memory, then the
2132          above left it without any location set up.  But,
2133          bpstat_stop_status requires a location to be able to report
2134          stops, so make sure there's at least a dummy one.  */
2135       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2136         {
2137           struct breakpoint *base = &b->base;
2138           base->loc = allocate_bp_location (base);
2139           base->loc->pspace = frame_pspace;
2140           base->loc->address = -1;
2141           base->loc->length = -1;
2142           base->loc->watchpoint_type = -1;
2143         }
2144     }
2145   else if (!within_current_scope)
2146     {
2147       printf_filtered (_("\
2148 Watchpoint %d deleted because the program has left the block\n\
2149 in which its expression is valid.\n"),
2150                        b->base.number);
2151       watchpoint_del_at_next_stop (b);
2152     }
2153
2154   /* Restore the selected frame.  */
2155   if (frame_saved)
2156     select_frame (frame_find_by_id (saved_frame_id));
2157 }
2158
2159
2160 /* Returns 1 iff breakpoint location should be
2161    inserted in the inferior.  We don't differentiate the type of BL's owner
2162    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2163    breakpoint_ops is not defined, because in insert_bp_location,
2164    tracepoint's insert_location will not be called.  */
2165 static int
2166 should_be_inserted (struct bp_location *bl)
2167 {
2168   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2169     return 0;
2170
2171   if (bl->owner->disposition == disp_del_at_next_stop)
2172     return 0;
2173
2174   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2175     return 0;
2176
2177   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2178     return 0;
2179
2180   /* This is set for example, when we're attached to the parent of a
2181      vfork, and have detached from the child.  The child is running
2182      free, and we expect it to do an exec or exit, at which point the
2183      OS makes the parent schedulable again (and the target reports
2184      that the vfork is done).  Until the child is done with the shared
2185      memory region, do not insert breakpoints in the parent, otherwise
2186      the child could still trip on the parent's breakpoints.  Since
2187      the parent is blocked anyway, it won't miss any breakpoint.  */
2188   if (bl->pspace->breakpoints_not_allowed)
2189     return 0;
2190
2191   /* Don't insert a breakpoint if we're trying to step past its
2192      location.  */
2193   if ((bl->loc_type == bp_loc_software_breakpoint
2194        || bl->loc_type == bp_loc_hardware_breakpoint)
2195       && stepping_past_instruction_at (bl->pspace->aspace,
2196                                        bl->address))
2197     {
2198       if (debug_infrun)
2199         {
2200           fprintf_unfiltered (gdb_stdlog,
2201                               "infrun: skipping breakpoint: "
2202                               "stepping past insn at: %s\n",
2203                               paddress (bl->gdbarch, bl->address));
2204         }
2205       return 0;
2206     }
2207
2208   /* Don't insert watchpoints if we're trying to step past the
2209      instruction that triggered one.  */
2210   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2211       && stepping_past_nonsteppable_watchpoint ())
2212     {
2213       if (debug_infrun)
2214         {
2215           fprintf_unfiltered (gdb_stdlog,
2216                               "infrun: stepping past non-steppable watchpoint. "
2217                               "skipping watchpoint at %s:%d\n",
2218                               paddress (bl->gdbarch, bl->address),
2219                               bl->length);
2220         }
2221       return 0;
2222     }
2223
2224   return 1;
2225 }
2226
2227 /* Same as should_be_inserted but does the check assuming
2228    that the location is not duplicated.  */
2229
2230 static int
2231 unduplicated_should_be_inserted (struct bp_location *bl)
2232 {
2233   int result;
2234   const int save_duplicate = bl->duplicate;
2235
2236   bl->duplicate = 0;
2237   result = should_be_inserted (bl);
2238   bl->duplicate = save_duplicate;
2239   return result;
2240 }
2241
2242 /* Parses a conditional described by an expression COND into an
2243    agent expression bytecode suitable for evaluation
2244    by the bytecode interpreter.  Return NULL if there was
2245    any error during parsing.  */
2246
2247 static struct agent_expr *
2248 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2249 {
2250   struct agent_expr *aexpr = NULL;
2251
2252   if (!cond)
2253     return NULL;
2254
2255   /* We don't want to stop processing, so catch any errors
2256      that may show up.  */
2257   TRY
2258     {
2259       aexpr = gen_eval_for_expr (scope, cond);
2260     }
2261
2262   CATCH (ex, RETURN_MASK_ERROR)
2263     {
2264       /* If we got here, it means the condition could not be parsed to a valid
2265          bytecode expression and thus can't be evaluated on the target's side.
2266          It's no use iterating through the conditions.  */
2267       return NULL;
2268     }
2269   END_CATCH
2270
2271   /* We have a valid agent expression.  */
2272   return aexpr;
2273 }
2274
2275 /* Based on location BL, create a list of breakpoint conditions to be
2276    passed on to the target.  If we have duplicated locations with different
2277    conditions, we will add such conditions to the list.  The idea is that the
2278    target will evaluate the list of conditions and will only notify GDB when
2279    one of them is true.  */
2280
2281 static void
2282 build_target_condition_list (struct bp_location *bl)
2283 {
2284   struct bp_location **locp = NULL, **loc2p;
2285   int null_condition_or_parse_error = 0;
2286   int modified = bl->needs_update;
2287   struct bp_location *loc;
2288
2289   /* Release conditions left over from a previous insert.  */
2290   VEC_free (agent_expr_p, bl->target_info.conditions);
2291
2292   /* This is only meaningful if the target is
2293      evaluating conditions and if the user has
2294      opted for condition evaluation on the target's
2295      side.  */
2296   if (gdb_evaluates_breakpoint_condition_p ()
2297       || !target_supports_evaluation_of_breakpoint_conditions ())
2298     return;
2299
2300   /* Do a first pass to check for locations with no assigned
2301      conditions or conditions that fail to parse to a valid agent expression
2302      bytecode.  If any of these happen, then it's no use to send conditions
2303      to the target since this location will always trigger and generate a
2304      response back to GDB.  */
2305   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2306     {
2307       loc = (*loc2p);
2308       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2309         {
2310           if (modified)
2311             {
2312               struct agent_expr *aexpr;
2313
2314               /* Re-parse the conditions since something changed.  In that
2315                  case we already freed the condition bytecodes (see
2316                  force_breakpoint_reinsertion).  We just
2317                  need to parse the condition to bytecodes again.  */
2318               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2319               loc->cond_bytecode = aexpr;
2320
2321               /* Check if we managed to parse the conditional expression
2322                  correctly.  If not, we will not send this condition
2323                  to the target.  */
2324               if (aexpr)
2325                 continue;
2326             }
2327
2328           /* If we have a NULL bytecode expression, it means something
2329              went wrong or we have a null condition expression.  */
2330           if (!loc->cond_bytecode)
2331             {
2332               null_condition_or_parse_error = 1;
2333               break;
2334             }
2335         }
2336     }
2337
2338   /* If any of these happened, it means we will have to evaluate the conditions
2339      for the location's address on gdb's side.  It is no use keeping bytecodes
2340      for all the other duplicate locations, thus we free all of them here.
2341
2342      This is so we have a finer control over which locations' conditions are
2343      being evaluated by GDB or the remote stub.  */
2344   if (null_condition_or_parse_error)
2345     {
2346       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2347         {
2348           loc = (*loc2p);
2349           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2350             {
2351               /* Only go as far as the first NULL bytecode is
2352                  located.  */
2353               if (!loc->cond_bytecode)
2354                 return;
2355
2356               free_agent_expr (loc->cond_bytecode);
2357               loc->cond_bytecode = NULL;
2358             }
2359         }
2360     }
2361
2362   /* No NULL conditions or failed bytecode generation.  Build a condition list
2363      for this location's address.  */
2364   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2365     {
2366       loc = (*loc2p);
2367       if (loc->cond
2368           && is_breakpoint (loc->owner)
2369           && loc->pspace->num == bl->pspace->num
2370           && loc->owner->enable_state == bp_enabled
2371           && loc->enabled)
2372         /* Add the condition to the vector.  This will be used later to send the
2373            conditions to the target.  */
2374         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2375                        loc->cond_bytecode);
2376     }
2377
2378   return;
2379 }
2380
2381 /* Parses a command described by string CMD into an agent expression
2382    bytecode suitable for evaluation by the bytecode interpreter.
2383    Return NULL if there was any error during parsing.  */
2384
2385 static struct agent_expr *
2386 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2387 {
2388   struct cleanup *old_cleanups = 0;
2389   struct expression *expr, **argvec;
2390   struct agent_expr *aexpr = NULL;
2391   const char *cmdrest;
2392   const char *format_start, *format_end;
2393   struct format_piece *fpieces;
2394   int nargs;
2395   struct gdbarch *gdbarch = get_current_arch ();
2396
2397   if (!cmd)
2398     return NULL;
2399
2400   cmdrest = cmd;
2401
2402   if (*cmdrest == ',')
2403     ++cmdrest;
2404   cmdrest = skip_spaces_const (cmdrest);
2405
2406   if (*cmdrest++ != '"')
2407     error (_("No format string following the location"));
2408
2409   format_start = cmdrest;
2410
2411   fpieces = parse_format_string (&cmdrest);
2412
2413   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2414
2415   format_end = cmdrest;
2416
2417   if (*cmdrest++ != '"')
2418     error (_("Bad format string, non-terminated '\"'."));
2419   
2420   cmdrest = skip_spaces_const (cmdrest);
2421
2422   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2423     error (_("Invalid argument syntax"));
2424
2425   if (*cmdrest == ',')
2426     cmdrest++;
2427   cmdrest = skip_spaces_const (cmdrest);
2428
2429   /* For each argument, make an expression.  */
2430
2431   argvec = (struct expression **) alloca (strlen (cmd)
2432                                          * sizeof (struct expression *));
2433
2434   nargs = 0;
2435   while (*cmdrest != '\0')
2436     {
2437       const char *cmd1;
2438
2439       cmd1 = cmdrest;
2440       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2441       argvec[nargs++] = expr;
2442       cmdrest = cmd1;
2443       if (*cmdrest == ',')
2444         ++cmdrest;
2445     }
2446
2447   /* We don't want to stop processing, so catch any errors
2448      that may show up.  */
2449   TRY
2450     {
2451       aexpr = gen_printf (scope, gdbarch, 0, 0,
2452                           format_start, format_end - format_start,
2453                           fpieces, nargs, argvec);
2454     }
2455   CATCH (ex, RETURN_MASK_ERROR)
2456     {
2457       /* If we got here, it means the command could not be parsed to a valid
2458          bytecode expression and thus can't be evaluated on the target's side.
2459          It's no use iterating through the other commands.  */
2460       aexpr = NULL;
2461     }
2462   END_CATCH
2463
2464   do_cleanups (old_cleanups);
2465
2466   /* We have a valid agent expression, return it.  */
2467   return aexpr;
2468 }
2469
2470 /* Based on location BL, create a list of breakpoint commands to be
2471    passed on to the target.  If we have duplicated locations with
2472    different commands, we will add any such to the list.  */
2473
2474 static void
2475 build_target_command_list (struct bp_location *bl)
2476 {
2477   struct bp_location **locp = NULL, **loc2p;
2478   int null_command_or_parse_error = 0;
2479   int modified = bl->needs_update;
2480   struct bp_location *loc;
2481
2482   /* Release commands left over from a previous insert.  */
2483   VEC_free (agent_expr_p, bl->target_info.tcommands);
2484
2485   if (!target_can_run_breakpoint_commands ())
2486     return;
2487
2488   /* For now, limit to agent-style dprintf breakpoints.  */
2489   if (dprintf_style != dprintf_style_agent)
2490     return;
2491
2492   /* For now, if we have any duplicate location that isn't a dprintf,
2493      don't install the target-side commands, as that would make the
2494      breakpoint not be reported to the core, and we'd lose
2495      control.  */
2496   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2497     {
2498       loc = (*loc2p);
2499       if (is_breakpoint (loc->owner)
2500           && loc->pspace->num == bl->pspace->num
2501           && loc->owner->type != bp_dprintf)
2502         return;
2503     }
2504
2505   /* Do a first pass to check for locations with no assigned
2506      conditions or conditions that fail to parse to a valid agent expression
2507      bytecode.  If any of these happen, then it's no use to send conditions
2508      to the target since this location will always trigger and generate a
2509      response back to GDB.  */
2510   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2511     {
2512       loc = (*loc2p);
2513       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2514         {
2515           if (modified)
2516             {
2517               struct agent_expr *aexpr;
2518
2519               /* Re-parse the commands since something changed.  In that
2520                  case we already freed the command bytecodes (see
2521                  force_breakpoint_reinsertion).  We just
2522                  need to parse the command to bytecodes again.  */
2523               aexpr = parse_cmd_to_aexpr (bl->address,
2524                                           loc->owner->extra_string);
2525               loc->cmd_bytecode = aexpr;
2526
2527               if (!aexpr)
2528                 continue;
2529             }
2530
2531           /* If we have a NULL bytecode expression, it means something
2532              went wrong or we have a null command expression.  */
2533           if (!loc->cmd_bytecode)
2534             {
2535               null_command_or_parse_error = 1;
2536               break;
2537             }
2538         }
2539     }
2540
2541   /* If anything failed, then we're not doing target-side commands,
2542      and so clean up.  */
2543   if (null_command_or_parse_error)
2544     {
2545       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2546         {
2547           loc = (*loc2p);
2548           if (is_breakpoint (loc->owner)
2549               && loc->pspace->num == bl->pspace->num)
2550             {
2551               /* Only go as far as the first NULL bytecode is
2552                  located.  */
2553               if (loc->cmd_bytecode == NULL)
2554                 return;
2555
2556               free_agent_expr (loc->cmd_bytecode);
2557               loc->cmd_bytecode = NULL;
2558             }
2559         }
2560     }
2561
2562   /* No NULL commands or failed bytecode generation.  Build a command list
2563      for this location's address.  */
2564   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2565     {
2566       loc = (*loc2p);
2567       if (loc->owner->extra_string
2568           && is_breakpoint (loc->owner)
2569           && loc->pspace->num == bl->pspace->num
2570           && loc->owner->enable_state == bp_enabled
2571           && loc->enabled)
2572         /* Add the command to the vector.  This will be used later
2573            to send the commands to the target.  */
2574         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2575                        loc->cmd_bytecode);
2576     }
2577
2578   bl->target_info.persist = 0;
2579   /* Maybe flag this location as persistent.  */
2580   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2581     bl->target_info.persist = 1;
2582 }
2583
2584 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2585    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2586    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2587    Returns 0 for success, 1 if the bp_location type is not supported or
2588    -1 for failure.
2589
2590    NOTE drow/2003-09-09: This routine could be broken down to an
2591    object-style method for each breakpoint or catchpoint type.  */
2592 static int
2593 insert_bp_location (struct bp_location *bl,
2594                     struct ui_file *tmp_error_stream,
2595                     int *disabled_breaks,
2596                     int *hw_breakpoint_error,
2597                     int *hw_bp_error_explained_already)
2598 {
2599   enum errors bp_err = GDB_NO_ERROR;
2600   const char *bp_err_message = NULL;
2601
2602   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2603     return 0;
2604
2605   /* Note we don't initialize bl->target_info, as that wipes out
2606      the breakpoint location's shadow_contents if the breakpoint
2607      is still inserted at that location.  This in turn breaks
2608      target_read_memory which depends on these buffers when
2609      a memory read is requested at the breakpoint location:
2610      Once the target_info has been wiped, we fail to see that
2611      we have a breakpoint inserted at that address and thus
2612      read the breakpoint instead of returning the data saved in
2613      the breakpoint location's shadow contents.  */
2614   bl->target_info.reqstd_address = bl->address;
2615   bl->target_info.placed_address_space = bl->pspace->aspace;
2616   bl->target_info.length = bl->length;
2617
2618   /* When working with target-side conditions, we must pass all the conditions
2619      for the same breakpoint address down to the target since GDB will not
2620      insert those locations.  With a list of breakpoint conditions, the target
2621      can decide when to stop and notify GDB.  */
2622
2623   if (is_breakpoint (bl->owner))
2624     {
2625       build_target_condition_list (bl);
2626       build_target_command_list (bl);
2627       /* Reset the modification marker.  */
2628       bl->needs_update = 0;
2629     }
2630
2631   if (bl->loc_type == bp_loc_software_breakpoint
2632       || bl->loc_type == bp_loc_hardware_breakpoint)
2633     {
2634       if (bl->owner->type != bp_hardware_breakpoint)
2635         {
2636           /* If the explicitly specified breakpoint type
2637              is not hardware breakpoint, check the memory map to see
2638              if the breakpoint address is in read only memory or not.
2639
2640              Two important cases are:
2641              - location type is not hardware breakpoint, memory
2642              is readonly.  We change the type of the location to
2643              hardware breakpoint.
2644              - location type is hardware breakpoint, memory is
2645              read-write.  This means we've previously made the
2646              location hardware one, but then the memory map changed,
2647              so we undo.
2648              
2649              When breakpoints are removed, remove_breakpoints will use
2650              location types we've just set here, the only possible
2651              problem is that memory map has changed during running
2652              program, but it's not going to work anyway with current
2653              gdb.  */
2654           struct mem_region *mr 
2655             = lookup_mem_region (bl->target_info.reqstd_address);
2656           
2657           if (mr)
2658             {
2659               if (automatic_hardware_breakpoints)
2660                 {
2661                   enum bp_loc_type new_type;
2662                   
2663                   if (mr->attrib.mode != MEM_RW)
2664                     new_type = bp_loc_hardware_breakpoint;
2665                   else 
2666                     new_type = bp_loc_software_breakpoint;
2667                   
2668                   if (new_type != bl->loc_type)
2669                     {
2670                       static int said = 0;
2671
2672                       bl->loc_type = new_type;
2673                       if (!said)
2674                         {
2675                           fprintf_filtered (gdb_stdout,
2676                                             _("Note: automatically using "
2677                                               "hardware breakpoints for "
2678                                               "read-only addresses.\n"));
2679                           said = 1;
2680                         }
2681                     }
2682                 }
2683               else if (bl->loc_type == bp_loc_software_breakpoint
2684                        && mr->attrib.mode != MEM_RW)
2685                 {
2686                   fprintf_unfiltered (tmp_error_stream,
2687                                       _("Cannot insert breakpoint %d.\n"
2688                                         "Cannot set software breakpoint "
2689                                         "at read-only address %s\n"),
2690                                       bl->owner->number,
2691                                       paddress (bl->gdbarch, bl->address));
2692                   return 1;
2693                 }
2694             }
2695         }
2696         
2697       /* First check to see if we have to handle an overlay.  */
2698       if (overlay_debugging == ovly_off
2699           || bl->section == NULL
2700           || !(section_is_overlay (bl->section)))
2701         {
2702           /* No overlay handling: just set the breakpoint.  */
2703           TRY
2704             {
2705               int val;
2706
2707               val = bl->owner->ops->insert_location (bl);
2708               if (val)
2709                 bp_err = GENERIC_ERROR;
2710             }
2711           CATCH (e, RETURN_MASK_ALL)
2712             {
2713               bp_err = e.error;
2714               bp_err_message = e.message;
2715             }
2716           END_CATCH
2717         }
2718       else
2719         {
2720           /* This breakpoint is in an overlay section.
2721              Shall we set a breakpoint at the LMA?  */
2722           if (!overlay_events_enabled)
2723             {
2724               /* Yes -- overlay event support is not active, 
2725                  so we must try to set a breakpoint at the LMA.
2726                  This will not work for a hardware breakpoint.  */
2727               if (bl->loc_type == bp_loc_hardware_breakpoint)
2728                 warning (_("hardware breakpoint %d not supported in overlay!"),
2729                          bl->owner->number);
2730               else
2731                 {
2732                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2733                                                              bl->section);
2734                   /* Set a software (trap) breakpoint at the LMA.  */
2735                   bl->overlay_target_info = bl->target_info;
2736                   bl->overlay_target_info.reqstd_address = addr;
2737
2738                   /* No overlay handling: just set the breakpoint.  */
2739                   TRY
2740                     {
2741                       int val;
2742
2743                       val = target_insert_breakpoint (bl->gdbarch,
2744                                                       &bl->overlay_target_info);
2745                       if (val)
2746                         bp_err = GENERIC_ERROR;
2747                     }
2748                   CATCH (e, RETURN_MASK_ALL)
2749                     {
2750                       bp_err = e.error;
2751                       bp_err_message = e.message;
2752                     }
2753                   END_CATCH
2754
2755                   if (bp_err != GDB_NO_ERROR)
2756                     fprintf_unfiltered (tmp_error_stream,
2757                                         "Overlay breakpoint %d "
2758                                         "failed: in ROM?\n",
2759                                         bl->owner->number);
2760                 }
2761             }
2762           /* Shall we set a breakpoint at the VMA? */
2763           if (section_is_mapped (bl->section))
2764             {
2765               /* Yes.  This overlay section is mapped into memory.  */
2766               TRY
2767                 {
2768                   int val;
2769
2770                   val = bl->owner->ops->insert_location (bl);
2771                   if (val)
2772                     bp_err = GENERIC_ERROR;
2773                 }
2774               CATCH (e, RETURN_MASK_ALL)
2775                 {
2776                   bp_err = e.error;
2777                   bp_err_message = e.message;
2778                 }
2779               END_CATCH
2780             }
2781           else
2782             {
2783               /* No.  This breakpoint will not be inserted.  
2784                  No error, but do not mark the bp as 'inserted'.  */
2785               return 0;
2786             }
2787         }
2788
2789       if (bp_err != GDB_NO_ERROR)
2790         {
2791           /* Can't set the breakpoint.  */
2792
2793           /* In some cases, we might not be able to insert a
2794              breakpoint in a shared library that has already been
2795              removed, but we have not yet processed the shlib unload
2796              event.  Unfortunately, some targets that implement
2797              breakpoint insertion themselves can't tell why the
2798              breakpoint insertion failed (e.g., the remote target
2799              doesn't define error codes), so we must treat generic
2800              errors as memory errors.  */
2801           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2802               && bl->loc_type == bp_loc_software_breakpoint
2803               && (solib_name_from_address (bl->pspace, bl->address)
2804                   || shared_objfile_contains_address_p (bl->pspace,
2805                                                         bl->address)))
2806             {
2807               /* See also: disable_breakpoints_in_shlibs.  */
2808               bl->shlib_disabled = 1;
2809               observer_notify_breakpoint_modified (bl->owner);
2810               if (!*disabled_breaks)
2811                 {
2812                   fprintf_unfiltered (tmp_error_stream, 
2813                                       "Cannot insert breakpoint %d.\n", 
2814                                       bl->owner->number);
2815                   fprintf_unfiltered (tmp_error_stream, 
2816                                       "Temporarily disabling shared "
2817                                       "library breakpoints:\n");
2818                 }
2819               *disabled_breaks = 1;
2820               fprintf_unfiltered (tmp_error_stream,
2821                                   "breakpoint #%d\n", bl->owner->number);
2822               return 0;
2823             }
2824           else
2825             {
2826               if (bl->loc_type == bp_loc_hardware_breakpoint)
2827                 {
2828                   *hw_breakpoint_error = 1;
2829                   *hw_bp_error_explained_already = bp_err_message != NULL;
2830                   fprintf_unfiltered (tmp_error_stream,
2831                                       "Cannot insert hardware breakpoint %d%s",
2832                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2833                   if (bp_err_message != NULL)
2834                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2835                 }
2836               else
2837                 {
2838                   if (bp_err_message == NULL)
2839                     {
2840                       char *message
2841                         = memory_error_message (TARGET_XFER_E_IO,
2842                                                 bl->gdbarch, bl->address);
2843                       struct cleanup *old_chain = make_cleanup (xfree, message);
2844
2845                       fprintf_unfiltered (tmp_error_stream,
2846                                           "Cannot insert breakpoint %d.\n"
2847                                           "%s\n",
2848                                           bl->owner->number, message);
2849                       do_cleanups (old_chain);
2850                     }
2851                   else
2852                     {
2853                       fprintf_unfiltered (tmp_error_stream,
2854                                           "Cannot insert breakpoint %d: %s\n",
2855                                           bl->owner->number,
2856                                           bp_err_message);
2857                     }
2858                 }
2859               return 1;
2860
2861             }
2862         }
2863       else
2864         bl->inserted = 1;
2865
2866       return 0;
2867     }
2868
2869   else if (bl->loc_type == bp_loc_hardware_watchpoint
2870            /* NOTE drow/2003-09-08: This state only exists for removing
2871               watchpoints.  It's not clear that it's necessary...  */
2872            && bl->owner->disposition != disp_del_at_next_stop)
2873     {
2874       int val;
2875
2876       gdb_assert (bl->owner->ops != NULL
2877                   && bl->owner->ops->insert_location != NULL);
2878
2879       val = bl->owner->ops->insert_location (bl);
2880
2881       /* If trying to set a read-watchpoint, and it turns out it's not
2882          supported, try emulating one with an access watchpoint.  */
2883       if (val == 1 && bl->watchpoint_type == hw_read)
2884         {
2885           struct bp_location *loc, **loc_temp;
2886
2887           /* But don't try to insert it, if there's already another
2888              hw_access location that would be considered a duplicate
2889              of this one.  */
2890           ALL_BP_LOCATIONS (loc, loc_temp)
2891             if (loc != bl
2892                 && loc->watchpoint_type == hw_access
2893                 && watchpoint_locations_match (bl, loc))
2894               {
2895                 bl->duplicate = 1;
2896                 bl->inserted = 1;
2897                 bl->target_info = loc->target_info;
2898                 bl->watchpoint_type = hw_access;
2899                 val = 0;
2900                 break;
2901               }
2902
2903           if (val == 1)
2904             {
2905               bl->watchpoint_type = hw_access;
2906               val = bl->owner->ops->insert_location (bl);
2907
2908               if (val)
2909                 /* Back to the original value.  */
2910                 bl->watchpoint_type = hw_read;
2911             }
2912         }
2913
2914       bl->inserted = (val == 0);
2915     }
2916
2917   else if (bl->owner->type == bp_catchpoint)
2918     {
2919       int val;
2920
2921       gdb_assert (bl->owner->ops != NULL
2922                   && bl->owner->ops->insert_location != NULL);
2923
2924       val = bl->owner->ops->insert_location (bl);
2925       if (val)
2926         {
2927           bl->owner->enable_state = bp_disabled;
2928
2929           if (val == 1)
2930             warning (_("\
2931 Error inserting catchpoint %d: Your system does not support this type\n\
2932 of catchpoint."), bl->owner->number);
2933           else
2934             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2935         }
2936
2937       bl->inserted = (val == 0);
2938
2939       /* We've already printed an error message if there was a problem
2940          inserting this catchpoint, and we've disabled the catchpoint,
2941          so just return success.  */
2942       return 0;
2943     }
2944
2945   return 0;
2946 }
2947
2948 /* This function is called when program space PSPACE is about to be
2949    deleted.  It takes care of updating breakpoints to not reference
2950    PSPACE anymore.  */
2951
2952 void
2953 breakpoint_program_space_exit (struct program_space *pspace)
2954 {
2955   struct breakpoint *b, *b_temp;
2956   struct bp_location *loc, **loc_temp;
2957
2958   /* Remove any breakpoint that was set through this program space.  */
2959   ALL_BREAKPOINTS_SAFE (b, b_temp)
2960     {
2961       if (b->pspace == pspace)
2962         delete_breakpoint (b);
2963     }
2964
2965   /* Breakpoints set through other program spaces could have locations
2966      bound to PSPACE as well.  Remove those.  */
2967   ALL_BP_LOCATIONS (loc, loc_temp)
2968     {
2969       struct bp_location *tmp;
2970
2971       if (loc->pspace == pspace)
2972         {
2973           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2974           if (loc->owner->loc == loc)
2975             loc->owner->loc = loc->next;
2976           else
2977             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2978               if (tmp->next == loc)
2979                 {
2980                   tmp->next = loc->next;
2981                   break;
2982                 }
2983         }
2984     }
2985
2986   /* Now update the global location list to permanently delete the
2987      removed locations above.  */
2988   update_global_location_list (UGLL_DONT_INSERT);
2989 }
2990
2991 /* Make sure all breakpoints are inserted in inferior.
2992    Throws exception on any error.
2993    A breakpoint that is already inserted won't be inserted
2994    again, so calling this function twice is safe.  */
2995 void
2996 insert_breakpoints (void)
2997 {
2998   struct breakpoint *bpt;
2999
3000   ALL_BREAKPOINTS (bpt)
3001     if (is_hardware_watchpoint (bpt))
3002       {
3003         struct watchpoint *w = (struct watchpoint *) bpt;
3004
3005         update_watchpoint (w, 0 /* don't reparse.  */);
3006       }
3007
3008   /* Updating watchpoints creates new locations, so update the global
3009      location list.  Explicitly tell ugll to insert locations and
3010      ignore breakpoints_always_inserted_mode.  */
3011   update_global_location_list (UGLL_INSERT);
3012 }
3013
3014 /* Invoke CALLBACK for each of bp_location.  */
3015
3016 void
3017 iterate_over_bp_locations (walk_bp_location_callback callback)
3018 {
3019   struct bp_location *loc, **loc_tmp;
3020
3021   ALL_BP_LOCATIONS (loc, loc_tmp)
3022     {
3023       callback (loc, NULL);
3024     }
3025 }
3026
3027 /* This is used when we need to synch breakpoint conditions between GDB and the
3028    target.  It is the case with deleting and disabling of breakpoints when using
3029    always-inserted mode.  */
3030
3031 static void
3032 update_inserted_breakpoint_locations (void)
3033 {
3034   struct bp_location *bl, **blp_tmp;
3035   int error_flag = 0;
3036   int val = 0;
3037   int disabled_breaks = 0;
3038   int hw_breakpoint_error = 0;
3039   int hw_bp_details_reported = 0;
3040
3041   struct ui_file *tmp_error_stream = mem_fileopen ();
3042   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3043
3044   /* Explicitly mark the warning -- this will only be printed if
3045      there was an error.  */
3046   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3047
3048   save_current_space_and_thread ();
3049
3050   ALL_BP_LOCATIONS (bl, blp_tmp)
3051     {
3052       /* We only want to update software breakpoints and hardware
3053          breakpoints.  */
3054       if (!is_breakpoint (bl->owner))
3055         continue;
3056
3057       /* We only want to update locations that are already inserted
3058          and need updating.  This is to avoid unwanted insertion during
3059          deletion of breakpoints.  */
3060       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3061         continue;
3062
3063       switch_to_program_space_and_thread (bl->pspace);
3064
3065       /* For targets that support global breakpoints, there's no need
3066          to select an inferior to insert breakpoint to.  In fact, even
3067          if we aren't attached to any process yet, we should still
3068          insert breakpoints.  */
3069       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3070           && ptid_equal (inferior_ptid, null_ptid))
3071         continue;
3072
3073       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3074                                     &hw_breakpoint_error, &hw_bp_details_reported);
3075       if (val)
3076         error_flag = val;
3077     }
3078
3079   if (error_flag)
3080     {
3081       target_terminal_ours_for_output ();
3082       error_stream (tmp_error_stream);
3083     }
3084
3085   do_cleanups (cleanups);
3086 }
3087
3088 /* Used when starting or continuing the program.  */
3089
3090 static void
3091 insert_breakpoint_locations (void)
3092 {
3093   struct breakpoint *bpt;
3094   struct bp_location *bl, **blp_tmp;
3095   int error_flag = 0;
3096   int val = 0;
3097   int disabled_breaks = 0;
3098   int hw_breakpoint_error = 0;
3099   int hw_bp_error_explained_already = 0;
3100
3101   struct ui_file *tmp_error_stream = mem_fileopen ();
3102   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3103   
3104   /* Explicitly mark the warning -- this will only be printed if
3105      there was an error.  */
3106   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3107
3108   save_current_space_and_thread ();
3109
3110   ALL_BP_LOCATIONS (bl, blp_tmp)
3111     {
3112       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3113         continue;
3114
3115       /* There is no point inserting thread-specific breakpoints if
3116          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3117          has BL->OWNER always non-NULL.  */
3118       if (bl->owner->thread != -1
3119           && !valid_thread_id (bl->owner->thread))
3120         continue;
3121
3122       switch_to_program_space_and_thread (bl->pspace);
3123
3124       /* For targets that support global breakpoints, there's no need
3125          to select an inferior to insert breakpoint to.  In fact, even
3126          if we aren't attached to any process yet, we should still
3127          insert breakpoints.  */
3128       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3129           && ptid_equal (inferior_ptid, null_ptid))
3130         continue;
3131
3132       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3133                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3134       if (val)
3135         error_flag = val;
3136     }
3137
3138   /* If we failed to insert all locations of a watchpoint, remove
3139      them, as half-inserted watchpoint is of limited use.  */
3140   ALL_BREAKPOINTS (bpt)  
3141     {
3142       int some_failed = 0;
3143       struct bp_location *loc;
3144
3145       if (!is_hardware_watchpoint (bpt))
3146         continue;
3147
3148       if (!breakpoint_enabled (bpt))
3149         continue;
3150
3151       if (bpt->disposition == disp_del_at_next_stop)
3152         continue;
3153       
3154       for (loc = bpt->loc; loc; loc = loc->next)
3155         if (!loc->inserted && should_be_inserted (loc))
3156           {
3157             some_failed = 1;
3158             break;
3159           }
3160       if (some_failed)
3161         {
3162           for (loc = bpt->loc; loc; loc = loc->next)
3163             if (loc->inserted)
3164               remove_breakpoint (loc, mark_uninserted);
3165
3166           hw_breakpoint_error = 1;
3167           fprintf_unfiltered (tmp_error_stream,
3168                               "Could not insert hardware watchpoint %d.\n", 
3169                               bpt->number);
3170           error_flag = -1;
3171         }
3172     }
3173
3174   if (error_flag)
3175     {
3176       /* If a hardware breakpoint or watchpoint was inserted, add a
3177          message about possibly exhausted resources.  */
3178       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3179         {
3180           fprintf_unfiltered (tmp_error_stream, 
3181                               "Could not insert hardware breakpoints:\n\
3182 You may have requested too many hardware breakpoints/watchpoints.\n");
3183         }
3184       target_terminal_ours_for_output ();
3185       error_stream (tmp_error_stream);
3186     }
3187
3188   do_cleanups (cleanups);
3189 }
3190
3191 /* Used when the program stops.
3192    Returns zero if successful, or non-zero if there was a problem
3193    removing a breakpoint location.  */
3194
3195 int
3196 remove_breakpoints (void)
3197 {
3198   struct bp_location *bl, **blp_tmp;
3199   int val = 0;
3200
3201   ALL_BP_LOCATIONS (bl, blp_tmp)
3202   {
3203     if (bl->inserted && !is_tracepoint (bl->owner))
3204       val |= remove_breakpoint (bl, mark_uninserted);
3205   }
3206   return val;
3207 }
3208
3209 /* When a thread exits, remove breakpoints that are related to
3210    that thread.  */
3211
3212 static void
3213 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3214 {
3215   struct breakpoint *b, *b_tmp;
3216
3217   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3218     {
3219       if (b->thread == tp->num && user_breakpoint_p (b))
3220         {
3221           b->disposition = disp_del_at_next_stop;
3222
3223           printf_filtered (_("\
3224 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3225                           b->number, tp->num);
3226
3227           /* Hide it from the user.  */
3228           b->number = 0;
3229        }
3230     }
3231 }
3232
3233 /* Remove breakpoints of process PID.  */
3234
3235 int
3236 remove_breakpoints_pid (int pid)
3237 {
3238   struct bp_location *bl, **blp_tmp;
3239   int val;
3240   struct inferior *inf = find_inferior_pid (pid);
3241
3242   ALL_BP_LOCATIONS (bl, blp_tmp)
3243   {
3244     if (bl->pspace != inf->pspace)
3245       continue;
3246
3247     if (bl->inserted && !bl->target_info.persist)
3248       {
3249         val = remove_breakpoint (bl, mark_uninserted);
3250         if (val != 0)
3251           return val;
3252       }
3253   }
3254   return 0;
3255 }
3256
3257 int
3258 reattach_breakpoints (int pid)
3259 {
3260   struct cleanup *old_chain;
3261   struct bp_location *bl, **blp_tmp;
3262   int val;
3263   struct ui_file *tmp_error_stream;
3264   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3265   struct inferior *inf;
3266   struct thread_info *tp;
3267
3268   tp = any_live_thread_of_process (pid);
3269   if (tp == NULL)
3270     return 1;
3271
3272   inf = find_inferior_pid (pid);
3273   old_chain = save_inferior_ptid ();
3274
3275   inferior_ptid = tp->ptid;
3276
3277   tmp_error_stream = mem_fileopen ();
3278   make_cleanup_ui_file_delete (tmp_error_stream);
3279
3280   ALL_BP_LOCATIONS (bl, blp_tmp)
3281   {
3282     if (bl->pspace != inf->pspace)
3283       continue;
3284
3285     if (bl->inserted)
3286       {
3287         bl->inserted = 0;
3288         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3289         if (val != 0)
3290           {
3291             do_cleanups (old_chain);
3292             return val;
3293           }
3294       }
3295   }
3296   do_cleanups (old_chain);
3297   return 0;
3298 }
3299
3300 static int internal_breakpoint_number = -1;
3301
3302 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3303    If INTERNAL is non-zero, the breakpoint number will be populated
3304    from internal_breakpoint_number and that variable decremented.
3305    Otherwise the breakpoint number will be populated from
3306    breakpoint_count and that value incremented.  Internal breakpoints
3307    do not set the internal var bpnum.  */
3308 static void
3309 set_breakpoint_number (int internal, struct breakpoint *b)
3310 {
3311   if (internal)
3312     b->number = internal_breakpoint_number--;
3313   else
3314     {
3315       set_breakpoint_count (breakpoint_count + 1);
3316       b->number = breakpoint_count;
3317     }
3318 }
3319
3320 static struct breakpoint *
3321 create_internal_breakpoint (struct gdbarch *gdbarch,
3322                             CORE_ADDR address, enum bptype type,
3323                             const struct breakpoint_ops *ops)
3324 {
3325   struct symtab_and_line sal;
3326   struct breakpoint *b;
3327
3328   init_sal (&sal);              /* Initialize to zeroes.  */
3329
3330   sal.pc = address;
3331   sal.section = find_pc_overlay (sal.pc);
3332   sal.pspace = current_program_space;
3333
3334   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3335   b->number = internal_breakpoint_number--;
3336   b->disposition = disp_donttouch;
3337
3338   return b;
3339 }
3340
3341 static const char *const longjmp_names[] =
3342   {
3343     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3344   };
3345 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3346
3347 /* Per-objfile data private to breakpoint.c.  */
3348 struct breakpoint_objfile_data
3349 {
3350   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3351   struct bound_minimal_symbol overlay_msym;
3352
3353   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3354   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3355
3356   /* True if we have looked for longjmp probes.  */
3357   int longjmp_searched;
3358
3359   /* SystemTap probe points for longjmp (if any).  */
3360   VEC (probe_p) *longjmp_probes;
3361
3362   /* Minimal symbol for "std::terminate()" (if any).  */
3363   struct bound_minimal_symbol terminate_msym;
3364
3365   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3366   struct bound_minimal_symbol exception_msym;
3367
3368   /* True if we have looked for exception probes.  */
3369   int exception_searched;
3370
3371   /* SystemTap probe points for unwinding (if any).  */
3372   VEC (probe_p) *exception_probes;
3373 };
3374
3375 static const struct objfile_data *breakpoint_objfile_key;
3376
3377 /* Minimal symbol not found sentinel.  */
3378 static struct minimal_symbol msym_not_found;
3379
3380 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3381
3382 static int
3383 msym_not_found_p (const struct minimal_symbol *msym)
3384 {
3385   return msym == &msym_not_found;
3386 }
3387
3388 /* Return per-objfile data needed by breakpoint.c.
3389    Allocate the data if necessary.  */
3390
3391 static struct breakpoint_objfile_data *
3392 get_breakpoint_objfile_data (struct objfile *objfile)
3393 {
3394   struct breakpoint_objfile_data *bp_objfile_data;
3395
3396   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3397   if (bp_objfile_data == NULL)
3398     {
3399       bp_objfile_data =
3400         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3401
3402       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3403       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3404     }
3405   return bp_objfile_data;
3406 }
3407
3408 static void
3409 free_breakpoint_probes (struct objfile *obj, void *data)
3410 {
3411   struct breakpoint_objfile_data *bp_objfile_data = data;
3412
3413   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3414   VEC_free (probe_p, bp_objfile_data->exception_probes);
3415 }
3416
3417 static void
3418 create_overlay_event_breakpoint (void)
3419 {
3420   struct objfile *objfile;
3421   const char *const func_name = "_ovly_debug_event";
3422
3423   ALL_OBJFILES (objfile)
3424     {
3425       struct breakpoint *b;
3426       struct breakpoint_objfile_data *bp_objfile_data;
3427       CORE_ADDR addr;
3428       struct explicit_location explicit_loc;
3429
3430       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3431
3432       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3433         continue;
3434
3435       if (bp_objfile_data->overlay_msym.minsym == NULL)
3436         {
3437           struct bound_minimal_symbol m;
3438
3439           m = lookup_minimal_symbol_text (func_name, objfile);
3440           if (m.minsym == NULL)
3441             {
3442               /* Avoid future lookups in this objfile.  */
3443               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3444               continue;
3445             }
3446           bp_objfile_data->overlay_msym = m;
3447         }
3448
3449       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3450       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3451                                       bp_overlay_event,
3452                                       &internal_breakpoint_ops);
3453       initialize_explicit_location (&explicit_loc);
3454       explicit_loc.function_name = ASTRDUP (func_name);
3455       b->location = new_explicit_location (&explicit_loc);
3456
3457       if (overlay_debugging == ovly_auto)
3458         {
3459           b->enable_state = bp_enabled;
3460           overlay_events_enabled = 1;
3461         }
3462       else
3463        {
3464          b->enable_state = bp_disabled;
3465          overlay_events_enabled = 0;
3466        }
3467     }
3468   update_global_location_list (UGLL_MAY_INSERT);
3469 }
3470
3471 static void
3472 create_longjmp_master_breakpoint (void)
3473 {
3474   struct program_space *pspace;
3475   struct cleanup *old_chain;
3476
3477   old_chain = save_current_program_space ();
3478
3479   ALL_PSPACES (pspace)
3480   {
3481     struct objfile *objfile;
3482
3483     set_current_program_space (pspace);
3484
3485     ALL_OBJFILES (objfile)
3486     {
3487       int i;
3488       struct gdbarch *gdbarch;
3489       struct breakpoint_objfile_data *bp_objfile_data;
3490
3491       gdbarch = get_objfile_arch (objfile);
3492
3493       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3494
3495       if (!bp_objfile_data->longjmp_searched)
3496         {
3497           VEC (probe_p) *ret;
3498
3499           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3500           if (ret != NULL)
3501             {
3502               /* We are only interested in checking one element.  */
3503               struct probe *p = VEC_index (probe_p, ret, 0);
3504
3505               if (!can_evaluate_probe_arguments (p))
3506                 {
3507                   /* We cannot use the probe interface here, because it does
3508                      not know how to evaluate arguments.  */
3509                   VEC_free (probe_p, ret);
3510                   ret = NULL;
3511                 }
3512             }
3513           bp_objfile_data->longjmp_probes = ret;
3514           bp_objfile_data->longjmp_searched = 1;
3515         }
3516
3517       if (bp_objfile_data->longjmp_probes != NULL)
3518         {
3519           int i;
3520           struct probe *probe;
3521           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3522
3523           for (i = 0;
3524                VEC_iterate (probe_p,
3525                             bp_objfile_data->longjmp_probes,
3526                             i, probe);
3527                ++i)
3528             {
3529               struct breakpoint *b;
3530
3531               b = create_internal_breakpoint (gdbarch,
3532                                               get_probe_address (probe,
3533                                                                  objfile),
3534                                               bp_longjmp_master,
3535                                               &internal_breakpoint_ops);
3536               b->location
3537                 = new_probe_location ("-probe-stap libc:longjmp");
3538               b->enable_state = bp_disabled;
3539             }
3540
3541           continue;
3542         }
3543
3544       if (!gdbarch_get_longjmp_target_p (gdbarch))
3545         continue;
3546
3547       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3548         {
3549           struct breakpoint *b;
3550           const char *func_name;
3551           CORE_ADDR addr;
3552           struct explicit_location explicit_loc;
3553
3554           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3555             continue;
3556
3557           func_name = longjmp_names[i];
3558           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3559             {
3560               struct bound_minimal_symbol m;
3561
3562               m = lookup_minimal_symbol_text (func_name, objfile);
3563               if (m.minsym == NULL)
3564                 {
3565                   /* Prevent future lookups in this objfile.  */
3566                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3567                   continue;
3568                 }
3569               bp_objfile_data->longjmp_msym[i] = m;
3570             }
3571
3572           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3573           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3574                                           &internal_breakpoint_ops);
3575           initialize_explicit_location (&explicit_loc);
3576           explicit_loc.function_name = ASTRDUP (func_name);
3577           b->location = new_explicit_location (&explicit_loc);
3578           b->enable_state = bp_disabled;
3579         }
3580     }
3581   }
3582   update_global_location_list (UGLL_MAY_INSERT);
3583
3584   do_cleanups (old_chain);
3585 }
3586
3587 /* Create a master std::terminate breakpoint.  */
3588 static void
3589 create_std_terminate_master_breakpoint (void)
3590 {
3591   struct program_space *pspace;
3592   struct cleanup *old_chain;
3593   const char *const func_name = "std::terminate()";
3594
3595   old_chain = save_current_program_space ();
3596
3597   ALL_PSPACES (pspace)
3598   {
3599     struct objfile *objfile;
3600     CORE_ADDR addr;
3601
3602     set_current_program_space (pspace);
3603
3604     ALL_OBJFILES (objfile)
3605     {
3606       struct breakpoint *b;
3607       struct breakpoint_objfile_data *bp_objfile_data;
3608       struct explicit_location explicit_loc;
3609
3610       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3611
3612       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3613         continue;
3614
3615       if (bp_objfile_data->terminate_msym.minsym == NULL)
3616         {
3617           struct bound_minimal_symbol m;
3618
3619           m = lookup_minimal_symbol (func_name, NULL, objfile);
3620           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3621                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3622             {
3623               /* Prevent future lookups in this objfile.  */
3624               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3625               continue;
3626             }
3627           bp_objfile_data->terminate_msym = m;
3628         }
3629
3630       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3631       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3632                                       bp_std_terminate_master,
3633                                       &internal_breakpoint_ops);
3634       initialize_explicit_location (&explicit_loc);
3635       explicit_loc.function_name = ASTRDUP (func_name);
3636       b->location = new_explicit_location (&explicit_loc);
3637       b->enable_state = bp_disabled;
3638     }
3639   }
3640
3641   update_global_location_list (UGLL_MAY_INSERT);
3642
3643   do_cleanups (old_chain);
3644 }
3645
3646 /* Install a master breakpoint on the unwinder's debug hook.  */
3647
3648 static void
3649 create_exception_master_breakpoint (void)
3650 {
3651   struct objfile *objfile;
3652   const char *const func_name = "_Unwind_DebugHook";
3653
3654   ALL_OBJFILES (objfile)
3655     {
3656       struct breakpoint *b;
3657       struct gdbarch *gdbarch;
3658       struct breakpoint_objfile_data *bp_objfile_data;
3659       CORE_ADDR addr;
3660       struct explicit_location explicit_loc;
3661
3662       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3663
3664       /* We prefer the SystemTap probe point if it exists.  */
3665       if (!bp_objfile_data->exception_searched)
3666         {
3667           VEC (probe_p) *ret;
3668
3669           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3670
3671           if (ret != NULL)
3672             {
3673               /* We are only interested in checking one element.  */
3674               struct probe *p = VEC_index (probe_p, ret, 0);
3675
3676               if (!can_evaluate_probe_arguments (p))
3677                 {
3678                   /* We cannot use the probe interface here, because it does
3679                      not know how to evaluate arguments.  */
3680                   VEC_free (probe_p, ret);
3681                   ret = NULL;
3682                 }
3683             }
3684           bp_objfile_data->exception_probes = ret;
3685           bp_objfile_data->exception_searched = 1;
3686         }
3687
3688       if (bp_objfile_data->exception_probes != NULL)
3689         {
3690           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3691           int i;
3692           struct probe *probe;
3693
3694           for (i = 0;
3695                VEC_iterate (probe_p,
3696                             bp_objfile_data->exception_probes,
3697                             i, probe);
3698                ++i)
3699             {
3700               struct breakpoint *b;
3701
3702               b = create_internal_breakpoint (gdbarch,
3703                                               get_probe_address (probe,
3704                                                                  objfile),
3705                                               bp_exception_master,
3706                                               &internal_breakpoint_ops);
3707               b->location
3708                 = new_probe_location ("-probe-stap libgcc:unwind");
3709               b->enable_state = bp_disabled;
3710             }
3711
3712           continue;
3713         }
3714
3715       /* Otherwise, try the hook function.  */
3716
3717       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3718         continue;
3719
3720       gdbarch = get_objfile_arch (objfile);
3721
3722       if (bp_objfile_data->exception_msym.minsym == NULL)
3723         {
3724           struct bound_minimal_symbol debug_hook;
3725
3726           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3727           if (debug_hook.minsym == NULL)
3728             {
3729               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3730               continue;
3731             }
3732
3733           bp_objfile_data->exception_msym = debug_hook;
3734         }
3735
3736       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3737       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3738                                                  &current_target);
3739       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3740                                       &internal_breakpoint_ops);
3741       initialize_explicit_location (&explicit_loc);
3742       explicit_loc.function_name = ASTRDUP (func_name);
3743       b->location = new_explicit_location (&explicit_loc);
3744       b->enable_state = bp_disabled;
3745     }
3746
3747   update_global_location_list (UGLL_MAY_INSERT);
3748 }
3749
3750 void
3751 update_breakpoints_after_exec (void)
3752 {
3753   struct breakpoint *b, *b_tmp;
3754   struct bp_location *bploc, **bplocp_tmp;
3755
3756   /* We're about to delete breakpoints from GDB's lists.  If the
3757      INSERTED flag is true, GDB will try to lift the breakpoints by
3758      writing the breakpoints' "shadow contents" back into memory.  The
3759      "shadow contents" are NOT valid after an exec, so GDB should not
3760      do that.  Instead, the target is responsible from marking
3761      breakpoints out as soon as it detects an exec.  We don't do that
3762      here instead, because there may be other attempts to delete
3763      breakpoints after detecting an exec and before reaching here.  */
3764   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3765     if (bploc->pspace == current_program_space)
3766       gdb_assert (!bploc->inserted);
3767
3768   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3769   {
3770     if (b->pspace != current_program_space)
3771       continue;
3772
3773     /* Solib breakpoints must be explicitly reset after an exec().  */
3774     if (b->type == bp_shlib_event)
3775       {
3776         delete_breakpoint (b);
3777         continue;
3778       }
3779
3780     /* JIT breakpoints must be explicitly reset after an exec().  */
3781     if (b->type == bp_jit_event)
3782       {
3783         delete_breakpoint (b);
3784         continue;
3785       }
3786
3787     /* Thread event breakpoints must be set anew after an exec(),
3788        as must overlay event and longjmp master breakpoints.  */
3789     if (b->type == bp_thread_event || b->type == bp_overlay_event
3790         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3791         || b->type == bp_exception_master)
3792       {
3793         delete_breakpoint (b);
3794         continue;
3795       }
3796
3797     /* Step-resume breakpoints are meaningless after an exec().  */
3798     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3799       {
3800         delete_breakpoint (b);
3801         continue;
3802       }
3803
3804     /* Just like single-step breakpoints.  */
3805     if (b->type == bp_single_step)
3806       {
3807         delete_breakpoint (b);
3808         continue;
3809       }
3810
3811     /* Longjmp and longjmp-resume breakpoints are also meaningless
3812        after an exec.  */
3813     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3814         || b->type == bp_longjmp_call_dummy
3815         || b->type == bp_exception || b->type == bp_exception_resume)
3816       {
3817         delete_breakpoint (b);
3818         continue;
3819       }
3820
3821     if (b->type == bp_catchpoint)
3822       {
3823         /* For now, none of the bp_catchpoint breakpoints need to
3824            do anything at this point.  In the future, if some of
3825            the catchpoints need to something, we will need to add
3826            a new method, and call this method from here.  */
3827         continue;
3828       }
3829
3830     /* bp_finish is a special case.  The only way we ought to be able
3831        to see one of these when an exec() has happened, is if the user
3832        caught a vfork, and then said "finish".  Ordinarily a finish just
3833        carries them to the call-site of the current callee, by setting
3834        a temporary bp there and resuming.  But in this case, the finish
3835        will carry them entirely through the vfork & exec.
3836
3837        We don't want to allow a bp_finish to remain inserted now.  But
3838        we can't safely delete it, 'cause finish_command has a handle to
3839        the bp on a bpstat, and will later want to delete it.  There's a
3840        chance (and I've seen it happen) that if we delete the bp_finish
3841        here, that its storage will get reused by the time finish_command
3842        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3843        We really must allow finish_command to delete a bp_finish.
3844
3845        In the absence of a general solution for the "how do we know
3846        it's safe to delete something others may have handles to?"
3847        problem, what we'll do here is just uninsert the bp_finish, and
3848        let finish_command delete it.
3849
3850        (We know the bp_finish is "doomed" in the sense that it's
3851        momentary, and will be deleted as soon as finish_command sees
3852        the inferior stopped.  So it doesn't matter that the bp's
3853        address is probably bogus in the new a.out, unlike e.g., the
3854        solib breakpoints.)  */
3855
3856     if (b->type == bp_finish)
3857       {
3858         continue;
3859       }
3860
3861     /* Without a symbolic address, we have little hope of the
3862        pre-exec() address meaning the same thing in the post-exec()
3863        a.out.  */
3864     if (event_location_empty_p (b->location))
3865       {
3866         delete_breakpoint (b);
3867         continue;
3868       }
3869   }
3870 }
3871
3872 int
3873 detach_breakpoints (ptid_t ptid)
3874 {
3875   struct bp_location *bl, **blp_tmp;
3876   int val = 0;
3877   struct cleanup *old_chain = save_inferior_ptid ();
3878   struct inferior *inf = current_inferior ();
3879
3880   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3881     error (_("Cannot detach breakpoints of inferior_ptid"));
3882
3883   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3884   inferior_ptid = ptid;
3885   ALL_BP_LOCATIONS (bl, blp_tmp)
3886   {
3887     if (bl->pspace != inf->pspace)
3888       continue;
3889
3890     /* This function must physically remove breakpoints locations
3891        from the specified ptid, without modifying the breakpoint
3892        package's state.  Locations of type bp_loc_other are only
3893        maintained at GDB side.  So, there is no need to remove
3894        these bp_loc_other locations.  Moreover, removing these
3895        would modify the breakpoint package's state.  */
3896     if (bl->loc_type == bp_loc_other)
3897       continue;
3898
3899     if (bl->inserted)
3900       val |= remove_breakpoint_1 (bl, mark_inserted);
3901   }
3902
3903   do_cleanups (old_chain);
3904   return val;
3905 }
3906
3907 /* Remove the breakpoint location BL from the current address space.
3908    Note that this is used to detach breakpoints from a child fork.
3909    When we get here, the child isn't in the inferior list, and neither
3910    do we have objects to represent its address space --- we should
3911    *not* look at bl->pspace->aspace here.  */
3912
3913 static int
3914 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3915 {
3916   int val;
3917
3918   /* BL is never in moribund_locations by our callers.  */
3919   gdb_assert (bl->owner != NULL);
3920
3921   /* The type of none suggests that owner is actually deleted.
3922      This should not ever happen.  */
3923   gdb_assert (bl->owner->type != bp_none);
3924
3925   if (bl->loc_type == bp_loc_software_breakpoint
3926       || bl->loc_type == bp_loc_hardware_breakpoint)
3927     {
3928       /* "Normal" instruction breakpoint: either the standard
3929          trap-instruction bp (bp_breakpoint), or a
3930          bp_hardware_breakpoint.  */
3931
3932       /* First check to see if we have to handle an overlay.  */
3933       if (overlay_debugging == ovly_off
3934           || bl->section == NULL
3935           || !(section_is_overlay (bl->section)))
3936         {
3937           /* No overlay handling: just remove the breakpoint.  */
3938
3939           /* If we're trying to uninsert a memory breakpoint that we
3940              know is set in a dynamic object that is marked
3941              shlib_disabled, then either the dynamic object was
3942              removed with "remove-symbol-file" or with
3943              "nosharedlibrary".  In the former case, we don't know
3944              whether another dynamic object might have loaded over the
3945              breakpoint's address -- the user might well let us know
3946              about it next with add-symbol-file (the whole point of
3947              add-symbol-file is letting the user manually maintain a
3948              list of dynamically loaded objects).  If we have the
3949              breakpoint's shadow memory, that is, this is a software
3950              breakpoint managed by GDB, check whether the breakpoint
3951              is still inserted in memory, to avoid overwriting wrong
3952              code with stale saved shadow contents.  Note that HW
3953              breakpoints don't have shadow memory, as they're
3954              implemented using a mechanism that is not dependent on
3955              being able to modify the target's memory, and as such
3956              they should always be removed.  */
3957           if (bl->shlib_disabled
3958               && bl->target_info.shadow_len != 0
3959               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3960             val = 0;
3961           else
3962             val = bl->owner->ops->remove_location (bl);
3963         }
3964       else
3965         {
3966           /* This breakpoint is in an overlay section.
3967              Did we set a breakpoint at the LMA?  */
3968           if (!overlay_events_enabled)
3969               {
3970                 /* Yes -- overlay event support is not active, so we
3971                    should have set a breakpoint at the LMA.  Remove it.  
3972                 */
3973                 /* Ignore any failures: if the LMA is in ROM, we will
3974                    have already warned when we failed to insert it.  */
3975                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3976                   target_remove_hw_breakpoint (bl->gdbarch,
3977                                                &bl->overlay_target_info);
3978                 else
3979                   target_remove_breakpoint (bl->gdbarch,
3980                                             &bl->overlay_target_info);
3981               }
3982           /* Did we set a breakpoint at the VMA? 
3983              If so, we will have marked the breakpoint 'inserted'.  */
3984           if (bl->inserted)
3985             {
3986               /* Yes -- remove it.  Previously we did not bother to
3987                  remove the breakpoint if the section had been
3988                  unmapped, but let's not rely on that being safe.  We
3989                  don't know what the overlay manager might do.  */
3990
3991               /* However, we should remove *software* breakpoints only
3992                  if the section is still mapped, or else we overwrite
3993                  wrong code with the saved shadow contents.  */
3994               if (bl->loc_type == bp_loc_hardware_breakpoint
3995                   || section_is_mapped (bl->section))
3996                 val = bl->owner->ops->remove_location (bl);
3997               else
3998                 val = 0;
3999             }
4000           else
4001             {
4002               /* No -- not inserted, so no need to remove.  No error.  */
4003               val = 0;
4004             }
4005         }
4006
4007       /* In some cases, we might not be able to remove a breakpoint in
4008          a shared library that has already been removed, but we have
4009          not yet processed the shlib unload event.  Similarly for an
4010          unloaded add-symbol-file object - the user might not yet have
4011          had the chance to remove-symbol-file it.  shlib_disabled will
4012          be set if the library/object has already been removed, but
4013          the breakpoint hasn't been uninserted yet, e.g., after
4014          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4015          always-inserted mode.  */
4016       if (val
4017           && (bl->loc_type == bp_loc_software_breakpoint
4018               && (bl->shlib_disabled
4019                   || solib_name_from_address (bl->pspace, bl->address)
4020                   || shared_objfile_contains_address_p (bl->pspace,
4021                                                         bl->address))))
4022         val = 0;
4023
4024       if (val)
4025         return val;
4026       bl->inserted = (is == mark_inserted);
4027     }
4028   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4029     {
4030       gdb_assert (bl->owner->ops != NULL
4031                   && bl->owner->ops->remove_location != NULL);
4032
4033       bl->inserted = (is == mark_inserted);
4034       bl->owner->ops->remove_location (bl);
4035
4036       /* Failure to remove any of the hardware watchpoints comes here.  */
4037       if ((is == mark_uninserted) && (bl->inserted))
4038         warning (_("Could not remove hardware watchpoint %d."),
4039                  bl->owner->number);
4040     }
4041   else if (bl->owner->type == bp_catchpoint
4042            && breakpoint_enabled (bl->owner)
4043            && !bl->duplicate)
4044     {
4045       gdb_assert (bl->owner->ops != NULL
4046                   && bl->owner->ops->remove_location != NULL);
4047
4048       val = bl->owner->ops->remove_location (bl);
4049       if (val)
4050         return val;
4051
4052       bl->inserted = (is == mark_inserted);
4053     }
4054
4055   return 0;
4056 }
4057
4058 static int
4059 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4060 {
4061   int ret;
4062   struct cleanup *old_chain;
4063
4064   /* BL is never in moribund_locations by our callers.  */
4065   gdb_assert (bl->owner != NULL);
4066
4067   /* The type of none suggests that owner is actually deleted.
4068      This should not ever happen.  */
4069   gdb_assert (bl->owner->type != bp_none);
4070
4071   old_chain = save_current_space_and_thread ();
4072
4073   switch_to_program_space_and_thread (bl->pspace);
4074
4075   ret = remove_breakpoint_1 (bl, is);
4076
4077   do_cleanups (old_chain);
4078   return ret;
4079 }
4080
4081 /* Clear the "inserted" flag in all breakpoints.  */
4082
4083 void
4084 mark_breakpoints_out (void)
4085 {
4086   struct bp_location *bl, **blp_tmp;
4087
4088   ALL_BP_LOCATIONS (bl, blp_tmp)
4089     if (bl->pspace == current_program_space)
4090       bl->inserted = 0;
4091 }
4092
4093 /* Clear the "inserted" flag in all breakpoints and delete any
4094    breakpoints which should go away between runs of the program.
4095
4096    Plus other such housekeeping that has to be done for breakpoints
4097    between runs.
4098
4099    Note: this function gets called at the end of a run (by
4100    generic_mourn_inferior) and when a run begins (by
4101    init_wait_for_inferior).  */
4102
4103
4104
4105 void
4106 breakpoint_init_inferior (enum inf_context context)
4107 {
4108   struct breakpoint *b, *b_tmp;
4109   struct bp_location *bl, **blp_tmp;
4110   int ix;
4111   struct program_space *pspace = current_program_space;
4112
4113   /* If breakpoint locations are shared across processes, then there's
4114      nothing to do.  */
4115   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4116     return;
4117
4118   mark_breakpoints_out ();
4119
4120   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4121   {
4122     if (b->loc && b->loc->pspace != pspace)
4123       continue;
4124
4125     switch (b->type)
4126       {
4127       case bp_call_dummy:
4128       case bp_longjmp_call_dummy:
4129
4130         /* If the call dummy breakpoint is at the entry point it will
4131            cause problems when the inferior is rerun, so we better get
4132            rid of it.  */
4133
4134       case bp_watchpoint_scope:
4135
4136         /* Also get rid of scope breakpoints.  */
4137
4138       case bp_shlib_event:
4139
4140         /* Also remove solib event breakpoints.  Their addresses may
4141            have changed since the last time we ran the program.
4142            Actually we may now be debugging against different target;
4143            and so the solib backend that installed this breakpoint may
4144            not be used in by the target.  E.g.,
4145
4146            (gdb) file prog-linux
4147            (gdb) run               # native linux target
4148            ...
4149            (gdb) kill
4150            (gdb) file prog-win.exe
4151            (gdb) tar rem :9999     # remote Windows gdbserver.
4152         */
4153
4154       case bp_step_resume:
4155
4156         /* Also remove step-resume breakpoints.  */
4157
4158       case bp_single_step:
4159
4160         /* Also remove single-step breakpoints.  */
4161
4162         delete_breakpoint (b);
4163         break;
4164
4165       case bp_watchpoint:
4166       case bp_hardware_watchpoint:
4167       case bp_read_watchpoint:
4168       case bp_access_watchpoint:
4169         {
4170           struct watchpoint *w = (struct watchpoint *) b;
4171
4172           /* Likewise for watchpoints on local expressions.  */
4173           if (w->exp_valid_block != NULL)
4174             delete_breakpoint (b);
4175           else if (context == inf_starting)
4176             {
4177               /* Reset val field to force reread of starting value in
4178                  insert_breakpoints.  */
4179               if (w->val)
4180                 value_free (w->val);
4181               w->val = NULL;
4182               w->val_valid = 0;
4183           }
4184         }
4185         break;
4186       default:
4187         break;
4188       }
4189   }
4190
4191   /* Get rid of the moribund locations.  */
4192   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4193     decref_bp_location (&bl);
4194   VEC_free (bp_location_p, moribund_locations);
4195 }
4196
4197 /* These functions concern about actual breakpoints inserted in the
4198    target --- to e.g. check if we need to do decr_pc adjustment or if
4199    we need to hop over the bkpt --- so we check for address space
4200    match, not program space.  */
4201
4202 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4203    exists at PC.  It returns ordinary_breakpoint_here if it's an
4204    ordinary breakpoint, or permanent_breakpoint_here if it's a
4205    permanent breakpoint.
4206    - When continuing from a location with an ordinary breakpoint, we
4207      actually single step once before calling insert_breakpoints.
4208    - When continuing from a location with a permanent breakpoint, we
4209      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4210      the target, to advance the PC past the breakpoint.  */
4211
4212 enum breakpoint_here
4213 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4214 {
4215   struct bp_location *bl, **blp_tmp;
4216   int any_breakpoint_here = 0;
4217
4218   ALL_BP_LOCATIONS (bl, blp_tmp)
4219     {
4220       if (bl->loc_type != bp_loc_software_breakpoint
4221           && bl->loc_type != bp_loc_hardware_breakpoint)
4222         continue;
4223
4224       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4225       if ((breakpoint_enabled (bl->owner)
4226            || bl->permanent)
4227           && breakpoint_location_address_match (bl, aspace, pc))
4228         {
4229           if (overlay_debugging 
4230               && section_is_overlay (bl->section)
4231               && !section_is_mapped (bl->section))
4232             continue;           /* unmapped overlay -- can't be a match */
4233           else if (bl->permanent)
4234             return permanent_breakpoint_here;
4235           else
4236             any_breakpoint_here = 1;
4237         }
4238     }
4239
4240   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4241 }
4242
4243 /* Return true if there's a moribund breakpoint at PC.  */
4244
4245 int
4246 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4247 {
4248   struct bp_location *loc;
4249   int ix;
4250
4251   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4252     if (breakpoint_location_address_match (loc, aspace, pc))
4253       return 1;
4254
4255   return 0;
4256 }
4257
4258 /* Returns non-zero iff BL is inserted at PC, in address space
4259    ASPACE.  */
4260
4261 static int
4262 bp_location_inserted_here_p (struct bp_location *bl,
4263                              struct address_space *aspace, CORE_ADDR pc)
4264 {
4265   if (bl->inserted
4266       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4267                                    aspace, pc))
4268     {
4269       if (overlay_debugging
4270           && section_is_overlay (bl->section)
4271           && !section_is_mapped (bl->section))
4272         return 0;               /* unmapped overlay -- can't be a match */
4273       else
4274         return 1;
4275     }
4276   return 0;
4277 }
4278
4279 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4280
4281 int
4282 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4283 {
4284   struct bp_location **blp, **blp_tmp = NULL;
4285   struct bp_location *bl;
4286
4287   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4288     {
4289       struct bp_location *bl = *blp;
4290
4291       if (bl->loc_type != bp_loc_software_breakpoint
4292           && bl->loc_type != bp_loc_hardware_breakpoint)
4293         continue;
4294
4295       if (bp_location_inserted_here_p (bl, aspace, pc))
4296         return 1;
4297     }
4298   return 0;
4299 }
4300
4301 /* This function returns non-zero iff there is a software breakpoint
4302    inserted at PC.  */
4303
4304 int
4305 software_breakpoint_inserted_here_p (struct address_space *aspace,
4306                                      CORE_ADDR pc)
4307 {
4308   struct bp_location **blp, **blp_tmp = NULL;
4309   struct bp_location *bl;
4310
4311   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4312     {
4313       struct bp_location *bl = *blp;
4314
4315       if (bl->loc_type != bp_loc_software_breakpoint)
4316         continue;
4317
4318       if (bp_location_inserted_here_p (bl, aspace, pc))
4319         return 1;
4320     }
4321
4322   return 0;
4323 }
4324
4325 /* See breakpoint.h.  */
4326
4327 int
4328 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4329                                      CORE_ADDR pc)
4330 {
4331   struct bp_location **blp, **blp_tmp = NULL;
4332   struct bp_location *bl;
4333
4334   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4335     {
4336       struct bp_location *bl = *blp;
4337
4338       if (bl->loc_type != bp_loc_hardware_breakpoint)
4339         continue;
4340
4341       if (bp_location_inserted_here_p (bl, aspace, pc))
4342         return 1;
4343     }
4344
4345   return 0;
4346 }
4347
4348 int
4349 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4350                                        CORE_ADDR addr, ULONGEST len)
4351 {
4352   struct breakpoint *bpt;
4353
4354   ALL_BREAKPOINTS (bpt)
4355     {
4356       struct bp_location *loc;
4357
4358       if (bpt->type != bp_hardware_watchpoint
4359           && bpt->type != bp_access_watchpoint)
4360         continue;
4361
4362       if (!breakpoint_enabled (bpt))
4363         continue;
4364
4365       for (loc = bpt->loc; loc; loc = loc->next)
4366         if (loc->pspace->aspace == aspace && loc->inserted)
4367           {
4368             CORE_ADDR l, h;
4369
4370             /* Check for intersection.  */
4371             l = max (loc->address, addr);
4372             h = min (loc->address + loc->length, addr + len);
4373             if (l < h)
4374               return 1;
4375           }
4376     }
4377   return 0;
4378 }
4379 \f
4380
4381 /* bpstat stuff.  External routines' interfaces are documented
4382    in breakpoint.h.  */
4383
4384 int
4385 is_catchpoint (struct breakpoint *ep)
4386 {
4387   return (ep->type == bp_catchpoint);
4388 }
4389
4390 /* Frees any storage that is part of a bpstat.  Does not walk the
4391    'next' chain.  */
4392
4393 static void
4394 bpstat_free (bpstat bs)
4395 {
4396   if (bs->old_val != NULL)
4397     value_free (bs->old_val);
4398   decref_counted_command_line (&bs->commands);
4399   decref_bp_location (&bs->bp_location_at);
4400   xfree (bs);
4401 }
4402
4403 /* Clear a bpstat so that it says we are not at any breakpoint.
4404    Also free any storage that is part of a bpstat.  */
4405
4406 void
4407 bpstat_clear (bpstat *bsp)
4408 {
4409   bpstat p;
4410   bpstat q;
4411
4412   if (bsp == 0)
4413     return;
4414   p = *bsp;
4415   while (p != NULL)
4416     {
4417       q = p->next;
4418       bpstat_free (p);
4419       p = q;
4420     }
4421   *bsp = NULL;
4422 }
4423
4424 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4425    is part of the bpstat is copied as well.  */
4426
4427 bpstat
4428 bpstat_copy (bpstat bs)
4429 {
4430   bpstat p = NULL;
4431   bpstat tmp;
4432   bpstat retval = NULL;
4433
4434   if (bs == NULL)
4435     return bs;
4436
4437   for (; bs != NULL; bs = bs->next)
4438     {
4439       tmp = (bpstat) xmalloc (sizeof (*tmp));
4440       memcpy (tmp, bs, sizeof (*tmp));
4441       incref_counted_command_line (tmp->commands);
4442       incref_bp_location (tmp->bp_location_at);
4443       if (bs->old_val != NULL)
4444         {
4445           tmp->old_val = value_copy (bs->old_val);
4446           release_value (tmp->old_val);
4447         }
4448
4449       if (p == NULL)
4450         /* This is the first thing in the chain.  */
4451         retval = tmp;
4452       else
4453         p->next = tmp;
4454       p = tmp;
4455     }
4456   p->next = NULL;
4457   return retval;
4458 }
4459
4460 /* Find the bpstat associated with this breakpoint.  */
4461
4462 bpstat
4463 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4464 {
4465   if (bsp == NULL)
4466     return NULL;
4467
4468   for (; bsp != NULL; bsp = bsp->next)
4469     {
4470       if (bsp->breakpoint_at == breakpoint)
4471         return bsp;
4472     }
4473   return NULL;
4474 }
4475
4476 /* See breakpoint.h.  */
4477
4478 int
4479 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4480 {
4481   for (; bsp != NULL; bsp = bsp->next)
4482     {
4483       if (bsp->breakpoint_at == NULL)
4484         {
4485           /* A moribund location can never explain a signal other than
4486              GDB_SIGNAL_TRAP.  */
4487           if (sig == GDB_SIGNAL_TRAP)
4488             return 1;
4489         }
4490       else
4491         {
4492           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4493                                                         sig))
4494             return 1;
4495         }
4496     }
4497
4498   return 0;
4499 }
4500
4501 /* Put in *NUM the breakpoint number of the first breakpoint we are
4502    stopped at.  *BSP upon return is a bpstat which points to the
4503    remaining breakpoints stopped at (but which is not guaranteed to be
4504    good for anything but further calls to bpstat_num).
4505
4506    Return 0 if passed a bpstat which does not indicate any breakpoints.
4507    Return -1 if stopped at a breakpoint that has been deleted since
4508    we set it.
4509    Return 1 otherwise.  */
4510
4511 int
4512 bpstat_num (bpstat *bsp, int *num)
4513 {
4514   struct breakpoint *b;
4515
4516   if ((*bsp) == NULL)
4517     return 0;                   /* No more breakpoint values */
4518
4519   /* We assume we'll never have several bpstats that correspond to a
4520      single breakpoint -- otherwise, this function might return the
4521      same number more than once and this will look ugly.  */
4522   b = (*bsp)->breakpoint_at;
4523   *bsp = (*bsp)->next;
4524   if (b == NULL)
4525     return -1;                  /* breakpoint that's been deleted since */
4526
4527   *num = b->number;             /* We have its number */
4528   return 1;
4529 }
4530
4531 /* See breakpoint.h.  */
4532
4533 void
4534 bpstat_clear_actions (void)
4535 {
4536   struct thread_info *tp;
4537   bpstat bs;
4538
4539   if (ptid_equal (inferior_ptid, null_ptid))
4540     return;
4541
4542   tp = find_thread_ptid (inferior_ptid);
4543   if (tp == NULL)
4544     return;
4545
4546   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4547     {
4548       decref_counted_command_line (&bs->commands);
4549
4550       if (bs->old_val != NULL)
4551         {
4552           value_free (bs->old_val);
4553           bs->old_val = NULL;
4554         }
4555     }
4556 }
4557
4558 /* Called when a command is about to proceed the inferior.  */
4559
4560 static void
4561 breakpoint_about_to_proceed (void)
4562 {
4563   if (!ptid_equal (inferior_ptid, null_ptid))
4564     {
4565       struct thread_info *tp = inferior_thread ();
4566
4567       /* Allow inferior function calls in breakpoint commands to not
4568          interrupt the command list.  When the call finishes
4569          successfully, the inferior will be standing at the same
4570          breakpoint as if nothing happened.  */
4571       if (tp->control.in_infcall)
4572         return;
4573     }
4574
4575   breakpoint_proceeded = 1;
4576 }
4577
4578 /* Stub for cleaning up our state if we error-out of a breakpoint
4579    command.  */
4580 static void
4581 cleanup_executing_breakpoints (void *ignore)
4582 {
4583   executing_breakpoint_commands = 0;
4584 }
4585
4586 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4587    or its equivalent.  */
4588
4589 static int
4590 command_line_is_silent (struct command_line *cmd)
4591 {
4592   return cmd && (strcmp ("silent", cmd->line) == 0);
4593 }
4594
4595 /* Execute all the commands associated with all the breakpoints at
4596    this location.  Any of these commands could cause the process to
4597    proceed beyond this point, etc.  We look out for such changes by
4598    checking the global "breakpoint_proceeded" after each command.
4599
4600    Returns true if a breakpoint command resumed the inferior.  In that
4601    case, it is the caller's responsibility to recall it again with the
4602    bpstat of the current thread.  */
4603
4604 static int
4605 bpstat_do_actions_1 (bpstat *bsp)
4606 {
4607   bpstat bs;
4608   struct cleanup *old_chain;
4609   int again = 0;
4610
4611   /* Avoid endless recursion if a `source' command is contained
4612      in bs->commands.  */
4613   if (executing_breakpoint_commands)
4614     return 0;
4615
4616   executing_breakpoint_commands = 1;
4617   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4618
4619   prevent_dont_repeat ();
4620
4621   /* This pointer will iterate over the list of bpstat's.  */
4622   bs = *bsp;
4623
4624   breakpoint_proceeded = 0;
4625   for (; bs != NULL; bs = bs->next)
4626     {
4627       struct counted_command_line *ccmd;
4628       struct command_line *cmd;
4629       struct cleanup *this_cmd_tree_chain;
4630
4631       /* Take ownership of the BSP's command tree, if it has one.
4632
4633          The command tree could legitimately contain commands like
4634          'step' and 'next', which call clear_proceed_status, which
4635          frees stop_bpstat's command tree.  To make sure this doesn't
4636          free the tree we're executing out from under us, we need to
4637          take ownership of the tree ourselves.  Since a given bpstat's
4638          commands are only executed once, we don't need to copy it; we
4639          can clear the pointer in the bpstat, and make sure we free
4640          the tree when we're done.  */
4641       ccmd = bs->commands;
4642       bs->commands = NULL;
4643       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4644       cmd = ccmd ? ccmd->commands : NULL;
4645       if (command_line_is_silent (cmd))
4646         {
4647           /* The action has been already done by bpstat_stop_status.  */
4648           cmd = cmd->next;
4649         }
4650
4651       while (cmd != NULL)
4652         {
4653           execute_control_command (cmd);
4654
4655           if (breakpoint_proceeded)
4656             break;
4657           else
4658             cmd = cmd->next;
4659         }
4660
4661       /* We can free this command tree now.  */
4662       do_cleanups (this_cmd_tree_chain);
4663
4664       if (breakpoint_proceeded)
4665         {
4666           if (interpreter_async)
4667             /* If we are in async mode, then the target might be still
4668                running, not stopped at any breakpoint, so nothing for
4669                us to do here -- just return to the event loop.  */
4670             ;
4671           else
4672             /* In sync mode, when execute_control_command returns
4673                we're already standing on the next breakpoint.
4674                Breakpoint commands for that stop were not run, since
4675                execute_command does not run breakpoint commands --
4676                only command_line_handler does, but that one is not
4677                involved in execution of breakpoint commands.  So, we
4678                can now execute breakpoint commands.  It should be
4679                noted that making execute_command do bpstat actions is
4680                not an option -- in this case we'll have recursive
4681                invocation of bpstat for each breakpoint with a
4682                command, and can easily blow up GDB stack.  Instead, we
4683                return true, which will trigger the caller to recall us
4684                with the new stop_bpstat.  */
4685             again = 1;
4686           break;
4687         }
4688     }
4689   do_cleanups (old_chain);
4690   return again;
4691 }
4692
4693 void
4694 bpstat_do_actions (void)
4695 {
4696   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4697
4698   /* Do any commands attached to breakpoint we are stopped at.  */
4699   while (!ptid_equal (inferior_ptid, null_ptid)
4700          && target_has_execution
4701          && !is_exited (inferior_ptid)
4702          && !is_executing (inferior_ptid))
4703     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4704        and only return when it is stopped at the next breakpoint, we
4705        keep doing breakpoint actions until it returns false to
4706        indicate the inferior was not resumed.  */
4707     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4708       break;
4709
4710   discard_cleanups (cleanup_if_error);
4711 }
4712
4713 /* Print out the (old or new) value associated with a watchpoint.  */
4714
4715 static void
4716 watchpoint_value_print (struct value *val, struct ui_file *stream)
4717 {
4718   if (val == NULL)
4719     fprintf_unfiltered (stream, _("<unreadable>"));
4720   else
4721     {
4722       struct value_print_options opts;
4723       get_user_print_options (&opts);
4724       value_print (val, stream, &opts);
4725     }
4726 }
4727
4728 /* Generic routine for printing messages indicating why we
4729    stopped.  The behavior of this function depends on the value
4730    'print_it' in the bpstat structure.  Under some circumstances we
4731    may decide not to print anything here and delegate the task to
4732    normal_stop().  */
4733
4734 static enum print_stop_action
4735 print_bp_stop_message (bpstat bs)
4736 {
4737   switch (bs->print_it)
4738     {
4739     case print_it_noop:
4740       /* Nothing should be printed for this bpstat entry.  */
4741       return PRINT_UNKNOWN;
4742       break;
4743
4744     case print_it_done:
4745       /* We still want to print the frame, but we already printed the
4746          relevant messages.  */
4747       return PRINT_SRC_AND_LOC;
4748       break;
4749
4750     case print_it_normal:
4751       {
4752         struct breakpoint *b = bs->breakpoint_at;
4753
4754         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4755            which has since been deleted.  */
4756         if (b == NULL)
4757           return PRINT_UNKNOWN;
4758
4759         /* Normal case.  Call the breakpoint's print_it method.  */
4760         return b->ops->print_it (bs);
4761       }
4762       break;
4763
4764     default:
4765       internal_error (__FILE__, __LINE__,
4766                       _("print_bp_stop_message: unrecognized enum value"));
4767       break;
4768     }
4769 }
4770
4771 /* A helper function that prints a shared library stopped event.  */
4772
4773 static void
4774 print_solib_event (int is_catchpoint)
4775 {
4776   int any_deleted
4777     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4778   int any_added
4779     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4780
4781   if (!is_catchpoint)
4782     {
4783       if (any_added || any_deleted)
4784         ui_out_text (current_uiout,
4785                      _("Stopped due to shared library event:\n"));
4786       else
4787         ui_out_text (current_uiout,
4788                      _("Stopped due to shared library event (no "
4789                        "libraries added or removed)\n"));
4790     }
4791
4792   if (ui_out_is_mi_like_p (current_uiout))
4793     ui_out_field_string (current_uiout, "reason",
4794                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4795
4796   if (any_deleted)
4797     {
4798       struct cleanup *cleanup;
4799       char *name;
4800       int ix;
4801
4802       ui_out_text (current_uiout, _("  Inferior unloaded "));
4803       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4804                                                     "removed");
4805       for (ix = 0;
4806            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4807                         ix, name);
4808            ++ix)
4809         {
4810           if (ix > 0)
4811             ui_out_text (current_uiout, "    ");
4812           ui_out_field_string (current_uiout, "library", name);
4813           ui_out_text (current_uiout, "\n");
4814         }
4815
4816       do_cleanups (cleanup);
4817     }
4818
4819   if (any_added)
4820     {
4821       struct so_list *iter;
4822       int ix;
4823       struct cleanup *cleanup;
4824
4825       ui_out_text (current_uiout, _("  Inferior loaded "));
4826       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4827                                                     "added");
4828       for (ix = 0;
4829            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4830                         ix, iter);
4831            ++ix)
4832         {
4833           if (ix > 0)
4834             ui_out_text (current_uiout, "    ");
4835           ui_out_field_string (current_uiout, "library", iter->so_name);
4836           ui_out_text (current_uiout, "\n");
4837         }
4838
4839       do_cleanups (cleanup);
4840     }
4841 }
4842
4843 /* Print a message indicating what happened.  This is called from
4844    normal_stop().  The input to this routine is the head of the bpstat
4845    list - a list of the eventpoints that caused this stop.  KIND is
4846    the target_waitkind for the stopping event.  This
4847    routine calls the generic print routine for printing a message
4848    about reasons for stopping.  This will print (for example) the
4849    "Breakpoint n," part of the output.  The return value of this
4850    routine is one of:
4851
4852    PRINT_UNKNOWN: Means we printed nothing.
4853    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4854    code to print the location.  An example is 
4855    "Breakpoint 1, " which should be followed by
4856    the location.
4857    PRINT_SRC_ONLY: Means we printed something, but there is no need
4858    to also print the location part of the message.
4859    An example is the catch/throw messages, which
4860    don't require a location appended to the end.
4861    PRINT_NOTHING: We have done some printing and we don't need any 
4862    further info to be printed.  */
4863
4864 enum print_stop_action
4865 bpstat_print (bpstat bs, int kind)
4866 {
4867   enum print_stop_action val;
4868
4869   /* Maybe another breakpoint in the chain caused us to stop.
4870      (Currently all watchpoints go on the bpstat whether hit or not.
4871      That probably could (should) be changed, provided care is taken
4872      with respect to bpstat_explains_signal).  */
4873   for (; bs; bs = bs->next)
4874     {
4875       val = print_bp_stop_message (bs);
4876       if (val == PRINT_SRC_ONLY 
4877           || val == PRINT_SRC_AND_LOC 
4878           || val == PRINT_NOTHING)
4879         return val;
4880     }
4881
4882   /* If we had hit a shared library event breakpoint,
4883      print_bp_stop_message would print out this message.  If we hit an
4884      OS-level shared library event, do the same thing.  */
4885   if (kind == TARGET_WAITKIND_LOADED)
4886     {
4887       print_solib_event (0);
4888       return PRINT_NOTHING;
4889     }
4890
4891   /* We reached the end of the chain, or we got a null BS to start
4892      with and nothing was printed.  */
4893   return PRINT_UNKNOWN;
4894 }
4895
4896 /* Evaluate the expression EXP and return 1 if value is zero.
4897    This returns the inverse of the condition because it is called
4898    from catch_errors which returns 0 if an exception happened, and if an
4899    exception happens we want execution to stop.
4900    The argument is a "struct expression *" that has been cast to a
4901    "void *" to make it pass through catch_errors.  */
4902
4903 static int
4904 breakpoint_cond_eval (void *exp)
4905 {
4906   struct value *mark = value_mark ();
4907   int i = !value_true (evaluate_expression ((struct expression *) exp));
4908
4909   value_free_to_mark (mark);
4910   return i;
4911 }
4912
4913 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4914
4915 static bpstat
4916 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4917 {
4918   bpstat bs;
4919
4920   bs = (bpstat) xmalloc (sizeof (*bs));
4921   bs->next = NULL;
4922   **bs_link_pointer = bs;
4923   *bs_link_pointer = &bs->next;
4924   bs->breakpoint_at = bl->owner;
4925   bs->bp_location_at = bl;
4926   incref_bp_location (bl);
4927   /* If the condition is false, etc., don't do the commands.  */
4928   bs->commands = NULL;
4929   bs->old_val = NULL;
4930   bs->print_it = print_it_normal;
4931   return bs;
4932 }
4933 \f
4934 /* The target has stopped with waitstatus WS.  Check if any hardware
4935    watchpoints have triggered, according to the target.  */
4936
4937 int
4938 watchpoints_triggered (struct target_waitstatus *ws)
4939 {
4940   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4941   CORE_ADDR addr;
4942   struct breakpoint *b;
4943
4944   if (!stopped_by_watchpoint)
4945     {
4946       /* We were not stopped by a watchpoint.  Mark all watchpoints
4947          as not triggered.  */
4948       ALL_BREAKPOINTS (b)
4949         if (is_hardware_watchpoint (b))
4950           {
4951             struct watchpoint *w = (struct watchpoint *) b;
4952
4953             w->watchpoint_triggered = watch_triggered_no;
4954           }
4955
4956       return 0;
4957     }
4958
4959   if (!target_stopped_data_address (&current_target, &addr))
4960     {
4961       /* We were stopped by a watchpoint, but we don't know where.
4962          Mark all watchpoints as unknown.  */
4963       ALL_BREAKPOINTS (b)
4964         if (is_hardware_watchpoint (b))
4965           {
4966             struct watchpoint *w = (struct watchpoint *) b;
4967
4968             w->watchpoint_triggered = watch_triggered_unknown;
4969           }
4970
4971       return 1;
4972     }
4973
4974   /* The target could report the data address.  Mark watchpoints
4975      affected by this data address as triggered, and all others as not
4976      triggered.  */
4977
4978   ALL_BREAKPOINTS (b)
4979     if (is_hardware_watchpoint (b))
4980       {
4981         struct watchpoint *w = (struct watchpoint *) b;
4982         struct bp_location *loc;
4983
4984         w->watchpoint_triggered = watch_triggered_no;
4985         for (loc = b->loc; loc; loc = loc->next)
4986           {
4987             if (is_masked_watchpoint (b))
4988               {
4989                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4990                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4991
4992                 if (newaddr == start)
4993                   {
4994                     w->watchpoint_triggered = watch_triggered_yes;
4995                     break;
4996                   }
4997               }
4998             /* Exact match not required.  Within range is sufficient.  */
4999             else if (target_watchpoint_addr_within_range (&current_target,
5000                                                          addr, loc->address,
5001                                                          loc->length))
5002               {
5003                 w->watchpoint_triggered = watch_triggered_yes;
5004                 break;
5005               }
5006           }
5007       }
5008
5009   return 1;
5010 }
5011
5012 /* Possible return values for watchpoint_check (this can't be an enum
5013    because of check_errors).  */
5014 /* The watchpoint has been deleted.  */
5015 #define WP_DELETED 1
5016 /* The value has changed.  */
5017 #define WP_VALUE_CHANGED 2
5018 /* The value has not changed.  */
5019 #define WP_VALUE_NOT_CHANGED 3
5020 /* Ignore this watchpoint, no matter if the value changed or not.  */
5021 #define WP_IGNORE 4
5022
5023 #define BP_TEMPFLAG 1
5024 #define BP_HARDWAREFLAG 2
5025
5026 /* Evaluate watchpoint condition expression and check if its value
5027    changed.
5028
5029    P should be a pointer to struct bpstat, but is defined as a void *
5030    in order for this function to be usable with catch_errors.  */
5031
5032 static int
5033 watchpoint_check (void *p)
5034 {
5035   bpstat bs = (bpstat) p;
5036   struct watchpoint *b;
5037   struct frame_info *fr;
5038   int within_current_scope;
5039
5040   /* BS is built from an existing struct breakpoint.  */
5041   gdb_assert (bs->breakpoint_at != NULL);
5042   b = (struct watchpoint *) bs->breakpoint_at;
5043
5044   /* If this is a local watchpoint, we only want to check if the
5045      watchpoint frame is in scope if the current thread is the thread
5046      that was used to create the watchpoint.  */
5047   if (!watchpoint_in_thread_scope (b))
5048     return WP_IGNORE;
5049
5050   if (b->exp_valid_block == NULL)
5051     within_current_scope = 1;
5052   else
5053     {
5054       struct frame_info *frame = get_current_frame ();
5055       struct gdbarch *frame_arch = get_frame_arch (frame);
5056       CORE_ADDR frame_pc = get_frame_pc (frame);
5057
5058       /* stack_frame_destroyed_p() returns a non-zero value if we're
5059          still in the function but the stack frame has already been
5060          invalidated.  Since we can't rely on the values of local
5061          variables after the stack has been destroyed, we are treating
5062          the watchpoint in that state as `not changed' without further
5063          checking.  Don't mark watchpoints as changed if the current
5064          frame is in an epilogue - even if they are in some other
5065          frame, our view of the stack is likely to be wrong and
5066          frame_find_by_id could error out.  */
5067       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5068         return WP_IGNORE;
5069
5070       fr = frame_find_by_id (b->watchpoint_frame);
5071       within_current_scope = (fr != NULL);
5072
5073       /* If we've gotten confused in the unwinder, we might have
5074          returned a frame that can't describe this variable.  */
5075       if (within_current_scope)
5076         {
5077           struct symbol *function;
5078
5079           function = get_frame_function (fr);
5080           if (function == NULL
5081               || !contained_in (b->exp_valid_block,
5082                                 SYMBOL_BLOCK_VALUE (function)))
5083             within_current_scope = 0;
5084         }
5085
5086       if (within_current_scope)
5087         /* If we end up stopping, the current frame will get selected
5088            in normal_stop.  So this call to select_frame won't affect
5089            the user.  */
5090         select_frame (fr);
5091     }
5092
5093   if (within_current_scope)
5094     {
5095       /* We use value_{,free_to_}mark because it could be a *long*
5096          time before we return to the command level and call
5097          free_all_values.  We can't call free_all_values because we
5098          might be in the middle of evaluating a function call.  */
5099
5100       int pc = 0;
5101       struct value *mark;
5102       struct value *new_val;
5103
5104       if (is_masked_watchpoint (&b->base))
5105         /* Since we don't know the exact trigger address (from
5106            stopped_data_address), just tell the user we've triggered
5107            a mask watchpoint.  */
5108         return WP_VALUE_CHANGED;
5109
5110       mark = value_mark ();
5111       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5112
5113       if (b->val_bitsize != 0)
5114         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5115
5116       /* We use value_equal_contents instead of value_equal because
5117          the latter coerces an array to a pointer, thus comparing just
5118          the address of the array instead of its contents.  This is
5119          not what we want.  */
5120       if ((b->val != NULL) != (new_val != NULL)
5121           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5122         {
5123           if (new_val != NULL)
5124             {
5125               release_value (new_val);
5126               value_free_to_mark (mark);
5127             }
5128           bs->old_val = b->val;
5129           b->val = new_val;
5130           b->val_valid = 1;
5131           return WP_VALUE_CHANGED;
5132         }
5133       else
5134         {
5135           /* Nothing changed.  */
5136           value_free_to_mark (mark);
5137           return WP_VALUE_NOT_CHANGED;
5138         }
5139     }
5140   else
5141     {
5142       struct ui_out *uiout = current_uiout;
5143
5144       /* This seems like the only logical thing to do because
5145          if we temporarily ignored the watchpoint, then when
5146          we reenter the block in which it is valid it contains
5147          garbage (in the case of a function, it may have two
5148          garbage values, one before and one after the prologue).
5149          So we can't even detect the first assignment to it and
5150          watch after that (since the garbage may or may not equal
5151          the first value assigned).  */
5152       /* We print all the stop information in
5153          breakpoint_ops->print_it, but in this case, by the time we
5154          call breakpoint_ops->print_it this bp will be deleted
5155          already.  So we have no choice but print the information
5156          here.  */
5157       if (ui_out_is_mi_like_p (uiout))
5158         ui_out_field_string
5159           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5160       ui_out_text (uiout, "\nWatchpoint ");
5161       ui_out_field_int (uiout, "wpnum", b->base.number);
5162       ui_out_text (uiout,
5163                    " deleted because the program has left the block in\n\
5164 which its expression is valid.\n");     
5165
5166       /* Make sure the watchpoint's commands aren't executed.  */
5167       decref_counted_command_line (&b->base.commands);
5168       watchpoint_del_at_next_stop (b);
5169
5170       return WP_DELETED;
5171     }
5172 }
5173
5174 /* Return true if it looks like target has stopped due to hitting
5175    breakpoint location BL.  This function does not check if we should
5176    stop, only if BL explains the stop.  */
5177
5178 static int
5179 bpstat_check_location (const struct bp_location *bl,
5180                        struct address_space *aspace, CORE_ADDR bp_addr,
5181                        const struct target_waitstatus *ws)
5182 {
5183   struct breakpoint *b = bl->owner;
5184
5185   /* BL is from an existing breakpoint.  */
5186   gdb_assert (b != NULL);
5187
5188   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5189 }
5190
5191 /* Determine if the watched values have actually changed, and we
5192    should stop.  If not, set BS->stop to 0.  */
5193
5194 static void
5195 bpstat_check_watchpoint (bpstat bs)
5196 {
5197   const struct bp_location *bl;
5198   struct watchpoint *b;
5199
5200   /* BS is built for existing struct breakpoint.  */
5201   bl = bs->bp_location_at;
5202   gdb_assert (bl != NULL);
5203   b = (struct watchpoint *) bs->breakpoint_at;
5204   gdb_assert (b != NULL);
5205
5206     {
5207       int must_check_value = 0;
5208       
5209       if (b->base.type == bp_watchpoint)
5210         /* For a software watchpoint, we must always check the
5211            watched value.  */
5212         must_check_value = 1;
5213       else if (b->watchpoint_triggered == watch_triggered_yes)
5214         /* We have a hardware watchpoint (read, write, or access)
5215            and the target earlier reported an address watched by
5216            this watchpoint.  */
5217         must_check_value = 1;
5218       else if (b->watchpoint_triggered == watch_triggered_unknown
5219                && b->base.type == bp_hardware_watchpoint)
5220         /* We were stopped by a hardware watchpoint, but the target could
5221            not report the data address.  We must check the watchpoint's
5222            value.  Access and read watchpoints are out of luck; without
5223            a data address, we can't figure it out.  */
5224         must_check_value = 1;
5225
5226       if (must_check_value)
5227         {
5228           char *message
5229             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5230                           b->base.number);
5231           struct cleanup *cleanups = make_cleanup (xfree, message);
5232           int e = catch_errors (watchpoint_check, bs, message,
5233                                 RETURN_MASK_ALL);
5234           do_cleanups (cleanups);
5235           switch (e)
5236             {
5237             case WP_DELETED:
5238               /* We've already printed what needs to be printed.  */
5239               bs->print_it = print_it_done;
5240               /* Stop.  */
5241               break;
5242             case WP_IGNORE:
5243               bs->print_it = print_it_noop;
5244               bs->stop = 0;
5245               break;
5246             case WP_VALUE_CHANGED:
5247               if (b->base.type == bp_read_watchpoint)
5248                 {
5249                   /* There are two cases to consider here:
5250
5251                      1. We're watching the triggered memory for reads.
5252                      In that case, trust the target, and always report
5253                      the watchpoint hit to the user.  Even though
5254                      reads don't cause value changes, the value may
5255                      have changed since the last time it was read, and
5256                      since we're not trapping writes, we will not see
5257                      those, and as such we should ignore our notion of
5258                      old value.
5259
5260                      2. We're watching the triggered memory for both
5261                      reads and writes.  There are two ways this may
5262                      happen:
5263
5264                      2.1. This is a target that can't break on data
5265                      reads only, but can break on accesses (reads or
5266                      writes), such as e.g., x86.  We detect this case
5267                      at the time we try to insert read watchpoints.
5268
5269                      2.2. Otherwise, the target supports read
5270                      watchpoints, but, the user set an access or write
5271                      watchpoint watching the same memory as this read
5272                      watchpoint.
5273
5274                      If we're watching memory writes as well as reads,
5275                      ignore watchpoint hits when we find that the
5276                      value hasn't changed, as reads don't cause
5277                      changes.  This still gives false positives when
5278                      the program writes the same value to memory as
5279                      what there was already in memory (we will confuse
5280                      it for a read), but it's much better than
5281                      nothing.  */
5282
5283                   int other_write_watchpoint = 0;
5284
5285                   if (bl->watchpoint_type == hw_read)
5286                     {
5287                       struct breakpoint *other_b;
5288
5289                       ALL_BREAKPOINTS (other_b)
5290                         if (other_b->type == bp_hardware_watchpoint
5291                             || other_b->type == bp_access_watchpoint)
5292                           {
5293                             struct watchpoint *other_w =
5294                               (struct watchpoint *) other_b;
5295
5296                             if (other_w->watchpoint_triggered
5297                                 == watch_triggered_yes)
5298                               {
5299                                 other_write_watchpoint = 1;
5300                                 break;
5301                               }
5302                           }
5303                     }
5304
5305                   if (other_write_watchpoint
5306                       || bl->watchpoint_type == hw_access)
5307                     {
5308                       /* We're watching the same memory for writes,
5309                          and the value changed since the last time we
5310                          updated it, so this trap must be for a write.
5311                          Ignore it.  */
5312                       bs->print_it = print_it_noop;
5313                       bs->stop = 0;
5314                     }
5315                 }
5316               break;
5317             case WP_VALUE_NOT_CHANGED:
5318               if (b->base.type == bp_hardware_watchpoint
5319                   || b->base.type == bp_watchpoint)
5320                 {
5321                   /* Don't stop: write watchpoints shouldn't fire if
5322                      the value hasn't changed.  */
5323                   bs->print_it = print_it_noop;
5324                   bs->stop = 0;
5325                 }
5326               /* Stop.  */
5327               break;
5328             default:
5329               /* Can't happen.  */
5330             case 0:
5331               /* Error from catch_errors.  */
5332               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5333               watchpoint_del_at_next_stop (b);
5334               /* We've already printed what needs to be printed.  */
5335               bs->print_it = print_it_done;
5336               break;
5337             }
5338         }
5339       else      /* must_check_value == 0 */
5340         {
5341           /* This is a case where some watchpoint(s) triggered, but
5342              not at the address of this watchpoint, or else no
5343              watchpoint triggered after all.  So don't print
5344              anything for this watchpoint.  */
5345           bs->print_it = print_it_noop;
5346           bs->stop = 0;
5347         }
5348     }
5349 }
5350
5351 /* For breakpoints that are currently marked as telling gdb to stop,
5352    check conditions (condition proper, frame, thread and ignore count)
5353    of breakpoint referred to by BS.  If we should not stop for this
5354    breakpoint, set BS->stop to 0.  */
5355
5356 static void
5357 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5358 {
5359   const struct bp_location *bl;
5360   struct breakpoint *b;
5361   int value_is_zero = 0;
5362   struct expression *cond;
5363
5364   gdb_assert (bs->stop);
5365
5366   /* BS is built for existing struct breakpoint.  */
5367   bl = bs->bp_location_at;
5368   gdb_assert (bl != NULL);
5369   b = bs->breakpoint_at;
5370   gdb_assert (b != NULL);
5371
5372   /* Even if the target evaluated the condition on its end and notified GDB, we
5373      need to do so again since GDB does not know if we stopped due to a
5374      breakpoint or a single step breakpoint.  */
5375
5376   if (frame_id_p (b->frame_id)
5377       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5378     {
5379       bs->stop = 0;
5380       return;
5381     }
5382
5383   /* If this is a thread/task-specific breakpoint, don't waste cpu
5384      evaluating the condition if this isn't the specified
5385      thread/task.  */
5386   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5387       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5388
5389     {
5390       bs->stop = 0;
5391       return;
5392     }
5393
5394   /* Evaluate extension language breakpoints that have a "stop" method
5395      implemented.  */
5396   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5397
5398   if (is_watchpoint (b))
5399     {
5400       struct watchpoint *w = (struct watchpoint *) b;
5401
5402       cond = w->cond_exp;
5403     }
5404   else
5405     cond = bl->cond;
5406
5407   if (cond && b->disposition != disp_del_at_next_stop)
5408     {
5409       int within_current_scope = 1;
5410       struct watchpoint * w;
5411
5412       /* We use value_mark and value_free_to_mark because it could
5413          be a long time before we return to the command level and
5414          call free_all_values.  We can't call free_all_values
5415          because we might be in the middle of evaluating a
5416          function call.  */
5417       struct value *mark = value_mark ();
5418
5419       if (is_watchpoint (b))
5420         w = (struct watchpoint *) b;
5421       else
5422         w = NULL;
5423
5424       /* Need to select the frame, with all that implies so that
5425          the conditions will have the right context.  Because we
5426          use the frame, we will not see an inlined function's
5427          variables when we arrive at a breakpoint at the start
5428          of the inlined function; the current frame will be the
5429          call site.  */
5430       if (w == NULL || w->cond_exp_valid_block == NULL)
5431         select_frame (get_current_frame ());
5432       else
5433         {
5434           struct frame_info *frame;
5435
5436           /* For local watchpoint expressions, which particular
5437              instance of a local is being watched matters, so we
5438              keep track of the frame to evaluate the expression
5439              in.  To evaluate the condition however, it doesn't
5440              really matter which instantiation of the function
5441              where the condition makes sense triggers the
5442              watchpoint.  This allows an expression like "watch
5443              global if q > 10" set in `func', catch writes to
5444              global on all threads that call `func', or catch
5445              writes on all recursive calls of `func' by a single
5446              thread.  We simply always evaluate the condition in
5447              the innermost frame that's executing where it makes
5448              sense to evaluate the condition.  It seems
5449              intuitive.  */
5450           frame = block_innermost_frame (w->cond_exp_valid_block);
5451           if (frame != NULL)
5452             select_frame (frame);
5453           else
5454             within_current_scope = 0;
5455         }
5456       if (within_current_scope)
5457         value_is_zero
5458           = catch_errors (breakpoint_cond_eval, cond,
5459                           "Error in testing breakpoint condition:\n",
5460                           RETURN_MASK_ALL);
5461       else
5462         {
5463           warning (_("Watchpoint condition cannot be tested "
5464                      "in the current scope"));
5465           /* If we failed to set the right context for this
5466              watchpoint, unconditionally report it.  */
5467           value_is_zero = 0;
5468         }
5469       /* FIXME-someday, should give breakpoint #.  */
5470       value_free_to_mark (mark);
5471     }
5472
5473   if (cond && value_is_zero)
5474     {
5475       bs->stop = 0;
5476     }
5477   else if (b->ignore_count > 0)
5478     {
5479       b->ignore_count--;
5480       bs->stop = 0;
5481       /* Increase the hit count even though we don't stop.  */
5482       ++(b->hit_count);
5483       observer_notify_breakpoint_modified (b);
5484     }   
5485 }
5486
5487 /* Returns true if we need to track moribund locations of LOC's type
5488    on the current target.  */
5489
5490 static int
5491 need_moribund_for_location_type (struct bp_location *loc)
5492 {
5493   return ((loc->loc_type == bp_loc_software_breakpoint
5494            && !target_supports_stopped_by_sw_breakpoint ())
5495           || (loc->loc_type == bp_loc_hardware_breakpoint
5496               && !target_supports_stopped_by_hw_breakpoint ()));
5497 }
5498
5499
5500 /* Get a bpstat associated with having just stopped at address
5501    BP_ADDR in thread PTID.
5502
5503    Determine whether we stopped at a breakpoint, etc, or whether we
5504    don't understand this stop.  Result is a chain of bpstat's such
5505    that:
5506
5507    if we don't understand the stop, the result is a null pointer.
5508
5509    if we understand why we stopped, the result is not null.
5510
5511    Each element of the chain refers to a particular breakpoint or
5512    watchpoint at which we have stopped.  (We may have stopped for
5513    several reasons concurrently.)
5514
5515    Each element of the chain has valid next, breakpoint_at,
5516    commands, FIXME??? fields.  */
5517
5518 bpstat
5519 bpstat_stop_status (struct address_space *aspace,
5520                     CORE_ADDR bp_addr, ptid_t ptid,
5521                     const struct target_waitstatus *ws)
5522 {
5523   struct breakpoint *b = NULL;
5524   struct bp_location *bl;
5525   struct bp_location *loc;
5526   /* First item of allocated bpstat's.  */
5527   bpstat bs_head = NULL, *bs_link = &bs_head;
5528   /* Pointer to the last thing in the chain currently.  */
5529   bpstat bs;
5530   int ix;
5531   int need_remove_insert;
5532   int removed_any;
5533
5534   /* First, build the bpstat chain with locations that explain a
5535      target stop, while being careful to not set the target running,
5536      as that may invalidate locations (in particular watchpoint
5537      locations are recreated).  Resuming will happen here with
5538      breakpoint conditions or watchpoint expressions that include
5539      inferior function calls.  */
5540
5541   ALL_BREAKPOINTS (b)
5542     {
5543       if (!breakpoint_enabled (b))
5544         continue;
5545
5546       for (bl = b->loc; bl != NULL; bl = bl->next)
5547         {
5548           /* For hardware watchpoints, we look only at the first
5549              location.  The watchpoint_check function will work on the
5550              entire expression, not the individual locations.  For
5551              read watchpoints, the watchpoints_triggered function has
5552              checked all locations already.  */
5553           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5554             break;
5555
5556           if (!bl->enabled || bl->shlib_disabled)
5557             continue;
5558
5559           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5560             continue;
5561
5562           /* Come here if it's a watchpoint, or if the break address
5563              matches.  */
5564
5565           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5566                                                    explain stop.  */
5567
5568           /* Assume we stop.  Should we find a watchpoint that is not
5569              actually triggered, or if the condition of the breakpoint
5570              evaluates as false, we'll reset 'stop' to 0.  */
5571           bs->stop = 1;
5572           bs->print = 1;
5573
5574           /* If this is a scope breakpoint, mark the associated
5575              watchpoint as triggered so that we will handle the
5576              out-of-scope event.  We'll get to the watchpoint next
5577              iteration.  */
5578           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5579             {
5580               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5581
5582               w->watchpoint_triggered = watch_triggered_yes;
5583             }
5584         }
5585     }
5586
5587   /* Check if a moribund breakpoint explains the stop.  */
5588   if (!target_supports_stopped_by_sw_breakpoint ()
5589       || !target_supports_stopped_by_hw_breakpoint ())
5590     {
5591       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5592         {
5593           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5594               && need_moribund_for_location_type (loc))
5595             {
5596               bs = bpstat_alloc (loc, &bs_link);
5597               /* For hits of moribund locations, we should just proceed.  */
5598               bs->stop = 0;
5599               bs->print = 0;
5600               bs->print_it = print_it_noop;
5601             }
5602         }
5603     }
5604
5605   /* A bit of special processing for shlib breakpoints.  We need to
5606      process solib loading here, so that the lists of loaded and
5607      unloaded libraries are correct before we handle "catch load" and
5608      "catch unload".  */
5609   for (bs = bs_head; bs != NULL; bs = bs->next)
5610     {
5611       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5612         {
5613           handle_solib_event ();
5614           break;
5615         }
5616     }
5617
5618   /* Now go through the locations that caused the target to stop, and
5619      check whether we're interested in reporting this stop to higher
5620      layers, or whether we should resume the target transparently.  */
5621
5622   removed_any = 0;
5623
5624   for (bs = bs_head; bs != NULL; bs = bs->next)
5625     {
5626       if (!bs->stop)
5627         continue;
5628
5629       b = bs->breakpoint_at;
5630       b->ops->check_status (bs);
5631       if (bs->stop)
5632         {
5633           bpstat_check_breakpoint_conditions (bs, ptid);
5634
5635           if (bs->stop)
5636             {
5637               ++(b->hit_count);
5638               observer_notify_breakpoint_modified (b);
5639
5640               /* We will stop here.  */
5641               if (b->disposition == disp_disable)
5642                 {
5643                   --(b->enable_count);
5644                   if (b->enable_count <= 0)
5645                     b->enable_state = bp_disabled;
5646                   removed_any = 1;
5647                 }
5648               if (b->silent)
5649                 bs->print = 0;
5650               bs->commands = b->commands;
5651               incref_counted_command_line (bs->commands);
5652               if (command_line_is_silent (bs->commands
5653                                           ? bs->commands->commands : NULL))
5654                 bs->print = 0;
5655
5656               b->ops->after_condition_true (bs);
5657             }
5658
5659         }
5660
5661       /* Print nothing for this entry if we don't stop or don't
5662          print.  */
5663       if (!bs->stop || !bs->print)
5664         bs->print_it = print_it_noop;
5665     }
5666
5667   /* If we aren't stopping, the value of some hardware watchpoint may
5668      not have changed, but the intermediate memory locations we are
5669      watching may have.  Don't bother if we're stopping; this will get
5670      done later.  */
5671   need_remove_insert = 0;
5672   if (! bpstat_causes_stop (bs_head))
5673     for (bs = bs_head; bs != NULL; bs = bs->next)
5674       if (!bs->stop
5675           && bs->breakpoint_at
5676           && is_hardware_watchpoint (bs->breakpoint_at))
5677         {
5678           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5679
5680           update_watchpoint (w, 0 /* don't reparse.  */);
5681           need_remove_insert = 1;
5682         }
5683
5684   if (need_remove_insert)
5685     update_global_location_list (UGLL_MAY_INSERT);
5686   else if (removed_any)
5687     update_global_location_list (UGLL_DONT_INSERT);
5688
5689   return bs_head;
5690 }
5691
5692 static void
5693 handle_jit_event (void)
5694 {
5695   struct frame_info *frame;
5696   struct gdbarch *gdbarch;
5697
5698   if (debug_infrun)
5699     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5700
5701   /* Switch terminal for any messages produced by
5702      breakpoint_re_set.  */
5703   target_terminal_ours_for_output ();
5704
5705   frame = get_current_frame ();
5706   gdbarch = get_frame_arch (frame);
5707
5708   jit_event_handler (gdbarch);
5709
5710   target_terminal_inferior ();
5711 }
5712
5713 /* Prepare WHAT final decision for infrun.  */
5714
5715 /* Decide what infrun needs to do with this bpstat.  */
5716
5717 struct bpstat_what
5718 bpstat_what (bpstat bs_head)
5719 {
5720   struct bpstat_what retval;
5721   int jit_event = 0;
5722   bpstat bs;
5723
5724   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5725   retval.call_dummy = STOP_NONE;
5726   retval.is_longjmp = 0;
5727
5728   for (bs = bs_head; bs != NULL; bs = bs->next)
5729     {
5730       /* Extract this BS's action.  After processing each BS, we check
5731          if its action overrides all we've seem so far.  */
5732       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5733       enum bptype bptype;
5734
5735       if (bs->breakpoint_at == NULL)
5736         {
5737           /* I suspect this can happen if it was a momentary
5738              breakpoint which has since been deleted.  */
5739           bptype = bp_none;
5740         }
5741       else
5742         bptype = bs->breakpoint_at->type;
5743
5744       switch (bptype)
5745         {
5746         case bp_none:
5747           break;
5748         case bp_breakpoint:
5749         case bp_hardware_breakpoint:
5750         case bp_single_step:
5751         case bp_until:
5752         case bp_finish:
5753         case bp_shlib_event:
5754           if (bs->stop)
5755             {
5756               if (bs->print)
5757                 this_action = BPSTAT_WHAT_STOP_NOISY;
5758               else
5759                 this_action = BPSTAT_WHAT_STOP_SILENT;
5760             }
5761           else
5762             this_action = BPSTAT_WHAT_SINGLE;
5763           break;
5764         case bp_watchpoint:
5765         case bp_hardware_watchpoint:
5766         case bp_read_watchpoint:
5767         case bp_access_watchpoint:
5768           if (bs->stop)
5769             {
5770               if (bs->print)
5771                 this_action = BPSTAT_WHAT_STOP_NOISY;
5772               else
5773                 this_action = BPSTAT_WHAT_STOP_SILENT;
5774             }
5775           else
5776             {
5777               /* There was a watchpoint, but we're not stopping.
5778                  This requires no further action.  */
5779             }
5780           break;
5781         case bp_longjmp:
5782         case bp_longjmp_call_dummy:
5783         case bp_exception:
5784           if (bs->stop)
5785             {
5786               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5787               retval.is_longjmp = bptype != bp_exception;
5788             }
5789           else
5790             this_action = BPSTAT_WHAT_SINGLE;
5791           break;
5792         case bp_longjmp_resume:
5793         case bp_exception_resume:
5794           if (bs->stop)
5795             {
5796               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5797               retval.is_longjmp = bptype == bp_longjmp_resume;
5798             }
5799           else
5800             this_action = BPSTAT_WHAT_SINGLE;
5801           break;
5802         case bp_step_resume:
5803           if (bs->stop)
5804             this_action = BPSTAT_WHAT_STEP_RESUME;
5805           else
5806             {
5807               /* It is for the wrong frame.  */
5808               this_action = BPSTAT_WHAT_SINGLE;
5809             }
5810           break;
5811         case bp_hp_step_resume:
5812           if (bs->stop)
5813             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5814           else
5815             {
5816               /* It is for the wrong frame.  */
5817               this_action = BPSTAT_WHAT_SINGLE;
5818             }
5819           break;
5820         case bp_watchpoint_scope:
5821         case bp_thread_event:
5822         case bp_overlay_event:
5823         case bp_longjmp_master:
5824         case bp_std_terminate_master:
5825         case bp_exception_master:
5826           this_action = BPSTAT_WHAT_SINGLE;
5827           break;
5828         case bp_catchpoint:
5829           if (bs->stop)
5830             {
5831               if (bs->print)
5832                 this_action = BPSTAT_WHAT_STOP_NOISY;
5833               else
5834                 this_action = BPSTAT_WHAT_STOP_SILENT;
5835             }
5836           else
5837             {
5838               /* There was a catchpoint, but we're not stopping.
5839                  This requires no further action.  */
5840             }
5841           break;
5842         case bp_jit_event:
5843           jit_event = 1;
5844           this_action = BPSTAT_WHAT_SINGLE;
5845           break;
5846         case bp_call_dummy:
5847           /* Make sure the action is stop (silent or noisy),
5848              so infrun.c pops the dummy frame.  */
5849           retval.call_dummy = STOP_STACK_DUMMY;
5850           this_action = BPSTAT_WHAT_STOP_SILENT;
5851           break;
5852         case bp_std_terminate:
5853           /* Make sure the action is stop (silent or noisy),
5854              so infrun.c pops the dummy frame.  */
5855           retval.call_dummy = STOP_STD_TERMINATE;
5856           this_action = BPSTAT_WHAT_STOP_SILENT;
5857           break;
5858         case bp_tracepoint:
5859         case bp_fast_tracepoint:
5860         case bp_static_tracepoint:
5861           /* Tracepoint hits should not be reported back to GDB, and
5862              if one got through somehow, it should have been filtered
5863              out already.  */
5864           internal_error (__FILE__, __LINE__,
5865                           _("bpstat_what: tracepoint encountered"));
5866           break;
5867         case bp_gnu_ifunc_resolver:
5868           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5869           this_action = BPSTAT_WHAT_SINGLE;
5870           break;
5871         case bp_gnu_ifunc_resolver_return:
5872           /* The breakpoint will be removed, execution will restart from the
5873              PC of the former breakpoint.  */
5874           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5875           break;
5876
5877         case bp_dprintf:
5878           if (bs->stop)
5879             this_action = BPSTAT_WHAT_STOP_SILENT;
5880           else
5881             this_action = BPSTAT_WHAT_SINGLE;
5882           break;
5883
5884         default:
5885           internal_error (__FILE__, __LINE__,
5886                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5887         }
5888
5889       retval.main_action = max (retval.main_action, this_action);
5890     }
5891
5892   return retval;
5893 }
5894
5895 void
5896 bpstat_run_callbacks (bpstat bs_head)
5897 {
5898   bpstat bs;
5899
5900   for (bs = bs_head; bs != NULL; bs = bs->next)
5901     {
5902       struct breakpoint *b = bs->breakpoint_at;
5903
5904       if (b == NULL)
5905         continue;
5906       switch (b->type)
5907         {
5908         case bp_jit_event:
5909           handle_jit_event ();
5910           break;
5911         case bp_gnu_ifunc_resolver:
5912           gnu_ifunc_resolver_stop (b);
5913           break;
5914         case bp_gnu_ifunc_resolver_return:
5915           gnu_ifunc_resolver_return_stop (b);
5916           break;
5917         }
5918     }
5919 }
5920
5921 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5922    without hardware support).  This isn't related to a specific bpstat,
5923    just to things like whether watchpoints are set.  */
5924
5925 int
5926 bpstat_should_step (void)
5927 {
5928   struct breakpoint *b;
5929
5930   ALL_BREAKPOINTS (b)
5931     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5932       return 1;
5933   return 0;
5934 }
5935
5936 int
5937 bpstat_causes_stop (bpstat bs)
5938 {
5939   for (; bs != NULL; bs = bs->next)
5940     if (bs->stop)
5941       return 1;
5942
5943   return 0;
5944 }
5945
5946 \f
5947
5948 /* Compute a string of spaces suitable to indent the next line
5949    so it starts at the position corresponding to the table column
5950    named COL_NAME in the currently active table of UIOUT.  */
5951
5952 static char *
5953 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5954 {
5955   static char wrap_indent[80];
5956   int i, total_width, width, align;
5957   char *text;
5958
5959   total_width = 0;
5960   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5961     {
5962       if (strcmp (text, col_name) == 0)
5963         {
5964           gdb_assert (total_width < sizeof wrap_indent);
5965           memset (wrap_indent, ' ', total_width);
5966           wrap_indent[total_width] = 0;
5967
5968           return wrap_indent;
5969         }
5970
5971       total_width += width + 1;
5972     }
5973
5974   return NULL;
5975 }
5976
5977 /* Determine if the locations of this breakpoint will have their conditions
5978    evaluated by the target, host or a mix of both.  Returns the following:
5979
5980     "host": Host evals condition.
5981     "host or target": Host or Target evals condition.
5982     "target": Target evals condition.
5983 */
5984
5985 static const char *
5986 bp_condition_evaluator (struct breakpoint *b)
5987 {
5988   struct bp_location *bl;
5989   char host_evals = 0;
5990   char target_evals = 0;
5991
5992   if (!b)
5993     return NULL;
5994
5995   if (!is_breakpoint (b))
5996     return NULL;
5997
5998   if (gdb_evaluates_breakpoint_condition_p ()
5999       || !target_supports_evaluation_of_breakpoint_conditions ())
6000     return condition_evaluation_host;
6001
6002   for (bl = b->loc; bl; bl = bl->next)
6003     {
6004       if (bl->cond_bytecode)
6005         target_evals++;
6006       else
6007         host_evals++;
6008     }
6009
6010   if (host_evals && target_evals)
6011     return condition_evaluation_both;
6012   else if (target_evals)
6013     return condition_evaluation_target;
6014   else
6015     return condition_evaluation_host;
6016 }
6017
6018 /* Determine the breakpoint location's condition evaluator.  This is
6019    similar to bp_condition_evaluator, but for locations.  */
6020
6021 static const char *
6022 bp_location_condition_evaluator (struct bp_location *bl)
6023 {
6024   if (bl && !is_breakpoint (bl->owner))
6025     return NULL;
6026
6027   if (gdb_evaluates_breakpoint_condition_p ()
6028       || !target_supports_evaluation_of_breakpoint_conditions ())
6029     return condition_evaluation_host;
6030
6031   if (bl && bl->cond_bytecode)
6032     return condition_evaluation_target;
6033   else
6034     return condition_evaluation_host;
6035 }
6036
6037 /* Print the LOC location out of the list of B->LOC locations.  */
6038
6039 static void
6040 print_breakpoint_location (struct breakpoint *b,
6041                            struct bp_location *loc)
6042 {
6043   struct ui_out *uiout = current_uiout;
6044   struct cleanup *old_chain = save_current_program_space ();
6045
6046   if (loc != NULL && loc->shlib_disabled)
6047     loc = NULL;
6048
6049   if (loc != NULL)
6050     set_current_program_space (loc->pspace);
6051
6052   if (b->display_canonical)
6053     ui_out_field_string (uiout, "what",
6054                          event_location_to_string (b->location));
6055   else if (loc && loc->symtab)
6056     {
6057       struct symbol *sym 
6058         = find_pc_sect_function (loc->address, loc->section);
6059       if (sym)
6060         {
6061           ui_out_text (uiout, "in ");
6062           ui_out_field_string (uiout, "func",
6063                                SYMBOL_PRINT_NAME (sym));
6064           ui_out_text (uiout, " ");
6065           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6066           ui_out_text (uiout, "at ");
6067         }
6068       ui_out_field_string (uiout, "file",
6069                            symtab_to_filename_for_display (loc->symtab));
6070       ui_out_text (uiout, ":");
6071
6072       if (ui_out_is_mi_like_p (uiout))
6073         ui_out_field_string (uiout, "fullname",
6074                              symtab_to_fullname (loc->symtab));
6075       
6076       ui_out_field_int (uiout, "line", loc->line_number);
6077     }
6078   else if (loc)
6079     {
6080       struct ui_file *stb = mem_fileopen ();
6081       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6082
6083       print_address_symbolic (loc->gdbarch, loc->address, stb,
6084                               demangle, "");
6085       ui_out_field_stream (uiout, "at", stb);
6086
6087       do_cleanups (stb_chain);
6088     }
6089   else
6090     {
6091       ui_out_field_string (uiout, "pending",
6092                            event_location_to_string (b->location));
6093       /* If extra_string is available, it could be holding a condition
6094          or dprintf arguments.  In either case, make sure it is printed,
6095          too, but only for non-MI streams.  */
6096       if (!ui_out_is_mi_like_p (uiout) && b->extra_string != NULL)
6097         {
6098           if (b->type == bp_dprintf)
6099             ui_out_text (uiout, ",");
6100           else
6101             ui_out_text (uiout, " ");
6102           ui_out_text (uiout, b->extra_string);
6103         }
6104     }
6105
6106   if (loc && is_breakpoint (b)
6107       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6108       && bp_condition_evaluator (b) == condition_evaluation_both)
6109     {
6110       ui_out_text (uiout, " (");
6111       ui_out_field_string (uiout, "evaluated-by",
6112                            bp_location_condition_evaluator (loc));
6113       ui_out_text (uiout, ")");
6114     }
6115
6116   do_cleanups (old_chain);
6117 }
6118
6119 static const char *
6120 bptype_string (enum bptype type)
6121 {
6122   struct ep_type_description
6123     {
6124       enum bptype type;
6125       char *description;
6126     };
6127   static struct ep_type_description bptypes[] =
6128   {
6129     {bp_none, "?deleted?"},
6130     {bp_breakpoint, "breakpoint"},
6131     {bp_hardware_breakpoint, "hw breakpoint"},
6132     {bp_single_step, "sw single-step"},
6133     {bp_until, "until"},
6134     {bp_finish, "finish"},
6135     {bp_watchpoint, "watchpoint"},
6136     {bp_hardware_watchpoint, "hw watchpoint"},
6137     {bp_read_watchpoint, "read watchpoint"},
6138     {bp_access_watchpoint, "acc watchpoint"},
6139     {bp_longjmp, "longjmp"},
6140     {bp_longjmp_resume, "longjmp resume"},
6141     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6142     {bp_exception, "exception"},
6143     {bp_exception_resume, "exception resume"},
6144     {bp_step_resume, "step resume"},
6145     {bp_hp_step_resume, "high-priority step resume"},
6146     {bp_watchpoint_scope, "watchpoint scope"},
6147     {bp_call_dummy, "call dummy"},
6148     {bp_std_terminate, "std::terminate"},
6149     {bp_shlib_event, "shlib events"},
6150     {bp_thread_event, "thread events"},
6151     {bp_overlay_event, "overlay events"},
6152     {bp_longjmp_master, "longjmp master"},
6153     {bp_std_terminate_master, "std::terminate master"},
6154     {bp_exception_master, "exception master"},
6155     {bp_catchpoint, "catchpoint"},
6156     {bp_tracepoint, "tracepoint"},
6157     {bp_fast_tracepoint, "fast tracepoint"},
6158     {bp_static_tracepoint, "static tracepoint"},
6159     {bp_dprintf, "dprintf"},
6160     {bp_jit_event, "jit events"},
6161     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6162     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6163   };
6164
6165   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6166       || ((int) type != bptypes[(int) type].type))
6167     internal_error (__FILE__, __LINE__,
6168                     _("bptypes table does not describe type #%d."),
6169                     (int) type);
6170
6171   return bptypes[(int) type].description;
6172 }
6173
6174 /* For MI, output a field named 'thread-groups' with a list as the value.
6175    For CLI, prefix the list with the string 'inf'. */
6176
6177 static void
6178 output_thread_groups (struct ui_out *uiout,
6179                       const char *field_name,
6180                       VEC(int) *inf_num,
6181                       int mi_only)
6182 {
6183   struct cleanup *back_to;
6184   int is_mi = ui_out_is_mi_like_p (uiout);
6185   int inf;
6186   int i;
6187
6188   /* For backward compatibility, don't display inferiors in CLI unless
6189      there are several.  Always display them for MI. */
6190   if (!is_mi && mi_only)
6191     return;
6192
6193   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6194
6195   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6196     {
6197       if (is_mi)
6198         {
6199           char mi_group[10];
6200
6201           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6202           ui_out_field_string (uiout, NULL, mi_group);
6203         }
6204       else
6205         {
6206           if (i == 0)
6207             ui_out_text (uiout, " inf ");
6208           else
6209             ui_out_text (uiout, ", ");
6210         
6211           ui_out_text (uiout, plongest (inf));
6212         }
6213     }
6214
6215   do_cleanups (back_to);
6216 }
6217
6218 /* Print B to gdb_stdout.  */
6219
6220 static void
6221 print_one_breakpoint_location (struct breakpoint *b,
6222                                struct bp_location *loc,
6223                                int loc_number,
6224                                struct bp_location **last_loc,
6225                                int allflag)
6226 {
6227   struct command_line *l;
6228   static char bpenables[] = "nynny";
6229
6230   struct ui_out *uiout = current_uiout;
6231   int header_of_multiple = 0;
6232   int part_of_multiple = (loc != NULL);
6233   struct value_print_options opts;
6234
6235   get_user_print_options (&opts);
6236
6237   gdb_assert (!loc || loc_number != 0);
6238   /* See comment in print_one_breakpoint concerning treatment of
6239      breakpoints with single disabled location.  */
6240   if (loc == NULL 
6241       && (b->loc != NULL 
6242           && (b->loc->next != NULL || !b->loc->enabled)))
6243     header_of_multiple = 1;
6244   if (loc == NULL)
6245     loc = b->loc;
6246
6247   annotate_record ();
6248
6249   /* 1 */
6250   annotate_field (0);
6251   if (part_of_multiple)
6252     {
6253       char *formatted;
6254       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6255       ui_out_field_string (uiout, "number", formatted);
6256       xfree (formatted);
6257     }
6258   else
6259     {
6260       ui_out_field_int (uiout, "number", b->number);
6261     }
6262
6263   /* 2 */
6264   annotate_field (1);
6265   if (part_of_multiple)
6266     ui_out_field_skip (uiout, "type");
6267   else
6268     ui_out_field_string (uiout, "type", bptype_string (b->type));
6269
6270   /* 3 */
6271   annotate_field (2);
6272   if (part_of_multiple)
6273     ui_out_field_skip (uiout, "disp");
6274   else
6275     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6276
6277
6278   /* 4 */
6279   annotate_field (3);
6280   if (part_of_multiple)
6281     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6282   else
6283     ui_out_field_fmt (uiout, "enabled", "%c", 
6284                       bpenables[(int) b->enable_state]);
6285   ui_out_spaces (uiout, 2);
6286
6287   
6288   /* 5 and 6 */
6289   if (b->ops != NULL && b->ops->print_one != NULL)
6290     {
6291       /* Although the print_one can possibly print all locations,
6292          calling it here is not likely to get any nice result.  So,
6293          make sure there's just one location.  */
6294       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6295       b->ops->print_one (b, last_loc);
6296     }
6297   else
6298     switch (b->type)
6299       {
6300       case bp_none:
6301         internal_error (__FILE__, __LINE__,
6302                         _("print_one_breakpoint: bp_none encountered\n"));
6303         break;
6304
6305       case bp_watchpoint:
6306       case bp_hardware_watchpoint:
6307       case bp_read_watchpoint:
6308       case bp_access_watchpoint:
6309         {
6310           struct watchpoint *w = (struct watchpoint *) b;
6311
6312           /* Field 4, the address, is omitted (which makes the columns
6313              not line up too nicely with the headers, but the effect
6314              is relatively readable).  */
6315           if (opts.addressprint)
6316             ui_out_field_skip (uiout, "addr");
6317           annotate_field (5);
6318           ui_out_field_string (uiout, "what", w->exp_string);
6319         }
6320         break;
6321
6322       case bp_breakpoint:
6323       case bp_hardware_breakpoint:
6324       case bp_single_step:
6325       case bp_until:
6326       case bp_finish:
6327       case bp_longjmp:
6328       case bp_longjmp_resume:
6329       case bp_longjmp_call_dummy:
6330       case bp_exception:
6331       case bp_exception_resume:
6332       case bp_step_resume:
6333       case bp_hp_step_resume:
6334       case bp_watchpoint_scope:
6335       case bp_call_dummy:
6336       case bp_std_terminate:
6337       case bp_shlib_event:
6338       case bp_thread_event:
6339       case bp_overlay_event:
6340       case bp_longjmp_master:
6341       case bp_std_terminate_master:
6342       case bp_exception_master:
6343       case bp_tracepoint:
6344       case bp_fast_tracepoint:
6345       case bp_static_tracepoint:
6346       case bp_dprintf:
6347       case bp_jit_event:
6348       case bp_gnu_ifunc_resolver:
6349       case bp_gnu_ifunc_resolver_return:
6350         if (opts.addressprint)
6351           {
6352             annotate_field (4);
6353             if (header_of_multiple)
6354               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6355             else if (b->loc == NULL || loc->shlib_disabled)
6356               ui_out_field_string (uiout, "addr", "<PENDING>");
6357             else
6358               ui_out_field_core_addr (uiout, "addr",
6359                                       loc->gdbarch, loc->address);
6360           }
6361         annotate_field (5);
6362         if (!header_of_multiple)
6363           print_breakpoint_location (b, loc);
6364         if (b->loc)
6365           *last_loc = b->loc;
6366         break;
6367       }
6368
6369
6370   if (loc != NULL && !header_of_multiple)
6371     {
6372       struct inferior *inf;
6373       VEC(int) *inf_num = NULL;
6374       int mi_only = 1;
6375
6376       ALL_INFERIORS (inf)
6377         {
6378           if (inf->pspace == loc->pspace)
6379             VEC_safe_push (int, inf_num, inf->num);
6380         }
6381
6382         /* For backward compatibility, don't display inferiors in CLI unless
6383            there are several.  Always display for MI. */
6384         if (allflag
6385             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6386                 && (number_of_program_spaces () > 1
6387                     || number_of_inferiors () > 1)
6388                 /* LOC is for existing B, it cannot be in
6389                    moribund_locations and thus having NULL OWNER.  */
6390                 && loc->owner->type != bp_catchpoint))
6391         mi_only = 0;
6392       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6393       VEC_free (int, inf_num);
6394     }
6395
6396   if (!part_of_multiple)
6397     {
6398       if (b->thread != -1)
6399         {
6400           /* FIXME: This seems to be redundant and lost here; see the
6401              "stop only in" line a little further down.  */
6402           ui_out_text (uiout, " thread ");
6403           ui_out_field_int (uiout, "thread", b->thread);
6404         }
6405       else if (b->task != 0)
6406         {
6407           ui_out_text (uiout, " task ");
6408           ui_out_field_int (uiout, "task", b->task);
6409         }
6410     }
6411
6412   ui_out_text (uiout, "\n");
6413
6414   if (!part_of_multiple)
6415     b->ops->print_one_detail (b, uiout);
6416
6417   if (part_of_multiple && frame_id_p (b->frame_id))
6418     {
6419       annotate_field (6);
6420       ui_out_text (uiout, "\tstop only in stack frame at ");
6421       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6422          the frame ID.  */
6423       ui_out_field_core_addr (uiout, "frame",
6424                               b->gdbarch, b->frame_id.stack_addr);
6425       ui_out_text (uiout, "\n");
6426     }
6427   
6428   if (!part_of_multiple && b->cond_string)
6429     {
6430       annotate_field (7);
6431       if (is_tracepoint (b))
6432         ui_out_text (uiout, "\ttrace only if ");
6433       else
6434         ui_out_text (uiout, "\tstop only if ");
6435       ui_out_field_string (uiout, "cond", b->cond_string);
6436
6437       /* Print whether the target is doing the breakpoint's condition
6438          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6439       if (is_breakpoint (b)
6440           && breakpoint_condition_evaluation_mode ()
6441           == condition_evaluation_target)
6442         {
6443           ui_out_text (uiout, " (");
6444           ui_out_field_string (uiout, "evaluated-by",
6445                                bp_condition_evaluator (b));
6446           ui_out_text (uiout, " evals)");
6447         }
6448       ui_out_text (uiout, "\n");
6449     }
6450
6451   if (!part_of_multiple && b->thread != -1)
6452     {
6453       /* FIXME should make an annotation for this.  */
6454       ui_out_text (uiout, "\tstop only in thread ");
6455       ui_out_field_int (uiout, "thread", b->thread);
6456       ui_out_text (uiout, "\n");
6457     }
6458   
6459   if (!part_of_multiple)
6460     {
6461       if (b->hit_count)
6462         {
6463           /* FIXME should make an annotation for this.  */
6464           if (is_catchpoint (b))
6465             ui_out_text (uiout, "\tcatchpoint");
6466           else if (is_tracepoint (b))
6467             ui_out_text (uiout, "\ttracepoint");
6468           else
6469             ui_out_text (uiout, "\tbreakpoint");
6470           ui_out_text (uiout, " already hit ");
6471           ui_out_field_int (uiout, "times", b->hit_count);
6472           if (b->hit_count == 1)
6473             ui_out_text (uiout, " time\n");
6474           else
6475             ui_out_text (uiout, " times\n");
6476         }
6477       else
6478         {
6479           /* Output the count also if it is zero, but only if this is mi.  */
6480           if (ui_out_is_mi_like_p (uiout))
6481             ui_out_field_int (uiout, "times", b->hit_count);
6482         }
6483     }
6484
6485   if (!part_of_multiple && b->ignore_count)
6486     {
6487       annotate_field (8);
6488       ui_out_text (uiout, "\tignore next ");
6489       ui_out_field_int (uiout, "ignore", b->ignore_count);
6490       ui_out_text (uiout, " hits\n");
6491     }
6492
6493   /* Note that an enable count of 1 corresponds to "enable once"
6494      behavior, which is reported by the combination of enablement and
6495      disposition, so we don't need to mention it here.  */
6496   if (!part_of_multiple && b->enable_count > 1)
6497     {
6498       annotate_field (8);
6499       ui_out_text (uiout, "\tdisable after ");
6500       /* Tweak the wording to clarify that ignore and enable counts
6501          are distinct, and have additive effect.  */
6502       if (b->ignore_count)
6503         ui_out_text (uiout, "additional ");
6504       else
6505         ui_out_text (uiout, "next ");
6506       ui_out_field_int (uiout, "enable", b->enable_count);
6507       ui_out_text (uiout, " hits\n");
6508     }
6509
6510   if (!part_of_multiple && is_tracepoint (b))
6511     {
6512       struct tracepoint *tp = (struct tracepoint *) b;
6513
6514       if (tp->traceframe_usage)
6515         {
6516           ui_out_text (uiout, "\ttrace buffer usage ");
6517           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6518           ui_out_text (uiout, " bytes\n");
6519         }
6520     }
6521
6522   l = b->commands ? b->commands->commands : NULL;
6523   if (!part_of_multiple && l)
6524     {
6525       struct cleanup *script_chain;
6526
6527       annotate_field (9);
6528       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6529       print_command_lines (uiout, l, 4);
6530       do_cleanups (script_chain);
6531     }
6532
6533   if (is_tracepoint (b))
6534     {
6535       struct tracepoint *t = (struct tracepoint *) b;
6536
6537       if (!part_of_multiple && t->pass_count)
6538         {
6539           annotate_field (10);
6540           ui_out_text (uiout, "\tpass count ");
6541           ui_out_field_int (uiout, "pass", t->pass_count);
6542           ui_out_text (uiout, " \n");
6543         }
6544
6545       /* Don't display it when tracepoint or tracepoint location is
6546          pending.   */
6547       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6548         {
6549           annotate_field (11);
6550
6551           if (ui_out_is_mi_like_p (uiout))
6552             ui_out_field_string (uiout, "installed",
6553                                  loc->inserted ? "y" : "n");
6554           else
6555             {
6556               if (loc->inserted)
6557                 ui_out_text (uiout, "\t");
6558               else
6559                 ui_out_text (uiout, "\tnot ");
6560               ui_out_text (uiout, "installed on target\n");
6561             }
6562         }
6563     }
6564
6565   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6566     {
6567       if (is_watchpoint (b))
6568         {
6569           struct watchpoint *w = (struct watchpoint *) b;
6570
6571           ui_out_field_string (uiout, "original-location", w->exp_string);
6572         }
6573       else if (b->location != NULL
6574                && event_location_to_string (b->location) != NULL)
6575         ui_out_field_string (uiout, "original-location",
6576                              event_location_to_string (b->location));
6577     }
6578 }
6579
6580 static void
6581 print_one_breakpoint (struct breakpoint *b,
6582                       struct bp_location **last_loc, 
6583                       int allflag)
6584 {
6585   struct cleanup *bkpt_chain;
6586   struct ui_out *uiout = current_uiout;
6587
6588   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6589
6590   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6591   do_cleanups (bkpt_chain);
6592
6593   /* If this breakpoint has custom print function,
6594      it's already printed.  Otherwise, print individual
6595      locations, if any.  */
6596   if (b->ops == NULL || b->ops->print_one == NULL)
6597     {
6598       /* If breakpoint has a single location that is disabled, we
6599          print it as if it had several locations, since otherwise it's
6600          hard to represent "breakpoint enabled, location disabled"
6601          situation.
6602
6603          Note that while hardware watchpoints have several locations
6604          internally, that's not a property exposed to user.  */
6605       if (b->loc 
6606           && !is_hardware_watchpoint (b)
6607           && (b->loc->next || !b->loc->enabled))
6608         {
6609           struct bp_location *loc;
6610           int n = 1;
6611
6612           for (loc = b->loc; loc; loc = loc->next, ++n)
6613             {
6614               struct cleanup *inner2 =
6615                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6616               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6617               do_cleanups (inner2);
6618             }
6619         }
6620     }
6621 }
6622
6623 static int
6624 breakpoint_address_bits (struct breakpoint *b)
6625 {
6626   int print_address_bits = 0;
6627   struct bp_location *loc;
6628
6629   for (loc = b->loc; loc; loc = loc->next)
6630     {
6631       int addr_bit;
6632
6633       /* Software watchpoints that aren't watching memory don't have
6634          an address to print.  */
6635       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6636         continue;
6637
6638       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6639       if (addr_bit > print_address_bits)
6640         print_address_bits = addr_bit;
6641     }
6642
6643   return print_address_bits;
6644 }
6645
6646 struct captured_breakpoint_query_args
6647   {
6648     int bnum;
6649   };
6650
6651 static int
6652 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6653 {
6654   struct captured_breakpoint_query_args *args = data;
6655   struct breakpoint *b;
6656   struct bp_location *dummy_loc = NULL;
6657
6658   ALL_BREAKPOINTS (b)
6659     {
6660       if (args->bnum == b->number)
6661         {
6662           print_one_breakpoint (b, &dummy_loc, 0);
6663           return GDB_RC_OK;
6664         }
6665     }
6666   return GDB_RC_NONE;
6667 }
6668
6669 enum gdb_rc
6670 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6671                       char **error_message)
6672 {
6673   struct captured_breakpoint_query_args args;
6674
6675   args.bnum = bnum;
6676   /* For the moment we don't trust print_one_breakpoint() to not throw
6677      an error.  */
6678   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6679                                  error_message, RETURN_MASK_ALL) < 0)
6680     return GDB_RC_FAIL;
6681   else
6682     return GDB_RC_OK;
6683 }
6684
6685 /* Return true if this breakpoint was set by the user, false if it is
6686    internal or momentary.  */
6687
6688 int
6689 user_breakpoint_p (struct breakpoint *b)
6690 {
6691   return b->number > 0;
6692 }
6693
6694 /* Print information on user settable breakpoint (watchpoint, etc)
6695    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6696    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6697    FILTER is non-NULL, call it on each breakpoint and only include the
6698    ones for which it returns non-zero.  Return the total number of
6699    breakpoints listed.  */
6700
6701 static int
6702 breakpoint_1 (char *args, int allflag, 
6703               int (*filter) (const struct breakpoint *))
6704 {
6705   struct breakpoint *b;
6706   struct bp_location *last_loc = NULL;
6707   int nr_printable_breakpoints;
6708   struct cleanup *bkpttbl_chain;
6709   struct value_print_options opts;
6710   int print_address_bits = 0;
6711   int print_type_col_width = 14;
6712   struct ui_out *uiout = current_uiout;
6713
6714   get_user_print_options (&opts);
6715
6716   /* Compute the number of rows in the table, as well as the size
6717      required for address fields.  */
6718   nr_printable_breakpoints = 0;
6719   ALL_BREAKPOINTS (b)
6720     {
6721       /* If we have a filter, only list the breakpoints it accepts.  */
6722       if (filter && !filter (b))
6723         continue;
6724
6725       /* If we have an "args" string, it is a list of breakpoints to 
6726          accept.  Skip the others.  */
6727       if (args != NULL && *args != '\0')
6728         {
6729           if (allflag && parse_and_eval_long (args) != b->number)
6730             continue;
6731           if (!allflag && !number_is_in_list (args, b->number))
6732             continue;
6733         }
6734
6735       if (allflag || user_breakpoint_p (b))
6736         {
6737           int addr_bit, type_len;
6738
6739           addr_bit = breakpoint_address_bits (b);
6740           if (addr_bit > print_address_bits)
6741             print_address_bits = addr_bit;
6742
6743           type_len = strlen (bptype_string (b->type));
6744           if (type_len > print_type_col_width)
6745             print_type_col_width = type_len;
6746
6747           nr_printable_breakpoints++;
6748         }
6749     }
6750
6751   if (opts.addressprint)
6752     bkpttbl_chain 
6753       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6754                                              nr_printable_breakpoints,
6755                                              "BreakpointTable");
6756   else
6757     bkpttbl_chain 
6758       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6759                                              nr_printable_breakpoints,
6760                                              "BreakpointTable");
6761
6762   if (nr_printable_breakpoints > 0)
6763     annotate_breakpoints_headers ();
6764   if (nr_printable_breakpoints > 0)
6765     annotate_field (0);
6766   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6767   if (nr_printable_breakpoints > 0)
6768     annotate_field (1);
6769   ui_out_table_header (uiout, print_type_col_width, ui_left,
6770                        "type", "Type");                         /* 2 */
6771   if (nr_printable_breakpoints > 0)
6772     annotate_field (2);
6773   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6774   if (nr_printable_breakpoints > 0)
6775     annotate_field (3);
6776   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6777   if (opts.addressprint)
6778     {
6779       if (nr_printable_breakpoints > 0)
6780         annotate_field (4);
6781       if (print_address_bits <= 32)
6782         ui_out_table_header (uiout, 10, ui_left, 
6783                              "addr", "Address");                /* 5 */
6784       else
6785         ui_out_table_header (uiout, 18, ui_left, 
6786                              "addr", "Address");                /* 5 */
6787     }
6788   if (nr_printable_breakpoints > 0)
6789     annotate_field (5);
6790   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6791   ui_out_table_body (uiout);
6792   if (nr_printable_breakpoints > 0)
6793     annotate_breakpoints_table ();
6794
6795   ALL_BREAKPOINTS (b)
6796     {
6797       QUIT;
6798       /* If we have a filter, only list the breakpoints it accepts.  */
6799       if (filter && !filter (b))
6800         continue;
6801
6802       /* If we have an "args" string, it is a list of breakpoints to 
6803          accept.  Skip the others.  */
6804
6805       if (args != NULL && *args != '\0')
6806         {
6807           if (allflag)  /* maintenance info breakpoint */
6808             {
6809               if (parse_and_eval_long (args) != b->number)
6810                 continue;
6811             }
6812           else          /* all others */
6813             {
6814               if (!number_is_in_list (args, b->number))
6815                 continue;
6816             }
6817         }
6818       /* We only print out user settable breakpoints unless the
6819          allflag is set.  */
6820       if (allflag || user_breakpoint_p (b))
6821         print_one_breakpoint (b, &last_loc, allflag);
6822     }
6823
6824   do_cleanups (bkpttbl_chain);
6825
6826   if (nr_printable_breakpoints == 0)
6827     {
6828       /* If there's a filter, let the caller decide how to report
6829          empty list.  */
6830       if (!filter)
6831         {
6832           if (args == NULL || *args == '\0')
6833             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6834           else
6835             ui_out_message (uiout, 0, 
6836                             "No breakpoint or watchpoint matching '%s'.\n",
6837                             args);
6838         }
6839     }
6840   else
6841     {
6842       if (last_loc && !server_command)
6843         set_next_address (last_loc->gdbarch, last_loc->address);
6844     }
6845
6846   /* FIXME?  Should this be moved up so that it is only called when
6847      there have been breakpoints? */
6848   annotate_breakpoints_table_end ();
6849
6850   return nr_printable_breakpoints;
6851 }
6852
6853 /* Display the value of default-collect in a way that is generally
6854    compatible with the breakpoint list.  */
6855
6856 static void
6857 default_collect_info (void)
6858 {
6859   struct ui_out *uiout = current_uiout;
6860
6861   /* If it has no value (which is frequently the case), say nothing; a
6862      message like "No default-collect." gets in user's face when it's
6863      not wanted.  */
6864   if (!*default_collect)
6865     return;
6866
6867   /* The following phrase lines up nicely with per-tracepoint collect
6868      actions.  */
6869   ui_out_text (uiout, "default collect ");
6870   ui_out_field_string (uiout, "default-collect", default_collect);
6871   ui_out_text (uiout, " \n");
6872 }
6873   
6874 static void
6875 breakpoints_info (char *args, int from_tty)
6876 {
6877   breakpoint_1 (args, 0, NULL);
6878
6879   default_collect_info ();
6880 }
6881
6882 static void
6883 watchpoints_info (char *args, int from_tty)
6884 {
6885   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6886   struct ui_out *uiout = current_uiout;
6887
6888   if (num_printed == 0)
6889     {
6890       if (args == NULL || *args == '\0')
6891         ui_out_message (uiout, 0, "No watchpoints.\n");
6892       else
6893         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6894     }
6895 }
6896
6897 static void
6898 maintenance_info_breakpoints (char *args, int from_tty)
6899 {
6900   breakpoint_1 (args, 1, NULL);
6901
6902   default_collect_info ();
6903 }
6904
6905 static int
6906 breakpoint_has_pc (struct breakpoint *b,
6907                    struct program_space *pspace,
6908                    CORE_ADDR pc, struct obj_section *section)
6909 {
6910   struct bp_location *bl = b->loc;
6911
6912   for (; bl; bl = bl->next)
6913     {
6914       if (bl->pspace == pspace
6915           && bl->address == pc
6916           && (!overlay_debugging || bl->section == section))
6917         return 1;         
6918     }
6919   return 0;
6920 }
6921
6922 /* Print a message describing any user-breakpoints set at PC.  This
6923    concerns with logical breakpoints, so we match program spaces, not
6924    address spaces.  */
6925
6926 static void
6927 describe_other_breakpoints (struct gdbarch *gdbarch,
6928                             struct program_space *pspace, CORE_ADDR pc,
6929                             struct obj_section *section, int thread)
6930 {
6931   int others = 0;
6932   struct breakpoint *b;
6933
6934   ALL_BREAKPOINTS (b)
6935     others += (user_breakpoint_p (b)
6936                && breakpoint_has_pc (b, pspace, pc, section));
6937   if (others > 0)
6938     {
6939       if (others == 1)
6940         printf_filtered (_("Note: breakpoint "));
6941       else /* if (others == ???) */
6942         printf_filtered (_("Note: breakpoints "));
6943       ALL_BREAKPOINTS (b)
6944         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6945           {
6946             others--;
6947             printf_filtered ("%d", b->number);
6948             if (b->thread == -1 && thread != -1)
6949               printf_filtered (" (all threads)");
6950             else if (b->thread != -1)
6951               printf_filtered (" (thread %d)", b->thread);
6952             printf_filtered ("%s%s ",
6953                              ((b->enable_state == bp_disabled
6954                                || b->enable_state == bp_call_disabled)
6955                               ? " (disabled)"
6956                               : ""),
6957                              (others > 1) ? "," 
6958                              : ((others == 1) ? " and" : ""));
6959           }
6960       printf_filtered (_("also set at pc "));
6961       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6962       printf_filtered (".\n");
6963     }
6964 }
6965 \f
6966
6967 /* Return true iff it is meaningful to use the address member of
6968    BPT locations.  For some breakpoint types, the locations' address members
6969    are irrelevant and it makes no sense to attempt to compare them to other
6970    addresses (or use them for any other purpose either).
6971
6972    More specifically, each of the following breakpoint types will
6973    always have a zero valued location address and we don't want to mark
6974    breakpoints of any of these types to be a duplicate of an actual
6975    breakpoint location at address zero:
6976
6977       bp_watchpoint
6978       bp_catchpoint
6979
6980 */
6981
6982 static int
6983 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6984 {
6985   enum bptype type = bpt->type;
6986
6987   return (type != bp_watchpoint && type != bp_catchpoint);
6988 }
6989
6990 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6991    true if LOC1 and LOC2 represent the same watchpoint location.  */
6992
6993 static int
6994 watchpoint_locations_match (struct bp_location *loc1, 
6995                             struct bp_location *loc2)
6996 {
6997   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6998   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6999
7000   /* Both of them must exist.  */
7001   gdb_assert (w1 != NULL);
7002   gdb_assert (w2 != NULL);
7003
7004   /* If the target can evaluate the condition expression in hardware,
7005      then we we need to insert both watchpoints even if they are at
7006      the same place.  Otherwise the watchpoint will only trigger when
7007      the condition of whichever watchpoint was inserted evaluates to
7008      true, not giving a chance for GDB to check the condition of the
7009      other watchpoint.  */
7010   if ((w1->cond_exp
7011        && target_can_accel_watchpoint_condition (loc1->address, 
7012                                                  loc1->length,
7013                                                  loc1->watchpoint_type,
7014                                                  w1->cond_exp))
7015       || (w2->cond_exp
7016           && target_can_accel_watchpoint_condition (loc2->address, 
7017                                                     loc2->length,
7018                                                     loc2->watchpoint_type,
7019                                                     w2->cond_exp)))
7020     return 0;
7021
7022   /* Note that this checks the owner's type, not the location's.  In
7023      case the target does not support read watchpoints, but does
7024      support access watchpoints, we'll have bp_read_watchpoint
7025      watchpoints with hw_access locations.  Those should be considered
7026      duplicates of hw_read locations.  The hw_read locations will
7027      become hw_access locations later.  */
7028   return (loc1->owner->type == loc2->owner->type
7029           && loc1->pspace->aspace == loc2->pspace->aspace
7030           && loc1->address == loc2->address
7031           && loc1->length == loc2->length);
7032 }
7033
7034 /* See breakpoint.h.  */
7035
7036 int
7037 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7038                           struct address_space *aspace2, CORE_ADDR addr2)
7039 {
7040   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7041            || aspace1 == aspace2)
7042           && addr1 == addr2);
7043 }
7044
7045 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7046    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7047    matches ASPACE2.  On targets that have global breakpoints, the address
7048    space doesn't really matter.  */
7049
7050 static int
7051 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7052                                 int len1, struct address_space *aspace2,
7053                                 CORE_ADDR addr2)
7054 {
7055   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7056            || aspace1 == aspace2)
7057           && addr2 >= addr1 && addr2 < addr1 + len1);
7058 }
7059
7060 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7061    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7062    matches the breakpoint's address space.  On targets that have global
7063    breakpoints, the address space doesn't really matter.  */
7064
7065 static int
7066 breakpoint_location_address_match (struct bp_location *bl,
7067                                    struct address_space *aspace,
7068                                    CORE_ADDR addr)
7069 {
7070   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7071                                     aspace, addr)
7072           || (bl->length
7073               && breakpoint_address_match_range (bl->pspace->aspace,
7074                                                  bl->address, bl->length,
7075                                                  aspace, addr)));
7076 }
7077
7078 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7079    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7080    true, otherwise returns false.  */
7081
7082 static int
7083 tracepoint_locations_match (struct bp_location *loc1,
7084                             struct bp_location *loc2)
7085 {
7086   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7087     /* Since tracepoint locations are never duplicated with others', tracepoint
7088        locations at the same address of different tracepoints are regarded as
7089        different locations.  */
7090     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7091   else
7092     return 0;
7093 }
7094
7095 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7096    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7097    represent the same location.  */
7098
7099 static int
7100 breakpoint_locations_match (struct bp_location *loc1, 
7101                             struct bp_location *loc2)
7102 {
7103   int hw_point1, hw_point2;
7104
7105   /* Both of them must not be in moribund_locations.  */
7106   gdb_assert (loc1->owner != NULL);
7107   gdb_assert (loc2->owner != NULL);
7108
7109   hw_point1 = is_hardware_watchpoint (loc1->owner);
7110   hw_point2 = is_hardware_watchpoint (loc2->owner);
7111
7112   if (hw_point1 != hw_point2)
7113     return 0;
7114   else if (hw_point1)
7115     return watchpoint_locations_match (loc1, loc2);
7116   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7117     return tracepoint_locations_match (loc1, loc2);
7118   else
7119     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7120     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7121                                      loc2->pspace->aspace, loc2->address)
7122             && loc1->length == loc2->length);
7123 }
7124
7125 static void
7126 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7127                                int bnum, int have_bnum)
7128 {
7129   /* The longest string possibly returned by hex_string_custom
7130      is 50 chars.  These must be at least that big for safety.  */
7131   char astr1[64];
7132   char astr2[64];
7133
7134   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7135   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7136   if (have_bnum)
7137     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7138              bnum, astr1, astr2);
7139   else
7140     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7141 }
7142
7143 /* Adjust a breakpoint's address to account for architectural
7144    constraints on breakpoint placement.  Return the adjusted address.
7145    Note: Very few targets require this kind of adjustment.  For most
7146    targets, this function is simply the identity function.  */
7147
7148 static CORE_ADDR
7149 adjust_breakpoint_address (struct gdbarch *gdbarch,
7150                            CORE_ADDR bpaddr, enum bptype bptype)
7151 {
7152   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7153     {
7154       /* Very few targets need any kind of breakpoint adjustment.  */
7155       return bpaddr;
7156     }
7157   else if (bptype == bp_watchpoint
7158            || bptype == bp_hardware_watchpoint
7159            || bptype == bp_read_watchpoint
7160            || bptype == bp_access_watchpoint
7161            || bptype == bp_catchpoint)
7162     {
7163       /* Watchpoints and the various bp_catch_* eventpoints should not
7164          have their addresses modified.  */
7165       return bpaddr;
7166     }
7167   else if (bptype == bp_single_step)
7168     {
7169       /* Single-step breakpoints should not have their addresses
7170          modified.  If there's any architectural constrain that
7171          applies to this address, then it should have already been
7172          taken into account when the breakpoint was created in the
7173          first place.  If we didn't do this, stepping through e.g.,
7174          Thumb-2 IT blocks would break.  */
7175       return bpaddr;
7176     }
7177   else
7178     {
7179       CORE_ADDR adjusted_bpaddr;
7180
7181       /* Some targets have architectural constraints on the placement
7182          of breakpoint instructions.  Obtain the adjusted address.  */
7183       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7184
7185       /* An adjusted breakpoint address can significantly alter
7186          a user's expectations.  Print a warning if an adjustment
7187          is required.  */
7188       if (adjusted_bpaddr != bpaddr)
7189         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7190
7191       return adjusted_bpaddr;
7192     }
7193 }
7194
7195 void
7196 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7197                   struct breakpoint *owner)
7198 {
7199   memset (loc, 0, sizeof (*loc));
7200
7201   gdb_assert (ops != NULL);
7202
7203   loc->ops = ops;
7204   loc->owner = owner;
7205   loc->cond = NULL;
7206   loc->cond_bytecode = NULL;
7207   loc->shlib_disabled = 0;
7208   loc->enabled = 1;
7209
7210   switch (owner->type)
7211     {
7212     case bp_breakpoint:
7213     case bp_single_step:
7214     case bp_until:
7215     case bp_finish:
7216     case bp_longjmp:
7217     case bp_longjmp_resume:
7218     case bp_longjmp_call_dummy:
7219     case bp_exception:
7220     case bp_exception_resume:
7221     case bp_step_resume:
7222     case bp_hp_step_resume:
7223     case bp_watchpoint_scope:
7224     case bp_call_dummy:
7225     case bp_std_terminate:
7226     case bp_shlib_event:
7227     case bp_thread_event:
7228     case bp_overlay_event:
7229     case bp_jit_event:
7230     case bp_longjmp_master:
7231     case bp_std_terminate_master:
7232     case bp_exception_master:
7233     case bp_gnu_ifunc_resolver:
7234     case bp_gnu_ifunc_resolver_return:
7235     case bp_dprintf:
7236       loc->loc_type = bp_loc_software_breakpoint;
7237       mark_breakpoint_location_modified (loc);
7238       break;
7239     case bp_hardware_breakpoint:
7240       loc->loc_type = bp_loc_hardware_breakpoint;
7241       mark_breakpoint_location_modified (loc);
7242       break;
7243     case bp_hardware_watchpoint:
7244     case bp_read_watchpoint:
7245     case bp_access_watchpoint:
7246       loc->loc_type = bp_loc_hardware_watchpoint;
7247       break;
7248     case bp_watchpoint:
7249     case bp_catchpoint:
7250     case bp_tracepoint:
7251     case bp_fast_tracepoint:
7252     case bp_static_tracepoint:
7253       loc->loc_type = bp_loc_other;
7254       break;
7255     default:
7256       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7257     }
7258
7259   loc->refc = 1;
7260 }
7261
7262 /* Allocate a struct bp_location.  */
7263
7264 static struct bp_location *
7265 allocate_bp_location (struct breakpoint *bpt)
7266 {
7267   return bpt->ops->allocate_location (bpt);
7268 }
7269
7270 static void
7271 free_bp_location (struct bp_location *loc)
7272 {
7273   loc->ops->dtor (loc);
7274   xfree (loc);
7275 }
7276
7277 /* Increment reference count.  */
7278
7279 static void
7280 incref_bp_location (struct bp_location *bl)
7281 {
7282   ++bl->refc;
7283 }
7284
7285 /* Decrement reference count.  If the reference count reaches 0,
7286    destroy the bp_location.  Sets *BLP to NULL.  */
7287
7288 static void
7289 decref_bp_location (struct bp_location **blp)
7290 {
7291   gdb_assert ((*blp)->refc > 0);
7292
7293   if (--(*blp)->refc == 0)
7294     free_bp_location (*blp);
7295   *blp = NULL;
7296 }
7297
7298 /* Add breakpoint B at the end of the global breakpoint chain.  */
7299
7300 static void
7301 add_to_breakpoint_chain (struct breakpoint *b)
7302 {
7303   struct breakpoint *b1;
7304
7305   /* Add this breakpoint to the end of the chain so that a list of
7306      breakpoints will come out in order of increasing numbers.  */
7307
7308   b1 = breakpoint_chain;
7309   if (b1 == 0)
7310     breakpoint_chain = b;
7311   else
7312     {
7313       while (b1->next)
7314         b1 = b1->next;
7315       b1->next = b;
7316     }
7317 }
7318
7319 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7320
7321 static void
7322 init_raw_breakpoint_without_location (struct breakpoint *b,
7323                                       struct gdbarch *gdbarch,
7324                                       enum bptype bptype,
7325                                       const struct breakpoint_ops *ops)
7326 {
7327   memset (b, 0, sizeof (*b));
7328
7329   gdb_assert (ops != NULL);
7330
7331   b->ops = ops;
7332   b->type = bptype;
7333   b->gdbarch = gdbarch;
7334   b->language = current_language->la_language;
7335   b->input_radix = input_radix;
7336   b->thread = -1;
7337   b->enable_state = bp_enabled;
7338   b->next = 0;
7339   b->silent = 0;
7340   b->ignore_count = 0;
7341   b->commands = NULL;
7342   b->frame_id = null_frame_id;
7343   b->condition_not_parsed = 0;
7344   b->py_bp_object = NULL;
7345   b->related_breakpoint = b;
7346   b->location = NULL;
7347 }
7348
7349 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7350    that has type BPTYPE and has no locations as yet.  */
7351
7352 static struct breakpoint *
7353 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7354                                      enum bptype bptype,
7355                                      const struct breakpoint_ops *ops)
7356 {
7357   struct breakpoint *b = XNEW (struct breakpoint);
7358
7359   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7360   add_to_breakpoint_chain (b);
7361   return b;
7362 }
7363
7364 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7365    resolutions should be made as the user specified the location explicitly
7366    enough.  */
7367
7368 static void
7369 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7370 {
7371   gdb_assert (loc->owner != NULL);
7372
7373   if (loc->owner->type == bp_breakpoint
7374       || loc->owner->type == bp_hardware_breakpoint
7375       || is_tracepoint (loc->owner))
7376     {
7377       int is_gnu_ifunc;
7378       const char *function_name;
7379       CORE_ADDR func_addr;
7380
7381       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7382                                           &func_addr, NULL, &is_gnu_ifunc);
7383
7384       if (is_gnu_ifunc && !explicit_loc)
7385         {
7386           struct breakpoint *b = loc->owner;
7387
7388           gdb_assert (loc->pspace == current_program_space);
7389           if (gnu_ifunc_resolve_name (function_name,
7390                                       &loc->requested_address))
7391             {
7392               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7393               loc->address = adjust_breakpoint_address (loc->gdbarch,
7394                                                         loc->requested_address,
7395                                                         b->type);
7396             }
7397           else if (b->type == bp_breakpoint && b->loc == loc
7398                    && loc->next == NULL && b->related_breakpoint == b)
7399             {
7400               /* Create only the whole new breakpoint of this type but do not
7401                  mess more complicated breakpoints with multiple locations.  */
7402               b->type = bp_gnu_ifunc_resolver;
7403               /* Remember the resolver's address for use by the return
7404                  breakpoint.  */
7405               loc->related_address = func_addr;
7406             }
7407         }
7408
7409       if (function_name)
7410         loc->function_name = xstrdup (function_name);
7411     }
7412 }
7413
7414 /* Attempt to determine architecture of location identified by SAL.  */
7415 struct gdbarch *
7416 get_sal_arch (struct symtab_and_line sal)
7417 {
7418   if (sal.section)
7419     return get_objfile_arch (sal.section->objfile);
7420   if (sal.symtab)
7421     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7422
7423   return NULL;
7424 }
7425
7426 /* Low level routine for partially initializing a breakpoint of type
7427    BPTYPE.  The newly created breakpoint's address, section, source
7428    file name, and line number are provided by SAL.
7429
7430    It is expected that the caller will complete the initialization of
7431    the newly created breakpoint struct as well as output any status
7432    information regarding the creation of a new breakpoint.  */
7433
7434 static void
7435 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7436                      struct symtab_and_line sal, enum bptype bptype,
7437                      const struct breakpoint_ops *ops)
7438 {
7439   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7440
7441   add_location_to_breakpoint (b, &sal);
7442
7443   if (bptype != bp_catchpoint)
7444     gdb_assert (sal.pspace != NULL);
7445
7446   /* Store the program space that was used to set the breakpoint,
7447      except for ordinary breakpoints, which are independent of the
7448      program space.  */
7449   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7450     b->pspace = sal.pspace;
7451 }
7452
7453 /* set_raw_breakpoint is a low level routine for allocating and
7454    partially initializing a breakpoint of type BPTYPE.  The newly
7455    created breakpoint's address, section, source file name, and line
7456    number are provided by SAL.  The newly created and partially
7457    initialized breakpoint is added to the breakpoint chain and
7458    is also returned as the value of this function.
7459
7460    It is expected that the caller will complete the initialization of
7461    the newly created breakpoint struct as well as output any status
7462    information regarding the creation of a new breakpoint.  In
7463    particular, set_raw_breakpoint does NOT set the breakpoint
7464    number!  Care should be taken to not allow an error to occur
7465    prior to completing the initialization of the breakpoint.  If this
7466    should happen, a bogus breakpoint will be left on the chain.  */
7467
7468 struct breakpoint *
7469 set_raw_breakpoint (struct gdbarch *gdbarch,
7470                     struct symtab_and_line sal, enum bptype bptype,
7471                     const struct breakpoint_ops *ops)
7472 {
7473   struct breakpoint *b = XNEW (struct breakpoint);
7474
7475   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7476   add_to_breakpoint_chain (b);
7477   return b;
7478 }
7479
7480 /* Call this routine when stepping and nexting to enable a breakpoint
7481    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7482    initiated the operation.  */
7483
7484 void
7485 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7486 {
7487   struct breakpoint *b, *b_tmp;
7488   int thread = tp->num;
7489
7490   /* To avoid having to rescan all objfile symbols at every step,
7491      we maintain a list of continually-inserted but always disabled
7492      longjmp "master" breakpoints.  Here, we simply create momentary
7493      clones of those and enable them for the requested thread.  */
7494   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7495     if (b->pspace == current_program_space
7496         && (b->type == bp_longjmp_master
7497             || b->type == bp_exception_master))
7498       {
7499         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7500         struct breakpoint *clone;
7501
7502         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7503            after their removal.  */
7504         clone = momentary_breakpoint_from_master (b, type,
7505                                                   &longjmp_breakpoint_ops, 1);
7506         clone->thread = thread;
7507       }
7508
7509   tp->initiating_frame = frame;
7510 }
7511
7512 /* Delete all longjmp breakpoints from THREAD.  */
7513 void
7514 delete_longjmp_breakpoint (int thread)
7515 {
7516   struct breakpoint *b, *b_tmp;
7517
7518   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7519     if (b->type == bp_longjmp || b->type == bp_exception)
7520       {
7521         if (b->thread == thread)
7522           delete_breakpoint (b);
7523       }
7524 }
7525
7526 void
7527 delete_longjmp_breakpoint_at_next_stop (int thread)
7528 {
7529   struct breakpoint *b, *b_tmp;
7530
7531   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7532     if (b->type == bp_longjmp || b->type == bp_exception)
7533       {
7534         if (b->thread == thread)
7535           b->disposition = disp_del_at_next_stop;
7536       }
7537 }
7538
7539 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7540    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7541    pointer to any of them.  Return NULL if this system cannot place longjmp
7542    breakpoints.  */
7543
7544 struct breakpoint *
7545 set_longjmp_breakpoint_for_call_dummy (void)
7546 {
7547   struct breakpoint *b, *retval = NULL;
7548
7549   ALL_BREAKPOINTS (b)
7550     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7551       {
7552         struct breakpoint *new_b;
7553
7554         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7555                                                   &momentary_breakpoint_ops,
7556                                                   1);
7557         new_b->thread = pid_to_thread_id (inferior_ptid);
7558
7559         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7560
7561         gdb_assert (new_b->related_breakpoint == new_b);
7562         if (retval == NULL)
7563           retval = new_b;
7564         new_b->related_breakpoint = retval;
7565         while (retval->related_breakpoint != new_b->related_breakpoint)
7566           retval = retval->related_breakpoint;
7567         retval->related_breakpoint = new_b;
7568       }
7569
7570   return retval;
7571 }
7572
7573 /* Verify all existing dummy frames and their associated breakpoints for
7574    TP.  Remove those which can no longer be found in the current frame
7575    stack.
7576
7577    You should call this function only at places where it is safe to currently
7578    unwind the whole stack.  Failed stack unwind would discard live dummy
7579    frames.  */
7580
7581 void
7582 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7583 {
7584   struct breakpoint *b, *b_tmp;
7585
7586   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7587     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7588       {
7589         struct breakpoint *dummy_b = b->related_breakpoint;
7590
7591         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7592           dummy_b = dummy_b->related_breakpoint;
7593         if (dummy_b->type != bp_call_dummy
7594             || frame_find_by_id (dummy_b->frame_id) != NULL)
7595           continue;
7596         
7597         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7598
7599         while (b->related_breakpoint != b)
7600           {
7601             if (b_tmp == b->related_breakpoint)
7602               b_tmp = b->related_breakpoint->next;
7603             delete_breakpoint (b->related_breakpoint);
7604           }
7605         delete_breakpoint (b);
7606       }
7607 }
7608
7609 void
7610 enable_overlay_breakpoints (void)
7611 {
7612   struct breakpoint *b;
7613
7614   ALL_BREAKPOINTS (b)
7615     if (b->type == bp_overlay_event)
7616     {
7617       b->enable_state = bp_enabled;
7618       update_global_location_list (UGLL_MAY_INSERT);
7619       overlay_events_enabled = 1;
7620     }
7621 }
7622
7623 void
7624 disable_overlay_breakpoints (void)
7625 {
7626   struct breakpoint *b;
7627
7628   ALL_BREAKPOINTS (b)
7629     if (b->type == bp_overlay_event)
7630     {
7631       b->enable_state = bp_disabled;
7632       update_global_location_list (UGLL_DONT_INSERT);
7633       overlay_events_enabled = 0;
7634     }
7635 }
7636
7637 /* Set an active std::terminate breakpoint for each std::terminate
7638    master breakpoint.  */
7639 void
7640 set_std_terminate_breakpoint (void)
7641 {
7642   struct breakpoint *b, *b_tmp;
7643
7644   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7645     if (b->pspace == current_program_space
7646         && b->type == bp_std_terminate_master)
7647       {
7648         momentary_breakpoint_from_master (b, bp_std_terminate,
7649                                           &momentary_breakpoint_ops, 1);
7650       }
7651 }
7652
7653 /* Delete all the std::terminate breakpoints.  */
7654 void
7655 delete_std_terminate_breakpoint (void)
7656 {
7657   struct breakpoint *b, *b_tmp;
7658
7659   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7660     if (b->type == bp_std_terminate)
7661       delete_breakpoint (b);
7662 }
7663
7664 struct breakpoint *
7665 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7666 {
7667   struct breakpoint *b;
7668
7669   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7670                                   &internal_breakpoint_ops);
7671
7672   b->enable_state = bp_enabled;
7673   /* location has to be used or breakpoint_re_set will delete me.  */
7674   b->location = new_address_location (b->loc->address);
7675
7676   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7677
7678   return b;
7679 }
7680
7681 void
7682 remove_thread_event_breakpoints (void)
7683 {
7684   struct breakpoint *b, *b_tmp;
7685
7686   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7687     if (b->type == bp_thread_event
7688         && b->loc->pspace == current_program_space)
7689       delete_breakpoint (b);
7690 }
7691
7692 struct lang_and_radix
7693   {
7694     enum language lang;
7695     int radix;
7696   };
7697
7698 /* Create a breakpoint for JIT code registration and unregistration.  */
7699
7700 struct breakpoint *
7701 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7702 {
7703   struct breakpoint *b;
7704
7705   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7706                                   &internal_breakpoint_ops);
7707   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7708   return b;
7709 }
7710
7711 /* Remove JIT code registration and unregistration breakpoint(s).  */
7712
7713 void
7714 remove_jit_event_breakpoints (void)
7715 {
7716   struct breakpoint *b, *b_tmp;
7717
7718   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7719     if (b->type == bp_jit_event
7720         && b->loc->pspace == current_program_space)
7721       delete_breakpoint (b);
7722 }
7723
7724 void
7725 remove_solib_event_breakpoints (void)
7726 {
7727   struct breakpoint *b, *b_tmp;
7728
7729   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7730     if (b->type == bp_shlib_event
7731         && b->loc->pspace == current_program_space)
7732       delete_breakpoint (b);
7733 }
7734
7735 /* See breakpoint.h.  */
7736
7737 void
7738 remove_solib_event_breakpoints_at_next_stop (void)
7739 {
7740   struct breakpoint *b, *b_tmp;
7741
7742   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7743     if (b->type == bp_shlib_event
7744         && b->loc->pspace == current_program_space)
7745       b->disposition = disp_del_at_next_stop;
7746 }
7747
7748 /* Helper for create_solib_event_breakpoint /
7749    create_and_insert_solib_event_breakpoint.  Allows specifying which
7750    INSERT_MODE to pass through to update_global_location_list.  */
7751
7752 static struct breakpoint *
7753 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7754                                  enum ugll_insert_mode insert_mode)
7755 {
7756   struct breakpoint *b;
7757
7758   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7759                                   &internal_breakpoint_ops);
7760   update_global_location_list_nothrow (insert_mode);
7761   return b;
7762 }
7763
7764 struct breakpoint *
7765 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7766 {
7767   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7768 }
7769
7770 /* See breakpoint.h.  */
7771
7772 struct breakpoint *
7773 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7774 {
7775   struct breakpoint *b;
7776
7777   /* Explicitly tell update_global_location_list to insert
7778      locations.  */
7779   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7780   if (!b->loc->inserted)
7781     {
7782       delete_breakpoint (b);
7783       return NULL;
7784     }
7785   return b;
7786 }
7787
7788 /* Disable any breakpoints that are on code in shared libraries.  Only
7789    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7790
7791 void
7792 disable_breakpoints_in_shlibs (void)
7793 {
7794   struct bp_location *loc, **locp_tmp;
7795
7796   ALL_BP_LOCATIONS (loc, locp_tmp)
7797   {
7798     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7799     struct breakpoint *b = loc->owner;
7800
7801     /* We apply the check to all breakpoints, including disabled for
7802        those with loc->duplicate set.  This is so that when breakpoint
7803        becomes enabled, or the duplicate is removed, gdb will try to
7804        insert all breakpoints.  If we don't set shlib_disabled here,
7805        we'll try to insert those breakpoints and fail.  */
7806     if (((b->type == bp_breakpoint)
7807          || (b->type == bp_jit_event)
7808          || (b->type == bp_hardware_breakpoint)
7809          || (is_tracepoint (b)))
7810         && loc->pspace == current_program_space
7811         && !loc->shlib_disabled
7812         && solib_name_from_address (loc->pspace, loc->address)
7813         )
7814       {
7815         loc->shlib_disabled = 1;
7816       }
7817   }
7818 }
7819
7820 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7821    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7822    disabled ones can just stay disabled.  */
7823
7824 static void
7825 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7826 {
7827   struct bp_location *loc, **locp_tmp;
7828   int disabled_shlib_breaks = 0;
7829
7830   /* SunOS a.out shared libraries are always mapped, so do not
7831      disable breakpoints; they will only be reported as unloaded
7832      through clear_solib when GDB discards its shared library
7833      list.  See clear_solib for more information.  */
7834   if (exec_bfd != NULL
7835       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7836     return;
7837
7838   ALL_BP_LOCATIONS (loc, locp_tmp)
7839   {
7840     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7841     struct breakpoint *b = loc->owner;
7842
7843     if (solib->pspace == loc->pspace
7844         && !loc->shlib_disabled
7845         && (((b->type == bp_breakpoint
7846               || b->type == bp_jit_event
7847               || b->type == bp_hardware_breakpoint)
7848              && (loc->loc_type == bp_loc_hardware_breakpoint
7849                  || loc->loc_type == bp_loc_software_breakpoint))
7850             || is_tracepoint (b))
7851         && solib_contains_address_p (solib, loc->address))
7852       {
7853         loc->shlib_disabled = 1;
7854         /* At this point, we cannot rely on remove_breakpoint
7855            succeeding so we must mark the breakpoint as not inserted
7856            to prevent future errors occurring in remove_breakpoints.  */
7857         loc->inserted = 0;
7858
7859         /* This may cause duplicate notifications for the same breakpoint.  */
7860         observer_notify_breakpoint_modified (b);
7861
7862         if (!disabled_shlib_breaks)
7863           {
7864             target_terminal_ours_for_output ();
7865             warning (_("Temporarily disabling breakpoints "
7866                        "for unloaded shared library \"%s\""),
7867                      solib->so_name);
7868           }
7869         disabled_shlib_breaks = 1;
7870       }
7871   }
7872 }
7873
7874 /* Disable any breakpoints and tracepoints in OBJFILE upon
7875    notification of free_objfile.  Only apply to enabled breakpoints,
7876    disabled ones can just stay disabled.  */
7877
7878 static void
7879 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7880 {
7881   struct breakpoint *b;
7882
7883   if (objfile == NULL)
7884     return;
7885
7886   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7887      managed by the user with add-symbol-file/remove-symbol-file.
7888      Similarly to how breakpoints in shared libraries are handled in
7889      response to "nosharedlibrary", mark breakpoints in such modules
7890      shlib_disabled so they end up uninserted on the next global
7891      location list update.  Shared libraries not loaded by the user
7892      aren't handled here -- they're already handled in
7893      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7894      solib_unloaded observer.  We skip objfiles that are not
7895      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7896      main objfile).  */
7897   if ((objfile->flags & OBJF_SHARED) == 0
7898       || (objfile->flags & OBJF_USERLOADED) == 0)
7899     return;
7900
7901   ALL_BREAKPOINTS (b)
7902     {
7903       struct bp_location *loc;
7904       int bp_modified = 0;
7905
7906       if (!is_breakpoint (b) && !is_tracepoint (b))
7907         continue;
7908
7909       for (loc = b->loc; loc != NULL; loc = loc->next)
7910         {
7911           CORE_ADDR loc_addr = loc->address;
7912
7913           if (loc->loc_type != bp_loc_hardware_breakpoint
7914               && loc->loc_type != bp_loc_software_breakpoint)
7915             continue;
7916
7917           if (loc->shlib_disabled != 0)
7918             continue;
7919
7920           if (objfile->pspace != loc->pspace)
7921             continue;
7922
7923           if (loc->loc_type != bp_loc_hardware_breakpoint
7924               && loc->loc_type != bp_loc_software_breakpoint)
7925             continue;
7926
7927           if (is_addr_in_objfile (loc_addr, objfile))
7928             {
7929               loc->shlib_disabled = 1;
7930               /* At this point, we don't know whether the object was
7931                  unmapped from the inferior or not, so leave the
7932                  inserted flag alone.  We'll handle failure to
7933                  uninsert quietly, in case the object was indeed
7934                  unmapped.  */
7935
7936               mark_breakpoint_location_modified (loc);
7937
7938               bp_modified = 1;
7939             }
7940         }
7941
7942       if (bp_modified)
7943         observer_notify_breakpoint_modified (b);
7944     }
7945 }
7946
7947 /* FORK & VFORK catchpoints.  */
7948
7949 /* An instance of this type is used to represent a fork or vfork
7950    catchpoint.  It includes a "struct breakpoint" as a kind of base
7951    class; users downcast to "struct breakpoint *" when needed.  A
7952    breakpoint is really of this type iff its ops pointer points to
7953    CATCH_FORK_BREAKPOINT_OPS.  */
7954
7955 struct fork_catchpoint
7956 {
7957   /* The base class.  */
7958   struct breakpoint base;
7959
7960   /* Process id of a child process whose forking triggered this
7961      catchpoint.  This field is only valid immediately after this
7962      catchpoint has triggered.  */
7963   ptid_t forked_inferior_pid;
7964 };
7965
7966 /* Implement the "insert" breakpoint_ops method for fork
7967    catchpoints.  */
7968
7969 static int
7970 insert_catch_fork (struct bp_location *bl)
7971 {
7972   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7973 }
7974
7975 /* Implement the "remove" breakpoint_ops method for fork
7976    catchpoints.  */
7977
7978 static int
7979 remove_catch_fork (struct bp_location *bl)
7980 {
7981   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7982 }
7983
7984 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7985    catchpoints.  */
7986
7987 static int
7988 breakpoint_hit_catch_fork (const struct bp_location *bl,
7989                            struct address_space *aspace, CORE_ADDR bp_addr,
7990                            const struct target_waitstatus *ws)
7991 {
7992   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7993
7994   if (ws->kind != TARGET_WAITKIND_FORKED)
7995     return 0;
7996
7997   c->forked_inferior_pid = ws->value.related_pid;
7998   return 1;
7999 }
8000
8001 /* Implement the "print_it" breakpoint_ops method for fork
8002    catchpoints.  */
8003
8004 static enum print_stop_action
8005 print_it_catch_fork (bpstat bs)
8006 {
8007   struct ui_out *uiout = current_uiout;
8008   struct breakpoint *b = bs->breakpoint_at;
8009   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8010
8011   annotate_catchpoint (b->number);
8012   if (b->disposition == disp_del)
8013     ui_out_text (uiout, "\nTemporary catchpoint ");
8014   else
8015     ui_out_text (uiout, "\nCatchpoint ");
8016   if (ui_out_is_mi_like_p (uiout))
8017     {
8018       ui_out_field_string (uiout, "reason",
8019                            async_reason_lookup (EXEC_ASYNC_FORK));
8020       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8021     }
8022   ui_out_field_int (uiout, "bkptno", b->number);
8023   ui_out_text (uiout, " (forked process ");
8024   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8025   ui_out_text (uiout, "), ");
8026   return PRINT_SRC_AND_LOC;
8027 }
8028
8029 /* Implement the "print_one" breakpoint_ops method for fork
8030    catchpoints.  */
8031
8032 static void
8033 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8034 {
8035   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8036   struct value_print_options opts;
8037   struct ui_out *uiout = current_uiout;
8038
8039   get_user_print_options (&opts);
8040
8041   /* Field 4, the address, is omitted (which makes the columns not
8042      line up too nicely with the headers, but the effect is relatively
8043      readable).  */
8044   if (opts.addressprint)
8045     ui_out_field_skip (uiout, "addr");
8046   annotate_field (5);
8047   ui_out_text (uiout, "fork");
8048   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8049     {
8050       ui_out_text (uiout, ", process ");
8051       ui_out_field_int (uiout, "what",
8052                         ptid_get_pid (c->forked_inferior_pid));
8053       ui_out_spaces (uiout, 1);
8054     }
8055
8056   if (ui_out_is_mi_like_p (uiout))
8057     ui_out_field_string (uiout, "catch-type", "fork");
8058 }
8059
8060 /* Implement the "print_mention" breakpoint_ops method for fork
8061    catchpoints.  */
8062
8063 static void
8064 print_mention_catch_fork (struct breakpoint *b)
8065 {
8066   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8067 }
8068
8069 /* Implement the "print_recreate" breakpoint_ops method for fork
8070    catchpoints.  */
8071
8072 static void
8073 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8074 {
8075   fprintf_unfiltered (fp, "catch fork");
8076   print_recreate_thread (b, fp);
8077 }
8078
8079 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8080
8081 static struct breakpoint_ops catch_fork_breakpoint_ops;
8082
8083 /* Implement the "insert" breakpoint_ops method for vfork
8084    catchpoints.  */
8085
8086 static int
8087 insert_catch_vfork (struct bp_location *bl)
8088 {
8089   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8090 }
8091
8092 /* Implement the "remove" breakpoint_ops method for vfork
8093    catchpoints.  */
8094
8095 static int
8096 remove_catch_vfork (struct bp_location *bl)
8097 {
8098   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8099 }
8100
8101 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8102    catchpoints.  */
8103
8104 static int
8105 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8106                             struct address_space *aspace, CORE_ADDR bp_addr,
8107                             const struct target_waitstatus *ws)
8108 {
8109   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8110
8111   if (ws->kind != TARGET_WAITKIND_VFORKED)
8112     return 0;
8113
8114   c->forked_inferior_pid = ws->value.related_pid;
8115   return 1;
8116 }
8117
8118 /* Implement the "print_it" breakpoint_ops method for vfork
8119    catchpoints.  */
8120
8121 static enum print_stop_action
8122 print_it_catch_vfork (bpstat bs)
8123 {
8124   struct ui_out *uiout = current_uiout;
8125   struct breakpoint *b = bs->breakpoint_at;
8126   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8127
8128   annotate_catchpoint (b->number);
8129   if (b->disposition == disp_del)
8130     ui_out_text (uiout, "\nTemporary catchpoint ");
8131   else
8132     ui_out_text (uiout, "\nCatchpoint ");
8133   if (ui_out_is_mi_like_p (uiout))
8134     {
8135       ui_out_field_string (uiout, "reason",
8136                            async_reason_lookup (EXEC_ASYNC_VFORK));
8137       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8138     }
8139   ui_out_field_int (uiout, "bkptno", b->number);
8140   ui_out_text (uiout, " (vforked process ");
8141   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8142   ui_out_text (uiout, "), ");
8143   return PRINT_SRC_AND_LOC;
8144 }
8145
8146 /* Implement the "print_one" breakpoint_ops method for vfork
8147    catchpoints.  */
8148
8149 static void
8150 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8151 {
8152   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8153   struct value_print_options opts;
8154   struct ui_out *uiout = current_uiout;
8155
8156   get_user_print_options (&opts);
8157   /* Field 4, the address, is omitted (which makes the columns not
8158      line up too nicely with the headers, but the effect is relatively
8159      readable).  */
8160   if (opts.addressprint)
8161     ui_out_field_skip (uiout, "addr");
8162   annotate_field (5);
8163   ui_out_text (uiout, "vfork");
8164   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8165     {
8166       ui_out_text (uiout, ", process ");
8167       ui_out_field_int (uiout, "what",
8168                         ptid_get_pid (c->forked_inferior_pid));
8169       ui_out_spaces (uiout, 1);
8170     }
8171
8172   if (ui_out_is_mi_like_p (uiout))
8173     ui_out_field_string (uiout, "catch-type", "vfork");
8174 }
8175
8176 /* Implement the "print_mention" breakpoint_ops method for vfork
8177    catchpoints.  */
8178
8179 static void
8180 print_mention_catch_vfork (struct breakpoint *b)
8181 {
8182   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8183 }
8184
8185 /* Implement the "print_recreate" breakpoint_ops method for vfork
8186    catchpoints.  */
8187
8188 static void
8189 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8190 {
8191   fprintf_unfiltered (fp, "catch vfork");
8192   print_recreate_thread (b, fp);
8193 }
8194
8195 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8196
8197 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8198
8199 /* An instance of this type is used to represent an solib catchpoint.
8200    It includes a "struct breakpoint" as a kind of base class; users
8201    downcast to "struct breakpoint *" when needed.  A breakpoint is
8202    really of this type iff its ops pointer points to
8203    CATCH_SOLIB_BREAKPOINT_OPS.  */
8204
8205 struct solib_catchpoint
8206 {
8207   /* The base class.  */
8208   struct breakpoint base;
8209
8210   /* True for "catch load", false for "catch unload".  */
8211   unsigned char is_load;
8212
8213   /* Regular expression to match, if any.  COMPILED is only valid when
8214      REGEX is non-NULL.  */
8215   char *regex;
8216   regex_t compiled;
8217 };
8218
8219 static void
8220 dtor_catch_solib (struct breakpoint *b)
8221 {
8222   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8223
8224   if (self->regex)
8225     regfree (&self->compiled);
8226   xfree (self->regex);
8227
8228   base_breakpoint_ops.dtor (b);
8229 }
8230
8231 static int
8232 insert_catch_solib (struct bp_location *ignore)
8233 {
8234   return 0;
8235 }
8236
8237 static int
8238 remove_catch_solib (struct bp_location *ignore)
8239 {
8240   return 0;
8241 }
8242
8243 static int
8244 breakpoint_hit_catch_solib (const struct bp_location *bl,
8245                             struct address_space *aspace,
8246                             CORE_ADDR bp_addr,
8247                             const struct target_waitstatus *ws)
8248 {
8249   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8250   struct breakpoint *other;
8251
8252   if (ws->kind == TARGET_WAITKIND_LOADED)
8253     return 1;
8254
8255   ALL_BREAKPOINTS (other)
8256   {
8257     struct bp_location *other_bl;
8258
8259     if (other == bl->owner)
8260       continue;
8261
8262     if (other->type != bp_shlib_event)
8263       continue;
8264
8265     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8266       continue;
8267
8268     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8269       {
8270         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8271           return 1;
8272       }
8273   }
8274
8275   return 0;
8276 }
8277
8278 static void
8279 check_status_catch_solib (struct bpstats *bs)
8280 {
8281   struct solib_catchpoint *self
8282     = (struct solib_catchpoint *) bs->breakpoint_at;
8283   int ix;
8284
8285   if (self->is_load)
8286     {
8287       struct so_list *iter;
8288
8289       for (ix = 0;
8290            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8291                         ix, iter);
8292            ++ix)
8293         {
8294           if (!self->regex
8295               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8296             return;
8297         }
8298     }
8299   else
8300     {
8301       char *iter;
8302
8303       for (ix = 0;
8304            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8305                         ix, iter);
8306            ++ix)
8307         {
8308           if (!self->regex
8309               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8310             return;
8311         }
8312     }
8313
8314   bs->stop = 0;
8315   bs->print_it = print_it_noop;
8316 }
8317
8318 static enum print_stop_action
8319 print_it_catch_solib (bpstat bs)
8320 {
8321   struct breakpoint *b = bs->breakpoint_at;
8322   struct ui_out *uiout = current_uiout;
8323
8324   annotate_catchpoint (b->number);
8325   if (b->disposition == disp_del)
8326     ui_out_text (uiout, "\nTemporary catchpoint ");
8327   else
8328     ui_out_text (uiout, "\nCatchpoint ");
8329   ui_out_field_int (uiout, "bkptno", b->number);
8330   ui_out_text (uiout, "\n");
8331   if (ui_out_is_mi_like_p (uiout))
8332     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8333   print_solib_event (1);
8334   return PRINT_SRC_AND_LOC;
8335 }
8336
8337 static void
8338 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8339 {
8340   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8341   struct value_print_options opts;
8342   struct ui_out *uiout = current_uiout;
8343   char *msg;
8344
8345   get_user_print_options (&opts);
8346   /* Field 4, the address, is omitted (which makes the columns not
8347      line up too nicely with the headers, but the effect is relatively
8348      readable).  */
8349   if (opts.addressprint)
8350     {
8351       annotate_field (4);
8352       ui_out_field_skip (uiout, "addr");
8353     }
8354
8355   annotate_field (5);
8356   if (self->is_load)
8357     {
8358       if (self->regex)
8359         msg = xstrprintf (_("load of library matching %s"), self->regex);
8360       else
8361         msg = xstrdup (_("load of library"));
8362     }
8363   else
8364     {
8365       if (self->regex)
8366         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8367       else
8368         msg = xstrdup (_("unload of library"));
8369     }
8370   ui_out_field_string (uiout, "what", msg);
8371   xfree (msg);
8372
8373   if (ui_out_is_mi_like_p (uiout))
8374     ui_out_field_string (uiout, "catch-type",
8375                          self->is_load ? "load" : "unload");
8376 }
8377
8378 static void
8379 print_mention_catch_solib (struct breakpoint *b)
8380 {
8381   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8382
8383   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8384                    self->is_load ? "load" : "unload");
8385 }
8386
8387 static void
8388 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8389 {
8390   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8391
8392   fprintf_unfiltered (fp, "%s %s",
8393                       b->disposition == disp_del ? "tcatch" : "catch",
8394                       self->is_load ? "load" : "unload");
8395   if (self->regex)
8396     fprintf_unfiltered (fp, " %s", self->regex);
8397   fprintf_unfiltered (fp, "\n");
8398 }
8399
8400 static struct breakpoint_ops catch_solib_breakpoint_ops;
8401
8402 /* Shared helper function (MI and CLI) for creating and installing
8403    a shared object event catchpoint.  If IS_LOAD is non-zero then
8404    the events to be caught are load events, otherwise they are
8405    unload events.  If IS_TEMP is non-zero the catchpoint is a
8406    temporary one.  If ENABLED is non-zero the catchpoint is
8407    created in an enabled state.  */
8408
8409 void
8410 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8411 {
8412   struct solib_catchpoint *c;
8413   struct gdbarch *gdbarch = get_current_arch ();
8414   struct cleanup *cleanup;
8415
8416   if (!arg)
8417     arg = "";
8418   arg = skip_spaces (arg);
8419
8420   c = XCNEW (struct solib_catchpoint);
8421   cleanup = make_cleanup (xfree, c);
8422
8423   if (*arg != '\0')
8424     {
8425       int errcode;
8426
8427       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8428       if (errcode != 0)
8429         {
8430           char *err = get_regcomp_error (errcode, &c->compiled);
8431
8432           make_cleanup (xfree, err);
8433           error (_("Invalid regexp (%s): %s"), err, arg);
8434         }
8435       c->regex = xstrdup (arg);
8436     }
8437
8438   c->is_load = is_load;
8439   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8440                    &catch_solib_breakpoint_ops);
8441
8442   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8443
8444   discard_cleanups (cleanup);
8445   install_breakpoint (0, &c->base, 1);
8446 }
8447
8448 /* A helper function that does all the work for "catch load" and
8449    "catch unload".  */
8450
8451 static void
8452 catch_load_or_unload (char *arg, int from_tty, int is_load,
8453                       struct cmd_list_element *command)
8454 {
8455   int tempflag;
8456   const int enabled = 1;
8457
8458   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8459
8460   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8461 }
8462
8463 static void
8464 catch_load_command_1 (char *arg, int from_tty,
8465                       struct cmd_list_element *command)
8466 {
8467   catch_load_or_unload (arg, from_tty, 1, command);
8468 }
8469
8470 static void
8471 catch_unload_command_1 (char *arg, int from_tty,
8472                         struct cmd_list_element *command)
8473 {
8474   catch_load_or_unload (arg, from_tty, 0, command);
8475 }
8476
8477 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8478    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8479    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8480    the breakpoint_ops structure associated to the catchpoint.  */
8481
8482 void
8483 init_catchpoint (struct breakpoint *b,
8484                  struct gdbarch *gdbarch, int tempflag,
8485                  char *cond_string,
8486                  const struct breakpoint_ops *ops)
8487 {
8488   struct symtab_and_line sal;
8489
8490   init_sal (&sal);
8491   sal.pspace = current_program_space;
8492
8493   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8494
8495   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8496   b->disposition = tempflag ? disp_del : disp_donttouch;
8497 }
8498
8499 void
8500 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8501 {
8502   add_to_breakpoint_chain (b);
8503   set_breakpoint_number (internal, b);
8504   if (is_tracepoint (b))
8505     set_tracepoint_count (breakpoint_count);
8506   if (!internal)
8507     mention (b);
8508   observer_notify_breakpoint_created (b);
8509
8510   if (update_gll)
8511     update_global_location_list (UGLL_MAY_INSERT);
8512 }
8513
8514 static void
8515 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8516                                     int tempflag, char *cond_string,
8517                                     const struct breakpoint_ops *ops)
8518 {
8519   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8520
8521   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8522
8523   c->forked_inferior_pid = null_ptid;
8524
8525   install_breakpoint (0, &c->base, 1);
8526 }
8527
8528 /* Exec catchpoints.  */
8529
8530 /* An instance of this type is used to represent an exec catchpoint.
8531    It includes a "struct breakpoint" as a kind of base class; users
8532    downcast to "struct breakpoint *" when needed.  A breakpoint is
8533    really of this type iff its ops pointer points to
8534    CATCH_EXEC_BREAKPOINT_OPS.  */
8535
8536 struct exec_catchpoint
8537 {
8538   /* The base class.  */
8539   struct breakpoint base;
8540
8541   /* Filename of a program whose exec triggered this catchpoint.
8542      This field is only valid immediately after this catchpoint has
8543      triggered.  */
8544   char *exec_pathname;
8545 };
8546
8547 /* Implement the "dtor" breakpoint_ops method for exec
8548    catchpoints.  */
8549
8550 static void
8551 dtor_catch_exec (struct breakpoint *b)
8552 {
8553   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8554
8555   xfree (c->exec_pathname);
8556
8557   base_breakpoint_ops.dtor (b);
8558 }
8559
8560 static int
8561 insert_catch_exec (struct bp_location *bl)
8562 {
8563   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8564 }
8565
8566 static int
8567 remove_catch_exec (struct bp_location *bl)
8568 {
8569   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8570 }
8571
8572 static int
8573 breakpoint_hit_catch_exec (const struct bp_location *bl,
8574                            struct address_space *aspace, CORE_ADDR bp_addr,
8575                            const struct target_waitstatus *ws)
8576 {
8577   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8578
8579   if (ws->kind != TARGET_WAITKIND_EXECD)
8580     return 0;
8581
8582   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8583   return 1;
8584 }
8585
8586 static enum print_stop_action
8587 print_it_catch_exec (bpstat bs)
8588 {
8589   struct ui_out *uiout = current_uiout;
8590   struct breakpoint *b = bs->breakpoint_at;
8591   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8592
8593   annotate_catchpoint (b->number);
8594   if (b->disposition == disp_del)
8595     ui_out_text (uiout, "\nTemporary catchpoint ");
8596   else
8597     ui_out_text (uiout, "\nCatchpoint ");
8598   if (ui_out_is_mi_like_p (uiout))
8599     {
8600       ui_out_field_string (uiout, "reason",
8601                            async_reason_lookup (EXEC_ASYNC_EXEC));
8602       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8603     }
8604   ui_out_field_int (uiout, "bkptno", b->number);
8605   ui_out_text (uiout, " (exec'd ");
8606   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8607   ui_out_text (uiout, "), ");
8608
8609   return PRINT_SRC_AND_LOC;
8610 }
8611
8612 static void
8613 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8614 {
8615   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8616   struct value_print_options opts;
8617   struct ui_out *uiout = current_uiout;
8618
8619   get_user_print_options (&opts);
8620
8621   /* Field 4, the address, is omitted (which makes the columns
8622      not line up too nicely with the headers, but the effect
8623      is relatively readable).  */
8624   if (opts.addressprint)
8625     ui_out_field_skip (uiout, "addr");
8626   annotate_field (5);
8627   ui_out_text (uiout, "exec");
8628   if (c->exec_pathname != NULL)
8629     {
8630       ui_out_text (uiout, ", program \"");
8631       ui_out_field_string (uiout, "what", c->exec_pathname);
8632       ui_out_text (uiout, "\" ");
8633     }
8634
8635   if (ui_out_is_mi_like_p (uiout))
8636     ui_out_field_string (uiout, "catch-type", "exec");
8637 }
8638
8639 static void
8640 print_mention_catch_exec (struct breakpoint *b)
8641 {
8642   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8643 }
8644
8645 /* Implement the "print_recreate" breakpoint_ops method for exec
8646    catchpoints.  */
8647
8648 static void
8649 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8650 {
8651   fprintf_unfiltered (fp, "catch exec");
8652   print_recreate_thread (b, fp);
8653 }
8654
8655 static struct breakpoint_ops catch_exec_breakpoint_ops;
8656
8657 static int
8658 hw_breakpoint_used_count (void)
8659 {
8660   int i = 0;
8661   struct breakpoint *b;
8662   struct bp_location *bl;
8663
8664   ALL_BREAKPOINTS (b)
8665   {
8666     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8667       for (bl = b->loc; bl; bl = bl->next)
8668         {
8669           /* Special types of hardware breakpoints may use more than
8670              one register.  */
8671           i += b->ops->resources_needed (bl);
8672         }
8673   }
8674
8675   return i;
8676 }
8677
8678 /* Returns the resources B would use if it were a hardware
8679    watchpoint.  */
8680
8681 static int
8682 hw_watchpoint_use_count (struct breakpoint *b)
8683 {
8684   int i = 0;
8685   struct bp_location *bl;
8686
8687   if (!breakpoint_enabled (b))
8688     return 0;
8689
8690   for (bl = b->loc; bl; bl = bl->next)
8691     {
8692       /* Special types of hardware watchpoints may use more than
8693          one register.  */
8694       i += b->ops->resources_needed (bl);
8695     }
8696
8697   return i;
8698 }
8699
8700 /* Returns the sum the used resources of all hardware watchpoints of
8701    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8702    the sum of the used resources of all hardware watchpoints of other
8703    types _not_ TYPE.  */
8704
8705 static int
8706 hw_watchpoint_used_count_others (struct breakpoint *except,
8707                                  enum bptype type, int *other_type_used)
8708 {
8709   int i = 0;
8710   struct breakpoint *b;
8711
8712   *other_type_used = 0;
8713   ALL_BREAKPOINTS (b)
8714     {
8715       if (b == except)
8716         continue;
8717       if (!breakpoint_enabled (b))
8718         continue;
8719
8720       if (b->type == type)
8721         i += hw_watchpoint_use_count (b);
8722       else if (is_hardware_watchpoint (b))
8723         *other_type_used = 1;
8724     }
8725
8726   return i;
8727 }
8728
8729 void
8730 disable_watchpoints_before_interactive_call_start (void)
8731 {
8732   struct breakpoint *b;
8733
8734   ALL_BREAKPOINTS (b)
8735   {
8736     if (is_watchpoint (b) && breakpoint_enabled (b))
8737       {
8738         b->enable_state = bp_call_disabled;
8739         update_global_location_list (UGLL_DONT_INSERT);
8740       }
8741   }
8742 }
8743
8744 void
8745 enable_watchpoints_after_interactive_call_stop (void)
8746 {
8747   struct breakpoint *b;
8748
8749   ALL_BREAKPOINTS (b)
8750   {
8751     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8752       {
8753         b->enable_state = bp_enabled;
8754         update_global_location_list (UGLL_MAY_INSERT);
8755       }
8756   }
8757 }
8758
8759 void
8760 disable_breakpoints_before_startup (void)
8761 {
8762   current_program_space->executing_startup = 1;
8763   update_global_location_list (UGLL_DONT_INSERT);
8764 }
8765
8766 void
8767 enable_breakpoints_after_startup (void)
8768 {
8769   current_program_space->executing_startup = 0;
8770   breakpoint_re_set ();
8771 }
8772
8773 /* Create a new single-step breakpoint for thread THREAD, with no
8774    locations.  */
8775
8776 static struct breakpoint *
8777 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8778 {
8779   struct breakpoint *b = XNEW (struct breakpoint);
8780
8781   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8782                                         &momentary_breakpoint_ops);
8783
8784   b->disposition = disp_donttouch;
8785   b->frame_id = null_frame_id;
8786
8787   b->thread = thread;
8788   gdb_assert (b->thread != 0);
8789
8790   add_to_breakpoint_chain (b);
8791
8792   return b;
8793 }
8794
8795 /* Set a momentary breakpoint of type TYPE at address specified by
8796    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8797    frame.  */
8798
8799 struct breakpoint *
8800 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8801                           struct frame_id frame_id, enum bptype type)
8802 {
8803   struct breakpoint *b;
8804
8805   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8806      tail-called one.  */
8807   gdb_assert (!frame_id_artificial_p (frame_id));
8808
8809   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8810   b->enable_state = bp_enabled;
8811   b->disposition = disp_donttouch;
8812   b->frame_id = frame_id;
8813
8814   /* If we're debugging a multi-threaded program, then we want
8815      momentary breakpoints to be active in only a single thread of
8816      control.  */
8817   if (in_thread_list (inferior_ptid))
8818     b->thread = pid_to_thread_id (inferior_ptid);
8819
8820   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8821
8822   return b;
8823 }
8824
8825 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8826    The new breakpoint will have type TYPE, use OPS as its
8827    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8828
8829 static struct breakpoint *
8830 momentary_breakpoint_from_master (struct breakpoint *orig,
8831                                   enum bptype type,
8832                                   const struct breakpoint_ops *ops,
8833                                   int loc_enabled)
8834 {
8835   struct breakpoint *copy;
8836
8837   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8838   copy->loc = allocate_bp_location (copy);
8839   set_breakpoint_location_function (copy->loc, 1);
8840
8841   copy->loc->gdbarch = orig->loc->gdbarch;
8842   copy->loc->requested_address = orig->loc->requested_address;
8843   copy->loc->address = orig->loc->address;
8844   copy->loc->section = orig->loc->section;
8845   copy->loc->pspace = orig->loc->pspace;
8846   copy->loc->probe = orig->loc->probe;
8847   copy->loc->line_number = orig->loc->line_number;
8848   copy->loc->symtab = orig->loc->symtab;
8849   copy->loc->enabled = loc_enabled;
8850   copy->frame_id = orig->frame_id;
8851   copy->thread = orig->thread;
8852   copy->pspace = orig->pspace;
8853
8854   copy->enable_state = bp_enabled;
8855   copy->disposition = disp_donttouch;
8856   copy->number = internal_breakpoint_number--;
8857
8858   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8859   return copy;
8860 }
8861
8862 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8863    ORIG is NULL.  */
8864
8865 struct breakpoint *
8866 clone_momentary_breakpoint (struct breakpoint *orig)
8867 {
8868   /* If there's nothing to clone, then return nothing.  */
8869   if (orig == NULL)
8870     return NULL;
8871
8872   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8873 }
8874
8875 struct breakpoint *
8876 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8877                                 enum bptype type)
8878 {
8879   struct symtab_and_line sal;
8880
8881   sal = find_pc_line (pc, 0);
8882   sal.pc = pc;
8883   sal.section = find_pc_overlay (pc);
8884   sal.explicit_pc = 1;
8885
8886   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8887 }
8888 \f
8889
8890 /* Tell the user we have just set a breakpoint B.  */
8891
8892 static void
8893 mention (struct breakpoint *b)
8894 {
8895   b->ops->print_mention (b);
8896   if (ui_out_is_mi_like_p (current_uiout))
8897     return;
8898   printf_filtered ("\n");
8899 }
8900 \f
8901
8902 static int bp_loc_is_permanent (struct bp_location *loc);
8903
8904 static struct bp_location *
8905 add_location_to_breakpoint (struct breakpoint *b,
8906                             const struct symtab_and_line *sal)
8907 {
8908   struct bp_location *loc, **tmp;
8909   CORE_ADDR adjusted_address;
8910   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8911
8912   if (loc_gdbarch == NULL)
8913     loc_gdbarch = b->gdbarch;
8914
8915   /* Adjust the breakpoint's address prior to allocating a location.
8916      Once we call allocate_bp_location(), that mostly uninitialized
8917      location will be placed on the location chain.  Adjustment of the
8918      breakpoint may cause target_read_memory() to be called and we do
8919      not want its scan of the location chain to find a breakpoint and
8920      location that's only been partially initialized.  */
8921   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8922                                                 sal->pc, b->type);
8923
8924   /* Sort the locations by their ADDRESS.  */
8925   loc = allocate_bp_location (b);
8926   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8927        tmp = &((*tmp)->next))
8928     ;
8929   loc->next = *tmp;
8930   *tmp = loc;
8931
8932   loc->requested_address = sal->pc;
8933   loc->address = adjusted_address;
8934   loc->pspace = sal->pspace;
8935   loc->probe.probe = sal->probe;
8936   loc->probe.objfile = sal->objfile;
8937   gdb_assert (loc->pspace != NULL);
8938   loc->section = sal->section;
8939   loc->gdbarch = loc_gdbarch;
8940   loc->line_number = sal->line;
8941   loc->symtab = sal->symtab;
8942
8943   set_breakpoint_location_function (loc,
8944                                     sal->explicit_pc || sal->explicit_line);
8945
8946   /* While by definition, permanent breakpoints are already present in the
8947      code, we don't mark the location as inserted.  Normally one would expect
8948      that GDB could rely on that breakpoint instruction to stop the program,
8949      thus removing the need to insert its own breakpoint, except that executing
8950      the breakpoint instruction can kill the target instead of reporting a
8951      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8952      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8953      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8954      breakpoint be inserted normally results in QEMU knowing about the GDB
8955      breakpoint, and thus trap before the breakpoint instruction is executed.
8956      (If GDB later needs to continue execution past the permanent breakpoint,
8957      it manually increments the PC, thus avoiding executing the breakpoint
8958      instruction.)  */
8959   if (bp_loc_is_permanent (loc))
8960     loc->permanent = 1;
8961
8962   return loc;
8963 }
8964 \f
8965
8966 /* See breakpoint.h.  */
8967
8968 int
8969 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8970 {
8971   int len;
8972   CORE_ADDR addr;
8973   const gdb_byte *bpoint;
8974   gdb_byte *target_mem;
8975   struct cleanup *cleanup;
8976   int retval = 0;
8977
8978   addr = address;
8979   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8980
8981   /* Software breakpoints unsupported?  */
8982   if (bpoint == NULL)
8983     return 0;
8984
8985   target_mem = alloca (len);
8986
8987   /* Enable the automatic memory restoration from breakpoints while
8988      we read the memory.  Otherwise we could say about our temporary
8989      breakpoints they are permanent.  */
8990   cleanup = make_show_memory_breakpoints_cleanup (0);
8991
8992   if (target_read_memory (address, target_mem, len) == 0
8993       && memcmp (target_mem, bpoint, len) == 0)
8994     retval = 1;
8995
8996   do_cleanups (cleanup);
8997
8998   return retval;
8999 }
9000
9001 /* Return 1 if LOC is pointing to a permanent breakpoint,
9002    return 0 otherwise.  */
9003
9004 static int
9005 bp_loc_is_permanent (struct bp_location *loc)
9006 {
9007   struct cleanup *cleanup;
9008   int retval;
9009
9010   gdb_assert (loc != NULL);
9011
9012   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9013      attempt to read from the addresses the locations of these breakpoint types
9014      point to.  program_breakpoint_here_p, below, will attempt to read
9015      memory.  */
9016   if (!breakpoint_address_is_meaningful (loc->owner))
9017     return 0;
9018
9019   cleanup = save_current_space_and_thread ();
9020   switch_to_program_space_and_thread (loc->pspace);
9021
9022   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9023
9024   do_cleanups (cleanup);
9025
9026   return retval;
9027 }
9028
9029 /* Build a command list for the dprintf corresponding to the current
9030    settings of the dprintf style options.  */
9031
9032 static void
9033 update_dprintf_command_list (struct breakpoint *b)
9034 {
9035   char *dprintf_args = b->extra_string;
9036   char *printf_line = NULL;
9037
9038   if (!dprintf_args)
9039     return;
9040
9041   dprintf_args = skip_spaces (dprintf_args);
9042
9043   /* Allow a comma, as it may have terminated a location, but don't
9044      insist on it.  */
9045   if (*dprintf_args == ',')
9046     ++dprintf_args;
9047   dprintf_args = skip_spaces (dprintf_args);
9048
9049   if (*dprintf_args != '"')
9050     error (_("Bad format string, missing '\"'."));
9051
9052   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9053     printf_line = xstrprintf ("printf %s", dprintf_args);
9054   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9055     {
9056       if (!dprintf_function)
9057         error (_("No function supplied for dprintf call"));
9058
9059       if (dprintf_channel && strlen (dprintf_channel) > 0)
9060         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9061                                   dprintf_function,
9062                                   dprintf_channel,
9063                                   dprintf_args);
9064       else
9065         printf_line = xstrprintf ("call (void) %s (%s)",
9066                                   dprintf_function,
9067                                   dprintf_args);
9068     }
9069   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9070     {
9071       if (target_can_run_breakpoint_commands ())
9072         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9073       else
9074         {
9075           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9076           printf_line = xstrprintf ("printf %s", dprintf_args);
9077         }
9078     }
9079   else
9080     internal_error (__FILE__, __LINE__,
9081                     _("Invalid dprintf style."));
9082
9083   gdb_assert (printf_line != NULL);
9084   /* Manufacture a printf sequence.  */
9085   {
9086     struct command_line *printf_cmd_line = XNEW (struct command_line);
9087
9088     printf_cmd_line->control_type = simple_control;
9089     printf_cmd_line->body_count = 0;
9090     printf_cmd_line->body_list = NULL;
9091     printf_cmd_line->next = NULL;
9092     printf_cmd_line->line = printf_line;
9093
9094     breakpoint_set_commands (b, printf_cmd_line);
9095   }
9096 }
9097
9098 /* Update all dprintf commands, making their command lists reflect
9099    current style settings.  */
9100
9101 static void
9102 update_dprintf_commands (char *args, int from_tty,
9103                          struct cmd_list_element *c)
9104 {
9105   struct breakpoint *b;
9106
9107   ALL_BREAKPOINTS (b)
9108     {
9109       if (b->type == bp_dprintf)
9110         update_dprintf_command_list (b);
9111     }
9112 }
9113
9114 /* Create a breakpoint with SAL as location.  Use LOCATION
9115    as a description of the location, and COND_STRING
9116    as condition expression.  */
9117
9118 static void
9119 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9120                      struct symtabs_and_lines sals,
9121                      struct event_location *location,
9122                      char *filter, char *cond_string,
9123                      char *extra_string,
9124                      enum bptype type, enum bpdisp disposition,
9125                      int thread, int task, int ignore_count,
9126                      const struct breakpoint_ops *ops, int from_tty,
9127                      int enabled, int internal, unsigned flags,
9128                      int display_canonical)
9129 {
9130   int i;
9131
9132   if (type == bp_hardware_breakpoint)
9133     {
9134       int target_resources_ok;
9135
9136       i = hw_breakpoint_used_count ();
9137       target_resources_ok =
9138         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9139                                             i + 1, 0);
9140       if (target_resources_ok == 0)
9141         error (_("No hardware breakpoint support in the target."));
9142       else if (target_resources_ok < 0)
9143         error (_("Hardware breakpoints used exceeds limit."));
9144     }
9145
9146   gdb_assert (sals.nelts > 0);
9147
9148   for (i = 0; i < sals.nelts; ++i)
9149     {
9150       struct symtab_and_line sal = sals.sals[i];
9151       struct bp_location *loc;
9152
9153       if (from_tty)
9154         {
9155           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9156           if (!loc_gdbarch)
9157             loc_gdbarch = gdbarch;
9158
9159           describe_other_breakpoints (loc_gdbarch,
9160                                       sal.pspace, sal.pc, sal.section, thread);
9161         }
9162
9163       if (i == 0)
9164         {
9165           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9166           b->thread = thread;
9167           b->task = task;
9168
9169           b->cond_string = cond_string;
9170           b->extra_string = extra_string;
9171           b->ignore_count = ignore_count;
9172           b->enable_state = enabled ? bp_enabled : bp_disabled;
9173           b->disposition = disposition;
9174
9175           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9176             b->loc->inserted = 1;
9177
9178           if (type == bp_static_tracepoint)
9179             {
9180               struct tracepoint *t = (struct tracepoint *) b;
9181               struct static_tracepoint_marker marker;
9182
9183               if (strace_marker_p (b))
9184                 {
9185                   /* We already know the marker exists, otherwise, we
9186                      wouldn't see a sal for it.  */
9187                   const char *p = &event_location_to_string (b->location)[3];
9188                   const char *endp;
9189                   char *marker_str;
9190
9191                   p = skip_spaces_const (p);
9192
9193                   endp = skip_to_space_const (p);
9194
9195                   marker_str = savestring (p, endp - p);
9196                   t->static_trace_marker_id = marker_str;
9197
9198                   printf_filtered (_("Probed static tracepoint "
9199                                      "marker \"%s\"\n"),
9200                                    t->static_trace_marker_id);
9201                 }
9202               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9203                 {
9204                   t->static_trace_marker_id = xstrdup (marker.str_id);
9205                   release_static_tracepoint_marker (&marker);
9206
9207                   printf_filtered (_("Probed static tracepoint "
9208                                      "marker \"%s\"\n"),
9209                                    t->static_trace_marker_id);
9210                 }
9211               else
9212                 warning (_("Couldn't determine the static "
9213                            "tracepoint marker to probe"));
9214             }
9215
9216           loc = b->loc;
9217         }
9218       else
9219         {
9220           loc = add_location_to_breakpoint (b, &sal);
9221           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9222             loc->inserted = 1;
9223         }
9224
9225       if (b->cond_string)
9226         {
9227           const char *arg = b->cond_string;
9228
9229           loc->cond = parse_exp_1 (&arg, loc->address,
9230                                    block_for_pc (loc->address), 0);
9231           if (*arg)
9232               error (_("Garbage '%s' follows condition"), arg);
9233         }
9234
9235       /* Dynamic printf requires and uses additional arguments on the
9236          command line, otherwise it's an error.  */
9237       if (type == bp_dprintf)
9238         {
9239           if (b->extra_string)
9240             update_dprintf_command_list (b);
9241           else
9242             error (_("Format string required"));
9243         }
9244       else if (b->extra_string)
9245         error (_("Garbage '%s' at end of command"), b->extra_string);
9246     }
9247
9248   b->display_canonical = display_canonical;
9249   if (location != NULL)
9250     b->location = location;
9251   else
9252     b->location = new_address_location (b->loc->address);
9253   b->filter = filter;
9254 }
9255
9256 static void
9257 create_breakpoint_sal (struct gdbarch *gdbarch,
9258                        struct symtabs_and_lines sals,
9259                        struct event_location *location,
9260                        char *filter, char *cond_string,
9261                        char *extra_string,
9262                        enum bptype type, enum bpdisp disposition,
9263                        int thread, int task, int ignore_count,
9264                        const struct breakpoint_ops *ops, int from_tty,
9265                        int enabled, int internal, unsigned flags,
9266                        int display_canonical)
9267 {
9268   struct breakpoint *b;
9269   struct cleanup *old_chain;
9270
9271   if (is_tracepoint_type (type))
9272     {
9273       struct tracepoint *t;
9274
9275       t = XCNEW (struct tracepoint);
9276       b = &t->base;
9277     }
9278   else
9279     b = XNEW (struct breakpoint);
9280
9281   old_chain = make_cleanup (xfree, b);
9282
9283   init_breakpoint_sal (b, gdbarch,
9284                        sals, location,
9285                        filter, cond_string, extra_string,
9286                        type, disposition,
9287                        thread, task, ignore_count,
9288                        ops, from_tty,
9289                        enabled, internal, flags,
9290                        display_canonical);
9291   discard_cleanups (old_chain);
9292
9293   install_breakpoint (internal, b, 0);
9294 }
9295
9296 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9297    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9298    value.  COND_STRING, if not NULL, specified the condition to be
9299    used for all breakpoints.  Essentially the only case where
9300    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9301    function.  In that case, it's still not possible to specify
9302    separate conditions for different overloaded functions, so
9303    we take just a single condition string.
9304    
9305    NOTE: If the function succeeds, the caller is expected to cleanup
9306    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9307    array contents).  If the function fails (error() is called), the
9308    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9309    COND and SALS arrays and each of those arrays contents.  */
9310
9311 static void
9312 create_breakpoints_sal (struct gdbarch *gdbarch,
9313                         struct linespec_result *canonical,
9314                         char *cond_string, char *extra_string,
9315                         enum bptype type, enum bpdisp disposition,
9316                         int thread, int task, int ignore_count,
9317                         const struct breakpoint_ops *ops, int from_tty,
9318                         int enabled, int internal, unsigned flags)
9319 {
9320   int i;
9321   struct linespec_sals *lsal;
9322
9323   if (canonical->pre_expanded)
9324     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9325
9326   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9327     {
9328       /* Note that 'location' can be NULL in the case of a plain
9329          'break', without arguments.  */
9330       struct event_location *location
9331         = (canonical->location != NULL
9332            ? copy_event_location (canonical->location) : NULL);
9333       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9334       struct cleanup *inner = make_cleanup_delete_event_location (location);
9335
9336       make_cleanup (xfree, filter_string);
9337       create_breakpoint_sal (gdbarch, lsal->sals,
9338                              location,
9339                              filter_string,
9340                              cond_string, extra_string,
9341                              type, disposition,
9342                              thread, task, ignore_count, ops,
9343                              from_tty, enabled, internal, flags,
9344                              canonical->special_display);
9345       discard_cleanups (inner);
9346     }
9347 }
9348
9349 /* Parse LOCATION which is assumed to be a SAL specification possibly
9350    followed by conditionals.  On return, SALS contains an array of SAL
9351    addresses found.  LOCATION points to the end of the SAL (for
9352    linespec locations).
9353
9354    The array and the line spec strings are allocated on the heap, it is
9355    the caller's responsibility to free them.  */
9356
9357 static void
9358 parse_breakpoint_sals (const struct event_location *location,
9359                        struct linespec_result *canonical)
9360 {
9361   struct symtab_and_line cursal;
9362
9363   if (event_location_type (location) == LINESPEC_LOCATION)
9364     {
9365       const char *address = get_linespec_location (location);
9366
9367       if (address == NULL)
9368         {
9369           /* The last displayed codepoint, if it's valid, is our default
9370              breakpoint address.  */
9371           if (last_displayed_sal_is_valid ())
9372             {
9373               struct linespec_sals lsal;
9374               struct symtab_and_line sal;
9375               CORE_ADDR pc;
9376
9377               init_sal (&sal);          /* Initialize to zeroes.  */
9378               lsal.sals.sals = XNEW (struct symtab_and_line);
9379
9380               /* Set sal's pspace, pc, symtab, and line to the values
9381                  corresponding to the last call to print_frame_info.
9382                  Be sure to reinitialize LINE with NOTCURRENT == 0
9383                  as the breakpoint line number is inappropriate otherwise.
9384                  find_pc_line would adjust PC, re-set it back.  */
9385               get_last_displayed_sal (&sal);
9386               pc = sal.pc;
9387               sal = find_pc_line (pc, 0);
9388
9389               /* "break" without arguments is equivalent to "break *PC"
9390                  where PC is the last displayed codepoint's address.  So
9391                  make sure to set sal.explicit_pc to prevent GDB from
9392                  trying to expand the list of sals to include all other
9393                  instances with the same symtab and line.  */
9394               sal.pc = pc;
9395               sal.explicit_pc = 1;
9396
9397               lsal.sals.sals[0] = sal;
9398               lsal.sals.nelts = 1;
9399               lsal.canonical = NULL;
9400
9401               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9402               return;
9403             }
9404           else
9405             error (_("No default breakpoint address now."));
9406         }
9407     }
9408
9409   /* Force almost all breakpoints to be in terms of the
9410      current_source_symtab (which is decode_line_1's default).
9411      This should produce the results we want almost all of the
9412      time while leaving default_breakpoint_* alone.
9413
9414      ObjC: However, don't match an Objective-C method name which
9415      may have a '+' or '-' succeeded by a '['.  */
9416   cursal = get_current_source_symtab_and_line ();
9417   if (last_displayed_sal_is_valid ())
9418     {
9419       const char *address = NULL;
9420
9421       if (event_location_type (location) == LINESPEC_LOCATION)
9422         address = get_linespec_location (location);
9423
9424       if (!cursal.symtab
9425           || (address != NULL
9426               && strchr ("+-", address[0]) != NULL
9427               && address[1] != '['))
9428         {
9429           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
9430                             get_last_displayed_symtab (),
9431                             get_last_displayed_line (),
9432                             canonical, NULL, NULL);
9433           return;
9434         }
9435     }
9436
9437   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
9438                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9439 }
9440
9441
9442 /* Convert each SAL into a real PC.  Verify that the PC can be
9443    inserted as a breakpoint.  If it can't throw an error.  */
9444
9445 static void
9446 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9447 {    
9448   int i;
9449
9450   for (i = 0; i < sals->nelts; i++)
9451     resolve_sal_pc (&sals->sals[i]);
9452 }
9453
9454 /* Fast tracepoints may have restrictions on valid locations.  For
9455    instance, a fast tracepoint using a jump instead of a trap will
9456    likely have to overwrite more bytes than a trap would, and so can
9457    only be placed where the instruction is longer than the jump, or a
9458    multi-instruction sequence does not have a jump into the middle of
9459    it, etc.  */
9460
9461 static void
9462 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9463                             struct symtabs_and_lines *sals)
9464 {
9465   int i, rslt;
9466   struct symtab_and_line *sal;
9467   char *msg;
9468   struct cleanup *old_chain;
9469
9470   for (i = 0; i < sals->nelts; i++)
9471     {
9472       struct gdbarch *sarch;
9473
9474       sal = &sals->sals[i];
9475
9476       sarch = get_sal_arch (*sal);
9477       /* We fall back to GDBARCH if there is no architecture
9478          associated with SAL.  */
9479       if (sarch == NULL)
9480         sarch = gdbarch;
9481       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9482       old_chain = make_cleanup (xfree, msg);
9483
9484       if (!rslt)
9485         error (_("May not have a fast tracepoint at 0x%s%s"),
9486                paddress (sarch, sal->pc), (msg ? msg : ""));
9487
9488       do_cleanups (old_chain);
9489     }
9490 }
9491
9492 /* Issue an invalid thread ID error.  */
9493
9494 static void ATTRIBUTE_NORETURN
9495 invalid_thread_id_error (int id)
9496 {
9497   error (_("Unknown thread %d."), id);
9498 }
9499
9500 /* Given TOK, a string specification of condition and thread, as
9501    accepted by the 'break' command, extract the condition
9502    string and thread number and set *COND_STRING and *THREAD.
9503    PC identifies the context at which the condition should be parsed.
9504    If no condition is found, *COND_STRING is set to NULL.
9505    If no thread is found, *THREAD is set to -1.  */
9506
9507 static void
9508 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9509                            char **cond_string, int *thread, int *task,
9510                            char **rest)
9511 {
9512   *cond_string = NULL;
9513   *thread = -1;
9514   *task = 0;
9515   *rest = NULL;
9516
9517   while (tok && *tok)
9518     {
9519       const char *end_tok;
9520       int toklen;
9521       const char *cond_start = NULL;
9522       const char *cond_end = NULL;
9523
9524       tok = skip_spaces_const (tok);
9525
9526       if ((*tok == '"' || *tok == ',') && rest)
9527         {
9528           *rest = savestring (tok, strlen (tok));
9529           return;
9530         }
9531
9532       end_tok = skip_to_space_const (tok);
9533
9534       toklen = end_tok - tok;
9535
9536       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9537         {
9538           struct expression *expr;
9539
9540           tok = cond_start = end_tok + 1;
9541           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9542           xfree (expr);
9543           cond_end = tok;
9544           *cond_string = savestring (cond_start, cond_end - cond_start);
9545         }
9546       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9547         {
9548           char *tmptok;
9549
9550           tok = end_tok + 1;
9551           *thread = strtol (tok, &tmptok, 0);
9552           if (tok == tmptok)
9553             error (_("Junk after thread keyword."));
9554           if (!valid_thread_id (*thread))
9555             invalid_thread_id_error (*thread);
9556           tok = tmptok;
9557         }
9558       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9559         {
9560           char *tmptok;
9561
9562           tok = end_tok + 1;
9563           *task = strtol (tok, &tmptok, 0);
9564           if (tok == tmptok)
9565             error (_("Junk after task keyword."));
9566           if (!valid_task_id (*task))
9567             error (_("Unknown task %d."), *task);
9568           tok = tmptok;
9569         }
9570       else if (rest)
9571         {
9572           *rest = savestring (tok, strlen (tok));
9573           return;
9574         }
9575       else
9576         error (_("Junk at end of arguments."));
9577     }
9578 }
9579
9580 /* Decode a static tracepoint marker spec.  */
9581
9582 static struct symtabs_and_lines
9583 decode_static_tracepoint_spec (const char **arg_p)
9584 {
9585   VEC(static_tracepoint_marker_p) *markers = NULL;
9586   struct symtabs_and_lines sals;
9587   struct cleanup *old_chain;
9588   const char *p = &(*arg_p)[3];
9589   const char *endp;
9590   char *marker_str;
9591   int i;
9592
9593   p = skip_spaces_const (p);
9594
9595   endp = skip_to_space_const (p);
9596
9597   marker_str = savestring (p, endp - p);
9598   old_chain = make_cleanup (xfree, marker_str);
9599
9600   markers = target_static_tracepoint_markers_by_strid (marker_str);
9601   if (VEC_empty(static_tracepoint_marker_p, markers))
9602     error (_("No known static tracepoint marker named %s"), marker_str);
9603
9604   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9605   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9606
9607   for (i = 0; i < sals.nelts; i++)
9608     {
9609       struct static_tracepoint_marker *marker;
9610
9611       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9612
9613       init_sal (&sals.sals[i]);
9614
9615       sals.sals[i] = find_pc_line (marker->address, 0);
9616       sals.sals[i].pc = marker->address;
9617
9618       release_static_tracepoint_marker (marker);
9619     }
9620
9621   do_cleanups (old_chain);
9622
9623   *arg_p = endp;
9624   return sals;
9625 }
9626
9627 /* See breakpoint.h.  */
9628
9629 int
9630 create_breakpoint (struct gdbarch *gdbarch,
9631                    const struct event_location *location, char *cond_string,
9632                    int thread, char *extra_string,
9633                    int parse_extra,
9634                    int tempflag, enum bptype type_wanted,
9635                    int ignore_count,
9636                    enum auto_boolean pending_break_support,
9637                    const struct breakpoint_ops *ops,
9638                    int from_tty, int enabled, int internal,
9639                    unsigned flags)
9640 {
9641   struct linespec_result canonical;
9642   struct cleanup *old_chain;
9643   struct cleanup *bkpt_chain = NULL;
9644   int pending = 0;
9645   int task = 0;
9646   int prev_bkpt_count = breakpoint_count;
9647
9648   gdb_assert (ops != NULL);
9649
9650   /* If extra_string isn't useful, set it to NULL.  */
9651   if (extra_string != NULL && *extra_string == '\0')
9652     extra_string = NULL;
9653
9654   init_linespec_result (&canonical);
9655
9656   TRY
9657     {
9658       ops->create_sals_from_location (location, &canonical, type_wanted);
9659     }
9660   CATCH (e, RETURN_MASK_ERROR)
9661     {
9662       /* If caller is interested in rc value from parse, set
9663          value.  */
9664       if (e.error == NOT_FOUND_ERROR)
9665         {
9666           /* If pending breakpoint support is turned off, throw
9667              error.  */
9668
9669           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9670             throw_exception (e);
9671
9672           exception_print (gdb_stderr, e);
9673
9674           /* If pending breakpoint support is auto query and the user
9675              selects no, then simply return the error code.  */
9676           if (pending_break_support == AUTO_BOOLEAN_AUTO
9677               && !nquery (_("Make %s pending on future shared library load? "),
9678                           bptype_string (type_wanted)))
9679             return 0;
9680
9681           /* At this point, either the user was queried about setting
9682              a pending breakpoint and selected yes, or pending
9683              breakpoint behavior is on and thus a pending breakpoint
9684              is defaulted on behalf of the user.  */
9685           pending = 1;
9686         }
9687       else
9688         throw_exception (e);
9689     }
9690   END_CATCH
9691
9692   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9693     return 0;
9694
9695   /* Create a chain of things that always need to be cleaned up.  */
9696   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9697
9698   /* ----------------------------- SNIP -----------------------------
9699      Anything added to the cleanup chain beyond this point is assumed
9700      to be part of a breakpoint.  If the breakpoint create succeeds
9701      then the memory is not reclaimed.  */
9702   bkpt_chain = make_cleanup (null_cleanup, 0);
9703
9704   /* Resolve all line numbers to PC's and verify that the addresses
9705      are ok for the target.  */
9706   if (!pending)
9707     {
9708       int ix;
9709       struct linespec_sals *iter;
9710
9711       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9712         breakpoint_sals_to_pc (&iter->sals);
9713     }
9714
9715   /* Fast tracepoints may have additional restrictions on location.  */
9716   if (!pending && type_wanted == bp_fast_tracepoint)
9717     {
9718       int ix;
9719       struct linespec_sals *iter;
9720
9721       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9722         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9723     }
9724
9725   /* Verify that condition can be parsed, before setting any
9726      breakpoints.  Allocate a separate condition expression for each
9727      breakpoint.  */
9728   if (!pending)
9729     {
9730       if (parse_extra)
9731         {
9732           char *rest;
9733           struct linespec_sals *lsal;
9734
9735           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9736
9737           /* Here we only parse 'arg' to separate condition
9738              from thread number, so parsing in context of first
9739              sal is OK.  When setting the breakpoint we'll
9740              re-parse it in context of each sal.  */
9741
9742           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9743                                      &cond_string, &thread, &task, &rest);
9744           if (cond_string)
9745             make_cleanup (xfree, cond_string);
9746           if (rest)
9747             make_cleanup (xfree, rest);
9748           if (rest)
9749             extra_string = rest;
9750           else
9751             extra_string = NULL;
9752         }
9753       else
9754         {
9755           if (type_wanted != bp_dprintf
9756               && extra_string != NULL && *extra_string != '\0')
9757                 error (_("Garbage '%s' at end of location"), extra_string);
9758
9759           /* Create a private copy of condition string.  */
9760           if (cond_string)
9761             {
9762               cond_string = xstrdup (cond_string);
9763               make_cleanup (xfree, cond_string);
9764             }
9765           /* Create a private copy of any extra string.  */
9766           if (extra_string)
9767             {
9768               extra_string = xstrdup (extra_string);
9769               make_cleanup (xfree, extra_string);
9770             }
9771         }
9772
9773       ops->create_breakpoints_sal (gdbarch, &canonical,
9774                                    cond_string, extra_string, type_wanted,
9775                                    tempflag ? disp_del : disp_donttouch,
9776                                    thread, task, ignore_count, ops,
9777                                    from_tty, enabled, internal, flags);
9778     }
9779   else
9780     {
9781       struct breakpoint *b;
9782
9783       if (is_tracepoint_type (type_wanted))
9784         {
9785           struct tracepoint *t;
9786
9787           t = XCNEW (struct tracepoint);
9788           b = &t->base;
9789         }
9790       else
9791         b = XNEW (struct breakpoint);
9792
9793       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9794       b->location = copy_event_location (location);
9795
9796       if (parse_extra)
9797         b->cond_string = NULL;
9798       else
9799         {
9800           /* Create a private copy of condition string.  */
9801           if (cond_string)
9802             {
9803               cond_string = xstrdup (cond_string);
9804               make_cleanup (xfree, cond_string);
9805             }
9806           b->cond_string = cond_string;
9807           b->thread = thread;
9808         }
9809
9810       /* Create a private copy of any extra string.  */
9811       if (extra_string != NULL)
9812         {
9813           extra_string = xstrdup (extra_string);
9814           make_cleanup (xfree, extra_string);
9815         }
9816       b->extra_string = extra_string;
9817       b->ignore_count = ignore_count;
9818       b->disposition = tempflag ? disp_del : disp_donttouch;
9819       b->condition_not_parsed = 1;
9820       b->enable_state = enabled ? bp_enabled : bp_disabled;
9821       if ((type_wanted != bp_breakpoint
9822            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9823         b->pspace = current_program_space;
9824
9825       install_breakpoint (internal, b, 0);
9826     }
9827   
9828   if (VEC_length (linespec_sals, canonical.sals) > 1)
9829     {
9830       warning (_("Multiple breakpoints were set.\nUse the "
9831                  "\"delete\" command to delete unwanted breakpoints."));
9832       prev_breakpoint_count = prev_bkpt_count;
9833     }
9834
9835   /* That's it.  Discard the cleanups for data inserted into the
9836      breakpoint.  */
9837   discard_cleanups (bkpt_chain);
9838   /* But cleanup everything else.  */
9839   do_cleanups (old_chain);
9840
9841   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9842   update_global_location_list (UGLL_MAY_INSERT);
9843
9844   return 1;
9845 }
9846
9847 /* Set a breakpoint.
9848    ARG is a string describing breakpoint address,
9849    condition, and thread.
9850    FLAG specifies if a breakpoint is hardware on,
9851    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9852    and BP_TEMPFLAG.  */
9853
9854 static void
9855 break_command_1 (char *arg, int flag, int from_tty)
9856 {
9857   int tempflag = flag & BP_TEMPFLAG;
9858   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9859                              ? bp_hardware_breakpoint
9860                              : bp_breakpoint);
9861   struct breakpoint_ops *ops;
9862   struct event_location *location;
9863   struct cleanup *cleanup;
9864
9865   location = string_to_event_location (&arg, current_language);
9866   cleanup = make_cleanup_delete_event_location (location);
9867
9868   /* Matching breakpoints on probes.  */
9869   if (location != NULL
9870       && event_location_type (location) == PROBE_LOCATION)
9871     ops = &bkpt_probe_breakpoint_ops;
9872   else
9873     ops = &bkpt_breakpoint_ops;
9874
9875   create_breakpoint (get_current_arch (),
9876                      location,
9877                      NULL, 0, arg, 1 /* parse arg */,
9878                      tempflag, type_wanted,
9879                      0 /* Ignore count */,
9880                      pending_break_support,
9881                      ops,
9882                      from_tty,
9883                      1 /* enabled */,
9884                      0 /* internal */,
9885                      0);
9886   do_cleanups (cleanup);
9887 }
9888
9889 /* Helper function for break_command_1 and disassemble_command.  */
9890
9891 void
9892 resolve_sal_pc (struct symtab_and_line *sal)
9893 {
9894   CORE_ADDR pc;
9895
9896   if (sal->pc == 0 && sal->symtab != NULL)
9897     {
9898       if (!find_line_pc (sal->symtab, sal->line, &pc))
9899         error (_("No line %d in file \"%s\"."),
9900                sal->line, symtab_to_filename_for_display (sal->symtab));
9901       sal->pc = pc;
9902
9903       /* If this SAL corresponds to a breakpoint inserted using a line
9904          number, then skip the function prologue if necessary.  */
9905       if (sal->explicit_line)
9906         skip_prologue_sal (sal);
9907     }
9908
9909   if (sal->section == 0 && sal->symtab != NULL)
9910     {
9911       const struct blockvector *bv;
9912       const struct block *b;
9913       struct symbol *sym;
9914
9915       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9916                                     SYMTAB_COMPUNIT (sal->symtab));
9917       if (bv != NULL)
9918         {
9919           sym = block_linkage_function (b);
9920           if (sym != NULL)
9921             {
9922               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9923               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9924                                                  sym);
9925             }
9926           else
9927             {
9928               /* It really is worthwhile to have the section, so we'll
9929                  just have to look harder. This case can be executed
9930                  if we have line numbers but no functions (as can
9931                  happen in assembly source).  */
9932
9933               struct bound_minimal_symbol msym;
9934               struct cleanup *old_chain = save_current_space_and_thread ();
9935
9936               switch_to_program_space_and_thread (sal->pspace);
9937
9938               msym = lookup_minimal_symbol_by_pc (sal->pc);
9939               if (msym.minsym)
9940                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9941
9942               do_cleanups (old_chain);
9943             }
9944         }
9945     }
9946 }
9947
9948 void
9949 break_command (char *arg, int from_tty)
9950 {
9951   break_command_1 (arg, 0, from_tty);
9952 }
9953
9954 void
9955 tbreak_command (char *arg, int from_tty)
9956 {
9957   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9958 }
9959
9960 static void
9961 hbreak_command (char *arg, int from_tty)
9962 {
9963   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9964 }
9965
9966 static void
9967 thbreak_command (char *arg, int from_tty)
9968 {
9969   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9970 }
9971
9972 static void
9973 stop_command (char *arg, int from_tty)
9974 {
9975   printf_filtered (_("Specify the type of breakpoint to set.\n\
9976 Usage: stop in <function | address>\n\
9977        stop at <line>\n"));
9978 }
9979
9980 static void
9981 stopin_command (char *arg, int from_tty)
9982 {
9983   int badInput = 0;
9984
9985   if (arg == (char *) NULL)
9986     badInput = 1;
9987   else if (*arg != '*')
9988     {
9989       char *argptr = arg;
9990       int hasColon = 0;
9991
9992       /* Look for a ':'.  If this is a line number specification, then
9993          say it is bad, otherwise, it should be an address or
9994          function/method name.  */
9995       while (*argptr && !hasColon)
9996         {
9997           hasColon = (*argptr == ':');
9998           argptr++;
9999         }
10000
10001       if (hasColon)
10002         badInput = (*argptr != ':');    /* Not a class::method */
10003       else
10004         badInput = isdigit (*arg);      /* a simple line number */
10005     }
10006
10007   if (badInput)
10008     printf_filtered (_("Usage: stop in <function | address>\n"));
10009   else
10010     break_command_1 (arg, 0, from_tty);
10011 }
10012
10013 static void
10014 stopat_command (char *arg, int from_tty)
10015 {
10016   int badInput = 0;
10017
10018   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10019     badInput = 1;
10020   else
10021     {
10022       char *argptr = arg;
10023       int hasColon = 0;
10024
10025       /* Look for a ':'.  If there is a '::' then get out, otherwise
10026          it is probably a line number.  */
10027       while (*argptr && !hasColon)
10028         {
10029           hasColon = (*argptr == ':');
10030           argptr++;
10031         }
10032
10033       if (hasColon)
10034         badInput = (*argptr == ':');    /* we have class::method */
10035       else
10036         badInput = !isdigit (*arg);     /* not a line number */
10037     }
10038
10039   if (badInput)
10040     printf_filtered (_("Usage: stop at <line>\n"));
10041   else
10042     break_command_1 (arg, 0, from_tty);
10043 }
10044
10045 /* The dynamic printf command is mostly like a regular breakpoint, but
10046    with a prewired command list consisting of a single output command,
10047    built from extra arguments supplied on the dprintf command
10048    line.  */
10049
10050 static void
10051 dprintf_command (char *arg, int from_tty)
10052 {
10053   struct event_location *location;
10054   struct cleanup *cleanup;
10055
10056   location = string_to_event_location (&arg, current_language);
10057   cleanup = make_cleanup_delete_event_location (location);
10058
10059   /* If non-NULL, ARG should have been advanced past the location;
10060      the next character must be ','.  */
10061   if (arg != NULL)
10062     {
10063       if (arg[0] != ',' || arg[1] == '\0')
10064         error (_("Format string required"));
10065       else
10066         {
10067           /* Skip the comma.  */
10068           ++arg;
10069         }
10070     }
10071
10072   create_breakpoint (get_current_arch (),
10073                      location,
10074                      NULL, 0, arg, 1 /* parse arg */,
10075                      0, bp_dprintf,
10076                      0 /* Ignore count */,
10077                      pending_break_support,
10078                      &dprintf_breakpoint_ops,
10079                      from_tty,
10080                      1 /* enabled */,
10081                      0 /* internal */,
10082                      0);
10083   do_cleanups (cleanup);
10084 }
10085
10086 static void
10087 agent_printf_command (char *arg, int from_tty)
10088 {
10089   error (_("May only run agent-printf on the target"));
10090 }
10091
10092 /* Implement the "breakpoint_hit" breakpoint_ops method for
10093    ranged breakpoints.  */
10094
10095 static int
10096 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10097                                   struct address_space *aspace,
10098                                   CORE_ADDR bp_addr,
10099                                   const struct target_waitstatus *ws)
10100 {
10101   if (ws->kind != TARGET_WAITKIND_STOPPED
10102       || ws->value.sig != GDB_SIGNAL_TRAP)
10103     return 0;
10104
10105   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10106                                          bl->length, aspace, bp_addr);
10107 }
10108
10109 /* Implement the "resources_needed" breakpoint_ops method for
10110    ranged breakpoints.  */
10111
10112 static int
10113 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10114 {
10115   return target_ranged_break_num_registers ();
10116 }
10117
10118 /* Implement the "print_it" breakpoint_ops method for
10119    ranged breakpoints.  */
10120
10121 static enum print_stop_action
10122 print_it_ranged_breakpoint (bpstat bs)
10123 {
10124   struct breakpoint *b = bs->breakpoint_at;
10125   struct bp_location *bl = b->loc;
10126   struct ui_out *uiout = current_uiout;
10127
10128   gdb_assert (b->type == bp_hardware_breakpoint);
10129
10130   /* Ranged breakpoints have only one location.  */
10131   gdb_assert (bl && bl->next == NULL);
10132
10133   annotate_breakpoint (b->number);
10134   if (b->disposition == disp_del)
10135     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10136   else
10137     ui_out_text (uiout, "\nRanged breakpoint ");
10138   if (ui_out_is_mi_like_p (uiout))
10139     {
10140       ui_out_field_string (uiout, "reason",
10141                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10142       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10143     }
10144   ui_out_field_int (uiout, "bkptno", b->number);
10145   ui_out_text (uiout, ", ");
10146
10147   return PRINT_SRC_AND_LOC;
10148 }
10149
10150 /* Implement the "print_one" breakpoint_ops method for
10151    ranged breakpoints.  */
10152
10153 static void
10154 print_one_ranged_breakpoint (struct breakpoint *b,
10155                              struct bp_location **last_loc)
10156 {
10157   struct bp_location *bl = b->loc;
10158   struct value_print_options opts;
10159   struct ui_out *uiout = current_uiout;
10160
10161   /* Ranged breakpoints have only one location.  */
10162   gdb_assert (bl && bl->next == NULL);
10163
10164   get_user_print_options (&opts);
10165
10166   if (opts.addressprint)
10167     /* We don't print the address range here, it will be printed later
10168        by print_one_detail_ranged_breakpoint.  */
10169     ui_out_field_skip (uiout, "addr");
10170   annotate_field (5);
10171   print_breakpoint_location (b, bl);
10172   *last_loc = bl;
10173 }
10174
10175 /* Implement the "print_one_detail" breakpoint_ops method for
10176    ranged breakpoints.  */
10177
10178 static void
10179 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10180                                     struct ui_out *uiout)
10181 {
10182   CORE_ADDR address_start, address_end;
10183   struct bp_location *bl = b->loc;
10184   struct ui_file *stb = mem_fileopen ();
10185   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10186
10187   gdb_assert (bl);
10188
10189   address_start = bl->address;
10190   address_end = address_start + bl->length - 1;
10191
10192   ui_out_text (uiout, "\taddress range: ");
10193   fprintf_unfiltered (stb, "[%s, %s]",
10194                       print_core_address (bl->gdbarch, address_start),
10195                       print_core_address (bl->gdbarch, address_end));
10196   ui_out_field_stream (uiout, "addr", stb);
10197   ui_out_text (uiout, "\n");
10198
10199   do_cleanups (cleanup);
10200 }
10201
10202 /* Implement the "print_mention" breakpoint_ops method for
10203    ranged breakpoints.  */
10204
10205 static void
10206 print_mention_ranged_breakpoint (struct breakpoint *b)
10207 {
10208   struct bp_location *bl = b->loc;
10209   struct ui_out *uiout = current_uiout;
10210
10211   gdb_assert (bl);
10212   gdb_assert (b->type == bp_hardware_breakpoint);
10213
10214   if (ui_out_is_mi_like_p (uiout))
10215     return;
10216
10217   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10218                    b->number, paddress (bl->gdbarch, bl->address),
10219                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10220 }
10221
10222 /* Implement the "print_recreate" breakpoint_ops method for
10223    ranged breakpoints.  */
10224
10225 static void
10226 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10227 {
10228   fprintf_unfiltered (fp, "break-range %s, %s",
10229                       event_location_to_string (b->location),
10230                       event_location_to_string (b->location_range_end));
10231   print_recreate_thread (b, fp);
10232 }
10233
10234 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10235
10236 static struct breakpoint_ops ranged_breakpoint_ops;
10237
10238 /* Find the address where the end of the breakpoint range should be
10239    placed, given the SAL of the end of the range.  This is so that if
10240    the user provides a line number, the end of the range is set to the
10241    last instruction of the given line.  */
10242
10243 static CORE_ADDR
10244 find_breakpoint_range_end (struct symtab_and_line sal)
10245 {
10246   CORE_ADDR end;
10247
10248   /* If the user provided a PC value, use it.  Otherwise,
10249      find the address of the end of the given location.  */
10250   if (sal.explicit_pc)
10251     end = sal.pc;
10252   else
10253     {
10254       int ret;
10255       CORE_ADDR start;
10256
10257       ret = find_line_pc_range (sal, &start, &end);
10258       if (!ret)
10259         error (_("Could not find location of the end of the range."));
10260
10261       /* find_line_pc_range returns the start of the next line.  */
10262       end--;
10263     }
10264
10265   return end;
10266 }
10267
10268 /* Implement the "break-range" CLI command.  */
10269
10270 static void
10271 break_range_command (char *arg, int from_tty)
10272 {
10273   char *arg_start, *addr_string_start, *addr_string_end;
10274   struct linespec_result canonical_start, canonical_end;
10275   int bp_count, can_use_bp, length;
10276   CORE_ADDR end;
10277   struct breakpoint *b;
10278   struct symtab_and_line sal_start, sal_end;
10279   struct cleanup *cleanup_bkpt;
10280   struct linespec_sals *lsal_start, *lsal_end;
10281   struct event_location *start_location, *end_location;
10282
10283   /* We don't support software ranged breakpoints.  */
10284   if (target_ranged_break_num_registers () < 0)
10285     error (_("This target does not support hardware ranged breakpoints."));
10286
10287   bp_count = hw_breakpoint_used_count ();
10288   bp_count += target_ranged_break_num_registers ();
10289   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10290                                                    bp_count, 0);
10291   if (can_use_bp < 0)
10292     error (_("Hardware breakpoints used exceeds limit."));
10293
10294   arg = skip_spaces (arg);
10295   if (arg == NULL || arg[0] == '\0')
10296     error(_("No address range specified."));
10297
10298   init_linespec_result (&canonical_start);
10299
10300   arg_start = arg;
10301   start_location = string_to_event_location (&arg, current_language);
10302   cleanup_bkpt = make_cleanup_delete_event_location (start_location);
10303   parse_breakpoint_sals (start_location, &canonical_start);
10304   make_cleanup_destroy_linespec_result (&canonical_start);
10305
10306   if (arg[0] != ',')
10307     error (_("Too few arguments."));
10308   else if (VEC_empty (linespec_sals, canonical_start.sals))
10309     error (_("Could not find location of the beginning of the range."));
10310
10311   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10312
10313   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10314       || lsal_start->sals.nelts != 1)
10315     error (_("Cannot create a ranged breakpoint with multiple locations."));
10316
10317   sal_start = lsal_start->sals.sals[0];
10318   addr_string_start = savestring (arg_start, arg - arg_start);
10319   make_cleanup (xfree, addr_string_start);
10320
10321   arg++;        /* Skip the comma.  */
10322   arg = skip_spaces (arg);
10323
10324   /* Parse the end location.  */
10325
10326   init_linespec_result (&canonical_end);
10327   arg_start = arg;
10328
10329   /* We call decode_line_full directly here instead of using
10330      parse_breakpoint_sals because we need to specify the start location's
10331      symtab and line as the default symtab and line for the end of the
10332      range.  This makes it possible to have ranges like "foo.c:27, +14",
10333      where +14 means 14 lines from the start location.  */
10334   end_location = string_to_event_location (&arg, current_language);
10335   make_cleanup_delete_event_location (end_location);
10336   decode_line_full (end_location, DECODE_LINE_FUNFIRSTLINE,
10337                     sal_start.symtab, sal_start.line,
10338                     &canonical_end, NULL, NULL);
10339
10340   make_cleanup_destroy_linespec_result (&canonical_end);
10341
10342   if (VEC_empty (linespec_sals, canonical_end.sals))
10343     error (_("Could not find location of the end of the range."));
10344
10345   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10346   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10347       || lsal_end->sals.nelts != 1)
10348     error (_("Cannot create a ranged breakpoint with multiple locations."));
10349
10350   sal_end = lsal_end->sals.sals[0];
10351
10352   end = find_breakpoint_range_end (sal_end);
10353   if (sal_start.pc > end)
10354     error (_("Invalid address range, end precedes start."));
10355
10356   length = end - sal_start.pc + 1;
10357   if (length < 0)
10358     /* Length overflowed.  */
10359     error (_("Address range too large."));
10360   else if (length == 1)
10361     {
10362       /* This range is simple enough to be handled by
10363          the `hbreak' command.  */
10364       hbreak_command (addr_string_start, 1);
10365
10366       do_cleanups (cleanup_bkpt);
10367
10368       return;
10369     }
10370
10371   /* Now set up the breakpoint.  */
10372   b = set_raw_breakpoint (get_current_arch (), sal_start,
10373                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10374   set_breakpoint_count (breakpoint_count + 1);
10375   b->number = breakpoint_count;
10376   b->disposition = disp_donttouch;
10377   b->location = copy_event_location (start_location);
10378   b->location_range_end = copy_event_location (end_location);
10379   b->loc->length = length;
10380
10381   do_cleanups (cleanup_bkpt);
10382
10383   mention (b);
10384   observer_notify_breakpoint_created (b);
10385   update_global_location_list (UGLL_MAY_INSERT);
10386 }
10387
10388 /*  Return non-zero if EXP is verified as constant.  Returned zero
10389     means EXP is variable.  Also the constant detection may fail for
10390     some constant expressions and in such case still falsely return
10391     zero.  */
10392
10393 static int
10394 watchpoint_exp_is_const (const struct expression *exp)
10395 {
10396   int i = exp->nelts;
10397
10398   while (i > 0)
10399     {
10400       int oplenp, argsp;
10401
10402       /* We are only interested in the descriptor of each element.  */
10403       operator_length (exp, i, &oplenp, &argsp);
10404       i -= oplenp;
10405
10406       switch (exp->elts[i].opcode)
10407         {
10408         case BINOP_ADD:
10409         case BINOP_SUB:
10410         case BINOP_MUL:
10411         case BINOP_DIV:
10412         case BINOP_REM:
10413         case BINOP_MOD:
10414         case BINOP_LSH:
10415         case BINOP_RSH:
10416         case BINOP_LOGICAL_AND:
10417         case BINOP_LOGICAL_OR:
10418         case BINOP_BITWISE_AND:
10419         case BINOP_BITWISE_IOR:
10420         case BINOP_BITWISE_XOR:
10421         case BINOP_EQUAL:
10422         case BINOP_NOTEQUAL:
10423         case BINOP_LESS:
10424         case BINOP_GTR:
10425         case BINOP_LEQ:
10426         case BINOP_GEQ:
10427         case BINOP_REPEAT:
10428         case BINOP_COMMA:
10429         case BINOP_EXP:
10430         case BINOP_MIN:
10431         case BINOP_MAX:
10432         case BINOP_INTDIV:
10433         case BINOP_CONCAT:
10434         case TERNOP_COND:
10435         case TERNOP_SLICE:
10436
10437         case OP_LONG:
10438         case OP_DOUBLE:
10439         case OP_DECFLOAT:
10440         case OP_LAST:
10441         case OP_COMPLEX:
10442         case OP_STRING:
10443         case OP_ARRAY:
10444         case OP_TYPE:
10445         case OP_TYPEOF:
10446         case OP_DECLTYPE:
10447         case OP_TYPEID:
10448         case OP_NAME:
10449         case OP_OBJC_NSSTRING:
10450
10451         case UNOP_NEG:
10452         case UNOP_LOGICAL_NOT:
10453         case UNOP_COMPLEMENT:
10454         case UNOP_ADDR:
10455         case UNOP_HIGH:
10456         case UNOP_CAST:
10457
10458         case UNOP_CAST_TYPE:
10459         case UNOP_REINTERPRET_CAST:
10460         case UNOP_DYNAMIC_CAST:
10461           /* Unary, binary and ternary operators: We have to check
10462              their operands.  If they are constant, then so is the
10463              result of that operation.  For instance, if A and B are
10464              determined to be constants, then so is "A + B".
10465
10466              UNOP_IND is one exception to the rule above, because the
10467              value of *ADDR is not necessarily a constant, even when
10468              ADDR is.  */
10469           break;
10470
10471         case OP_VAR_VALUE:
10472           /* Check whether the associated symbol is a constant.
10473
10474              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10475              possible that a buggy compiler could mark a variable as
10476              constant even when it is not, and TYPE_CONST would return
10477              true in this case, while SYMBOL_CLASS wouldn't.
10478
10479              We also have to check for function symbols because they
10480              are always constant.  */
10481           {
10482             struct symbol *s = exp->elts[i + 2].symbol;
10483
10484             if (SYMBOL_CLASS (s) != LOC_BLOCK
10485                 && SYMBOL_CLASS (s) != LOC_CONST
10486                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10487               return 0;
10488             break;
10489           }
10490
10491         /* The default action is to return 0 because we are using
10492            the optimistic approach here: If we don't know something,
10493            then it is not a constant.  */
10494         default:
10495           return 0;
10496         }
10497     }
10498
10499   return 1;
10500 }
10501
10502 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10503
10504 static void
10505 dtor_watchpoint (struct breakpoint *self)
10506 {
10507   struct watchpoint *w = (struct watchpoint *) self;
10508
10509   xfree (w->cond_exp);
10510   xfree (w->exp);
10511   xfree (w->exp_string);
10512   xfree (w->exp_string_reparse);
10513   value_free (w->val);
10514
10515   base_breakpoint_ops.dtor (self);
10516 }
10517
10518 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10519
10520 static void
10521 re_set_watchpoint (struct breakpoint *b)
10522 {
10523   struct watchpoint *w = (struct watchpoint *) b;
10524
10525   /* Watchpoint can be either on expression using entirely global
10526      variables, or it can be on local variables.
10527
10528      Watchpoints of the first kind are never auto-deleted, and even
10529      persist across program restarts.  Since they can use variables
10530      from shared libraries, we need to reparse expression as libraries
10531      are loaded and unloaded.
10532
10533      Watchpoints on local variables can also change meaning as result
10534      of solib event.  For example, if a watchpoint uses both a local
10535      and a global variables in expression, it's a local watchpoint,
10536      but unloading of a shared library will make the expression
10537      invalid.  This is not a very common use case, but we still
10538      re-evaluate expression, to avoid surprises to the user.
10539
10540      Note that for local watchpoints, we re-evaluate it only if
10541      watchpoints frame id is still valid.  If it's not, it means the
10542      watchpoint is out of scope and will be deleted soon.  In fact,
10543      I'm not sure we'll ever be called in this case.
10544
10545      If a local watchpoint's frame id is still valid, then
10546      w->exp_valid_block is likewise valid, and we can safely use it.
10547
10548      Don't do anything about disabled watchpoints, since they will be
10549      reevaluated again when enabled.  */
10550   update_watchpoint (w, 1 /* reparse */);
10551 }
10552
10553 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10554
10555 static int
10556 insert_watchpoint (struct bp_location *bl)
10557 {
10558   struct watchpoint *w = (struct watchpoint *) bl->owner;
10559   int length = w->exact ? 1 : bl->length;
10560
10561   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10562                                    w->cond_exp);
10563 }
10564
10565 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10566
10567 static int
10568 remove_watchpoint (struct bp_location *bl)
10569 {
10570   struct watchpoint *w = (struct watchpoint *) bl->owner;
10571   int length = w->exact ? 1 : bl->length;
10572
10573   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10574                                    w->cond_exp);
10575 }
10576
10577 static int
10578 breakpoint_hit_watchpoint (const struct bp_location *bl,
10579                            struct address_space *aspace, CORE_ADDR bp_addr,
10580                            const struct target_waitstatus *ws)
10581 {
10582   struct breakpoint *b = bl->owner;
10583   struct watchpoint *w = (struct watchpoint *) b;
10584
10585   /* Continuable hardware watchpoints are treated as non-existent if the
10586      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10587      some data address).  Otherwise gdb won't stop on a break instruction
10588      in the code (not from a breakpoint) when a hardware watchpoint has
10589      been defined.  Also skip watchpoints which we know did not trigger
10590      (did not match the data address).  */
10591   if (is_hardware_watchpoint (b)
10592       && w->watchpoint_triggered == watch_triggered_no)
10593     return 0;
10594
10595   return 1;
10596 }
10597
10598 static void
10599 check_status_watchpoint (bpstat bs)
10600 {
10601   gdb_assert (is_watchpoint (bs->breakpoint_at));
10602
10603   bpstat_check_watchpoint (bs);
10604 }
10605
10606 /* Implement the "resources_needed" breakpoint_ops method for
10607    hardware watchpoints.  */
10608
10609 static int
10610 resources_needed_watchpoint (const struct bp_location *bl)
10611 {
10612   struct watchpoint *w = (struct watchpoint *) bl->owner;
10613   int length = w->exact? 1 : bl->length;
10614
10615   return target_region_ok_for_hw_watchpoint (bl->address, length);
10616 }
10617
10618 /* Implement the "works_in_software_mode" breakpoint_ops method for
10619    hardware watchpoints.  */
10620
10621 static int
10622 works_in_software_mode_watchpoint (const struct breakpoint *b)
10623 {
10624   /* Read and access watchpoints only work with hardware support.  */
10625   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10626 }
10627
10628 static enum print_stop_action
10629 print_it_watchpoint (bpstat bs)
10630 {
10631   struct cleanup *old_chain;
10632   struct breakpoint *b;
10633   struct ui_file *stb;
10634   enum print_stop_action result;
10635   struct watchpoint *w;
10636   struct ui_out *uiout = current_uiout;
10637
10638   gdb_assert (bs->bp_location_at != NULL);
10639
10640   b = bs->breakpoint_at;
10641   w = (struct watchpoint *) b;
10642
10643   stb = mem_fileopen ();
10644   old_chain = make_cleanup_ui_file_delete (stb);
10645
10646   switch (b->type)
10647     {
10648     case bp_watchpoint:
10649     case bp_hardware_watchpoint:
10650       annotate_watchpoint (b->number);
10651       if (ui_out_is_mi_like_p (uiout))
10652         ui_out_field_string
10653           (uiout, "reason",
10654            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10655       mention (b);
10656       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10657       ui_out_text (uiout, "\nOld value = ");
10658       watchpoint_value_print (bs->old_val, stb);
10659       ui_out_field_stream (uiout, "old", stb);
10660       ui_out_text (uiout, "\nNew value = ");
10661       watchpoint_value_print (w->val, stb);
10662       ui_out_field_stream (uiout, "new", stb);
10663       ui_out_text (uiout, "\n");
10664       /* More than one watchpoint may have been triggered.  */
10665       result = PRINT_UNKNOWN;
10666       break;
10667
10668     case bp_read_watchpoint:
10669       if (ui_out_is_mi_like_p (uiout))
10670         ui_out_field_string
10671           (uiout, "reason",
10672            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10673       mention (b);
10674       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10675       ui_out_text (uiout, "\nValue = ");
10676       watchpoint_value_print (w->val, stb);
10677       ui_out_field_stream (uiout, "value", stb);
10678       ui_out_text (uiout, "\n");
10679       result = PRINT_UNKNOWN;
10680       break;
10681
10682     case bp_access_watchpoint:
10683       if (bs->old_val != NULL)
10684         {
10685           annotate_watchpoint (b->number);
10686           if (ui_out_is_mi_like_p (uiout))
10687             ui_out_field_string
10688               (uiout, "reason",
10689                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10690           mention (b);
10691           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10692           ui_out_text (uiout, "\nOld value = ");
10693           watchpoint_value_print (bs->old_val, stb);
10694           ui_out_field_stream (uiout, "old", stb);
10695           ui_out_text (uiout, "\nNew value = ");
10696         }
10697       else
10698         {
10699           mention (b);
10700           if (ui_out_is_mi_like_p (uiout))
10701             ui_out_field_string
10702               (uiout, "reason",
10703                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10704           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10705           ui_out_text (uiout, "\nValue = ");
10706         }
10707       watchpoint_value_print (w->val, stb);
10708       ui_out_field_stream (uiout, "new", stb);
10709       ui_out_text (uiout, "\n");
10710       result = PRINT_UNKNOWN;
10711       break;
10712     default:
10713       result = PRINT_UNKNOWN;
10714     }
10715
10716   do_cleanups (old_chain);
10717   return result;
10718 }
10719
10720 /* Implement the "print_mention" breakpoint_ops method for hardware
10721    watchpoints.  */
10722
10723 static void
10724 print_mention_watchpoint (struct breakpoint *b)
10725 {
10726   struct cleanup *ui_out_chain;
10727   struct watchpoint *w = (struct watchpoint *) b;
10728   struct ui_out *uiout = current_uiout;
10729
10730   switch (b->type)
10731     {
10732     case bp_watchpoint:
10733       ui_out_text (uiout, "Watchpoint ");
10734       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10735       break;
10736     case bp_hardware_watchpoint:
10737       ui_out_text (uiout, "Hardware watchpoint ");
10738       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10739       break;
10740     case bp_read_watchpoint:
10741       ui_out_text (uiout, "Hardware read watchpoint ");
10742       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10743       break;
10744     case bp_access_watchpoint:
10745       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10746       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10747       break;
10748     default:
10749       internal_error (__FILE__, __LINE__,
10750                       _("Invalid hardware watchpoint type."));
10751     }
10752
10753   ui_out_field_int (uiout, "number", b->number);
10754   ui_out_text (uiout, ": ");
10755   ui_out_field_string (uiout, "exp", w->exp_string);
10756   do_cleanups (ui_out_chain);
10757 }
10758
10759 /* Implement the "print_recreate" breakpoint_ops method for
10760    watchpoints.  */
10761
10762 static void
10763 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10764 {
10765   struct watchpoint *w = (struct watchpoint *) b;
10766
10767   switch (b->type)
10768     {
10769     case bp_watchpoint:
10770     case bp_hardware_watchpoint:
10771       fprintf_unfiltered (fp, "watch");
10772       break;
10773     case bp_read_watchpoint:
10774       fprintf_unfiltered (fp, "rwatch");
10775       break;
10776     case bp_access_watchpoint:
10777       fprintf_unfiltered (fp, "awatch");
10778       break;
10779     default:
10780       internal_error (__FILE__, __LINE__,
10781                       _("Invalid watchpoint type."));
10782     }
10783
10784   fprintf_unfiltered (fp, " %s", w->exp_string);
10785   print_recreate_thread (b, fp);
10786 }
10787
10788 /* Implement the "explains_signal" breakpoint_ops method for
10789    watchpoints.  */
10790
10791 static int
10792 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10793 {
10794   /* A software watchpoint cannot cause a signal other than
10795      GDB_SIGNAL_TRAP.  */
10796   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10797     return 0;
10798
10799   return 1;
10800 }
10801
10802 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10803
10804 static struct breakpoint_ops watchpoint_breakpoint_ops;
10805
10806 /* Implement the "insert" breakpoint_ops method for
10807    masked hardware watchpoints.  */
10808
10809 static int
10810 insert_masked_watchpoint (struct bp_location *bl)
10811 {
10812   struct watchpoint *w = (struct watchpoint *) bl->owner;
10813
10814   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10815                                         bl->watchpoint_type);
10816 }
10817
10818 /* Implement the "remove" breakpoint_ops method for
10819    masked hardware watchpoints.  */
10820
10821 static int
10822 remove_masked_watchpoint (struct bp_location *bl)
10823 {
10824   struct watchpoint *w = (struct watchpoint *) bl->owner;
10825
10826   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10827                                         bl->watchpoint_type);
10828 }
10829
10830 /* Implement the "resources_needed" breakpoint_ops method for
10831    masked hardware watchpoints.  */
10832
10833 static int
10834 resources_needed_masked_watchpoint (const struct bp_location *bl)
10835 {
10836   struct watchpoint *w = (struct watchpoint *) bl->owner;
10837
10838   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10839 }
10840
10841 /* Implement the "works_in_software_mode" breakpoint_ops method for
10842    masked hardware watchpoints.  */
10843
10844 static int
10845 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10846 {
10847   return 0;
10848 }
10849
10850 /* Implement the "print_it" breakpoint_ops method for
10851    masked hardware watchpoints.  */
10852
10853 static enum print_stop_action
10854 print_it_masked_watchpoint (bpstat bs)
10855 {
10856   struct breakpoint *b = bs->breakpoint_at;
10857   struct ui_out *uiout = current_uiout;
10858
10859   /* Masked watchpoints have only one location.  */
10860   gdb_assert (b->loc && b->loc->next == NULL);
10861
10862   switch (b->type)
10863     {
10864     case bp_hardware_watchpoint:
10865       annotate_watchpoint (b->number);
10866       if (ui_out_is_mi_like_p (uiout))
10867         ui_out_field_string
10868           (uiout, "reason",
10869            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10870       break;
10871
10872     case bp_read_watchpoint:
10873       if (ui_out_is_mi_like_p (uiout))
10874         ui_out_field_string
10875           (uiout, "reason",
10876            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10877       break;
10878
10879     case bp_access_watchpoint:
10880       if (ui_out_is_mi_like_p (uiout))
10881         ui_out_field_string
10882           (uiout, "reason",
10883            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10884       break;
10885     default:
10886       internal_error (__FILE__, __LINE__,
10887                       _("Invalid hardware watchpoint type."));
10888     }
10889
10890   mention (b);
10891   ui_out_text (uiout, _("\n\
10892 Check the underlying instruction at PC for the memory\n\
10893 address and value which triggered this watchpoint.\n"));
10894   ui_out_text (uiout, "\n");
10895
10896   /* More than one watchpoint may have been triggered.  */
10897   return PRINT_UNKNOWN;
10898 }
10899
10900 /* Implement the "print_one_detail" breakpoint_ops method for
10901    masked hardware watchpoints.  */
10902
10903 static void
10904 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10905                                     struct ui_out *uiout)
10906 {
10907   struct watchpoint *w = (struct watchpoint *) b;
10908
10909   /* Masked watchpoints have only one location.  */
10910   gdb_assert (b->loc && b->loc->next == NULL);
10911
10912   ui_out_text (uiout, "\tmask ");
10913   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10914   ui_out_text (uiout, "\n");
10915 }
10916
10917 /* Implement the "print_mention" breakpoint_ops method for
10918    masked hardware watchpoints.  */
10919
10920 static void
10921 print_mention_masked_watchpoint (struct breakpoint *b)
10922 {
10923   struct watchpoint *w = (struct watchpoint *) b;
10924   struct ui_out *uiout = current_uiout;
10925   struct cleanup *ui_out_chain;
10926
10927   switch (b->type)
10928     {
10929     case bp_hardware_watchpoint:
10930       ui_out_text (uiout, "Masked hardware watchpoint ");
10931       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10932       break;
10933     case bp_read_watchpoint:
10934       ui_out_text (uiout, "Masked hardware read watchpoint ");
10935       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10936       break;
10937     case bp_access_watchpoint:
10938       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10939       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10940       break;
10941     default:
10942       internal_error (__FILE__, __LINE__,
10943                       _("Invalid hardware watchpoint type."));
10944     }
10945
10946   ui_out_field_int (uiout, "number", b->number);
10947   ui_out_text (uiout, ": ");
10948   ui_out_field_string (uiout, "exp", w->exp_string);
10949   do_cleanups (ui_out_chain);
10950 }
10951
10952 /* Implement the "print_recreate" breakpoint_ops method for
10953    masked hardware watchpoints.  */
10954
10955 static void
10956 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10957 {
10958   struct watchpoint *w = (struct watchpoint *) b;
10959   char tmp[40];
10960
10961   switch (b->type)
10962     {
10963     case bp_hardware_watchpoint:
10964       fprintf_unfiltered (fp, "watch");
10965       break;
10966     case bp_read_watchpoint:
10967       fprintf_unfiltered (fp, "rwatch");
10968       break;
10969     case bp_access_watchpoint:
10970       fprintf_unfiltered (fp, "awatch");
10971       break;
10972     default:
10973       internal_error (__FILE__, __LINE__,
10974                       _("Invalid hardware watchpoint type."));
10975     }
10976
10977   sprintf_vma (tmp, w->hw_wp_mask);
10978   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10979   print_recreate_thread (b, fp);
10980 }
10981
10982 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10983
10984 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10985
10986 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10987
10988 static int
10989 is_masked_watchpoint (const struct breakpoint *b)
10990 {
10991   return b->ops == &masked_watchpoint_breakpoint_ops;
10992 }
10993
10994 /* accessflag:  hw_write:  watch write, 
10995                 hw_read:   watch read, 
10996                 hw_access: watch access (read or write) */
10997 static void
10998 watch_command_1 (const char *arg, int accessflag, int from_tty,
10999                  int just_location, int internal)
11000 {
11001   struct breakpoint *b, *scope_breakpoint = NULL;
11002   struct expression *exp;
11003   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11004   struct value *val, *mark, *result;
11005   int saved_bitpos = 0, saved_bitsize = 0;
11006   struct frame_info *frame;
11007   const char *exp_start = NULL;
11008   const char *exp_end = NULL;
11009   const char *tok, *end_tok;
11010   int toklen = -1;
11011   const char *cond_start = NULL;
11012   const char *cond_end = NULL;
11013   enum bptype bp_type;
11014   int thread = -1;
11015   int pc = 0;
11016   /* Flag to indicate whether we are going to use masks for
11017      the hardware watchpoint.  */
11018   int use_mask = 0;
11019   CORE_ADDR mask = 0;
11020   struct watchpoint *w;
11021   char *expression;
11022   struct cleanup *back_to;
11023
11024   /* Make sure that we actually have parameters to parse.  */
11025   if (arg != NULL && arg[0] != '\0')
11026     {
11027       const char *value_start;
11028
11029       exp_end = arg + strlen (arg);
11030
11031       /* Look for "parameter value" pairs at the end
11032          of the arguments string.  */
11033       for (tok = exp_end - 1; tok > arg; tok--)
11034         {
11035           /* Skip whitespace at the end of the argument list.  */
11036           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11037             tok--;
11038
11039           /* Find the beginning of the last token.
11040              This is the value of the parameter.  */
11041           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11042             tok--;
11043           value_start = tok + 1;
11044
11045           /* Skip whitespace.  */
11046           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11047             tok--;
11048
11049           end_tok = tok;
11050
11051           /* Find the beginning of the second to last token.
11052              This is the parameter itself.  */
11053           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11054             tok--;
11055           tok++;
11056           toklen = end_tok - tok + 1;
11057
11058           if (toklen == 6 && startswith (tok, "thread"))
11059             {
11060               /* At this point we've found a "thread" token, which means
11061                  the user is trying to set a watchpoint that triggers
11062                  only in a specific thread.  */
11063               char *endp;
11064
11065               if (thread != -1)
11066                 error(_("You can specify only one thread."));
11067
11068               /* Extract the thread ID from the next token.  */
11069               thread = strtol (value_start, &endp, 0);
11070
11071               /* Check if the user provided a valid numeric value for the
11072                  thread ID.  */
11073               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11074                 error (_("Invalid thread ID specification %s."), value_start);
11075
11076               /* Check if the thread actually exists.  */
11077               if (!valid_thread_id (thread))
11078                 invalid_thread_id_error (thread);
11079             }
11080           else if (toklen == 4 && startswith (tok, "mask"))
11081             {
11082               /* We've found a "mask" token, which means the user wants to
11083                  create a hardware watchpoint that is going to have the mask
11084                  facility.  */
11085               struct value *mask_value, *mark;
11086
11087               if (use_mask)
11088                 error(_("You can specify only one mask."));
11089
11090               use_mask = just_location = 1;
11091
11092               mark = value_mark ();
11093               mask_value = parse_to_comma_and_eval (&value_start);
11094               mask = value_as_address (mask_value);
11095               value_free_to_mark (mark);
11096             }
11097           else
11098             /* We didn't recognize what we found.  We should stop here.  */
11099             break;
11100
11101           /* Truncate the string and get rid of the "parameter value" pair before
11102              the arguments string is parsed by the parse_exp_1 function.  */
11103           exp_end = tok;
11104         }
11105     }
11106   else
11107     exp_end = arg;
11108
11109   /* Parse the rest of the arguments.  From here on out, everything
11110      is in terms of a newly allocated string instead of the original
11111      ARG.  */
11112   innermost_block = NULL;
11113   expression = savestring (arg, exp_end - arg);
11114   back_to = make_cleanup (xfree, expression);
11115   exp_start = arg = expression;
11116   exp = parse_exp_1 (&arg, 0, 0, 0);
11117   exp_end = arg;
11118   /* Remove trailing whitespace from the expression before saving it.
11119      This makes the eventual display of the expression string a bit
11120      prettier.  */
11121   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11122     --exp_end;
11123
11124   /* Checking if the expression is not constant.  */
11125   if (watchpoint_exp_is_const (exp))
11126     {
11127       int len;
11128
11129       len = exp_end - exp_start;
11130       while (len > 0 && isspace (exp_start[len - 1]))
11131         len--;
11132       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11133     }
11134
11135   exp_valid_block = innermost_block;
11136   mark = value_mark ();
11137   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11138
11139   if (val != NULL && just_location)
11140     {
11141       saved_bitpos = value_bitpos (val);
11142       saved_bitsize = value_bitsize (val);
11143     }
11144
11145   if (just_location)
11146     {
11147       int ret;
11148
11149       exp_valid_block = NULL;
11150       val = value_addr (result);
11151       release_value (val);
11152       value_free_to_mark (mark);
11153
11154       if (use_mask)
11155         {
11156           ret = target_masked_watch_num_registers (value_as_address (val),
11157                                                    mask);
11158           if (ret == -1)
11159             error (_("This target does not support masked watchpoints."));
11160           else if (ret == -2)
11161             error (_("Invalid mask or memory region."));
11162         }
11163     }
11164   else if (val != NULL)
11165     release_value (val);
11166
11167   tok = skip_spaces_const (arg);
11168   end_tok = skip_to_space_const (tok);
11169
11170   toklen = end_tok - tok;
11171   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11172     {
11173       struct expression *cond;
11174
11175       innermost_block = NULL;
11176       tok = cond_start = end_tok + 1;
11177       cond = parse_exp_1 (&tok, 0, 0, 0);
11178
11179       /* The watchpoint expression may not be local, but the condition
11180          may still be.  E.g.: `watch global if local > 0'.  */
11181       cond_exp_valid_block = innermost_block;
11182
11183       xfree (cond);
11184       cond_end = tok;
11185     }
11186   if (*tok)
11187     error (_("Junk at end of command."));
11188
11189   frame = block_innermost_frame (exp_valid_block);
11190
11191   /* If the expression is "local", then set up a "watchpoint scope"
11192      breakpoint at the point where we've left the scope of the watchpoint
11193      expression.  Create the scope breakpoint before the watchpoint, so
11194      that we will encounter it first in bpstat_stop_status.  */
11195   if (exp_valid_block && frame)
11196     {
11197       if (frame_id_p (frame_unwind_caller_id (frame)))
11198         {
11199           scope_breakpoint
11200             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11201                                           frame_unwind_caller_pc (frame),
11202                                           bp_watchpoint_scope,
11203                                           &momentary_breakpoint_ops);
11204
11205           scope_breakpoint->enable_state = bp_enabled;
11206
11207           /* Automatically delete the breakpoint when it hits.  */
11208           scope_breakpoint->disposition = disp_del;
11209
11210           /* Only break in the proper frame (help with recursion).  */
11211           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11212
11213           /* Set the address at which we will stop.  */
11214           scope_breakpoint->loc->gdbarch
11215             = frame_unwind_caller_arch (frame);
11216           scope_breakpoint->loc->requested_address
11217             = frame_unwind_caller_pc (frame);
11218           scope_breakpoint->loc->address
11219             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11220                                          scope_breakpoint->loc->requested_address,
11221                                          scope_breakpoint->type);
11222         }
11223     }
11224
11225   /* Now set up the breakpoint.  We create all watchpoints as hardware
11226      watchpoints here even if hardware watchpoints are turned off, a call
11227      to update_watchpoint later in this function will cause the type to
11228      drop back to bp_watchpoint (software watchpoint) if required.  */
11229
11230   if (accessflag == hw_read)
11231     bp_type = bp_read_watchpoint;
11232   else if (accessflag == hw_access)
11233     bp_type = bp_access_watchpoint;
11234   else
11235     bp_type = bp_hardware_watchpoint;
11236
11237   w = XCNEW (struct watchpoint);
11238   b = &w->base;
11239   if (use_mask)
11240     init_raw_breakpoint_without_location (b, NULL, bp_type,
11241                                           &masked_watchpoint_breakpoint_ops);
11242   else
11243     init_raw_breakpoint_without_location (b, NULL, bp_type,
11244                                           &watchpoint_breakpoint_ops);
11245   b->thread = thread;
11246   b->disposition = disp_donttouch;
11247   b->pspace = current_program_space;
11248   w->exp = exp;
11249   w->exp_valid_block = exp_valid_block;
11250   w->cond_exp_valid_block = cond_exp_valid_block;
11251   if (just_location)
11252     {
11253       struct type *t = value_type (val);
11254       CORE_ADDR addr = value_as_address (val);
11255       char *name;
11256
11257       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11258       name = type_to_string (t);
11259
11260       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11261                                           core_addr_to_string (addr));
11262       xfree (name);
11263
11264       w->exp_string = xstrprintf ("-location %.*s",
11265                                   (int) (exp_end - exp_start), exp_start);
11266
11267       /* The above expression is in C.  */
11268       b->language = language_c;
11269     }
11270   else
11271     w->exp_string = savestring (exp_start, exp_end - exp_start);
11272
11273   if (use_mask)
11274     {
11275       w->hw_wp_mask = mask;
11276     }
11277   else
11278     {
11279       w->val = val;
11280       w->val_bitpos = saved_bitpos;
11281       w->val_bitsize = saved_bitsize;
11282       w->val_valid = 1;
11283     }
11284
11285   if (cond_start)
11286     b->cond_string = savestring (cond_start, cond_end - cond_start);
11287   else
11288     b->cond_string = 0;
11289
11290   if (frame)
11291     {
11292       w->watchpoint_frame = get_frame_id (frame);
11293       w->watchpoint_thread = inferior_ptid;
11294     }
11295   else
11296     {
11297       w->watchpoint_frame = null_frame_id;
11298       w->watchpoint_thread = null_ptid;
11299     }
11300
11301   if (scope_breakpoint != NULL)
11302     {
11303       /* The scope breakpoint is related to the watchpoint.  We will
11304          need to act on them together.  */
11305       b->related_breakpoint = scope_breakpoint;
11306       scope_breakpoint->related_breakpoint = b;
11307     }
11308
11309   if (!just_location)
11310     value_free_to_mark (mark);
11311
11312   TRY
11313     {
11314       /* Finally update the new watchpoint.  This creates the locations
11315          that should be inserted.  */
11316       update_watchpoint (w, 1);
11317     }
11318   CATCH (e, RETURN_MASK_ALL)
11319     {
11320       delete_breakpoint (b);
11321       throw_exception (e);
11322     }
11323   END_CATCH
11324
11325   install_breakpoint (internal, b, 1);
11326   do_cleanups (back_to);
11327 }
11328
11329 /* Return count of debug registers needed to watch the given expression.
11330    If the watchpoint cannot be handled in hardware return zero.  */
11331
11332 static int
11333 can_use_hardware_watchpoint (struct value *v)
11334 {
11335   int found_memory_cnt = 0;
11336   struct value *head = v;
11337
11338   /* Did the user specifically forbid us to use hardware watchpoints? */
11339   if (!can_use_hw_watchpoints)
11340     return 0;
11341
11342   /* Make sure that the value of the expression depends only upon
11343      memory contents, and values computed from them within GDB.  If we
11344      find any register references or function calls, we can't use a
11345      hardware watchpoint.
11346
11347      The idea here is that evaluating an expression generates a series
11348      of values, one holding the value of every subexpression.  (The
11349      expression a*b+c has five subexpressions: a, b, a*b, c, and
11350      a*b+c.)  GDB's values hold almost enough information to establish
11351      the criteria given above --- they identify memory lvalues,
11352      register lvalues, computed values, etcetera.  So we can evaluate
11353      the expression, and then scan the chain of values that leaves
11354      behind to decide whether we can detect any possible change to the
11355      expression's final value using only hardware watchpoints.
11356
11357      However, I don't think that the values returned by inferior
11358      function calls are special in any way.  So this function may not
11359      notice that an expression involving an inferior function call
11360      can't be watched with hardware watchpoints.  FIXME.  */
11361   for (; v; v = value_next (v))
11362     {
11363       if (VALUE_LVAL (v) == lval_memory)
11364         {
11365           if (v != head && value_lazy (v))
11366             /* A lazy memory lvalue in the chain is one that GDB never
11367                needed to fetch; we either just used its address (e.g.,
11368                `a' in `a.b') or we never needed it at all (e.g., `a'
11369                in `a,b').  This doesn't apply to HEAD; if that is
11370                lazy then it was not readable, but watch it anyway.  */
11371             ;
11372           else
11373             {
11374               /* Ahh, memory we actually used!  Check if we can cover
11375                  it with hardware watchpoints.  */
11376               struct type *vtype = check_typedef (value_type (v));
11377
11378               /* We only watch structs and arrays if user asked for it
11379                  explicitly, never if they just happen to appear in a
11380                  middle of some value chain.  */
11381               if (v == head
11382                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11383                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11384                 {
11385                   CORE_ADDR vaddr = value_address (v);
11386                   int len;
11387                   int num_regs;
11388
11389                   len = (target_exact_watchpoints
11390                          && is_scalar_type_recursive (vtype))?
11391                     1 : TYPE_LENGTH (value_type (v));
11392
11393                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11394                   if (!num_regs)
11395                     return 0;
11396                   else
11397                     found_memory_cnt += num_regs;
11398                 }
11399             }
11400         }
11401       else if (VALUE_LVAL (v) != not_lval
11402                && deprecated_value_modifiable (v) == 0)
11403         return 0;       /* These are values from the history (e.g., $1).  */
11404       else if (VALUE_LVAL (v) == lval_register)
11405         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11406     }
11407
11408   /* The expression itself looks suitable for using a hardware
11409      watchpoint, but give the target machine a chance to reject it.  */
11410   return found_memory_cnt;
11411 }
11412
11413 void
11414 watch_command_wrapper (char *arg, int from_tty, int internal)
11415 {
11416   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11417 }
11418
11419 /* A helper function that looks for the "-location" argument and then
11420    calls watch_command_1.  */
11421
11422 static void
11423 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11424 {
11425   int just_location = 0;
11426
11427   if (arg
11428       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11429           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11430     {
11431       arg = skip_spaces (arg);
11432       just_location = 1;
11433     }
11434
11435   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11436 }
11437
11438 static void
11439 watch_command (char *arg, int from_tty)
11440 {
11441   watch_maybe_just_location (arg, hw_write, from_tty);
11442 }
11443
11444 void
11445 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11446 {
11447   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11448 }
11449
11450 static void
11451 rwatch_command (char *arg, int from_tty)
11452 {
11453   watch_maybe_just_location (arg, hw_read, from_tty);
11454 }
11455
11456 void
11457 awatch_command_wrapper (char *arg, int from_tty, int internal)
11458 {
11459   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11460 }
11461
11462 static void
11463 awatch_command (char *arg, int from_tty)
11464 {
11465   watch_maybe_just_location (arg, hw_access, from_tty);
11466 }
11467 \f
11468
11469 /* Data for the FSM that manages the until(location)/advance commands
11470    in infcmd.c.  Here because it uses the mechanisms of
11471    breakpoints.  */
11472
11473 struct until_break_fsm
11474 {
11475   /* The base class.  */
11476   struct thread_fsm thread_fsm;
11477
11478   /* The thread that as current when the command was executed.  */
11479   int thread;
11480
11481   /* The breakpoint set at the destination location.  */
11482   struct breakpoint *location_breakpoint;
11483
11484   /* Breakpoint set at the return address in the caller frame.  May be
11485      NULL.  */
11486   struct breakpoint *caller_breakpoint;
11487 };
11488
11489 static void until_break_fsm_clean_up (struct thread_fsm *self);
11490 static int until_break_fsm_should_stop (struct thread_fsm *self);
11491 static enum async_reply_reason
11492   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11493
11494 /* until_break_fsm's vtable.  */
11495
11496 static struct thread_fsm_ops until_break_fsm_ops =
11497 {
11498   NULL, /* dtor */
11499   until_break_fsm_clean_up,
11500   until_break_fsm_should_stop,
11501   NULL, /* return_value */
11502   until_break_fsm_async_reply_reason,
11503 };
11504
11505 /* Allocate a new until_break_command_fsm.  */
11506
11507 static struct until_break_fsm *
11508 new_until_break_fsm (int thread,
11509                      struct breakpoint *location_breakpoint,
11510                      struct breakpoint *caller_breakpoint)
11511 {
11512   struct until_break_fsm *sm;
11513
11514   sm = XCNEW (struct until_break_fsm);
11515   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops);
11516
11517   sm->thread = thread;
11518   sm->location_breakpoint = location_breakpoint;
11519   sm->caller_breakpoint = caller_breakpoint;
11520
11521   return sm;
11522 }
11523
11524 /* Implementation of the 'should_stop' FSM method for the
11525    until(location)/advance commands.  */
11526
11527 static int
11528 until_break_fsm_should_stop (struct thread_fsm *self)
11529 {
11530   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11531   struct thread_info *tp = inferior_thread ();
11532
11533   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11534                               sm->location_breakpoint) != NULL
11535       || (sm->caller_breakpoint != NULL
11536           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11537                                      sm->caller_breakpoint) != NULL))
11538     thread_fsm_set_finished (self);
11539
11540   return 1;
11541 }
11542
11543 /* Implementation of the 'clean_up' FSM method for the
11544    until(location)/advance commands.  */
11545
11546 static void
11547 until_break_fsm_clean_up (struct thread_fsm *self)
11548 {
11549   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11550
11551   /* Clean up our temporary breakpoints.  */
11552   if (sm->location_breakpoint != NULL)
11553     {
11554       delete_breakpoint (sm->location_breakpoint);
11555       sm->location_breakpoint = NULL;
11556     }
11557   if (sm->caller_breakpoint != NULL)
11558     {
11559       delete_breakpoint (sm->caller_breakpoint);
11560       sm->caller_breakpoint = NULL;
11561     }
11562   delete_longjmp_breakpoint (sm->thread);
11563 }
11564
11565 /* Implementation of the 'async_reply_reason' FSM method for the
11566    until(location)/advance commands.  */
11567
11568 static enum async_reply_reason
11569 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11570 {
11571   return EXEC_ASYNC_LOCATION_REACHED;
11572 }
11573
11574 void
11575 until_break_command (char *arg, int from_tty, int anywhere)
11576 {
11577   struct symtabs_and_lines sals;
11578   struct symtab_and_line sal;
11579   struct frame_info *frame;
11580   struct gdbarch *frame_gdbarch;
11581   struct frame_id stack_frame_id;
11582   struct frame_id caller_frame_id;
11583   struct breakpoint *location_breakpoint;
11584   struct breakpoint *caller_breakpoint = NULL;
11585   struct cleanup *old_chain, *cleanup;
11586   int thread;
11587   struct thread_info *tp;
11588   struct event_location *location;
11589   struct until_break_fsm *sm;
11590
11591   clear_proceed_status (0);
11592
11593   /* Set a breakpoint where the user wants it and at return from
11594      this function.  */
11595
11596   location = string_to_event_location (&arg, current_language);
11597   cleanup = make_cleanup_delete_event_location (location);
11598
11599   if (last_displayed_sal_is_valid ())
11600     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11601                           get_last_displayed_symtab (),
11602                           get_last_displayed_line ());
11603   else
11604     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11605                           (struct symtab *) NULL, 0);
11606
11607   if (sals.nelts != 1)
11608     error (_("Couldn't get information on specified line."));
11609
11610   sal = sals.sals[0];
11611   xfree (sals.sals);    /* malloc'd, so freed.  */
11612
11613   if (*arg)
11614     error (_("Junk at end of arguments."));
11615
11616   resolve_sal_pc (&sal);
11617
11618   tp = inferior_thread ();
11619   thread = tp->num;
11620
11621   old_chain = make_cleanup (null_cleanup, NULL);
11622
11623   /* Note linespec handling above invalidates the frame chain.
11624      Installing a breakpoint also invalidates the frame chain (as it
11625      may need to switch threads), so do any frame handling before
11626      that.  */
11627
11628   frame = get_selected_frame (NULL);
11629   frame_gdbarch = get_frame_arch (frame);
11630   stack_frame_id = get_stack_frame_id (frame);
11631   caller_frame_id = frame_unwind_caller_id (frame);
11632
11633   /* Keep within the current frame, or in frames called by the current
11634      one.  */
11635
11636   if (frame_id_p (caller_frame_id))
11637     {
11638       struct symtab_and_line sal2;
11639       struct gdbarch *caller_gdbarch;
11640
11641       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11642       sal2.pc = frame_unwind_caller_pc (frame);
11643       caller_gdbarch = frame_unwind_caller_arch (frame);
11644       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11645                                                     sal2,
11646                                                     caller_frame_id,
11647                                                     bp_until);
11648       make_cleanup_delete_breakpoint (caller_breakpoint);
11649
11650       set_longjmp_breakpoint (tp, caller_frame_id);
11651       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11652     }
11653
11654   /* set_momentary_breakpoint could invalidate FRAME.  */
11655   frame = NULL;
11656
11657   if (anywhere)
11658     /* If the user told us to continue until a specified location,
11659        we don't specify a frame at which we need to stop.  */
11660     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11661                                                     null_frame_id, bp_until);
11662   else
11663     /* Otherwise, specify the selected frame, because we want to stop
11664        only at the very same frame.  */
11665     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11666                                                     stack_frame_id, bp_until);
11667   make_cleanup_delete_breakpoint (location_breakpoint);
11668
11669   sm = new_until_break_fsm (tp->num, location_breakpoint, caller_breakpoint);
11670   tp->thread_fsm = &sm->thread_fsm;
11671
11672   discard_cleanups (old_chain);
11673
11674   proceed (-1, GDB_SIGNAL_DEFAULT);
11675
11676   do_cleanups (cleanup);
11677 }
11678
11679 /* This function attempts to parse an optional "if <cond>" clause
11680    from the arg string.  If one is not found, it returns NULL.
11681
11682    Else, it returns a pointer to the condition string.  (It does not
11683    attempt to evaluate the string against a particular block.)  And,
11684    it updates arg to point to the first character following the parsed
11685    if clause in the arg string.  */
11686
11687 char *
11688 ep_parse_optional_if_clause (char **arg)
11689 {
11690   char *cond_string;
11691
11692   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11693     return NULL;
11694
11695   /* Skip the "if" keyword.  */
11696   (*arg) += 2;
11697
11698   /* Skip any extra leading whitespace, and record the start of the
11699      condition string.  */
11700   *arg = skip_spaces (*arg);
11701   cond_string = *arg;
11702
11703   /* Assume that the condition occupies the remainder of the arg
11704      string.  */
11705   (*arg) += strlen (cond_string);
11706
11707   return cond_string;
11708 }
11709
11710 /* Commands to deal with catching events, such as signals, exceptions,
11711    process start/exit, etc.  */
11712
11713 typedef enum
11714 {
11715   catch_fork_temporary, catch_vfork_temporary,
11716   catch_fork_permanent, catch_vfork_permanent
11717 }
11718 catch_fork_kind;
11719
11720 static void
11721 catch_fork_command_1 (char *arg, int from_tty, 
11722                       struct cmd_list_element *command)
11723 {
11724   struct gdbarch *gdbarch = get_current_arch ();
11725   char *cond_string = NULL;
11726   catch_fork_kind fork_kind;
11727   int tempflag;
11728
11729   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11730   tempflag = (fork_kind == catch_fork_temporary
11731               || fork_kind == catch_vfork_temporary);
11732
11733   if (!arg)
11734     arg = "";
11735   arg = skip_spaces (arg);
11736
11737   /* The allowed syntax is:
11738      catch [v]fork
11739      catch [v]fork if <cond>
11740
11741      First, check if there's an if clause.  */
11742   cond_string = ep_parse_optional_if_clause (&arg);
11743
11744   if ((*arg != '\0') && !isspace (*arg))
11745     error (_("Junk at end of arguments."));
11746
11747   /* If this target supports it, create a fork or vfork catchpoint
11748      and enable reporting of such events.  */
11749   switch (fork_kind)
11750     {
11751     case catch_fork_temporary:
11752     case catch_fork_permanent:
11753       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11754                                           &catch_fork_breakpoint_ops);
11755       break;
11756     case catch_vfork_temporary:
11757     case catch_vfork_permanent:
11758       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11759                                           &catch_vfork_breakpoint_ops);
11760       break;
11761     default:
11762       error (_("unsupported or unknown fork kind; cannot catch it"));
11763       break;
11764     }
11765 }
11766
11767 static void
11768 catch_exec_command_1 (char *arg, int from_tty, 
11769                       struct cmd_list_element *command)
11770 {
11771   struct exec_catchpoint *c;
11772   struct gdbarch *gdbarch = get_current_arch ();
11773   int tempflag;
11774   char *cond_string = NULL;
11775
11776   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11777
11778   if (!arg)
11779     arg = "";
11780   arg = skip_spaces (arg);
11781
11782   /* The allowed syntax is:
11783      catch exec
11784      catch exec if <cond>
11785
11786      First, check if there's an if clause.  */
11787   cond_string = ep_parse_optional_if_clause (&arg);
11788
11789   if ((*arg != '\0') && !isspace (*arg))
11790     error (_("Junk at end of arguments."));
11791
11792   c = XNEW (struct exec_catchpoint);
11793   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11794                    &catch_exec_breakpoint_ops);
11795   c->exec_pathname = NULL;
11796
11797   install_breakpoint (0, &c->base, 1);
11798 }
11799
11800 void
11801 init_ada_exception_breakpoint (struct breakpoint *b,
11802                                struct gdbarch *gdbarch,
11803                                struct symtab_and_line sal,
11804                                char *addr_string,
11805                                const struct breakpoint_ops *ops,
11806                                int tempflag,
11807                                int enabled,
11808                                int from_tty)
11809 {
11810   if (from_tty)
11811     {
11812       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11813       if (!loc_gdbarch)
11814         loc_gdbarch = gdbarch;
11815
11816       describe_other_breakpoints (loc_gdbarch,
11817                                   sal.pspace, sal.pc, sal.section, -1);
11818       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11819          version for exception catchpoints, because two catchpoints
11820          used for different exception names will use the same address.
11821          In this case, a "breakpoint ... also set at..." warning is
11822          unproductive.  Besides, the warning phrasing is also a bit
11823          inappropriate, we should use the word catchpoint, and tell
11824          the user what type of catchpoint it is.  The above is good
11825          enough for now, though.  */
11826     }
11827
11828   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11829
11830   b->enable_state = enabled ? bp_enabled : bp_disabled;
11831   b->disposition = tempflag ? disp_del : disp_donttouch;
11832   b->location = string_to_event_location (&addr_string,
11833                                           language_def (language_ada));
11834   b->language = language_ada;
11835 }
11836
11837 static void
11838 catch_command (char *arg, int from_tty)
11839 {
11840   error (_("Catch requires an event name."));
11841 }
11842 \f
11843
11844 static void
11845 tcatch_command (char *arg, int from_tty)
11846 {
11847   error (_("Catch requires an event name."));
11848 }
11849
11850 /* A qsort comparison function that sorts breakpoints in order.  */
11851
11852 static int
11853 compare_breakpoints (const void *a, const void *b)
11854 {
11855   const breakpoint_p *ba = a;
11856   uintptr_t ua = (uintptr_t) *ba;
11857   const breakpoint_p *bb = b;
11858   uintptr_t ub = (uintptr_t) *bb;
11859
11860   if ((*ba)->number < (*bb)->number)
11861     return -1;
11862   else if ((*ba)->number > (*bb)->number)
11863     return 1;
11864
11865   /* Now sort by address, in case we see, e..g, two breakpoints with
11866      the number 0.  */
11867   if (ua < ub)
11868     return -1;
11869   return ua > ub ? 1 : 0;
11870 }
11871
11872 /* Delete breakpoints by address or line.  */
11873
11874 static void
11875 clear_command (char *arg, int from_tty)
11876 {
11877   struct breakpoint *b, *prev;
11878   VEC(breakpoint_p) *found = 0;
11879   int ix;
11880   int default_match;
11881   struct symtabs_and_lines sals;
11882   struct symtab_and_line sal;
11883   int i;
11884   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11885
11886   if (arg)
11887     {
11888       sals = decode_line_with_current_source (arg,
11889                                               (DECODE_LINE_FUNFIRSTLINE
11890                                                | DECODE_LINE_LIST_MODE));
11891       make_cleanup (xfree, sals.sals);
11892       default_match = 0;
11893     }
11894   else
11895     {
11896       sals.sals = XNEW (struct symtab_and_line);
11897       make_cleanup (xfree, sals.sals);
11898       init_sal (&sal);          /* Initialize to zeroes.  */
11899
11900       /* Set sal's line, symtab, pc, and pspace to the values
11901          corresponding to the last call to print_frame_info.  If the
11902          codepoint is not valid, this will set all the fields to 0.  */
11903       get_last_displayed_sal (&sal);
11904       if (sal.symtab == 0)
11905         error (_("No source file specified."));
11906
11907       sals.sals[0] = sal;
11908       sals.nelts = 1;
11909
11910       default_match = 1;
11911     }
11912
11913   /* We don't call resolve_sal_pc here.  That's not as bad as it
11914      seems, because all existing breakpoints typically have both
11915      file/line and pc set.  So, if clear is given file/line, we can
11916      match this to existing breakpoint without obtaining pc at all.
11917
11918      We only support clearing given the address explicitly 
11919      present in breakpoint table.  Say, we've set breakpoint 
11920      at file:line.  There were several PC values for that file:line,
11921      due to optimization, all in one block.
11922
11923      We've picked one PC value.  If "clear" is issued with another
11924      PC corresponding to the same file:line, the breakpoint won't
11925      be cleared.  We probably can still clear the breakpoint, but 
11926      since the other PC value is never presented to user, user
11927      can only find it by guessing, and it does not seem important
11928      to support that.  */
11929
11930   /* For each line spec given, delete bps which correspond to it.  Do
11931      it in two passes, solely to preserve the current behavior that
11932      from_tty is forced true if we delete more than one
11933      breakpoint.  */
11934
11935   found = NULL;
11936   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11937   for (i = 0; i < sals.nelts; i++)
11938     {
11939       const char *sal_fullname;
11940
11941       /* If exact pc given, clear bpts at that pc.
11942          If line given (pc == 0), clear all bpts on specified line.
11943          If defaulting, clear all bpts on default line
11944          or at default pc.
11945
11946          defaulting    sal.pc != 0    tests to do
11947
11948          0              1             pc
11949          1              1             pc _and_ line
11950          0              0             line
11951          1              0             <can't happen> */
11952
11953       sal = sals.sals[i];
11954       sal_fullname = (sal.symtab == NULL
11955                       ? NULL : symtab_to_fullname (sal.symtab));
11956
11957       /* Find all matching breakpoints and add them to 'found'.  */
11958       ALL_BREAKPOINTS (b)
11959         {
11960           int match = 0;
11961           /* Are we going to delete b?  */
11962           if (b->type != bp_none && !is_watchpoint (b))
11963             {
11964               struct bp_location *loc = b->loc;
11965               for (; loc; loc = loc->next)
11966                 {
11967                   /* If the user specified file:line, don't allow a PC
11968                      match.  This matches historical gdb behavior.  */
11969                   int pc_match = (!sal.explicit_line
11970                                   && sal.pc
11971                                   && (loc->pspace == sal.pspace)
11972                                   && (loc->address == sal.pc)
11973                                   && (!section_is_overlay (loc->section)
11974                                       || loc->section == sal.section));
11975                   int line_match = 0;
11976
11977                   if ((default_match || sal.explicit_line)
11978                       && loc->symtab != NULL
11979                       && sal_fullname != NULL
11980                       && sal.pspace == loc->pspace
11981                       && loc->line_number == sal.line
11982                       && filename_cmp (symtab_to_fullname (loc->symtab),
11983                                        sal_fullname) == 0)
11984                     line_match = 1;
11985
11986                   if (pc_match || line_match)
11987                     {
11988                       match = 1;
11989                       break;
11990                     }
11991                 }
11992             }
11993
11994           if (match)
11995             VEC_safe_push(breakpoint_p, found, b);
11996         }
11997     }
11998
11999   /* Now go thru the 'found' chain and delete them.  */
12000   if (VEC_empty(breakpoint_p, found))
12001     {
12002       if (arg)
12003         error (_("No breakpoint at %s."), arg);
12004       else
12005         error (_("No breakpoint at this line."));
12006     }
12007
12008   /* Remove duplicates from the vec.  */
12009   qsort (VEC_address (breakpoint_p, found),
12010          VEC_length (breakpoint_p, found),
12011          sizeof (breakpoint_p),
12012          compare_breakpoints);
12013   prev = VEC_index (breakpoint_p, found, 0);
12014   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12015     {
12016       if (b == prev)
12017         {
12018           VEC_ordered_remove (breakpoint_p, found, ix);
12019           --ix;
12020         }
12021     }
12022
12023   if (VEC_length(breakpoint_p, found) > 1)
12024     from_tty = 1;       /* Always report if deleted more than one.  */
12025   if (from_tty)
12026     {
12027       if (VEC_length(breakpoint_p, found) == 1)
12028         printf_unfiltered (_("Deleted breakpoint "));
12029       else
12030         printf_unfiltered (_("Deleted breakpoints "));
12031     }
12032
12033   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12034     {
12035       if (from_tty)
12036         printf_unfiltered ("%d ", b->number);
12037       delete_breakpoint (b);
12038     }
12039   if (from_tty)
12040     putchar_unfiltered ('\n');
12041
12042   do_cleanups (cleanups);
12043 }
12044 \f
12045 /* Delete breakpoint in BS if they are `delete' breakpoints and
12046    all breakpoints that are marked for deletion, whether hit or not.
12047    This is called after any breakpoint is hit, or after errors.  */
12048
12049 void
12050 breakpoint_auto_delete (bpstat bs)
12051 {
12052   struct breakpoint *b, *b_tmp;
12053
12054   for (; bs; bs = bs->next)
12055     if (bs->breakpoint_at
12056         && bs->breakpoint_at->disposition == disp_del
12057         && bs->stop)
12058       delete_breakpoint (bs->breakpoint_at);
12059
12060   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12061   {
12062     if (b->disposition == disp_del_at_next_stop)
12063       delete_breakpoint (b);
12064   }
12065 }
12066
12067 /* A comparison function for bp_location AP and BP being interfaced to
12068    qsort.  Sort elements primarily by their ADDRESS (no matter what
12069    does breakpoint_address_is_meaningful say for its OWNER),
12070    secondarily by ordering first permanent elements and
12071    terciarily just ensuring the array is sorted stable way despite
12072    qsort being an unstable algorithm.  */
12073
12074 static int
12075 bp_location_compare (const void *ap, const void *bp)
12076 {
12077   struct bp_location *a = *(void **) ap;
12078   struct bp_location *b = *(void **) bp;
12079
12080   if (a->address != b->address)
12081     return (a->address > b->address) - (a->address < b->address);
12082
12083   /* Sort locations at the same address by their pspace number, keeping
12084      locations of the same inferior (in a multi-inferior environment)
12085      grouped.  */
12086
12087   if (a->pspace->num != b->pspace->num)
12088     return ((a->pspace->num > b->pspace->num)
12089             - (a->pspace->num < b->pspace->num));
12090
12091   /* Sort permanent breakpoints first.  */
12092   if (a->permanent != b->permanent)
12093     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12094
12095   /* Make the internal GDB representation stable across GDB runs
12096      where A and B memory inside GDB can differ.  Breakpoint locations of
12097      the same type at the same address can be sorted in arbitrary order.  */
12098
12099   if (a->owner->number != b->owner->number)
12100     return ((a->owner->number > b->owner->number)
12101             - (a->owner->number < b->owner->number));
12102
12103   return (a > b) - (a < b);
12104 }
12105
12106 /* Set bp_location_placed_address_before_address_max and
12107    bp_location_shadow_len_after_address_max according to the current
12108    content of the bp_location array.  */
12109
12110 static void
12111 bp_location_target_extensions_update (void)
12112 {
12113   struct bp_location *bl, **blp_tmp;
12114
12115   bp_location_placed_address_before_address_max = 0;
12116   bp_location_shadow_len_after_address_max = 0;
12117
12118   ALL_BP_LOCATIONS (bl, blp_tmp)
12119     {
12120       CORE_ADDR start, end, addr;
12121
12122       if (!bp_location_has_shadow (bl))
12123         continue;
12124
12125       start = bl->target_info.placed_address;
12126       end = start + bl->target_info.shadow_len;
12127
12128       gdb_assert (bl->address >= start);
12129       addr = bl->address - start;
12130       if (addr > bp_location_placed_address_before_address_max)
12131         bp_location_placed_address_before_address_max = addr;
12132
12133       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12134
12135       gdb_assert (bl->address < end);
12136       addr = end - bl->address;
12137       if (addr > bp_location_shadow_len_after_address_max)
12138         bp_location_shadow_len_after_address_max = addr;
12139     }
12140 }
12141
12142 /* Download tracepoint locations if they haven't been.  */
12143
12144 static void
12145 download_tracepoint_locations (void)
12146 {
12147   struct breakpoint *b;
12148   struct cleanup *old_chain;
12149   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12150
12151   old_chain = save_current_space_and_thread ();
12152
12153   ALL_TRACEPOINTS (b)
12154     {
12155       struct bp_location *bl;
12156       struct tracepoint *t;
12157       int bp_location_downloaded = 0;
12158
12159       if ((b->type == bp_fast_tracepoint
12160            ? !may_insert_fast_tracepoints
12161            : !may_insert_tracepoints))
12162         continue;
12163
12164       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12165         {
12166           if (target_can_download_tracepoint ())
12167             can_download_tracepoint = TRIBOOL_TRUE;
12168           else
12169             can_download_tracepoint = TRIBOOL_FALSE;
12170         }
12171
12172       if (can_download_tracepoint == TRIBOOL_FALSE)
12173         break;
12174
12175       for (bl = b->loc; bl; bl = bl->next)
12176         {
12177           /* In tracepoint, locations are _never_ duplicated, so
12178              should_be_inserted is equivalent to
12179              unduplicated_should_be_inserted.  */
12180           if (!should_be_inserted (bl) || bl->inserted)
12181             continue;
12182
12183           switch_to_program_space_and_thread (bl->pspace);
12184
12185           target_download_tracepoint (bl);
12186
12187           bl->inserted = 1;
12188           bp_location_downloaded = 1;
12189         }
12190       t = (struct tracepoint *) b;
12191       t->number_on_target = b->number;
12192       if (bp_location_downloaded)
12193         observer_notify_breakpoint_modified (b);
12194     }
12195
12196   do_cleanups (old_chain);
12197 }
12198
12199 /* Swap the insertion/duplication state between two locations.  */
12200
12201 static void
12202 swap_insertion (struct bp_location *left, struct bp_location *right)
12203 {
12204   const int left_inserted = left->inserted;
12205   const int left_duplicate = left->duplicate;
12206   const int left_needs_update = left->needs_update;
12207   const struct bp_target_info left_target_info = left->target_info;
12208
12209   /* Locations of tracepoints can never be duplicated.  */
12210   if (is_tracepoint (left->owner))
12211     gdb_assert (!left->duplicate);
12212   if (is_tracepoint (right->owner))
12213     gdb_assert (!right->duplicate);
12214
12215   left->inserted = right->inserted;
12216   left->duplicate = right->duplicate;
12217   left->needs_update = right->needs_update;
12218   left->target_info = right->target_info;
12219   right->inserted = left_inserted;
12220   right->duplicate = left_duplicate;
12221   right->needs_update = left_needs_update;
12222   right->target_info = left_target_info;
12223 }
12224
12225 /* Force the re-insertion of the locations at ADDRESS.  This is called
12226    once a new/deleted/modified duplicate location is found and we are evaluating
12227    conditions on the target's side.  Such conditions need to be updated on
12228    the target.  */
12229
12230 static void
12231 force_breakpoint_reinsertion (struct bp_location *bl)
12232 {
12233   struct bp_location **locp = NULL, **loc2p;
12234   struct bp_location *loc;
12235   CORE_ADDR address = 0;
12236   int pspace_num;
12237
12238   address = bl->address;
12239   pspace_num = bl->pspace->num;
12240
12241   /* This is only meaningful if the target is
12242      evaluating conditions and if the user has
12243      opted for condition evaluation on the target's
12244      side.  */
12245   if (gdb_evaluates_breakpoint_condition_p ()
12246       || !target_supports_evaluation_of_breakpoint_conditions ())
12247     return;
12248
12249   /* Flag all breakpoint locations with this address and
12250      the same program space as the location
12251      as "its condition has changed".  We need to
12252      update the conditions on the target's side.  */
12253   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12254     {
12255       loc = *loc2p;
12256
12257       if (!is_breakpoint (loc->owner)
12258           || pspace_num != loc->pspace->num)
12259         continue;
12260
12261       /* Flag the location appropriately.  We use a different state to
12262          let everyone know that we already updated the set of locations
12263          with addr bl->address and program space bl->pspace.  This is so
12264          we don't have to keep calling these functions just to mark locations
12265          that have already been marked.  */
12266       loc->condition_changed = condition_updated;
12267
12268       /* Free the agent expression bytecode as well.  We will compute
12269          it later on.  */
12270       if (loc->cond_bytecode)
12271         {
12272           free_agent_expr (loc->cond_bytecode);
12273           loc->cond_bytecode = NULL;
12274         }
12275     }
12276 }
12277 /* Called whether new breakpoints are created, or existing breakpoints
12278    deleted, to update the global location list and recompute which
12279    locations are duplicate of which.
12280
12281    The INSERT_MODE flag determines whether locations may not, may, or
12282    shall be inserted now.  See 'enum ugll_insert_mode' for more
12283    info.  */
12284
12285 static void
12286 update_global_location_list (enum ugll_insert_mode insert_mode)
12287 {
12288   struct breakpoint *b;
12289   struct bp_location **locp, *loc;
12290   struct cleanup *cleanups;
12291   /* Last breakpoint location address that was marked for update.  */
12292   CORE_ADDR last_addr = 0;
12293   /* Last breakpoint location program space that was marked for update.  */
12294   int last_pspace_num = -1;
12295
12296   /* Used in the duplicates detection below.  When iterating over all
12297      bp_locations, points to the first bp_location of a given address.
12298      Breakpoints and watchpoints of different types are never
12299      duplicates of each other.  Keep one pointer for each type of
12300      breakpoint/watchpoint, so we only need to loop over all locations
12301      once.  */
12302   struct bp_location *bp_loc_first;  /* breakpoint */
12303   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12304   struct bp_location *awp_loc_first; /* access watchpoint */
12305   struct bp_location *rwp_loc_first; /* read watchpoint */
12306
12307   /* Saved former bp_location array which we compare against the newly
12308      built bp_location from the current state of ALL_BREAKPOINTS.  */
12309   struct bp_location **old_location, **old_locp;
12310   unsigned old_location_count;
12311
12312   old_location = bp_location;
12313   old_location_count = bp_location_count;
12314   bp_location = NULL;
12315   bp_location_count = 0;
12316   cleanups = make_cleanup (xfree, old_location);
12317
12318   ALL_BREAKPOINTS (b)
12319     for (loc = b->loc; loc; loc = loc->next)
12320       bp_location_count++;
12321
12322   bp_location = XNEWVEC (struct bp_location *, bp_location_count);
12323   locp = bp_location;
12324   ALL_BREAKPOINTS (b)
12325     for (loc = b->loc; loc; loc = loc->next)
12326       *locp++ = loc;
12327   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12328          bp_location_compare);
12329
12330   bp_location_target_extensions_update ();
12331
12332   /* Identify bp_location instances that are no longer present in the
12333      new list, and therefore should be freed.  Note that it's not
12334      necessary that those locations should be removed from inferior --
12335      if there's another location at the same address (previously
12336      marked as duplicate), we don't need to remove/insert the
12337      location.
12338      
12339      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12340      and former bp_location array state respectively.  */
12341
12342   locp = bp_location;
12343   for (old_locp = old_location; old_locp < old_location + old_location_count;
12344        old_locp++)
12345     {
12346       struct bp_location *old_loc = *old_locp;
12347       struct bp_location **loc2p;
12348
12349       /* Tells if 'old_loc' is found among the new locations.  If
12350          not, we have to free it.  */
12351       int found_object = 0;
12352       /* Tells if the location should remain inserted in the target.  */
12353       int keep_in_target = 0;
12354       int removed = 0;
12355
12356       /* Skip LOCP entries which will definitely never be needed.
12357          Stop either at or being the one matching OLD_LOC.  */
12358       while (locp < bp_location + bp_location_count
12359              && (*locp)->address < old_loc->address)
12360         locp++;
12361
12362       for (loc2p = locp;
12363            (loc2p < bp_location + bp_location_count
12364             && (*loc2p)->address == old_loc->address);
12365            loc2p++)
12366         {
12367           /* Check if this is a new/duplicated location or a duplicated
12368              location that had its condition modified.  If so, we want to send
12369              its condition to the target if evaluation of conditions is taking
12370              place there.  */
12371           if ((*loc2p)->condition_changed == condition_modified
12372               && (last_addr != old_loc->address
12373                   || last_pspace_num != old_loc->pspace->num))
12374             {
12375               force_breakpoint_reinsertion (*loc2p);
12376               last_pspace_num = old_loc->pspace->num;
12377             }
12378
12379           if (*loc2p == old_loc)
12380             found_object = 1;
12381         }
12382
12383       /* We have already handled this address, update it so that we don't
12384          have to go through updates again.  */
12385       last_addr = old_loc->address;
12386
12387       /* Target-side condition evaluation: Handle deleted locations.  */
12388       if (!found_object)
12389         force_breakpoint_reinsertion (old_loc);
12390
12391       /* If this location is no longer present, and inserted, look if
12392          there's maybe a new location at the same address.  If so,
12393          mark that one inserted, and don't remove this one.  This is
12394          needed so that we don't have a time window where a breakpoint
12395          at certain location is not inserted.  */
12396
12397       if (old_loc->inserted)
12398         {
12399           /* If the location is inserted now, we might have to remove
12400              it.  */
12401
12402           if (found_object && should_be_inserted (old_loc))
12403             {
12404               /* The location is still present in the location list,
12405                  and still should be inserted.  Don't do anything.  */
12406               keep_in_target = 1;
12407             }
12408           else
12409             {
12410               /* This location still exists, but it won't be kept in the
12411                  target since it may have been disabled.  We proceed to
12412                  remove its target-side condition.  */
12413
12414               /* The location is either no longer present, or got
12415                  disabled.  See if there's another location at the
12416                  same address, in which case we don't need to remove
12417                  this one from the target.  */
12418
12419               /* OLD_LOC comes from existing struct breakpoint.  */
12420               if (breakpoint_address_is_meaningful (old_loc->owner))
12421                 {
12422                   for (loc2p = locp;
12423                        (loc2p < bp_location + bp_location_count
12424                         && (*loc2p)->address == old_loc->address);
12425                        loc2p++)
12426                     {
12427                       struct bp_location *loc2 = *loc2p;
12428
12429                       if (breakpoint_locations_match (loc2, old_loc))
12430                         {
12431                           /* Read watchpoint locations are switched to
12432                              access watchpoints, if the former are not
12433                              supported, but the latter are.  */
12434                           if (is_hardware_watchpoint (old_loc->owner))
12435                             {
12436                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12437                               loc2->watchpoint_type = old_loc->watchpoint_type;
12438                             }
12439
12440                           /* loc2 is a duplicated location. We need to check
12441                              if it should be inserted in case it will be
12442                              unduplicated.  */
12443                           if (loc2 != old_loc
12444                               && unduplicated_should_be_inserted (loc2))
12445                             {
12446                               swap_insertion (old_loc, loc2);
12447                               keep_in_target = 1;
12448                               break;
12449                             }
12450                         }
12451                     }
12452                 }
12453             }
12454
12455           if (!keep_in_target)
12456             {
12457               if (remove_breakpoint (old_loc, mark_uninserted))
12458                 {
12459                   /* This is just about all we can do.  We could keep
12460                      this location on the global list, and try to
12461                      remove it next time, but there's no particular
12462                      reason why we will succeed next time.
12463                      
12464                      Note that at this point, old_loc->owner is still
12465                      valid, as delete_breakpoint frees the breakpoint
12466                      only after calling us.  */
12467                   printf_filtered (_("warning: Error removing "
12468                                      "breakpoint %d\n"), 
12469                                    old_loc->owner->number);
12470                 }
12471               removed = 1;
12472             }
12473         }
12474
12475       if (!found_object)
12476         {
12477           if (removed && target_is_non_stop_p ()
12478               && need_moribund_for_location_type (old_loc))
12479             {
12480               /* This location was removed from the target.  In
12481                  non-stop mode, a race condition is possible where
12482                  we've removed a breakpoint, but stop events for that
12483                  breakpoint are already queued and will arrive later.
12484                  We apply an heuristic to be able to distinguish such
12485                  SIGTRAPs from other random SIGTRAPs: we keep this
12486                  breakpoint location for a bit, and will retire it
12487                  after we see some number of events.  The theory here
12488                  is that reporting of events should, "on the average",
12489                  be fair, so after a while we'll see events from all
12490                  threads that have anything of interest, and no longer
12491                  need to keep this breakpoint location around.  We
12492                  don't hold locations forever so to reduce chances of
12493                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12494                  SIGTRAP.
12495
12496                  The heuristic failing can be disastrous on
12497                  decr_pc_after_break targets.
12498
12499                  On decr_pc_after_break targets, like e.g., x86-linux,
12500                  if we fail to recognize a late breakpoint SIGTRAP,
12501                  because events_till_retirement has reached 0 too
12502                  soon, we'll fail to do the PC adjustment, and report
12503                  a random SIGTRAP to the user.  When the user resumes
12504                  the inferior, it will most likely immediately crash
12505                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12506                  corrupted, because of being resumed e.g., in the
12507                  middle of a multi-byte instruction, or skipped a
12508                  one-byte instruction.  This was actually seen happen
12509                  on native x86-linux, and should be less rare on
12510                  targets that do not support new thread events, like
12511                  remote, due to the heuristic depending on
12512                  thread_count.
12513
12514                  Mistaking a random SIGTRAP for a breakpoint trap
12515                  causes similar symptoms (PC adjustment applied when
12516                  it shouldn't), but then again, playing with SIGTRAPs
12517                  behind the debugger's back is asking for trouble.
12518
12519                  Since hardware watchpoint traps are always
12520                  distinguishable from other traps, so we don't need to
12521                  apply keep hardware watchpoint moribund locations
12522                  around.  We simply always ignore hardware watchpoint
12523                  traps we can no longer explain.  */
12524
12525               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12526               old_loc->owner = NULL;
12527
12528               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12529             }
12530           else
12531             {
12532               old_loc->owner = NULL;
12533               decref_bp_location (&old_loc);
12534             }
12535         }
12536     }
12537
12538   /* Rescan breakpoints at the same address and section, marking the
12539      first one as "first" and any others as "duplicates".  This is so
12540      that the bpt instruction is only inserted once.  If we have a
12541      permanent breakpoint at the same place as BPT, make that one the
12542      official one, and the rest as duplicates.  Permanent breakpoints
12543      are sorted first for the same address.
12544
12545      Do the same for hardware watchpoints, but also considering the
12546      watchpoint's type (regular/access/read) and length.  */
12547
12548   bp_loc_first = NULL;
12549   wp_loc_first = NULL;
12550   awp_loc_first = NULL;
12551   rwp_loc_first = NULL;
12552   ALL_BP_LOCATIONS (loc, locp)
12553     {
12554       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12555          non-NULL.  */
12556       struct bp_location **loc_first_p;
12557       b = loc->owner;
12558
12559       if (!unduplicated_should_be_inserted (loc)
12560           || !breakpoint_address_is_meaningful (b)
12561           /* Don't detect duplicate for tracepoint locations because they are
12562            never duplicated.  See the comments in field `duplicate' of
12563            `struct bp_location'.  */
12564           || is_tracepoint (b))
12565         {
12566           /* Clear the condition modification flag.  */
12567           loc->condition_changed = condition_unchanged;
12568           continue;
12569         }
12570
12571       if (b->type == bp_hardware_watchpoint)
12572         loc_first_p = &wp_loc_first;
12573       else if (b->type == bp_read_watchpoint)
12574         loc_first_p = &rwp_loc_first;
12575       else if (b->type == bp_access_watchpoint)
12576         loc_first_p = &awp_loc_first;
12577       else
12578         loc_first_p = &bp_loc_first;
12579
12580       if (*loc_first_p == NULL
12581           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12582           || !breakpoint_locations_match (loc, *loc_first_p))
12583         {
12584           *loc_first_p = loc;
12585           loc->duplicate = 0;
12586
12587           if (is_breakpoint (loc->owner) && loc->condition_changed)
12588             {
12589               loc->needs_update = 1;
12590               /* Clear the condition modification flag.  */
12591               loc->condition_changed = condition_unchanged;
12592             }
12593           continue;
12594         }
12595
12596
12597       /* This and the above ensure the invariant that the first location
12598          is not duplicated, and is the inserted one.
12599          All following are marked as duplicated, and are not inserted.  */
12600       if (loc->inserted)
12601         swap_insertion (loc, *loc_first_p);
12602       loc->duplicate = 1;
12603
12604       /* Clear the condition modification flag.  */
12605       loc->condition_changed = condition_unchanged;
12606     }
12607
12608   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12609     {
12610       if (insert_mode != UGLL_DONT_INSERT)
12611         insert_breakpoint_locations ();
12612       else
12613         {
12614           /* Even though the caller told us to not insert new
12615              locations, we may still need to update conditions on the
12616              target's side of breakpoints that were already inserted
12617              if the target is evaluating breakpoint conditions.  We
12618              only update conditions for locations that are marked
12619              "needs_update".  */
12620           update_inserted_breakpoint_locations ();
12621         }
12622     }
12623
12624   if (insert_mode != UGLL_DONT_INSERT)
12625     download_tracepoint_locations ();
12626
12627   do_cleanups (cleanups);
12628 }
12629
12630 void
12631 breakpoint_retire_moribund (void)
12632 {
12633   struct bp_location *loc;
12634   int ix;
12635
12636   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12637     if (--(loc->events_till_retirement) == 0)
12638       {
12639         decref_bp_location (&loc);
12640         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12641         --ix;
12642       }
12643 }
12644
12645 static void
12646 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12647 {
12648
12649   TRY
12650     {
12651       update_global_location_list (insert_mode);
12652     }
12653   CATCH (e, RETURN_MASK_ERROR)
12654     {
12655     }
12656   END_CATCH
12657 }
12658
12659 /* Clear BKP from a BPS.  */
12660
12661 static void
12662 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12663 {
12664   bpstat bs;
12665
12666   for (bs = bps; bs; bs = bs->next)
12667     if (bs->breakpoint_at == bpt)
12668       {
12669         bs->breakpoint_at = NULL;
12670         bs->old_val = NULL;
12671         /* bs->commands will be freed later.  */
12672       }
12673 }
12674
12675 /* Callback for iterate_over_threads.  */
12676 static int
12677 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12678 {
12679   struct breakpoint *bpt = data;
12680
12681   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12682   return 0;
12683 }
12684
12685 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12686    callbacks.  */
12687
12688 static void
12689 say_where (struct breakpoint *b)
12690 {
12691   struct value_print_options opts;
12692
12693   get_user_print_options (&opts);
12694
12695   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12696      single string.  */
12697   if (b->loc == NULL)
12698     {
12699       /* For pending locations, the output differs slightly based
12700          on b->extra_string.  If this is non-NULL, it contains either
12701          a condition or dprintf arguments.  */
12702       if (b->extra_string == NULL)
12703         {
12704           printf_filtered (_(" (%s) pending."),
12705                            event_location_to_string (b->location));
12706         }
12707       else if (b->type == bp_dprintf)
12708         {
12709           printf_filtered (_(" (%s,%s) pending."),
12710                            event_location_to_string (b->location),
12711                            b->extra_string);
12712         }
12713       else
12714         {
12715           printf_filtered (_(" (%s %s) pending."),
12716                            event_location_to_string (b->location),
12717                            b->extra_string);
12718         }
12719     }
12720   else
12721     {
12722       if (opts.addressprint || b->loc->symtab == NULL)
12723         {
12724           printf_filtered (" at ");
12725           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12726                           gdb_stdout);
12727         }
12728       if (b->loc->symtab != NULL)
12729         {
12730           /* If there is a single location, we can print the location
12731              more nicely.  */
12732           if (b->loc->next == NULL)
12733             printf_filtered (": file %s, line %d.",
12734                              symtab_to_filename_for_display (b->loc->symtab),
12735                              b->loc->line_number);
12736           else
12737             /* This is not ideal, but each location may have a
12738                different file name, and this at least reflects the
12739                real situation somewhat.  */
12740             printf_filtered (": %s.",
12741                              event_location_to_string (b->location));
12742         }
12743
12744       if (b->loc->next)
12745         {
12746           struct bp_location *loc = b->loc;
12747           int n = 0;
12748           for (; loc; loc = loc->next)
12749             ++n;
12750           printf_filtered (" (%d locations)", n);
12751         }
12752     }
12753 }
12754
12755 /* Default bp_location_ops methods.  */
12756
12757 static void
12758 bp_location_dtor (struct bp_location *self)
12759 {
12760   xfree (self->cond);
12761   if (self->cond_bytecode)
12762     free_agent_expr (self->cond_bytecode);
12763   xfree (self->function_name);
12764
12765   VEC_free (agent_expr_p, self->target_info.conditions);
12766   VEC_free (agent_expr_p, self->target_info.tcommands);
12767 }
12768
12769 static const struct bp_location_ops bp_location_ops =
12770 {
12771   bp_location_dtor
12772 };
12773
12774 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12775    inherit from.  */
12776
12777 static void
12778 base_breakpoint_dtor (struct breakpoint *self)
12779 {
12780   decref_counted_command_line (&self->commands);
12781   xfree (self->cond_string);
12782   xfree (self->extra_string);
12783   xfree (self->filter);
12784   delete_event_location (self->location);
12785   delete_event_location (self->location_range_end);
12786 }
12787
12788 static struct bp_location *
12789 base_breakpoint_allocate_location (struct breakpoint *self)
12790 {
12791   struct bp_location *loc;
12792
12793   loc = XNEW (struct bp_location);
12794   init_bp_location (loc, &bp_location_ops, self);
12795   return loc;
12796 }
12797
12798 static void
12799 base_breakpoint_re_set (struct breakpoint *b)
12800 {
12801   /* Nothing to re-set. */
12802 }
12803
12804 #define internal_error_pure_virtual_called() \
12805   gdb_assert_not_reached ("pure virtual function called")
12806
12807 static int
12808 base_breakpoint_insert_location (struct bp_location *bl)
12809 {
12810   internal_error_pure_virtual_called ();
12811 }
12812
12813 static int
12814 base_breakpoint_remove_location (struct bp_location *bl)
12815 {
12816   internal_error_pure_virtual_called ();
12817 }
12818
12819 static int
12820 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12821                                 struct address_space *aspace,
12822                                 CORE_ADDR bp_addr,
12823                                 const struct target_waitstatus *ws)
12824 {
12825   internal_error_pure_virtual_called ();
12826 }
12827
12828 static void
12829 base_breakpoint_check_status (bpstat bs)
12830 {
12831   /* Always stop.   */
12832 }
12833
12834 /* A "works_in_software_mode" breakpoint_ops method that just internal
12835    errors.  */
12836
12837 static int
12838 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12839 {
12840   internal_error_pure_virtual_called ();
12841 }
12842
12843 /* A "resources_needed" breakpoint_ops method that just internal
12844    errors.  */
12845
12846 static int
12847 base_breakpoint_resources_needed (const struct bp_location *bl)
12848 {
12849   internal_error_pure_virtual_called ();
12850 }
12851
12852 static enum print_stop_action
12853 base_breakpoint_print_it (bpstat bs)
12854 {
12855   internal_error_pure_virtual_called ();
12856 }
12857
12858 static void
12859 base_breakpoint_print_one_detail (const struct breakpoint *self,
12860                                   struct ui_out *uiout)
12861 {
12862   /* nothing */
12863 }
12864
12865 static void
12866 base_breakpoint_print_mention (struct breakpoint *b)
12867 {
12868   internal_error_pure_virtual_called ();
12869 }
12870
12871 static void
12872 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12873 {
12874   internal_error_pure_virtual_called ();
12875 }
12876
12877 static void
12878 base_breakpoint_create_sals_from_location
12879   (const struct event_location *location,
12880    struct linespec_result *canonical,
12881    enum bptype type_wanted)
12882 {
12883   internal_error_pure_virtual_called ();
12884 }
12885
12886 static void
12887 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12888                                         struct linespec_result *c,
12889                                         char *cond_string,
12890                                         char *extra_string,
12891                                         enum bptype type_wanted,
12892                                         enum bpdisp disposition,
12893                                         int thread,
12894                                         int task, int ignore_count,
12895                                         const struct breakpoint_ops *o,
12896                                         int from_tty, int enabled,
12897                                         int internal, unsigned flags)
12898 {
12899   internal_error_pure_virtual_called ();
12900 }
12901
12902 static void
12903 base_breakpoint_decode_location (struct breakpoint *b,
12904                                  const struct event_location *location,
12905                                  struct symtabs_and_lines *sals)
12906 {
12907   internal_error_pure_virtual_called ();
12908 }
12909
12910 /* The default 'explains_signal' method.  */
12911
12912 static int
12913 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12914 {
12915   return 1;
12916 }
12917
12918 /* The default "after_condition_true" method.  */
12919
12920 static void
12921 base_breakpoint_after_condition_true (struct bpstats *bs)
12922 {
12923   /* Nothing to do.   */
12924 }
12925
12926 struct breakpoint_ops base_breakpoint_ops =
12927 {
12928   base_breakpoint_dtor,
12929   base_breakpoint_allocate_location,
12930   base_breakpoint_re_set,
12931   base_breakpoint_insert_location,
12932   base_breakpoint_remove_location,
12933   base_breakpoint_breakpoint_hit,
12934   base_breakpoint_check_status,
12935   base_breakpoint_resources_needed,
12936   base_breakpoint_works_in_software_mode,
12937   base_breakpoint_print_it,
12938   NULL,
12939   base_breakpoint_print_one_detail,
12940   base_breakpoint_print_mention,
12941   base_breakpoint_print_recreate,
12942   base_breakpoint_create_sals_from_location,
12943   base_breakpoint_create_breakpoints_sal,
12944   base_breakpoint_decode_location,
12945   base_breakpoint_explains_signal,
12946   base_breakpoint_after_condition_true,
12947 };
12948
12949 /* Default breakpoint_ops methods.  */
12950
12951 static void
12952 bkpt_re_set (struct breakpoint *b)
12953 {
12954   /* FIXME: is this still reachable?  */
12955   if (event_location_empty_p (b->location))
12956     {
12957       /* Anything without a location can't be re-set.  */
12958       delete_breakpoint (b);
12959       return;
12960     }
12961
12962   breakpoint_re_set_default (b);
12963 }
12964
12965 static int
12966 bkpt_insert_location (struct bp_location *bl)
12967 {
12968   if (bl->loc_type == bp_loc_hardware_breakpoint)
12969     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12970   else
12971     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12972 }
12973
12974 static int
12975 bkpt_remove_location (struct bp_location *bl)
12976 {
12977   if (bl->loc_type == bp_loc_hardware_breakpoint)
12978     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12979   else
12980     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12981 }
12982
12983 static int
12984 bkpt_breakpoint_hit (const struct bp_location *bl,
12985                      struct address_space *aspace, CORE_ADDR bp_addr,
12986                      const struct target_waitstatus *ws)
12987 {
12988   if (ws->kind != TARGET_WAITKIND_STOPPED
12989       || ws->value.sig != GDB_SIGNAL_TRAP)
12990     return 0;
12991
12992   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12993                                  aspace, bp_addr))
12994     return 0;
12995
12996   if (overlay_debugging         /* unmapped overlay section */
12997       && section_is_overlay (bl->section)
12998       && !section_is_mapped (bl->section))
12999     return 0;
13000
13001   return 1;
13002 }
13003
13004 static int
13005 dprintf_breakpoint_hit (const struct bp_location *bl,
13006                         struct address_space *aspace, CORE_ADDR bp_addr,
13007                         const struct target_waitstatus *ws)
13008 {
13009   if (dprintf_style == dprintf_style_agent
13010       && target_can_run_breakpoint_commands ())
13011     {
13012       /* An agent-style dprintf never causes a stop.  If we see a trap
13013          for this address it must be for a breakpoint that happens to
13014          be set at the same address.  */
13015       return 0;
13016     }
13017
13018   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13019 }
13020
13021 static int
13022 bkpt_resources_needed (const struct bp_location *bl)
13023 {
13024   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13025
13026   return 1;
13027 }
13028
13029 static enum print_stop_action
13030 bkpt_print_it (bpstat bs)
13031 {
13032   struct breakpoint *b;
13033   const struct bp_location *bl;
13034   int bp_temp;
13035   struct ui_out *uiout = current_uiout;
13036
13037   gdb_assert (bs->bp_location_at != NULL);
13038
13039   bl = bs->bp_location_at;
13040   b = bs->breakpoint_at;
13041
13042   bp_temp = b->disposition == disp_del;
13043   if (bl->address != bl->requested_address)
13044     breakpoint_adjustment_warning (bl->requested_address,
13045                                    bl->address,
13046                                    b->number, 1);
13047   annotate_breakpoint (b->number);
13048   if (bp_temp)
13049     ui_out_text (uiout, "\nTemporary breakpoint ");
13050   else
13051     ui_out_text (uiout, "\nBreakpoint ");
13052   if (ui_out_is_mi_like_p (uiout))
13053     {
13054       ui_out_field_string (uiout, "reason",
13055                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13056       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13057     }
13058   ui_out_field_int (uiout, "bkptno", b->number);
13059   ui_out_text (uiout, ", ");
13060
13061   return PRINT_SRC_AND_LOC;
13062 }
13063
13064 static void
13065 bkpt_print_mention (struct breakpoint *b)
13066 {
13067   if (ui_out_is_mi_like_p (current_uiout))
13068     return;
13069
13070   switch (b->type)
13071     {
13072     case bp_breakpoint:
13073     case bp_gnu_ifunc_resolver:
13074       if (b->disposition == disp_del)
13075         printf_filtered (_("Temporary breakpoint"));
13076       else
13077         printf_filtered (_("Breakpoint"));
13078       printf_filtered (_(" %d"), b->number);
13079       if (b->type == bp_gnu_ifunc_resolver)
13080         printf_filtered (_(" at gnu-indirect-function resolver"));
13081       break;
13082     case bp_hardware_breakpoint:
13083       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13084       break;
13085     case bp_dprintf:
13086       printf_filtered (_("Dprintf %d"), b->number);
13087       break;
13088     }
13089
13090   say_where (b);
13091 }
13092
13093 static void
13094 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13095 {
13096   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13097     fprintf_unfiltered (fp, "tbreak");
13098   else if (tp->type == bp_breakpoint)
13099     fprintf_unfiltered (fp, "break");
13100   else if (tp->type == bp_hardware_breakpoint
13101            && tp->disposition == disp_del)
13102     fprintf_unfiltered (fp, "thbreak");
13103   else if (tp->type == bp_hardware_breakpoint)
13104     fprintf_unfiltered (fp, "hbreak");
13105   else
13106     internal_error (__FILE__, __LINE__,
13107                     _("unhandled breakpoint type %d"), (int) tp->type);
13108
13109   fprintf_unfiltered (fp, " %s",
13110                       event_location_to_string (tp->location));
13111
13112   /* Print out extra_string if this breakpoint is pending.  It might
13113      contain, for example, conditions that were set by the user.  */
13114   if (tp->loc == NULL && tp->extra_string != NULL)
13115     fprintf_unfiltered (fp, " %s", tp->extra_string);
13116
13117   print_recreate_thread (tp, fp);
13118 }
13119
13120 static void
13121 bkpt_create_sals_from_location (const struct event_location *location,
13122                                 struct linespec_result *canonical,
13123                                 enum bptype type_wanted)
13124 {
13125   create_sals_from_location_default (location, canonical, type_wanted);
13126 }
13127
13128 static void
13129 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13130                              struct linespec_result *canonical,
13131                              char *cond_string,
13132                              char *extra_string,
13133                              enum bptype type_wanted,
13134                              enum bpdisp disposition,
13135                              int thread,
13136                              int task, int ignore_count,
13137                              const struct breakpoint_ops *ops,
13138                              int from_tty, int enabled,
13139                              int internal, unsigned flags)
13140 {
13141   create_breakpoints_sal_default (gdbarch, canonical,
13142                                   cond_string, extra_string,
13143                                   type_wanted,
13144                                   disposition, thread, task,
13145                                   ignore_count, ops, from_tty,
13146                                   enabled, internal, flags);
13147 }
13148
13149 static void
13150 bkpt_decode_location (struct breakpoint *b,
13151                       const struct event_location *location,
13152                       struct symtabs_and_lines *sals)
13153 {
13154   decode_location_default (b, location, sals);
13155 }
13156
13157 /* Virtual table for internal breakpoints.  */
13158
13159 static void
13160 internal_bkpt_re_set (struct breakpoint *b)
13161 {
13162   switch (b->type)
13163     {
13164       /* Delete overlay event and longjmp master breakpoints; they
13165          will be reset later by breakpoint_re_set.  */
13166     case bp_overlay_event:
13167     case bp_longjmp_master:
13168     case bp_std_terminate_master:
13169     case bp_exception_master:
13170       delete_breakpoint (b);
13171       break;
13172
13173       /* This breakpoint is special, it's set up when the inferior
13174          starts and we really don't want to touch it.  */
13175     case bp_shlib_event:
13176
13177       /* Like bp_shlib_event, this breakpoint type is special.  Once
13178          it is set up, we do not want to touch it.  */
13179     case bp_thread_event:
13180       break;
13181     }
13182 }
13183
13184 static void
13185 internal_bkpt_check_status (bpstat bs)
13186 {
13187   if (bs->breakpoint_at->type == bp_shlib_event)
13188     {
13189       /* If requested, stop when the dynamic linker notifies GDB of
13190          events.  This allows the user to get control and place
13191          breakpoints in initializer routines for dynamically loaded
13192          objects (among other things).  */
13193       bs->stop = stop_on_solib_events;
13194       bs->print = stop_on_solib_events;
13195     }
13196   else
13197     bs->stop = 0;
13198 }
13199
13200 static enum print_stop_action
13201 internal_bkpt_print_it (bpstat bs)
13202 {
13203   struct breakpoint *b;
13204
13205   b = bs->breakpoint_at;
13206
13207   switch (b->type)
13208     {
13209     case bp_shlib_event:
13210       /* Did we stop because the user set the stop_on_solib_events
13211          variable?  (If so, we report this as a generic, "Stopped due
13212          to shlib event" message.) */
13213       print_solib_event (0);
13214       break;
13215
13216     case bp_thread_event:
13217       /* Not sure how we will get here.
13218          GDB should not stop for these breakpoints.  */
13219       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13220       break;
13221
13222     case bp_overlay_event:
13223       /* By analogy with the thread event, GDB should not stop for these.  */
13224       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13225       break;
13226
13227     case bp_longjmp_master:
13228       /* These should never be enabled.  */
13229       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13230       break;
13231
13232     case bp_std_terminate_master:
13233       /* These should never be enabled.  */
13234       printf_filtered (_("std::terminate Master Breakpoint: "
13235                          "gdb should not stop!\n"));
13236       break;
13237
13238     case bp_exception_master:
13239       /* These should never be enabled.  */
13240       printf_filtered (_("Exception Master Breakpoint: "
13241                          "gdb should not stop!\n"));
13242       break;
13243     }
13244
13245   return PRINT_NOTHING;
13246 }
13247
13248 static void
13249 internal_bkpt_print_mention (struct breakpoint *b)
13250 {
13251   /* Nothing to mention.  These breakpoints are internal.  */
13252 }
13253
13254 /* Virtual table for momentary breakpoints  */
13255
13256 static void
13257 momentary_bkpt_re_set (struct breakpoint *b)
13258 {
13259   /* Keep temporary breakpoints, which can be encountered when we step
13260      over a dlopen call and solib_add is resetting the breakpoints.
13261      Otherwise these should have been blown away via the cleanup chain
13262      or by breakpoint_init_inferior when we rerun the executable.  */
13263 }
13264
13265 static void
13266 momentary_bkpt_check_status (bpstat bs)
13267 {
13268   /* Nothing.  The point of these breakpoints is causing a stop.  */
13269 }
13270
13271 static enum print_stop_action
13272 momentary_bkpt_print_it (bpstat bs)
13273 {
13274   return PRINT_UNKNOWN;
13275 }
13276
13277 static void
13278 momentary_bkpt_print_mention (struct breakpoint *b)
13279 {
13280   /* Nothing to mention.  These breakpoints are internal.  */
13281 }
13282
13283 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13284
13285    It gets cleared already on the removal of the first one of such placed
13286    breakpoints.  This is OK as they get all removed altogether.  */
13287
13288 static void
13289 longjmp_bkpt_dtor (struct breakpoint *self)
13290 {
13291   struct thread_info *tp = find_thread_id (self->thread);
13292
13293   if (tp)
13294     tp->initiating_frame = null_frame_id;
13295
13296   momentary_breakpoint_ops.dtor (self);
13297 }
13298
13299 /* Specific methods for probe breakpoints.  */
13300
13301 static int
13302 bkpt_probe_insert_location (struct bp_location *bl)
13303 {
13304   int v = bkpt_insert_location (bl);
13305
13306   if (v == 0)
13307     {
13308       /* The insertion was successful, now let's set the probe's semaphore
13309          if needed.  */
13310       if (bl->probe.probe->pops->set_semaphore != NULL)
13311         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13312                                               bl->probe.objfile,
13313                                               bl->gdbarch);
13314     }
13315
13316   return v;
13317 }
13318
13319 static int
13320 bkpt_probe_remove_location (struct bp_location *bl)
13321 {
13322   /* Let's clear the semaphore before removing the location.  */
13323   if (bl->probe.probe->pops->clear_semaphore != NULL)
13324     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13325                                             bl->probe.objfile,
13326                                             bl->gdbarch);
13327
13328   return bkpt_remove_location (bl);
13329 }
13330
13331 static void
13332 bkpt_probe_create_sals_from_location (const struct event_location *location,
13333                                       struct linespec_result *canonical,
13334                                       enum bptype type_wanted)
13335 {
13336   struct linespec_sals lsal;
13337
13338   lsal.sals = parse_probes (location, canonical);
13339   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13340   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13341 }
13342
13343 static void
13344 bkpt_probe_decode_location (struct breakpoint *b,
13345                             const struct event_location *location,
13346                             struct symtabs_and_lines *sals)
13347 {
13348   *sals = parse_probes (location, NULL);
13349   if (!sals->sals)
13350     error (_("probe not found"));
13351 }
13352
13353 /* The breakpoint_ops structure to be used in tracepoints.  */
13354
13355 static void
13356 tracepoint_re_set (struct breakpoint *b)
13357 {
13358   breakpoint_re_set_default (b);
13359 }
13360
13361 static int
13362 tracepoint_breakpoint_hit (const struct bp_location *bl,
13363                            struct address_space *aspace, CORE_ADDR bp_addr,
13364                            const struct target_waitstatus *ws)
13365 {
13366   /* By definition, the inferior does not report stops at
13367      tracepoints.  */
13368   return 0;
13369 }
13370
13371 static void
13372 tracepoint_print_one_detail (const struct breakpoint *self,
13373                              struct ui_out *uiout)
13374 {
13375   struct tracepoint *tp = (struct tracepoint *) self;
13376   if (tp->static_trace_marker_id)
13377     {
13378       gdb_assert (self->type == bp_static_tracepoint);
13379
13380       ui_out_text (uiout, "\tmarker id is ");
13381       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13382                            tp->static_trace_marker_id);
13383       ui_out_text (uiout, "\n");
13384     }
13385 }
13386
13387 static void
13388 tracepoint_print_mention (struct breakpoint *b)
13389 {
13390   if (ui_out_is_mi_like_p (current_uiout))
13391     return;
13392
13393   switch (b->type)
13394     {
13395     case bp_tracepoint:
13396       printf_filtered (_("Tracepoint"));
13397       printf_filtered (_(" %d"), b->number);
13398       break;
13399     case bp_fast_tracepoint:
13400       printf_filtered (_("Fast tracepoint"));
13401       printf_filtered (_(" %d"), b->number);
13402       break;
13403     case bp_static_tracepoint:
13404       printf_filtered (_("Static tracepoint"));
13405       printf_filtered (_(" %d"), b->number);
13406       break;
13407     default:
13408       internal_error (__FILE__, __LINE__,
13409                       _("unhandled tracepoint type %d"), (int) b->type);
13410     }
13411
13412   say_where (b);
13413 }
13414
13415 static void
13416 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13417 {
13418   struct tracepoint *tp = (struct tracepoint *) self;
13419
13420   if (self->type == bp_fast_tracepoint)
13421     fprintf_unfiltered (fp, "ftrace");
13422   if (self->type == bp_static_tracepoint)
13423     fprintf_unfiltered (fp, "strace");
13424   else if (self->type == bp_tracepoint)
13425     fprintf_unfiltered (fp, "trace");
13426   else
13427     internal_error (__FILE__, __LINE__,
13428                     _("unhandled tracepoint type %d"), (int) self->type);
13429
13430   fprintf_unfiltered (fp, " %s",
13431                       event_location_to_string (self->location));
13432   print_recreate_thread (self, fp);
13433
13434   if (tp->pass_count)
13435     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13436 }
13437
13438 static void
13439 tracepoint_create_sals_from_location (const struct event_location *location,
13440                                       struct linespec_result *canonical,
13441                                       enum bptype type_wanted)
13442 {
13443   create_sals_from_location_default (location, canonical, type_wanted);
13444 }
13445
13446 static void
13447 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13448                                    struct linespec_result *canonical,
13449                                    char *cond_string,
13450                                    char *extra_string,
13451                                    enum bptype type_wanted,
13452                                    enum bpdisp disposition,
13453                                    int thread,
13454                                    int task, int ignore_count,
13455                                    const struct breakpoint_ops *ops,
13456                                    int from_tty, int enabled,
13457                                    int internal, unsigned flags)
13458 {
13459   create_breakpoints_sal_default (gdbarch, canonical,
13460                                   cond_string, extra_string,
13461                                   type_wanted,
13462                                   disposition, thread, task,
13463                                   ignore_count, ops, from_tty,
13464                                   enabled, internal, flags);
13465 }
13466
13467 static void
13468 tracepoint_decode_location (struct breakpoint *b,
13469                             const struct event_location *location,
13470                             struct symtabs_and_lines *sals)
13471 {
13472   decode_location_default (b, location, sals);
13473 }
13474
13475 struct breakpoint_ops tracepoint_breakpoint_ops;
13476
13477 /* The breakpoint_ops structure to be use on tracepoints placed in a
13478    static probe.  */
13479
13480 static void
13481 tracepoint_probe_create_sals_from_location
13482   (const struct event_location *location,
13483    struct linespec_result *canonical,
13484    enum bptype type_wanted)
13485 {
13486   /* We use the same method for breakpoint on probes.  */
13487   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13488 }
13489
13490 static void
13491 tracepoint_probe_decode_location (struct breakpoint *b,
13492                                   const struct event_location *location,
13493                                   struct symtabs_and_lines *sals)
13494 {
13495   /* We use the same method for breakpoint on probes.  */
13496   bkpt_probe_decode_location (b, location, sals);
13497 }
13498
13499 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13500
13501 /* Dprintf breakpoint_ops methods.  */
13502
13503 static void
13504 dprintf_re_set (struct breakpoint *b)
13505 {
13506   breakpoint_re_set_default (b);
13507
13508   /* extra_string should never be non-NULL for dprintf.  */
13509   gdb_assert (b->extra_string != NULL);
13510
13511   /* 1 - connect to target 1, that can run breakpoint commands.
13512      2 - create a dprintf, which resolves fine.
13513      3 - disconnect from target 1
13514      4 - connect to target 2, that can NOT run breakpoint commands.
13515
13516      After steps #3/#4, you'll want the dprintf command list to
13517      be updated, because target 1 and 2 may well return different
13518      answers for target_can_run_breakpoint_commands().
13519      Given absence of finer grained resetting, we get to do
13520      it all the time.  */
13521   if (b->extra_string != NULL)
13522     update_dprintf_command_list (b);
13523 }
13524
13525 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13526
13527 static void
13528 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13529 {
13530   fprintf_unfiltered (fp, "dprintf %s,%s",
13531                       event_location_to_string (tp->location),
13532                       tp->extra_string);
13533   print_recreate_thread (tp, fp);
13534 }
13535
13536 /* Implement the "after_condition_true" breakpoint_ops method for
13537    dprintf.
13538
13539    dprintf's are implemented with regular commands in their command
13540    list, but we run the commands here instead of before presenting the
13541    stop to the user, as dprintf's don't actually cause a stop.  This
13542    also makes it so that the commands of multiple dprintfs at the same
13543    address are all handled.  */
13544
13545 static void
13546 dprintf_after_condition_true (struct bpstats *bs)
13547 {
13548   struct cleanup *old_chain;
13549   struct bpstats tmp_bs = { NULL };
13550   struct bpstats *tmp_bs_p = &tmp_bs;
13551
13552   /* dprintf's never cause a stop.  This wasn't set in the
13553      check_status hook instead because that would make the dprintf's
13554      condition not be evaluated.  */
13555   bs->stop = 0;
13556
13557   /* Run the command list here.  Take ownership of it instead of
13558      copying.  We never want these commands to run later in
13559      bpstat_do_actions, if a breakpoint that causes a stop happens to
13560      be set at same address as this dprintf, or even if running the
13561      commands here throws.  */
13562   tmp_bs.commands = bs->commands;
13563   bs->commands = NULL;
13564   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13565
13566   bpstat_do_actions_1 (&tmp_bs_p);
13567
13568   /* 'tmp_bs.commands' will usually be NULL by now, but
13569      bpstat_do_actions_1 may return early without processing the whole
13570      list.  */
13571   do_cleanups (old_chain);
13572 }
13573
13574 /* The breakpoint_ops structure to be used on static tracepoints with
13575    markers (`-m').  */
13576
13577 static void
13578 strace_marker_create_sals_from_location (const struct event_location *location,
13579                                          struct linespec_result *canonical,
13580                                          enum bptype type_wanted)
13581 {
13582   struct linespec_sals lsal;
13583   const char *arg_start, *arg;
13584   char *str;
13585   struct cleanup *cleanup;
13586
13587   arg = arg_start = get_linespec_location (location);
13588   lsal.sals = decode_static_tracepoint_spec (&arg);
13589
13590   str = savestring (arg_start, arg - arg_start);
13591   cleanup = make_cleanup (xfree, str);
13592   canonical->location = new_linespec_location (&str);
13593   do_cleanups (cleanup);
13594
13595   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13596   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13597 }
13598
13599 static void
13600 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13601                                       struct linespec_result *canonical,
13602                                       char *cond_string,
13603                                       char *extra_string,
13604                                       enum bptype type_wanted,
13605                                       enum bpdisp disposition,
13606                                       int thread,
13607                                       int task, int ignore_count,
13608                                       const struct breakpoint_ops *ops,
13609                                       int from_tty, int enabled,
13610                                       int internal, unsigned flags)
13611 {
13612   int i;
13613   struct linespec_sals *lsal = VEC_index (linespec_sals,
13614                                           canonical->sals, 0);
13615
13616   /* If the user is creating a static tracepoint by marker id
13617      (strace -m MARKER_ID), then store the sals index, so that
13618      breakpoint_re_set can try to match up which of the newly
13619      found markers corresponds to this one, and, don't try to
13620      expand multiple locations for each sal, given than SALS
13621      already should contain all sals for MARKER_ID.  */
13622
13623   for (i = 0; i < lsal->sals.nelts; ++i)
13624     {
13625       struct symtabs_and_lines expanded;
13626       struct tracepoint *tp;
13627       struct cleanup *old_chain;
13628       struct event_location *location;
13629
13630       expanded.nelts = 1;
13631       expanded.sals = &lsal->sals.sals[i];
13632
13633       location = copy_event_location (canonical->location);
13634       old_chain = make_cleanup_delete_event_location (location);
13635
13636       tp = XCNEW (struct tracepoint);
13637       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13638                            location, NULL,
13639                            cond_string, extra_string,
13640                            type_wanted, disposition,
13641                            thread, task, ignore_count, ops,
13642                            from_tty, enabled, internal, flags,
13643                            canonical->special_display);
13644       /* Given that its possible to have multiple markers with
13645          the same string id, if the user is creating a static
13646          tracepoint by marker id ("strace -m MARKER_ID"), then
13647          store the sals index, so that breakpoint_re_set can
13648          try to match up which of the newly found markers
13649          corresponds to this one  */
13650       tp->static_trace_marker_id_idx = i;
13651
13652       install_breakpoint (internal, &tp->base, 0);
13653
13654       discard_cleanups (old_chain);
13655     }
13656 }
13657
13658 static void
13659 strace_marker_decode_location (struct breakpoint *b,
13660                                const struct event_location *location,
13661                                struct symtabs_and_lines *sals)
13662 {
13663   struct tracepoint *tp = (struct tracepoint *) b;
13664   const char *s = get_linespec_location (location);
13665
13666   *sals = decode_static_tracepoint_spec (&s);
13667   if (sals->nelts > tp->static_trace_marker_id_idx)
13668     {
13669       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13670       sals->nelts = 1;
13671     }
13672   else
13673     error (_("marker %s not found"), tp->static_trace_marker_id);
13674 }
13675
13676 static struct breakpoint_ops strace_marker_breakpoint_ops;
13677
13678 static int
13679 strace_marker_p (struct breakpoint *b)
13680 {
13681   return b->ops == &strace_marker_breakpoint_ops;
13682 }
13683
13684 /* Delete a breakpoint and clean up all traces of it in the data
13685    structures.  */
13686
13687 void
13688 delete_breakpoint (struct breakpoint *bpt)
13689 {
13690   struct breakpoint *b;
13691
13692   gdb_assert (bpt != NULL);
13693
13694   /* Has this bp already been deleted?  This can happen because
13695      multiple lists can hold pointers to bp's.  bpstat lists are
13696      especial culprits.
13697
13698      One example of this happening is a watchpoint's scope bp.  When
13699      the scope bp triggers, we notice that the watchpoint is out of
13700      scope, and delete it.  We also delete its scope bp.  But the
13701      scope bp is marked "auto-deleting", and is already on a bpstat.
13702      That bpstat is then checked for auto-deleting bp's, which are
13703      deleted.
13704
13705      A real solution to this problem might involve reference counts in
13706      bp's, and/or giving them pointers back to their referencing
13707      bpstat's, and teaching delete_breakpoint to only free a bp's
13708      storage when no more references were extent.  A cheaper bandaid
13709      was chosen.  */
13710   if (bpt->type == bp_none)
13711     return;
13712
13713   /* At least avoid this stale reference until the reference counting
13714      of breakpoints gets resolved.  */
13715   if (bpt->related_breakpoint != bpt)
13716     {
13717       struct breakpoint *related;
13718       struct watchpoint *w;
13719
13720       if (bpt->type == bp_watchpoint_scope)
13721         w = (struct watchpoint *) bpt->related_breakpoint;
13722       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13723         w = (struct watchpoint *) bpt;
13724       else
13725         w = NULL;
13726       if (w != NULL)
13727         watchpoint_del_at_next_stop (w);
13728
13729       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13730       for (related = bpt; related->related_breakpoint != bpt;
13731            related = related->related_breakpoint);
13732       related->related_breakpoint = bpt->related_breakpoint;
13733       bpt->related_breakpoint = bpt;
13734     }
13735
13736   /* watch_command_1 creates a watchpoint but only sets its number if
13737      update_watchpoint succeeds in creating its bp_locations.  If there's
13738      a problem in that process, we'll be asked to delete the half-created
13739      watchpoint.  In that case, don't announce the deletion.  */
13740   if (bpt->number)
13741     observer_notify_breakpoint_deleted (bpt);
13742
13743   if (breakpoint_chain == bpt)
13744     breakpoint_chain = bpt->next;
13745
13746   ALL_BREAKPOINTS (b)
13747     if (b->next == bpt)
13748     {
13749       b->next = bpt->next;
13750       break;
13751     }
13752
13753   /* Be sure no bpstat's are pointing at the breakpoint after it's
13754      been freed.  */
13755   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13756      in all threads for now.  Note that we cannot just remove bpstats
13757      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13758      commands are associated with the bpstat; if we remove it here,
13759      then the later call to bpstat_do_actions (&stop_bpstat); in
13760      event-top.c won't do anything, and temporary breakpoints with
13761      commands won't work.  */
13762
13763   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13764
13765   /* Now that breakpoint is removed from breakpoint list, update the
13766      global location list.  This will remove locations that used to
13767      belong to this breakpoint.  Do this before freeing the breakpoint
13768      itself, since remove_breakpoint looks at location's owner.  It
13769      might be better design to have location completely
13770      self-contained, but it's not the case now.  */
13771   update_global_location_list (UGLL_DONT_INSERT);
13772
13773   bpt->ops->dtor (bpt);
13774   /* On the chance that someone will soon try again to delete this
13775      same bp, we mark it as deleted before freeing its storage.  */
13776   bpt->type = bp_none;
13777   xfree (bpt);
13778 }
13779
13780 static void
13781 do_delete_breakpoint_cleanup (void *b)
13782 {
13783   delete_breakpoint (b);
13784 }
13785
13786 struct cleanup *
13787 make_cleanup_delete_breakpoint (struct breakpoint *b)
13788 {
13789   return make_cleanup (do_delete_breakpoint_cleanup, b);
13790 }
13791
13792 /* Iterator function to call a user-provided callback function once
13793    for each of B and its related breakpoints.  */
13794
13795 static void
13796 iterate_over_related_breakpoints (struct breakpoint *b,
13797                                   void (*function) (struct breakpoint *,
13798                                                     void *),
13799                                   void *data)
13800 {
13801   struct breakpoint *related;
13802
13803   related = b;
13804   do
13805     {
13806       struct breakpoint *next;
13807
13808       /* FUNCTION may delete RELATED.  */
13809       next = related->related_breakpoint;
13810
13811       if (next == related)
13812         {
13813           /* RELATED is the last ring entry.  */
13814           function (related, data);
13815
13816           /* FUNCTION may have deleted it, so we'd never reach back to
13817              B.  There's nothing left to do anyway, so just break
13818              out.  */
13819           break;
13820         }
13821       else
13822         function (related, data);
13823
13824       related = next;
13825     }
13826   while (related != b);
13827 }
13828
13829 static void
13830 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13831 {
13832   delete_breakpoint (b);
13833 }
13834
13835 /* A callback for map_breakpoint_numbers that calls
13836    delete_breakpoint.  */
13837
13838 static void
13839 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13840 {
13841   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13842 }
13843
13844 void
13845 delete_command (char *arg, int from_tty)
13846 {
13847   struct breakpoint *b, *b_tmp;
13848
13849   dont_repeat ();
13850
13851   if (arg == 0)
13852     {
13853       int breaks_to_delete = 0;
13854
13855       /* Delete all breakpoints if no argument.  Do not delete
13856          internal breakpoints, these have to be deleted with an
13857          explicit breakpoint number argument.  */
13858       ALL_BREAKPOINTS (b)
13859         if (user_breakpoint_p (b))
13860           {
13861             breaks_to_delete = 1;
13862             break;
13863           }
13864
13865       /* Ask user only if there are some breakpoints to delete.  */
13866       if (!from_tty
13867           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13868         {
13869           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13870             if (user_breakpoint_p (b))
13871               delete_breakpoint (b);
13872         }
13873     }
13874   else
13875     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13876 }
13877
13878 static int
13879 all_locations_are_pending (struct bp_location *loc)
13880 {
13881   for (; loc; loc = loc->next)
13882     if (!loc->shlib_disabled
13883         && !loc->pspace->executing_startup)
13884       return 0;
13885   return 1;
13886 }
13887
13888 /* Subroutine of update_breakpoint_locations to simplify it.
13889    Return non-zero if multiple fns in list LOC have the same name.
13890    Null names are ignored.  */
13891
13892 static int
13893 ambiguous_names_p (struct bp_location *loc)
13894 {
13895   struct bp_location *l;
13896   htab_t htab = htab_create_alloc (13, htab_hash_string,
13897                                    (int (*) (const void *, 
13898                                              const void *)) streq,
13899                                    NULL, xcalloc, xfree);
13900
13901   for (l = loc; l != NULL; l = l->next)
13902     {
13903       const char **slot;
13904       const char *name = l->function_name;
13905
13906       /* Allow for some names to be NULL, ignore them.  */
13907       if (name == NULL)
13908         continue;
13909
13910       slot = (const char **) htab_find_slot (htab, (const void *) name,
13911                                              INSERT);
13912       /* NOTE: We can assume slot != NULL here because xcalloc never
13913          returns NULL.  */
13914       if (*slot != NULL)
13915         {
13916           htab_delete (htab);
13917           return 1;
13918         }
13919       *slot = name;
13920     }
13921
13922   htab_delete (htab);
13923   return 0;
13924 }
13925
13926 /* When symbols change, it probably means the sources changed as well,
13927    and it might mean the static tracepoint markers are no longer at
13928    the same address or line numbers they used to be at last we
13929    checked.  Losing your static tracepoints whenever you rebuild is
13930    undesirable.  This function tries to resync/rematch gdb static
13931    tracepoints with the markers on the target, for static tracepoints
13932    that have not been set by marker id.  Static tracepoint that have
13933    been set by marker id are reset by marker id in breakpoint_re_set.
13934    The heuristic is:
13935
13936    1) For a tracepoint set at a specific address, look for a marker at
13937    the old PC.  If one is found there, assume to be the same marker.
13938    If the name / string id of the marker found is different from the
13939    previous known name, assume that means the user renamed the marker
13940    in the sources, and output a warning.
13941
13942    2) For a tracepoint set at a given line number, look for a marker
13943    at the new address of the old line number.  If one is found there,
13944    assume to be the same marker.  If the name / string id of the
13945    marker found is different from the previous known name, assume that
13946    means the user renamed the marker in the sources, and output a
13947    warning.
13948
13949    3) If a marker is no longer found at the same address or line, it
13950    may mean the marker no longer exists.  But it may also just mean
13951    the code changed a bit.  Maybe the user added a few lines of code
13952    that made the marker move up or down (in line number terms).  Ask
13953    the target for info about the marker with the string id as we knew
13954    it.  If found, update line number and address in the matching
13955    static tracepoint.  This will get confused if there's more than one
13956    marker with the same ID (possible in UST, although unadvised
13957    precisely because it confuses tools).  */
13958
13959 static struct symtab_and_line
13960 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13961 {
13962   struct tracepoint *tp = (struct tracepoint *) b;
13963   struct static_tracepoint_marker marker;
13964   CORE_ADDR pc;
13965
13966   pc = sal.pc;
13967   if (sal.line)
13968     find_line_pc (sal.symtab, sal.line, &pc);
13969
13970   if (target_static_tracepoint_marker_at (pc, &marker))
13971     {
13972       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13973         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13974                  b->number,
13975                  tp->static_trace_marker_id, marker.str_id);
13976
13977       xfree (tp->static_trace_marker_id);
13978       tp->static_trace_marker_id = xstrdup (marker.str_id);
13979       release_static_tracepoint_marker (&marker);
13980
13981       return sal;
13982     }
13983
13984   /* Old marker wasn't found on target at lineno.  Try looking it up
13985      by string ID.  */
13986   if (!sal.explicit_pc
13987       && sal.line != 0
13988       && sal.symtab != NULL
13989       && tp->static_trace_marker_id != NULL)
13990     {
13991       VEC(static_tracepoint_marker_p) *markers;
13992
13993       markers
13994         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13995
13996       if (!VEC_empty(static_tracepoint_marker_p, markers))
13997         {
13998           struct symtab_and_line sal2;
13999           struct symbol *sym;
14000           struct static_tracepoint_marker *tpmarker;
14001           struct ui_out *uiout = current_uiout;
14002           struct explicit_location explicit_loc;
14003
14004           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14005
14006           xfree (tp->static_trace_marker_id);
14007           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14008
14009           warning (_("marker for static tracepoint %d (%s) not "
14010                      "found at previous line number"),
14011                    b->number, tp->static_trace_marker_id);
14012
14013           init_sal (&sal2);
14014
14015           sal2.pc = tpmarker->address;
14016
14017           sal2 = find_pc_line (tpmarker->address, 0);
14018           sym = find_pc_sect_function (tpmarker->address, NULL);
14019           ui_out_text (uiout, "Now in ");
14020           if (sym)
14021             {
14022               ui_out_field_string (uiout, "func",
14023                                    SYMBOL_PRINT_NAME (sym));
14024               ui_out_text (uiout, " at ");
14025             }
14026           ui_out_field_string (uiout, "file",
14027                                symtab_to_filename_for_display (sal2.symtab));
14028           ui_out_text (uiout, ":");
14029
14030           if (ui_out_is_mi_like_p (uiout))
14031             {
14032               const char *fullname = symtab_to_fullname (sal2.symtab);
14033
14034               ui_out_field_string (uiout, "fullname", fullname);
14035             }
14036
14037           ui_out_field_int (uiout, "line", sal2.line);
14038           ui_out_text (uiout, "\n");
14039
14040           b->loc->line_number = sal2.line;
14041           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14042
14043           delete_event_location (b->location);
14044           initialize_explicit_location (&explicit_loc);
14045           explicit_loc.source_filename
14046             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14047           explicit_loc.line_offset.offset = b->loc->line_number;
14048           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14049           b->location = new_explicit_location (&explicit_loc);
14050
14051           /* Might be nice to check if function changed, and warn if
14052              so.  */
14053
14054           release_static_tracepoint_marker (tpmarker);
14055         }
14056     }
14057   return sal;
14058 }
14059
14060 /* Returns 1 iff locations A and B are sufficiently same that
14061    we don't need to report breakpoint as changed.  */
14062
14063 static int
14064 locations_are_equal (struct bp_location *a, struct bp_location *b)
14065 {
14066   while (a && b)
14067     {
14068       if (a->address != b->address)
14069         return 0;
14070
14071       if (a->shlib_disabled != b->shlib_disabled)
14072         return 0;
14073
14074       if (a->enabled != b->enabled)
14075         return 0;
14076
14077       a = a->next;
14078       b = b->next;
14079     }
14080
14081   if ((a == NULL) != (b == NULL))
14082     return 0;
14083
14084   return 1;
14085 }
14086
14087 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14088    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14089    a ranged breakpoint.  */
14090
14091 void
14092 update_breakpoint_locations (struct breakpoint *b,
14093                              struct symtabs_and_lines sals,
14094                              struct symtabs_and_lines sals_end)
14095 {
14096   int i;
14097   struct bp_location *existing_locations = b->loc;
14098
14099   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14100     {
14101       /* Ranged breakpoints have only one start location and one end
14102          location.  */
14103       b->enable_state = bp_disabled;
14104       update_global_location_list (UGLL_MAY_INSERT);
14105       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14106                            "multiple locations found\n"),
14107                          b->number);
14108       return;
14109     }
14110
14111   /* If there's no new locations, and all existing locations are
14112      pending, don't do anything.  This optimizes the common case where
14113      all locations are in the same shared library, that was unloaded.
14114      We'd like to retain the location, so that when the library is
14115      loaded again, we don't loose the enabled/disabled status of the
14116      individual locations.  */
14117   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14118     return;
14119
14120   b->loc = NULL;
14121
14122   for (i = 0; i < sals.nelts; ++i)
14123     {
14124       struct bp_location *new_loc;
14125
14126       switch_to_program_space_and_thread (sals.sals[i].pspace);
14127
14128       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14129
14130       /* Reparse conditions, they might contain references to the
14131          old symtab.  */
14132       if (b->cond_string != NULL)
14133         {
14134           const char *s;
14135
14136           s = b->cond_string;
14137           TRY
14138             {
14139               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14140                                            block_for_pc (sals.sals[i].pc), 
14141                                            0);
14142             }
14143           CATCH (e, RETURN_MASK_ERROR)
14144             {
14145               warning (_("failed to reevaluate condition "
14146                          "for breakpoint %d: %s"), 
14147                        b->number, e.message);
14148               new_loc->enabled = 0;
14149             }
14150           END_CATCH
14151         }
14152
14153       if (sals_end.nelts)
14154         {
14155           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14156
14157           new_loc->length = end - sals.sals[0].pc + 1;
14158         }
14159     }
14160
14161   /* If possible, carry over 'disable' status from existing
14162      breakpoints.  */
14163   {
14164     struct bp_location *e = existing_locations;
14165     /* If there are multiple breakpoints with the same function name,
14166        e.g. for inline functions, comparing function names won't work.
14167        Instead compare pc addresses; this is just a heuristic as things
14168        may have moved, but in practice it gives the correct answer
14169        often enough until a better solution is found.  */
14170     int have_ambiguous_names = ambiguous_names_p (b->loc);
14171
14172     for (; e; e = e->next)
14173       {
14174         if (!e->enabled && e->function_name)
14175           {
14176             struct bp_location *l = b->loc;
14177             if (have_ambiguous_names)
14178               {
14179                 for (; l; l = l->next)
14180                   if (breakpoint_locations_match (e, l))
14181                     {
14182                       l->enabled = 0;
14183                       break;
14184                     }
14185               }
14186             else
14187               {
14188                 for (; l; l = l->next)
14189                   if (l->function_name
14190                       && strcmp (e->function_name, l->function_name) == 0)
14191                     {
14192                       l->enabled = 0;
14193                       break;
14194                     }
14195               }
14196           }
14197       }
14198   }
14199
14200   if (!locations_are_equal (existing_locations, b->loc))
14201     observer_notify_breakpoint_modified (b);
14202
14203   update_global_location_list (UGLL_MAY_INSERT);
14204 }
14205
14206 /* Find the SaL locations corresponding to the given LOCATION.
14207    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14208
14209 static struct symtabs_and_lines
14210 location_to_sals (struct breakpoint *b, struct event_location *location,
14211                   int *found)
14212 {
14213   struct symtabs_and_lines sals = {0};
14214   struct gdb_exception exception = exception_none;
14215
14216   gdb_assert (b->ops != NULL);
14217
14218   TRY
14219     {
14220       b->ops->decode_location (b, location, &sals);
14221     }
14222   CATCH (e, RETURN_MASK_ERROR)
14223     {
14224       int not_found_and_ok = 0;
14225
14226       exception = e;
14227
14228       /* For pending breakpoints, it's expected that parsing will
14229          fail until the right shared library is loaded.  User has
14230          already told to create pending breakpoints and don't need
14231          extra messages.  If breakpoint is in bp_shlib_disabled
14232          state, then user already saw the message about that
14233          breakpoint being disabled, and don't want to see more
14234          errors.  */
14235       if (e.error == NOT_FOUND_ERROR
14236           && (b->condition_not_parsed 
14237               || (b->loc && b->loc->shlib_disabled)
14238               || (b->loc && b->loc->pspace->executing_startup)
14239               || b->enable_state == bp_disabled))
14240         not_found_and_ok = 1;
14241
14242       if (!not_found_and_ok)
14243         {
14244           /* We surely don't want to warn about the same breakpoint
14245              10 times.  One solution, implemented here, is disable
14246              the breakpoint on error.  Another solution would be to
14247              have separate 'warning emitted' flag.  Since this
14248              happens only when a binary has changed, I don't know
14249              which approach is better.  */
14250           b->enable_state = bp_disabled;
14251           throw_exception (e);
14252         }
14253     }
14254   END_CATCH
14255
14256   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14257     {
14258       int i;
14259
14260       for (i = 0; i < sals.nelts; ++i)
14261         resolve_sal_pc (&sals.sals[i]);
14262       if (b->condition_not_parsed && b->extra_string != NULL)
14263         {
14264           char *cond_string, *extra_string;
14265           int thread, task;
14266
14267           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14268                                      &cond_string, &thread, &task,
14269                                      &extra_string);
14270           gdb_assert (b->cond_string == NULL);
14271           if (cond_string)
14272             b->cond_string = cond_string;
14273           b->thread = thread;
14274           b->task = task;
14275           if (extra_string)
14276             {
14277               xfree (b->extra_string);
14278               b->extra_string = extra_string;
14279             }
14280           b->condition_not_parsed = 0;
14281         }
14282
14283       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14284         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14285
14286       *found = 1;
14287     }
14288   else
14289     *found = 0;
14290
14291   return sals;
14292 }
14293
14294 /* The default re_set method, for typical hardware or software
14295    breakpoints.  Reevaluate the breakpoint and recreate its
14296    locations.  */
14297
14298 static void
14299 breakpoint_re_set_default (struct breakpoint *b)
14300 {
14301   int found;
14302   struct symtabs_and_lines sals, sals_end;
14303   struct symtabs_and_lines expanded = {0};
14304   struct symtabs_and_lines expanded_end = {0};
14305
14306   sals = location_to_sals (b, b->location, &found);
14307   if (found)
14308     {
14309       make_cleanup (xfree, sals.sals);
14310       expanded = sals;
14311     }
14312
14313   if (b->location_range_end != NULL)
14314     {
14315       sals_end = location_to_sals (b, b->location_range_end, &found);
14316       if (found)
14317         {
14318           make_cleanup (xfree, sals_end.sals);
14319           expanded_end = sals_end;
14320         }
14321     }
14322
14323   update_breakpoint_locations (b, expanded, expanded_end);
14324 }
14325
14326 /* Default method for creating SALs from an address string.  It basically
14327    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14328
14329 static void
14330 create_sals_from_location_default (const struct event_location *location,
14331                                    struct linespec_result *canonical,
14332                                    enum bptype type_wanted)
14333 {
14334   parse_breakpoint_sals (location, canonical);
14335 }
14336
14337 /* Call create_breakpoints_sal for the given arguments.  This is the default
14338    function for the `create_breakpoints_sal' method of
14339    breakpoint_ops.  */
14340
14341 static void
14342 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14343                                 struct linespec_result *canonical,
14344                                 char *cond_string,
14345                                 char *extra_string,
14346                                 enum bptype type_wanted,
14347                                 enum bpdisp disposition,
14348                                 int thread,
14349                                 int task, int ignore_count,
14350                                 const struct breakpoint_ops *ops,
14351                                 int from_tty, int enabled,
14352                                 int internal, unsigned flags)
14353 {
14354   create_breakpoints_sal (gdbarch, canonical, cond_string,
14355                           extra_string,
14356                           type_wanted, disposition,
14357                           thread, task, ignore_count, ops, from_tty,
14358                           enabled, internal, flags);
14359 }
14360
14361 /* Decode the line represented by S by calling decode_line_full.  This is the
14362    default function for the `decode_location' method of breakpoint_ops.  */
14363
14364 static void
14365 decode_location_default (struct breakpoint *b,
14366                          const struct event_location *location,
14367                          struct symtabs_and_lines *sals)
14368 {
14369   struct linespec_result canonical;
14370
14371   init_linespec_result (&canonical);
14372   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE,
14373                     (struct symtab *) NULL, 0,
14374                     &canonical, multiple_symbols_all,
14375                     b->filter);
14376
14377   /* We should get 0 or 1 resulting SALs.  */
14378   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14379
14380   if (VEC_length (linespec_sals, canonical.sals) > 0)
14381     {
14382       struct linespec_sals *lsal;
14383
14384       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14385       *sals = lsal->sals;
14386       /* Arrange it so the destructor does not free the
14387          contents.  */
14388       lsal->sals.sals = NULL;
14389     }
14390
14391   destroy_linespec_result (&canonical);
14392 }
14393
14394 /* Prepare the global context for a re-set of breakpoint B.  */
14395
14396 static struct cleanup *
14397 prepare_re_set_context (struct breakpoint *b)
14398 {
14399   struct cleanup *cleanups;
14400
14401   input_radix = b->input_radix;
14402   cleanups = save_current_space_and_thread ();
14403   if (b->pspace != NULL)
14404     switch_to_program_space_and_thread (b->pspace);
14405   set_language (b->language);
14406
14407   return cleanups;
14408 }
14409
14410 /* Reset a breakpoint given it's struct breakpoint * BINT.
14411    The value we return ends up being the return value from catch_errors.
14412    Unused in this case.  */
14413
14414 static int
14415 breakpoint_re_set_one (void *bint)
14416 {
14417   /* Get past catch_errs.  */
14418   struct breakpoint *b = (struct breakpoint *) bint;
14419   struct cleanup *cleanups;
14420
14421   cleanups = prepare_re_set_context (b);
14422   b->ops->re_set (b);
14423   do_cleanups (cleanups);
14424   return 0;
14425 }
14426
14427 /* Re-set all breakpoints after symbols have been re-loaded.  */
14428 void
14429 breakpoint_re_set (void)
14430 {
14431   struct breakpoint *b, *b_tmp;
14432   enum language save_language;
14433   int save_input_radix;
14434   struct cleanup *old_chain;
14435
14436   save_language = current_language->la_language;
14437   save_input_radix = input_radix;
14438   old_chain = save_current_program_space ();
14439
14440   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14441   {
14442     /* Format possible error msg.  */
14443     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14444                                 b->number);
14445     struct cleanup *cleanups = make_cleanup (xfree, message);
14446     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14447     do_cleanups (cleanups);
14448   }
14449   set_language (save_language);
14450   input_radix = save_input_radix;
14451
14452   jit_breakpoint_re_set ();
14453
14454   do_cleanups (old_chain);
14455
14456   create_overlay_event_breakpoint ();
14457   create_longjmp_master_breakpoint ();
14458   create_std_terminate_master_breakpoint ();
14459   create_exception_master_breakpoint ();
14460 }
14461 \f
14462 /* Reset the thread number of this breakpoint:
14463
14464    - If the breakpoint is for all threads, leave it as-is.
14465    - Else, reset it to the current thread for inferior_ptid.  */
14466 void
14467 breakpoint_re_set_thread (struct breakpoint *b)
14468 {
14469   if (b->thread != -1)
14470     {
14471       if (in_thread_list (inferior_ptid))
14472         b->thread = pid_to_thread_id (inferior_ptid);
14473
14474       /* We're being called after following a fork.  The new fork is
14475          selected as current, and unless this was a vfork will have a
14476          different program space from the original thread.  Reset that
14477          as well.  */
14478       b->loc->pspace = current_program_space;
14479     }
14480 }
14481
14482 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14483    If from_tty is nonzero, it prints a message to that effect,
14484    which ends with a period (no newline).  */
14485
14486 void
14487 set_ignore_count (int bptnum, int count, int from_tty)
14488 {
14489   struct breakpoint *b;
14490
14491   if (count < 0)
14492     count = 0;
14493
14494   ALL_BREAKPOINTS (b)
14495     if (b->number == bptnum)
14496     {
14497       if (is_tracepoint (b))
14498         {
14499           if (from_tty && count != 0)
14500             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14501                              bptnum);
14502           return;
14503         }
14504       
14505       b->ignore_count = count;
14506       if (from_tty)
14507         {
14508           if (count == 0)
14509             printf_filtered (_("Will stop next time "
14510                                "breakpoint %d is reached."),
14511                              bptnum);
14512           else if (count == 1)
14513             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14514                              bptnum);
14515           else
14516             printf_filtered (_("Will ignore next %d "
14517                                "crossings of breakpoint %d."),
14518                              count, bptnum);
14519         }
14520       observer_notify_breakpoint_modified (b);
14521       return;
14522     }
14523
14524   error (_("No breakpoint number %d."), bptnum);
14525 }
14526
14527 /* Command to set ignore-count of breakpoint N to COUNT.  */
14528
14529 static void
14530 ignore_command (char *args, int from_tty)
14531 {
14532   char *p = args;
14533   int num;
14534
14535   if (p == 0)
14536     error_no_arg (_("a breakpoint number"));
14537
14538   num = get_number (&p);
14539   if (num == 0)
14540     error (_("bad breakpoint number: '%s'"), args);
14541   if (*p == 0)
14542     error (_("Second argument (specified ignore-count) is missing."));
14543
14544   set_ignore_count (num,
14545                     longest_to_int (value_as_long (parse_and_eval (p))),
14546                     from_tty);
14547   if (from_tty)
14548     printf_filtered ("\n");
14549 }
14550 \f
14551 /* Call FUNCTION on each of the breakpoints
14552    whose numbers are given in ARGS.  */
14553
14554 static void
14555 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14556                                                       void *),
14557                         void *data)
14558 {
14559   int num;
14560   struct breakpoint *b, *tmp;
14561   int match;
14562   struct get_number_or_range_state state;
14563
14564   if (args == 0 || *args == '\0')
14565     error_no_arg (_("one or more breakpoint numbers"));
14566
14567   init_number_or_range (&state, args);
14568
14569   while (!state.finished)
14570     {
14571       const char *p = state.string;
14572
14573       match = 0;
14574
14575       num = get_number_or_range (&state);
14576       if (num == 0)
14577         {
14578           warning (_("bad breakpoint number at or near '%s'"), p);
14579         }
14580       else
14581         {
14582           ALL_BREAKPOINTS_SAFE (b, tmp)
14583             if (b->number == num)
14584               {
14585                 match = 1;
14586                 function (b, data);
14587                 break;
14588               }
14589           if (match == 0)
14590             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14591         }
14592     }
14593 }
14594
14595 static struct bp_location *
14596 find_location_by_number (char *number)
14597 {
14598   char *dot = strchr (number, '.');
14599   char *p1;
14600   int bp_num;
14601   int loc_num;
14602   struct breakpoint *b;
14603   struct bp_location *loc;  
14604
14605   *dot = '\0';
14606
14607   p1 = number;
14608   bp_num = get_number (&p1);
14609   if (bp_num == 0)
14610     error (_("Bad breakpoint number '%s'"), number);
14611
14612   ALL_BREAKPOINTS (b)
14613     if (b->number == bp_num)
14614       {
14615         break;
14616       }
14617
14618   if (!b || b->number != bp_num)
14619     error (_("Bad breakpoint number '%s'"), number);
14620   
14621   p1 = dot+1;
14622   loc_num = get_number (&p1);
14623   if (loc_num == 0)
14624     error (_("Bad breakpoint location number '%s'"), number);
14625
14626   --loc_num;
14627   loc = b->loc;
14628   for (;loc_num && loc; --loc_num, loc = loc->next)
14629     ;
14630   if (!loc)
14631     error (_("Bad breakpoint location number '%s'"), dot+1);
14632     
14633   return loc;  
14634 }
14635
14636
14637 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14638    If from_tty is nonzero, it prints a message to that effect,
14639    which ends with a period (no newline).  */
14640
14641 void
14642 disable_breakpoint (struct breakpoint *bpt)
14643 {
14644   /* Never disable a watchpoint scope breakpoint; we want to
14645      hit them when we leave scope so we can delete both the
14646      watchpoint and its scope breakpoint at that time.  */
14647   if (bpt->type == bp_watchpoint_scope)
14648     return;
14649
14650   bpt->enable_state = bp_disabled;
14651
14652   /* Mark breakpoint locations modified.  */
14653   mark_breakpoint_modified (bpt);
14654
14655   if (target_supports_enable_disable_tracepoint ()
14656       && current_trace_status ()->running && is_tracepoint (bpt))
14657     {
14658       struct bp_location *location;
14659      
14660       for (location = bpt->loc; location; location = location->next)
14661         target_disable_tracepoint (location);
14662     }
14663
14664   update_global_location_list (UGLL_DONT_INSERT);
14665
14666   observer_notify_breakpoint_modified (bpt);
14667 }
14668
14669 /* A callback for iterate_over_related_breakpoints.  */
14670
14671 static void
14672 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14673 {
14674   disable_breakpoint (b);
14675 }
14676
14677 /* A callback for map_breakpoint_numbers that calls
14678    disable_breakpoint.  */
14679
14680 static void
14681 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14682 {
14683   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14684 }
14685
14686 static void
14687 disable_command (char *args, int from_tty)
14688 {
14689   if (args == 0)
14690     {
14691       struct breakpoint *bpt;
14692
14693       ALL_BREAKPOINTS (bpt)
14694         if (user_breakpoint_p (bpt))
14695           disable_breakpoint (bpt);
14696     }
14697   else
14698     {
14699       char *num = extract_arg (&args);
14700
14701       while (num)
14702         {
14703           if (strchr (num, '.'))
14704             {
14705               struct bp_location *loc = find_location_by_number (num);
14706
14707               if (loc)
14708                 {
14709                   if (loc->enabled)
14710                     {
14711                       loc->enabled = 0;
14712                       mark_breakpoint_location_modified (loc);
14713                     }
14714                   if (target_supports_enable_disable_tracepoint ()
14715                       && current_trace_status ()->running && loc->owner
14716                       && is_tracepoint (loc->owner))
14717                     target_disable_tracepoint (loc);
14718                 }
14719               update_global_location_list (UGLL_DONT_INSERT);
14720             }
14721           else
14722             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14723           num = extract_arg (&args);
14724         }
14725     }
14726 }
14727
14728 static void
14729 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14730                         int count)
14731 {
14732   int target_resources_ok;
14733
14734   if (bpt->type == bp_hardware_breakpoint)
14735     {
14736       int i;
14737       i = hw_breakpoint_used_count ();
14738       target_resources_ok = 
14739         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14740                                             i + 1, 0);
14741       if (target_resources_ok == 0)
14742         error (_("No hardware breakpoint support in the target."));
14743       else if (target_resources_ok < 0)
14744         error (_("Hardware breakpoints used exceeds limit."));
14745     }
14746
14747   if (is_watchpoint (bpt))
14748     {
14749       /* Initialize it just to avoid a GCC false warning.  */
14750       enum enable_state orig_enable_state = bp_disabled;
14751
14752       TRY
14753         {
14754           struct watchpoint *w = (struct watchpoint *) bpt;
14755
14756           orig_enable_state = bpt->enable_state;
14757           bpt->enable_state = bp_enabled;
14758           update_watchpoint (w, 1 /* reparse */);
14759         }
14760       CATCH (e, RETURN_MASK_ALL)
14761         {
14762           bpt->enable_state = orig_enable_state;
14763           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14764                              bpt->number);
14765           return;
14766         }
14767       END_CATCH
14768     }
14769
14770   bpt->enable_state = bp_enabled;
14771
14772   /* Mark breakpoint locations modified.  */
14773   mark_breakpoint_modified (bpt);
14774
14775   if (target_supports_enable_disable_tracepoint ()
14776       && current_trace_status ()->running && is_tracepoint (bpt))
14777     {
14778       struct bp_location *location;
14779
14780       for (location = bpt->loc; location; location = location->next)
14781         target_enable_tracepoint (location);
14782     }
14783
14784   bpt->disposition = disposition;
14785   bpt->enable_count = count;
14786   update_global_location_list (UGLL_MAY_INSERT);
14787
14788   observer_notify_breakpoint_modified (bpt);
14789 }
14790
14791
14792 void
14793 enable_breakpoint (struct breakpoint *bpt)
14794 {
14795   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14796 }
14797
14798 static void
14799 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14800 {
14801   enable_breakpoint (bpt);
14802 }
14803
14804 /* A callback for map_breakpoint_numbers that calls
14805    enable_breakpoint.  */
14806
14807 static void
14808 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14809 {
14810   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14811 }
14812
14813 /* The enable command enables the specified breakpoints (or all defined
14814    breakpoints) so they once again become (or continue to be) effective
14815    in stopping the inferior.  */
14816
14817 static void
14818 enable_command (char *args, int from_tty)
14819 {
14820   if (args == 0)
14821     {
14822       struct breakpoint *bpt;
14823
14824       ALL_BREAKPOINTS (bpt)
14825         if (user_breakpoint_p (bpt))
14826           enable_breakpoint (bpt);
14827     }
14828   else
14829     {
14830       char *num = extract_arg (&args);
14831
14832       while (num)
14833         {
14834           if (strchr (num, '.'))
14835             {
14836               struct bp_location *loc = find_location_by_number (num);
14837
14838               if (loc)
14839                 {
14840                   if (!loc->enabled)
14841                     {
14842                       loc->enabled = 1;
14843                       mark_breakpoint_location_modified (loc);
14844                     }
14845                   if (target_supports_enable_disable_tracepoint ()
14846                       && current_trace_status ()->running && loc->owner
14847                       && is_tracepoint (loc->owner))
14848                     target_enable_tracepoint (loc);
14849                 }
14850               update_global_location_list (UGLL_MAY_INSERT);
14851             }
14852           else
14853             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14854           num = extract_arg (&args);
14855         }
14856     }
14857 }
14858
14859 /* This struct packages up disposition data for application to multiple
14860    breakpoints.  */
14861
14862 struct disp_data
14863 {
14864   enum bpdisp disp;
14865   int count;
14866 };
14867
14868 static void
14869 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14870 {
14871   struct disp_data disp_data = *(struct disp_data *) arg;
14872
14873   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14874 }
14875
14876 static void
14877 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14878 {
14879   struct disp_data disp = { disp_disable, 1 };
14880
14881   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14882 }
14883
14884 static void
14885 enable_once_command (char *args, int from_tty)
14886 {
14887   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14888 }
14889
14890 static void
14891 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14892 {
14893   struct disp_data disp = { disp_disable, *(int *) countptr };
14894
14895   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14896 }
14897
14898 static void
14899 enable_count_command (char *args, int from_tty)
14900 {
14901   int count;
14902
14903   if (args == NULL)
14904     error_no_arg (_("hit count"));
14905
14906   count = get_number (&args);
14907
14908   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14909 }
14910
14911 static void
14912 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14913 {
14914   struct disp_data disp = { disp_del, 1 };
14915
14916   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14917 }
14918
14919 static void
14920 enable_delete_command (char *args, int from_tty)
14921 {
14922   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14923 }
14924 \f
14925 static void
14926 set_breakpoint_cmd (char *args, int from_tty)
14927 {
14928 }
14929
14930 static void
14931 show_breakpoint_cmd (char *args, int from_tty)
14932 {
14933 }
14934
14935 /* Invalidate last known value of any hardware watchpoint if
14936    the memory which that value represents has been written to by
14937    GDB itself.  */
14938
14939 static void
14940 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14941                                       CORE_ADDR addr, ssize_t len,
14942                                       const bfd_byte *data)
14943 {
14944   struct breakpoint *bp;
14945
14946   ALL_BREAKPOINTS (bp)
14947     if (bp->enable_state == bp_enabled
14948         && bp->type == bp_hardware_watchpoint)
14949       {
14950         struct watchpoint *wp = (struct watchpoint *) bp;
14951
14952         if (wp->val_valid && wp->val)
14953           {
14954             struct bp_location *loc;
14955
14956             for (loc = bp->loc; loc != NULL; loc = loc->next)
14957               if (loc->loc_type == bp_loc_hardware_watchpoint
14958                   && loc->address + loc->length > addr
14959                   && addr + len > loc->address)
14960                 {
14961                   value_free (wp->val);
14962                   wp->val = NULL;
14963                   wp->val_valid = 0;
14964                 }
14965           }
14966       }
14967 }
14968
14969 /* Create and insert a breakpoint for software single step.  */
14970
14971 void
14972 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14973                                struct address_space *aspace, 
14974                                CORE_ADDR next_pc)
14975 {
14976   struct thread_info *tp = inferior_thread ();
14977   struct symtab_and_line sal;
14978   CORE_ADDR pc = next_pc;
14979
14980   if (tp->control.single_step_breakpoints == NULL)
14981     {
14982       tp->control.single_step_breakpoints
14983         = new_single_step_breakpoint (tp->num, gdbarch);
14984     }
14985
14986   sal = find_pc_line (pc, 0);
14987   sal.pc = pc;
14988   sal.section = find_pc_overlay (pc);
14989   sal.explicit_pc = 1;
14990   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14991
14992   update_global_location_list (UGLL_INSERT);
14993 }
14994
14995 /* See breakpoint.h.  */
14996
14997 int
14998 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14999                                        struct address_space *aspace,
15000                                        CORE_ADDR pc)
15001 {
15002   struct bp_location *loc;
15003
15004   for (loc = bp->loc; loc != NULL; loc = loc->next)
15005     if (loc->inserted
15006         && breakpoint_location_address_match (loc, aspace, pc))
15007       return 1;
15008
15009   return 0;
15010 }
15011
15012 /* Check whether a software single-step breakpoint is inserted at
15013    PC.  */
15014
15015 int
15016 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15017                                         CORE_ADDR pc)
15018 {
15019   struct breakpoint *bpt;
15020
15021   ALL_BREAKPOINTS (bpt)
15022     {
15023       if (bpt->type == bp_single_step
15024           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15025         return 1;
15026     }
15027   return 0;
15028 }
15029
15030 /* Tracepoint-specific operations.  */
15031
15032 /* Set tracepoint count to NUM.  */
15033 static void
15034 set_tracepoint_count (int num)
15035 {
15036   tracepoint_count = num;
15037   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15038 }
15039
15040 static void
15041 trace_command (char *arg, int from_tty)
15042 {
15043   struct breakpoint_ops *ops;
15044   struct event_location *location;
15045   struct cleanup *back_to;
15046
15047   location = string_to_event_location (&arg, current_language);
15048   back_to = make_cleanup_delete_event_location (location);
15049   if (location != NULL
15050       && event_location_type (location) == PROBE_LOCATION)
15051     ops = &tracepoint_probe_breakpoint_ops;
15052   else
15053     ops = &tracepoint_breakpoint_ops;
15054
15055   create_breakpoint (get_current_arch (),
15056                      location,
15057                      NULL, 0, arg, 1 /* parse arg */,
15058                      0 /* tempflag */,
15059                      bp_tracepoint /* type_wanted */,
15060                      0 /* Ignore count */,
15061                      pending_break_support,
15062                      ops,
15063                      from_tty,
15064                      1 /* enabled */,
15065                      0 /* internal */, 0);
15066   do_cleanups (back_to);
15067 }
15068
15069 static void
15070 ftrace_command (char *arg, int from_tty)
15071 {
15072   struct event_location *location;
15073   struct cleanup *back_to;
15074
15075   location = string_to_event_location (&arg, current_language);
15076   back_to = make_cleanup_delete_event_location (location);
15077   create_breakpoint (get_current_arch (),
15078                      location,
15079                      NULL, 0, arg, 1 /* parse arg */,
15080                      0 /* tempflag */,
15081                      bp_fast_tracepoint /* type_wanted */,
15082                      0 /* Ignore count */,
15083                      pending_break_support,
15084                      &tracepoint_breakpoint_ops,
15085                      from_tty,
15086                      1 /* enabled */,
15087                      0 /* internal */, 0);
15088   do_cleanups (back_to);
15089 }
15090
15091 /* strace command implementation.  Creates a static tracepoint.  */
15092
15093 static void
15094 strace_command (char *arg, int from_tty)
15095 {
15096   struct breakpoint_ops *ops;
15097   struct event_location *location;
15098   struct cleanup *back_to;
15099
15100   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15101      or with a normal static tracepoint.  */
15102   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15103     {
15104       ops = &strace_marker_breakpoint_ops;
15105       location = new_linespec_location (&arg);
15106     }
15107   else
15108     {
15109       ops = &tracepoint_breakpoint_ops;
15110       location = string_to_event_location (&arg, current_language);
15111     }
15112
15113   back_to = make_cleanup_delete_event_location (location);
15114   create_breakpoint (get_current_arch (),
15115                      location,
15116                      NULL, 0, arg, 1 /* parse arg */,
15117                      0 /* tempflag */,
15118                      bp_static_tracepoint /* type_wanted */,
15119                      0 /* Ignore count */,
15120                      pending_break_support,
15121                      ops,
15122                      from_tty,
15123                      1 /* enabled */,
15124                      0 /* internal */, 0);
15125   do_cleanups (back_to);
15126 }
15127
15128 /* Set up a fake reader function that gets command lines from a linked
15129    list that was acquired during tracepoint uploading.  */
15130
15131 static struct uploaded_tp *this_utp;
15132 static int next_cmd;
15133
15134 static char *
15135 read_uploaded_action (void)
15136 {
15137   char *rslt;
15138
15139   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15140
15141   next_cmd++;
15142
15143   return rslt;
15144 }
15145
15146 /* Given information about a tracepoint as recorded on a target (which
15147    can be either a live system or a trace file), attempt to create an
15148    equivalent GDB tracepoint.  This is not a reliable process, since
15149    the target does not necessarily have all the information used when
15150    the tracepoint was originally defined.  */
15151   
15152 struct tracepoint *
15153 create_tracepoint_from_upload (struct uploaded_tp *utp)
15154 {
15155   char *addr_str, small_buf[100];
15156   struct tracepoint *tp;
15157   struct event_location *location;
15158   struct cleanup *cleanup;
15159
15160   if (utp->at_string)
15161     addr_str = utp->at_string;
15162   else
15163     {
15164       /* In the absence of a source location, fall back to raw
15165          address.  Since there is no way to confirm that the address
15166          means the same thing as when the trace was started, warn the
15167          user.  */
15168       warning (_("Uploaded tracepoint %d has no "
15169                  "source location, using raw address"),
15170                utp->number);
15171       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15172       addr_str = small_buf;
15173     }
15174
15175   /* There's not much we can do with a sequence of bytecodes.  */
15176   if (utp->cond && !utp->cond_string)
15177     warning (_("Uploaded tracepoint %d condition "
15178                "has no source form, ignoring it"),
15179              utp->number);
15180
15181   location = string_to_event_location (&addr_str, current_language);
15182   cleanup = make_cleanup_delete_event_location (location);
15183   if (!create_breakpoint (get_current_arch (),
15184                           location,
15185                           utp->cond_string, -1, addr_str,
15186                           0 /* parse cond/thread */,
15187                           0 /* tempflag */,
15188                           utp->type /* type_wanted */,
15189                           0 /* Ignore count */,
15190                           pending_break_support,
15191                           &tracepoint_breakpoint_ops,
15192                           0 /* from_tty */,
15193                           utp->enabled /* enabled */,
15194                           0 /* internal */,
15195                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15196     {
15197       do_cleanups (cleanup);
15198       return NULL;
15199     }
15200
15201   do_cleanups (cleanup);
15202
15203   /* Get the tracepoint we just created.  */
15204   tp = get_tracepoint (tracepoint_count);
15205   gdb_assert (tp != NULL);
15206
15207   if (utp->pass > 0)
15208     {
15209       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15210                  tp->base.number);
15211
15212       trace_pass_command (small_buf, 0);
15213     }
15214
15215   /* If we have uploaded versions of the original commands, set up a
15216      special-purpose "reader" function and call the usual command line
15217      reader, then pass the result to the breakpoint command-setting
15218      function.  */
15219   if (!VEC_empty (char_ptr, utp->cmd_strings))
15220     {
15221       struct command_line *cmd_list;
15222
15223       this_utp = utp;
15224       next_cmd = 0;
15225
15226       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15227
15228       breakpoint_set_commands (&tp->base, cmd_list);
15229     }
15230   else if (!VEC_empty (char_ptr, utp->actions)
15231            || !VEC_empty (char_ptr, utp->step_actions))
15232     warning (_("Uploaded tracepoint %d actions "
15233                "have no source form, ignoring them"),
15234              utp->number);
15235
15236   /* Copy any status information that might be available.  */
15237   tp->base.hit_count = utp->hit_count;
15238   tp->traceframe_usage = utp->traceframe_usage;
15239
15240   return tp;
15241 }
15242   
15243 /* Print information on tracepoint number TPNUM_EXP, or all if
15244    omitted.  */
15245
15246 static void
15247 tracepoints_info (char *args, int from_tty)
15248 {
15249   struct ui_out *uiout = current_uiout;
15250   int num_printed;
15251
15252   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15253
15254   if (num_printed == 0)
15255     {
15256       if (args == NULL || *args == '\0')
15257         ui_out_message (uiout, 0, "No tracepoints.\n");
15258       else
15259         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15260     }
15261
15262   default_collect_info ();
15263 }
15264
15265 /* The 'enable trace' command enables tracepoints.
15266    Not supported by all targets.  */
15267 static void
15268 enable_trace_command (char *args, int from_tty)
15269 {
15270   enable_command (args, from_tty);
15271 }
15272
15273 /* The 'disable trace' command disables tracepoints.
15274    Not supported by all targets.  */
15275 static void
15276 disable_trace_command (char *args, int from_tty)
15277 {
15278   disable_command (args, from_tty);
15279 }
15280
15281 /* Remove a tracepoint (or all if no argument).  */
15282 static void
15283 delete_trace_command (char *arg, int from_tty)
15284 {
15285   struct breakpoint *b, *b_tmp;
15286
15287   dont_repeat ();
15288
15289   if (arg == 0)
15290     {
15291       int breaks_to_delete = 0;
15292
15293       /* Delete all breakpoints if no argument.
15294          Do not delete internal or call-dummy breakpoints, these
15295          have to be deleted with an explicit breakpoint number 
15296          argument.  */
15297       ALL_TRACEPOINTS (b)
15298         if (is_tracepoint (b) && user_breakpoint_p (b))
15299           {
15300             breaks_to_delete = 1;
15301             break;
15302           }
15303
15304       /* Ask user only if there are some breakpoints to delete.  */
15305       if (!from_tty
15306           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15307         {
15308           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15309             if (is_tracepoint (b) && user_breakpoint_p (b))
15310               delete_breakpoint (b);
15311         }
15312     }
15313   else
15314     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15315 }
15316
15317 /* Helper function for trace_pass_command.  */
15318
15319 static void
15320 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15321 {
15322   tp->pass_count = count;
15323   observer_notify_breakpoint_modified (&tp->base);
15324   if (from_tty)
15325     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15326                      tp->base.number, count);
15327 }
15328
15329 /* Set passcount for tracepoint.
15330
15331    First command argument is passcount, second is tracepoint number.
15332    If tracepoint number omitted, apply to most recently defined.
15333    Also accepts special argument "all".  */
15334
15335 static void
15336 trace_pass_command (char *args, int from_tty)
15337 {
15338   struct tracepoint *t1;
15339   unsigned int count;
15340
15341   if (args == 0 || *args == 0)
15342     error (_("passcount command requires an "
15343              "argument (count + optional TP num)"));
15344
15345   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15346
15347   args = skip_spaces (args);
15348   if (*args && strncasecmp (args, "all", 3) == 0)
15349     {
15350       struct breakpoint *b;
15351
15352       args += 3;                        /* Skip special argument "all".  */
15353       if (*args)
15354         error (_("Junk at end of arguments."));
15355
15356       ALL_TRACEPOINTS (b)
15357       {
15358         t1 = (struct tracepoint *) b;
15359         trace_pass_set_count (t1, count, from_tty);
15360       }
15361     }
15362   else if (*args == '\0')
15363     {
15364       t1 = get_tracepoint_by_number (&args, NULL);
15365       if (t1)
15366         trace_pass_set_count (t1, count, from_tty);
15367     }
15368   else
15369     {
15370       struct get_number_or_range_state state;
15371
15372       init_number_or_range (&state, args);
15373       while (!state.finished)
15374         {
15375           t1 = get_tracepoint_by_number (&args, &state);
15376           if (t1)
15377             trace_pass_set_count (t1, count, from_tty);
15378         }
15379     }
15380 }
15381
15382 struct tracepoint *
15383 get_tracepoint (int num)
15384 {
15385   struct breakpoint *t;
15386
15387   ALL_TRACEPOINTS (t)
15388     if (t->number == num)
15389       return (struct tracepoint *) t;
15390
15391   return NULL;
15392 }
15393
15394 /* Find the tracepoint with the given target-side number (which may be
15395    different from the tracepoint number after disconnecting and
15396    reconnecting).  */
15397
15398 struct tracepoint *
15399 get_tracepoint_by_number_on_target (int num)
15400 {
15401   struct breakpoint *b;
15402
15403   ALL_TRACEPOINTS (b)
15404     {
15405       struct tracepoint *t = (struct tracepoint *) b;
15406
15407       if (t->number_on_target == num)
15408         return t;
15409     }
15410
15411   return NULL;
15412 }
15413
15414 /* Utility: parse a tracepoint number and look it up in the list.
15415    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15416    If the argument is missing, the most recent tracepoint
15417    (tracepoint_count) is returned.  */
15418
15419 struct tracepoint *
15420 get_tracepoint_by_number (char **arg,
15421                           struct get_number_or_range_state *state)
15422 {
15423   struct breakpoint *t;
15424   int tpnum;
15425   char *instring = arg == NULL ? NULL : *arg;
15426
15427   if (state)
15428     {
15429       gdb_assert (!state->finished);
15430       tpnum = get_number_or_range (state);
15431     }
15432   else if (arg == NULL || *arg == NULL || ! **arg)
15433     tpnum = tracepoint_count;
15434   else
15435     tpnum = get_number (arg);
15436
15437   if (tpnum <= 0)
15438     {
15439       if (instring && *instring)
15440         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15441                          instring);
15442       else
15443         printf_filtered (_("No previous tracepoint\n"));
15444       return NULL;
15445     }
15446
15447   ALL_TRACEPOINTS (t)
15448     if (t->number == tpnum)
15449     {
15450       return (struct tracepoint *) t;
15451     }
15452
15453   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15454   return NULL;
15455 }
15456
15457 void
15458 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15459 {
15460   if (b->thread != -1)
15461     fprintf_unfiltered (fp, " thread %d", b->thread);
15462
15463   if (b->task != 0)
15464     fprintf_unfiltered (fp, " task %d", b->task);
15465
15466   fprintf_unfiltered (fp, "\n");
15467 }
15468
15469 /* Save information on user settable breakpoints (watchpoints, etc) to
15470    a new script file named FILENAME.  If FILTER is non-NULL, call it
15471    on each breakpoint and only include the ones for which it returns
15472    non-zero.  */
15473
15474 static void
15475 save_breakpoints (char *filename, int from_tty,
15476                   int (*filter) (const struct breakpoint *))
15477 {
15478   struct breakpoint *tp;
15479   int any = 0;
15480   struct cleanup *cleanup;
15481   struct ui_file *fp;
15482   int extra_trace_bits = 0;
15483
15484   if (filename == 0 || *filename == 0)
15485     error (_("Argument required (file name in which to save)"));
15486
15487   /* See if we have anything to save.  */
15488   ALL_BREAKPOINTS (tp)
15489   {
15490     /* Skip internal and momentary breakpoints.  */
15491     if (!user_breakpoint_p (tp))
15492       continue;
15493
15494     /* If we have a filter, only save the breakpoints it accepts.  */
15495     if (filter && !filter (tp))
15496       continue;
15497
15498     any = 1;
15499
15500     if (is_tracepoint (tp))
15501       {
15502         extra_trace_bits = 1;
15503
15504         /* We can stop searching.  */
15505         break;
15506       }
15507   }
15508
15509   if (!any)
15510     {
15511       warning (_("Nothing to save."));
15512       return;
15513     }
15514
15515   filename = tilde_expand (filename);
15516   cleanup = make_cleanup (xfree, filename);
15517   fp = gdb_fopen (filename, "w");
15518   if (!fp)
15519     error (_("Unable to open file '%s' for saving (%s)"),
15520            filename, safe_strerror (errno));
15521   make_cleanup_ui_file_delete (fp);
15522
15523   if (extra_trace_bits)
15524     save_trace_state_variables (fp);
15525
15526   ALL_BREAKPOINTS (tp)
15527   {
15528     /* Skip internal and momentary breakpoints.  */
15529     if (!user_breakpoint_p (tp))
15530       continue;
15531
15532     /* If we have a filter, only save the breakpoints it accepts.  */
15533     if (filter && !filter (tp))
15534       continue;
15535
15536     tp->ops->print_recreate (tp, fp);
15537
15538     /* Note, we can't rely on tp->number for anything, as we can't
15539        assume the recreated breakpoint numbers will match.  Use $bpnum
15540        instead.  */
15541
15542     if (tp->cond_string)
15543       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15544
15545     if (tp->ignore_count)
15546       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15547
15548     if (tp->type != bp_dprintf && tp->commands)
15549       {
15550         struct gdb_exception exception;
15551
15552         fprintf_unfiltered (fp, "  commands\n");
15553         
15554         ui_out_redirect (current_uiout, fp);
15555         TRY
15556           {
15557             print_command_lines (current_uiout, tp->commands->commands, 2);
15558           }
15559         CATCH (ex, RETURN_MASK_ALL)
15560           {
15561             ui_out_redirect (current_uiout, NULL);
15562             throw_exception (ex);
15563           }
15564         END_CATCH
15565
15566         ui_out_redirect (current_uiout, NULL);
15567         fprintf_unfiltered (fp, "  end\n");
15568       }
15569
15570     if (tp->enable_state == bp_disabled)
15571       fprintf_unfiltered (fp, "disable $bpnum\n");
15572
15573     /* If this is a multi-location breakpoint, check if the locations
15574        should be individually disabled.  Watchpoint locations are
15575        special, and not user visible.  */
15576     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15577       {
15578         struct bp_location *loc;
15579         int n = 1;
15580
15581         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15582           if (!loc->enabled)
15583             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15584       }
15585   }
15586
15587   if (extra_trace_bits && *default_collect)
15588     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15589
15590   if (from_tty)
15591     printf_filtered (_("Saved to file '%s'.\n"), filename);
15592   do_cleanups (cleanup);
15593 }
15594
15595 /* The `save breakpoints' command.  */
15596
15597 static void
15598 save_breakpoints_command (char *args, int from_tty)
15599 {
15600   save_breakpoints (args, from_tty, NULL);
15601 }
15602
15603 /* The `save tracepoints' command.  */
15604
15605 static void
15606 save_tracepoints_command (char *args, int from_tty)
15607 {
15608   save_breakpoints (args, from_tty, is_tracepoint);
15609 }
15610
15611 /* Create a vector of all tracepoints.  */
15612
15613 VEC(breakpoint_p) *
15614 all_tracepoints (void)
15615 {
15616   VEC(breakpoint_p) *tp_vec = 0;
15617   struct breakpoint *tp;
15618
15619   ALL_TRACEPOINTS (tp)
15620   {
15621     VEC_safe_push (breakpoint_p, tp_vec, tp);
15622   }
15623
15624   return tp_vec;
15625 }
15626
15627 \f
15628 /* This help string is used to consolidate all the help string for specifying
15629    locations used by several commands.  */
15630
15631 #define LOCATION_HELP_STRING \
15632 "Linespecs are colon-separated lists of location parameters, such as\n\
15633 source filename, function name, label name, and line number.\n\
15634 Example: To specify the start of a label named \"the_top\" in the\n\
15635 function \"fact\" in the file \"factorial.c\", use\n\
15636 \"factorial.c:fact:the_top\".\n\
15637 \n\
15638 Address locations begin with \"*\" and specify an exact address in the\n\
15639 program.  Example: To specify the fourth byte past the start function\n\
15640 \"main\", use \"*main + 4\".\n\
15641 \n\
15642 Explicit locations are similar to linespecs but use an option/argument\n\
15643 syntax to specify location parameters.\n\
15644 Example: To specify the start of the label named \"the_top\" in the\n\
15645 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15646 -function fact -label the_top\".\n"
15647
15648 /* This help string is used for the break, hbreak, tbreak and thbreak
15649    commands.  It is defined as a macro to prevent duplication.
15650    COMMAND should be a string constant containing the name of the
15651    command.  */
15652
15653 #define BREAK_ARGS_HELP(command) \
15654 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15655 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15656 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15657 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15658 `-probe-dtrace' (for a DTrace probe).\n\
15659 LOCATION may be a linespec, address, or explicit location as described\n\
15660 below.\n\
15661 \n\
15662 With no LOCATION, uses current execution address of the selected\n\
15663 stack frame.  This is useful for breaking on return to a stack frame.\n\
15664 \n\
15665 THREADNUM is the number from \"info threads\".\n\
15666 CONDITION is a boolean expression.\n\
15667 \n" LOCATION_HELP_STRING "\n\
15668 Multiple breakpoints at one place are permitted, and useful if their\n\
15669 conditions are different.\n\
15670 \n\
15671 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15672
15673 /* List of subcommands for "catch".  */
15674 static struct cmd_list_element *catch_cmdlist;
15675
15676 /* List of subcommands for "tcatch".  */
15677 static struct cmd_list_element *tcatch_cmdlist;
15678
15679 void
15680 add_catch_command (char *name, char *docstring,
15681                    cmd_sfunc_ftype *sfunc,
15682                    completer_ftype *completer,
15683                    void *user_data_catch,
15684                    void *user_data_tcatch)
15685 {
15686   struct cmd_list_element *command;
15687
15688   command = add_cmd (name, class_breakpoint, NULL, docstring,
15689                      &catch_cmdlist);
15690   set_cmd_sfunc (command, sfunc);
15691   set_cmd_context (command, user_data_catch);
15692   set_cmd_completer (command, completer);
15693
15694   command = add_cmd (name, class_breakpoint, NULL, docstring,
15695                      &tcatch_cmdlist);
15696   set_cmd_sfunc (command, sfunc);
15697   set_cmd_context (command, user_data_tcatch);
15698   set_cmd_completer (command, completer);
15699 }
15700
15701 static void
15702 save_command (char *arg, int from_tty)
15703 {
15704   printf_unfiltered (_("\"save\" must be followed by "
15705                        "the name of a save subcommand.\n"));
15706   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15707 }
15708
15709 struct breakpoint *
15710 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15711                           void *data)
15712 {
15713   struct breakpoint *b, *b_tmp;
15714
15715   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15716     {
15717       if ((*callback) (b, data))
15718         return b;
15719     }
15720
15721   return NULL;
15722 }
15723
15724 /* Zero if any of the breakpoint's locations could be a location where
15725    functions have been inlined, nonzero otherwise.  */
15726
15727 static int
15728 is_non_inline_function (struct breakpoint *b)
15729 {
15730   /* The shared library event breakpoint is set on the address of a
15731      non-inline function.  */
15732   if (b->type == bp_shlib_event)
15733     return 1;
15734
15735   return 0;
15736 }
15737
15738 /* Nonzero if the specified PC cannot be a location where functions
15739    have been inlined.  */
15740
15741 int
15742 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15743                            const struct target_waitstatus *ws)
15744 {
15745   struct breakpoint *b;
15746   struct bp_location *bl;
15747
15748   ALL_BREAKPOINTS (b)
15749     {
15750       if (!is_non_inline_function (b))
15751         continue;
15752
15753       for (bl = b->loc; bl != NULL; bl = bl->next)
15754         {
15755           if (!bl->shlib_disabled
15756               && bpstat_check_location (bl, aspace, pc, ws))
15757             return 1;
15758         }
15759     }
15760
15761   return 0;
15762 }
15763
15764 /* Remove any references to OBJFILE which is going to be freed.  */
15765
15766 void
15767 breakpoint_free_objfile (struct objfile *objfile)
15768 {
15769   struct bp_location **locp, *loc;
15770
15771   ALL_BP_LOCATIONS (loc, locp)
15772     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15773       loc->symtab = NULL;
15774 }
15775
15776 void
15777 initialize_breakpoint_ops (void)
15778 {
15779   static int initialized = 0;
15780
15781   struct breakpoint_ops *ops;
15782
15783   if (initialized)
15784     return;
15785   initialized = 1;
15786
15787   /* The breakpoint_ops structure to be inherit by all kinds of
15788      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15789      internal and momentary breakpoints, etc.).  */
15790   ops = &bkpt_base_breakpoint_ops;
15791   *ops = base_breakpoint_ops;
15792   ops->re_set = bkpt_re_set;
15793   ops->insert_location = bkpt_insert_location;
15794   ops->remove_location = bkpt_remove_location;
15795   ops->breakpoint_hit = bkpt_breakpoint_hit;
15796   ops->create_sals_from_location = bkpt_create_sals_from_location;
15797   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15798   ops->decode_location = bkpt_decode_location;
15799
15800   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15801   ops = &bkpt_breakpoint_ops;
15802   *ops = bkpt_base_breakpoint_ops;
15803   ops->re_set = bkpt_re_set;
15804   ops->resources_needed = bkpt_resources_needed;
15805   ops->print_it = bkpt_print_it;
15806   ops->print_mention = bkpt_print_mention;
15807   ops->print_recreate = bkpt_print_recreate;
15808
15809   /* Ranged breakpoints.  */
15810   ops = &ranged_breakpoint_ops;
15811   *ops = bkpt_breakpoint_ops;
15812   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15813   ops->resources_needed = resources_needed_ranged_breakpoint;
15814   ops->print_it = print_it_ranged_breakpoint;
15815   ops->print_one = print_one_ranged_breakpoint;
15816   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15817   ops->print_mention = print_mention_ranged_breakpoint;
15818   ops->print_recreate = print_recreate_ranged_breakpoint;
15819
15820   /* Internal breakpoints.  */
15821   ops = &internal_breakpoint_ops;
15822   *ops = bkpt_base_breakpoint_ops;
15823   ops->re_set = internal_bkpt_re_set;
15824   ops->check_status = internal_bkpt_check_status;
15825   ops->print_it = internal_bkpt_print_it;
15826   ops->print_mention = internal_bkpt_print_mention;
15827
15828   /* Momentary breakpoints.  */
15829   ops = &momentary_breakpoint_ops;
15830   *ops = bkpt_base_breakpoint_ops;
15831   ops->re_set = momentary_bkpt_re_set;
15832   ops->check_status = momentary_bkpt_check_status;
15833   ops->print_it = momentary_bkpt_print_it;
15834   ops->print_mention = momentary_bkpt_print_mention;
15835
15836   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15837   ops = &longjmp_breakpoint_ops;
15838   *ops = momentary_breakpoint_ops;
15839   ops->dtor = longjmp_bkpt_dtor;
15840
15841   /* Probe breakpoints.  */
15842   ops = &bkpt_probe_breakpoint_ops;
15843   *ops = bkpt_breakpoint_ops;
15844   ops->insert_location = bkpt_probe_insert_location;
15845   ops->remove_location = bkpt_probe_remove_location;
15846   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15847   ops->decode_location = bkpt_probe_decode_location;
15848
15849   /* Watchpoints.  */
15850   ops = &watchpoint_breakpoint_ops;
15851   *ops = base_breakpoint_ops;
15852   ops->dtor = dtor_watchpoint;
15853   ops->re_set = re_set_watchpoint;
15854   ops->insert_location = insert_watchpoint;
15855   ops->remove_location = remove_watchpoint;
15856   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15857   ops->check_status = check_status_watchpoint;
15858   ops->resources_needed = resources_needed_watchpoint;
15859   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15860   ops->print_it = print_it_watchpoint;
15861   ops->print_mention = print_mention_watchpoint;
15862   ops->print_recreate = print_recreate_watchpoint;
15863   ops->explains_signal = explains_signal_watchpoint;
15864
15865   /* Masked watchpoints.  */
15866   ops = &masked_watchpoint_breakpoint_ops;
15867   *ops = watchpoint_breakpoint_ops;
15868   ops->insert_location = insert_masked_watchpoint;
15869   ops->remove_location = remove_masked_watchpoint;
15870   ops->resources_needed = resources_needed_masked_watchpoint;
15871   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15872   ops->print_it = print_it_masked_watchpoint;
15873   ops->print_one_detail = print_one_detail_masked_watchpoint;
15874   ops->print_mention = print_mention_masked_watchpoint;
15875   ops->print_recreate = print_recreate_masked_watchpoint;
15876
15877   /* Tracepoints.  */
15878   ops = &tracepoint_breakpoint_ops;
15879   *ops = base_breakpoint_ops;
15880   ops->re_set = tracepoint_re_set;
15881   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15882   ops->print_one_detail = tracepoint_print_one_detail;
15883   ops->print_mention = tracepoint_print_mention;
15884   ops->print_recreate = tracepoint_print_recreate;
15885   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15886   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15887   ops->decode_location = tracepoint_decode_location;
15888
15889   /* Probe tracepoints.  */
15890   ops = &tracepoint_probe_breakpoint_ops;
15891   *ops = tracepoint_breakpoint_ops;
15892   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15893   ops->decode_location = tracepoint_probe_decode_location;
15894
15895   /* Static tracepoints with marker (`-m').  */
15896   ops = &strace_marker_breakpoint_ops;
15897   *ops = tracepoint_breakpoint_ops;
15898   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15899   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15900   ops->decode_location = strace_marker_decode_location;
15901
15902   /* Fork catchpoints.  */
15903   ops = &catch_fork_breakpoint_ops;
15904   *ops = base_breakpoint_ops;
15905   ops->insert_location = insert_catch_fork;
15906   ops->remove_location = remove_catch_fork;
15907   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15908   ops->print_it = print_it_catch_fork;
15909   ops->print_one = print_one_catch_fork;
15910   ops->print_mention = print_mention_catch_fork;
15911   ops->print_recreate = print_recreate_catch_fork;
15912
15913   /* Vfork catchpoints.  */
15914   ops = &catch_vfork_breakpoint_ops;
15915   *ops = base_breakpoint_ops;
15916   ops->insert_location = insert_catch_vfork;
15917   ops->remove_location = remove_catch_vfork;
15918   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15919   ops->print_it = print_it_catch_vfork;
15920   ops->print_one = print_one_catch_vfork;
15921   ops->print_mention = print_mention_catch_vfork;
15922   ops->print_recreate = print_recreate_catch_vfork;
15923
15924   /* Exec catchpoints.  */
15925   ops = &catch_exec_breakpoint_ops;
15926   *ops = base_breakpoint_ops;
15927   ops->dtor = dtor_catch_exec;
15928   ops->insert_location = insert_catch_exec;
15929   ops->remove_location = remove_catch_exec;
15930   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15931   ops->print_it = print_it_catch_exec;
15932   ops->print_one = print_one_catch_exec;
15933   ops->print_mention = print_mention_catch_exec;
15934   ops->print_recreate = print_recreate_catch_exec;
15935
15936   /* Solib-related catchpoints.  */
15937   ops = &catch_solib_breakpoint_ops;
15938   *ops = base_breakpoint_ops;
15939   ops->dtor = dtor_catch_solib;
15940   ops->insert_location = insert_catch_solib;
15941   ops->remove_location = remove_catch_solib;
15942   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15943   ops->check_status = check_status_catch_solib;
15944   ops->print_it = print_it_catch_solib;
15945   ops->print_one = print_one_catch_solib;
15946   ops->print_mention = print_mention_catch_solib;
15947   ops->print_recreate = print_recreate_catch_solib;
15948
15949   ops = &dprintf_breakpoint_ops;
15950   *ops = bkpt_base_breakpoint_ops;
15951   ops->re_set = dprintf_re_set;
15952   ops->resources_needed = bkpt_resources_needed;
15953   ops->print_it = bkpt_print_it;
15954   ops->print_mention = bkpt_print_mention;
15955   ops->print_recreate = dprintf_print_recreate;
15956   ops->after_condition_true = dprintf_after_condition_true;
15957   ops->breakpoint_hit = dprintf_breakpoint_hit;
15958 }
15959
15960 /* Chain containing all defined "enable breakpoint" subcommands.  */
15961
15962 static struct cmd_list_element *enablebreaklist = NULL;
15963
15964 void
15965 _initialize_breakpoint (void)
15966 {
15967   struct cmd_list_element *c;
15968
15969   initialize_breakpoint_ops ();
15970
15971   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15972   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15973   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15974
15975   breakpoint_objfile_key
15976     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15977
15978   breakpoint_chain = 0;
15979   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15980      before a breakpoint is set.  */
15981   breakpoint_count = 0;
15982
15983   tracepoint_count = 0;
15984
15985   add_com ("ignore", class_breakpoint, ignore_command, _("\
15986 Set ignore-count of breakpoint number N to COUNT.\n\
15987 Usage is `ignore N COUNT'."));
15988
15989   add_com ("commands", class_breakpoint, commands_command, _("\
15990 Set commands to be executed when a breakpoint is hit.\n\
15991 Give breakpoint number as argument after \"commands\".\n\
15992 With no argument, the targeted breakpoint is the last one set.\n\
15993 The commands themselves follow starting on the next line.\n\
15994 Type a line containing \"end\" to indicate the end of them.\n\
15995 Give \"silent\" as the first line to make the breakpoint silent;\n\
15996 then no output is printed when it is hit, except what the commands print."));
15997
15998   c = add_com ("condition", class_breakpoint, condition_command, _("\
15999 Specify breakpoint number N to break only if COND is true.\n\
16000 Usage is `condition N COND', where N is an integer and COND is an\n\
16001 expression to be evaluated whenever breakpoint N is reached."));
16002   set_cmd_completer (c, condition_completer);
16003
16004   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16005 Set a temporary breakpoint.\n\
16006 Like \"break\" except the breakpoint is only temporary,\n\
16007 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16008 by using \"enable delete\" on the breakpoint number.\n\
16009 \n"
16010 BREAK_ARGS_HELP ("tbreak")));
16011   set_cmd_completer (c, location_completer);
16012
16013   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16014 Set a hardware assisted breakpoint.\n\
16015 Like \"break\" except the breakpoint requires hardware support,\n\
16016 some target hardware may not have this support.\n\
16017 \n"
16018 BREAK_ARGS_HELP ("hbreak")));
16019   set_cmd_completer (c, location_completer);
16020
16021   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16022 Set a temporary hardware assisted breakpoint.\n\
16023 Like \"hbreak\" except the breakpoint is only temporary,\n\
16024 so it will be deleted when hit.\n\
16025 \n"
16026 BREAK_ARGS_HELP ("thbreak")));
16027   set_cmd_completer (c, location_completer);
16028
16029   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16030 Enable some breakpoints.\n\
16031 Give breakpoint numbers (separated by spaces) as arguments.\n\
16032 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16033 This is used to cancel the effect of the \"disable\" command.\n\
16034 With a subcommand you can enable temporarily."),
16035                   &enablelist, "enable ", 1, &cmdlist);
16036
16037   add_com_alias ("en", "enable", class_breakpoint, 1);
16038
16039   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16040 Enable some breakpoints.\n\
16041 Give breakpoint numbers (separated by spaces) as arguments.\n\
16042 This is used to cancel the effect of the \"disable\" command.\n\
16043 May be abbreviated to simply \"enable\".\n"),
16044                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16045
16046   add_cmd ("once", no_class, enable_once_command, _("\
16047 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16048 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16049            &enablebreaklist);
16050
16051   add_cmd ("delete", no_class, enable_delete_command, _("\
16052 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16053 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16054            &enablebreaklist);
16055
16056   add_cmd ("count", no_class, enable_count_command, _("\
16057 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16058 If a breakpoint is hit while enabled in this fashion,\n\
16059 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16060            &enablebreaklist);
16061
16062   add_cmd ("delete", no_class, enable_delete_command, _("\
16063 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16064 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16065            &enablelist);
16066
16067   add_cmd ("once", no_class, enable_once_command, _("\
16068 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16069 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16070            &enablelist);
16071
16072   add_cmd ("count", no_class, enable_count_command, _("\
16073 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16074 If a breakpoint is hit while enabled in this fashion,\n\
16075 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16076            &enablelist);
16077
16078   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16079 Disable some breakpoints.\n\
16080 Arguments are breakpoint numbers with spaces in between.\n\
16081 To disable all breakpoints, give no argument.\n\
16082 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16083                   &disablelist, "disable ", 1, &cmdlist);
16084   add_com_alias ("dis", "disable", class_breakpoint, 1);
16085   add_com_alias ("disa", "disable", class_breakpoint, 1);
16086
16087   add_cmd ("breakpoints", class_alias, disable_command, _("\
16088 Disable some breakpoints.\n\
16089 Arguments are breakpoint numbers with spaces in between.\n\
16090 To disable all breakpoints, give no argument.\n\
16091 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16092 This command may be abbreviated \"disable\"."),
16093            &disablelist);
16094
16095   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16096 Delete some breakpoints or auto-display expressions.\n\
16097 Arguments are breakpoint numbers with spaces in between.\n\
16098 To delete all breakpoints, give no argument.\n\
16099 \n\
16100 Also a prefix command for deletion of other GDB objects.\n\
16101 The \"unset\" command is also an alias for \"delete\"."),
16102                   &deletelist, "delete ", 1, &cmdlist);
16103   add_com_alias ("d", "delete", class_breakpoint, 1);
16104   add_com_alias ("del", "delete", class_breakpoint, 1);
16105
16106   add_cmd ("breakpoints", class_alias, delete_command, _("\
16107 Delete some breakpoints or auto-display expressions.\n\
16108 Arguments are breakpoint numbers with spaces in between.\n\
16109 To delete all breakpoints, give no argument.\n\
16110 This command may be abbreviated \"delete\"."),
16111            &deletelist);
16112
16113   add_com ("clear", class_breakpoint, clear_command, _("\
16114 Clear breakpoint at specified location.\n\
16115 Argument may be a linespec, explicit, or address location as described below.\n\
16116 \n\
16117 With no argument, clears all breakpoints in the line that the selected frame\n\
16118 is executing in.\n"
16119 "\n" LOCATION_HELP_STRING "\n\
16120 See also the \"delete\" command which clears breakpoints by number."));
16121   add_com_alias ("cl", "clear", class_breakpoint, 1);
16122
16123   c = add_com ("break", class_breakpoint, break_command, _("\
16124 Set breakpoint at specified location.\n"
16125 BREAK_ARGS_HELP ("break")));
16126   set_cmd_completer (c, location_completer);
16127
16128   add_com_alias ("b", "break", class_run, 1);
16129   add_com_alias ("br", "break", class_run, 1);
16130   add_com_alias ("bre", "break", class_run, 1);
16131   add_com_alias ("brea", "break", class_run, 1);
16132
16133   if (dbx_commands)
16134     {
16135       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16136 Break in function/address or break at a line in the current file."),
16137                              &stoplist, "stop ", 1, &cmdlist);
16138       add_cmd ("in", class_breakpoint, stopin_command,
16139                _("Break in function or address."), &stoplist);
16140       add_cmd ("at", class_breakpoint, stopat_command,
16141                _("Break at a line in the current file."), &stoplist);
16142       add_com ("status", class_info, breakpoints_info, _("\
16143 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16144 The \"Type\" column indicates one of:\n\
16145 \tbreakpoint     - normal breakpoint\n\
16146 \twatchpoint     - watchpoint\n\
16147 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16148 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16149 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16150 address and file/line number respectively.\n\
16151 \n\
16152 Convenience variable \"$_\" and default examine address for \"x\"\n\
16153 are set to the address of the last breakpoint listed unless the command\n\
16154 is prefixed with \"server \".\n\n\
16155 Convenience variable \"$bpnum\" contains the number of the last\n\
16156 breakpoint set."));
16157     }
16158
16159   add_info ("breakpoints", breakpoints_info, _("\
16160 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16161 The \"Type\" column indicates one of:\n\
16162 \tbreakpoint     - normal breakpoint\n\
16163 \twatchpoint     - watchpoint\n\
16164 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16165 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16166 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16167 address and file/line number respectively.\n\
16168 \n\
16169 Convenience variable \"$_\" and default examine address for \"x\"\n\
16170 are set to the address of the last breakpoint listed unless the command\n\
16171 is prefixed with \"server \".\n\n\
16172 Convenience variable \"$bpnum\" contains the number of the last\n\
16173 breakpoint set."));
16174
16175   add_info_alias ("b", "breakpoints", 1);
16176
16177   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16178 Status of all breakpoints, or breakpoint number NUMBER.\n\
16179 The \"Type\" column indicates one of:\n\
16180 \tbreakpoint     - normal breakpoint\n\
16181 \twatchpoint     - watchpoint\n\
16182 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16183 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16184 \tuntil          - internal breakpoint used by the \"until\" command\n\
16185 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16186 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16187 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16188 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16189 address and file/line number respectively.\n\
16190 \n\
16191 Convenience variable \"$_\" and default examine address for \"x\"\n\
16192 are set to the address of the last breakpoint listed unless the command\n\
16193 is prefixed with \"server \".\n\n\
16194 Convenience variable \"$bpnum\" contains the number of the last\n\
16195 breakpoint set."),
16196            &maintenanceinfolist);
16197
16198   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16199 Set catchpoints to catch events."),
16200                   &catch_cmdlist, "catch ",
16201                   0/*allow-unknown*/, &cmdlist);
16202
16203   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16204 Set temporary catchpoints to catch events."),
16205                   &tcatch_cmdlist, "tcatch ",
16206                   0/*allow-unknown*/, &cmdlist);
16207
16208   add_catch_command ("fork", _("Catch calls to fork."),
16209                      catch_fork_command_1,
16210                      NULL,
16211                      (void *) (uintptr_t) catch_fork_permanent,
16212                      (void *) (uintptr_t) catch_fork_temporary);
16213   add_catch_command ("vfork", _("Catch calls to vfork."),
16214                      catch_fork_command_1,
16215                      NULL,
16216                      (void *) (uintptr_t) catch_vfork_permanent,
16217                      (void *) (uintptr_t) catch_vfork_temporary);
16218   add_catch_command ("exec", _("Catch calls to exec."),
16219                      catch_exec_command_1,
16220                      NULL,
16221                      CATCH_PERMANENT,
16222                      CATCH_TEMPORARY);
16223   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16224 Usage: catch load [REGEX]\n\
16225 If REGEX is given, only stop for libraries matching the regular expression."),
16226                      catch_load_command_1,
16227                      NULL,
16228                      CATCH_PERMANENT,
16229                      CATCH_TEMPORARY);
16230   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16231 Usage: catch unload [REGEX]\n\
16232 If REGEX is given, only stop for libraries matching the regular expression."),
16233                      catch_unload_command_1,
16234                      NULL,
16235                      CATCH_PERMANENT,
16236                      CATCH_TEMPORARY);
16237
16238   c = add_com ("watch", class_breakpoint, watch_command, _("\
16239 Set a watchpoint for an expression.\n\
16240 Usage: watch [-l|-location] EXPRESSION\n\
16241 A watchpoint stops execution of your program whenever the value of\n\
16242 an expression changes.\n\
16243 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16244 the memory to which it refers."));
16245   set_cmd_completer (c, expression_completer);
16246
16247   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16248 Set a read watchpoint for an expression.\n\
16249 Usage: rwatch [-l|-location] EXPRESSION\n\
16250 A watchpoint stops execution of your program whenever the value of\n\
16251 an expression is read.\n\
16252 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16253 the memory to which it refers."));
16254   set_cmd_completer (c, expression_completer);
16255
16256   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16257 Set a watchpoint for an expression.\n\
16258 Usage: awatch [-l|-location] EXPRESSION\n\
16259 A watchpoint stops execution of your program whenever the value of\n\
16260 an expression is either read or written.\n\
16261 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16262 the memory to which it refers."));
16263   set_cmd_completer (c, expression_completer);
16264
16265   add_info ("watchpoints", watchpoints_info, _("\
16266 Status of specified watchpoints (all watchpoints if no argument)."));
16267
16268   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16269      respond to changes - contrary to the description.  */
16270   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16271                             &can_use_hw_watchpoints, _("\
16272 Set debugger's willingness to use watchpoint hardware."), _("\
16273 Show debugger's willingness to use watchpoint hardware."), _("\
16274 If zero, gdb will not use hardware for new watchpoints, even if\n\
16275 such is available.  (However, any hardware watchpoints that were\n\
16276 created before setting this to nonzero, will continue to use watchpoint\n\
16277 hardware.)"),
16278                             NULL,
16279                             show_can_use_hw_watchpoints,
16280                             &setlist, &showlist);
16281
16282   can_use_hw_watchpoints = 1;
16283
16284   /* Tracepoint manipulation commands.  */
16285
16286   c = add_com ("trace", class_breakpoint, trace_command, _("\
16287 Set a tracepoint at specified location.\n\
16288 \n"
16289 BREAK_ARGS_HELP ("trace") "\n\
16290 Do \"help tracepoints\" for info on other tracepoint commands."));
16291   set_cmd_completer (c, location_completer);
16292
16293   add_com_alias ("tp", "trace", class_alias, 0);
16294   add_com_alias ("tr", "trace", class_alias, 1);
16295   add_com_alias ("tra", "trace", class_alias, 1);
16296   add_com_alias ("trac", "trace", class_alias, 1);
16297
16298   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16299 Set a fast tracepoint at specified location.\n\
16300 \n"
16301 BREAK_ARGS_HELP ("ftrace") "\n\
16302 Do \"help tracepoints\" for info on other tracepoint commands."));
16303   set_cmd_completer (c, location_completer);
16304
16305   c = add_com ("strace", class_breakpoint, strace_command, _("\
16306 Set a static tracepoint at location or marker.\n\
16307 \n\
16308 strace [LOCATION] [if CONDITION]\n\
16309 LOCATION may be a linespec, explicit, or address location (described below) \n\
16310 or -m MARKER_ID.\n\n\
16311 If a marker id is specified, probe the marker with that name.  With\n\
16312 no LOCATION, uses current execution address of the selected stack frame.\n\
16313 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16314 This collects arbitrary user data passed in the probe point call to the\n\
16315 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16316 by printing the $_sdata variable like any other convenience variable.\n\
16317 \n\
16318 CONDITION is a boolean expression.\n\
16319 \n" LOCATION_HELP_STRING "\n\
16320 Multiple tracepoints at one place are permitted, and useful if their\n\
16321 conditions are different.\n\
16322 \n\
16323 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16324 Do \"help tracepoints\" for info on other tracepoint commands."));
16325   set_cmd_completer (c, location_completer);
16326
16327   add_info ("tracepoints", tracepoints_info, _("\
16328 Status of specified tracepoints (all tracepoints if no argument).\n\
16329 Convenience variable \"$tpnum\" contains the number of the\n\
16330 last tracepoint set."));
16331
16332   add_info_alias ("tp", "tracepoints", 1);
16333
16334   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16335 Delete specified tracepoints.\n\
16336 Arguments are tracepoint numbers, separated by spaces.\n\
16337 No argument means delete all tracepoints."),
16338            &deletelist);
16339   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16340
16341   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16342 Disable specified tracepoints.\n\
16343 Arguments are tracepoint numbers, separated by spaces.\n\
16344 No argument means disable all tracepoints."),
16345            &disablelist);
16346   deprecate_cmd (c, "disable");
16347
16348   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16349 Enable specified tracepoints.\n\
16350 Arguments are tracepoint numbers, separated by spaces.\n\
16351 No argument means enable all tracepoints."),
16352            &enablelist);
16353   deprecate_cmd (c, "enable");
16354
16355   add_com ("passcount", class_trace, trace_pass_command, _("\
16356 Set the passcount for a tracepoint.\n\
16357 The trace will end when the tracepoint has been passed 'count' times.\n\
16358 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16359 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16360
16361   add_prefix_cmd ("save", class_breakpoint, save_command,
16362                   _("Save breakpoint definitions as a script."),
16363                   &save_cmdlist, "save ",
16364                   0/*allow-unknown*/, &cmdlist);
16365
16366   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16367 Save current breakpoint definitions as a script.\n\
16368 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16369 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16370 session to restore them."),
16371                &save_cmdlist);
16372   set_cmd_completer (c, filename_completer);
16373
16374   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16375 Save current tracepoint definitions as a script.\n\
16376 Use the 'source' command in another debug session to restore them."),
16377                &save_cmdlist);
16378   set_cmd_completer (c, filename_completer);
16379
16380   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16381   deprecate_cmd (c, "save tracepoints");
16382
16383   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16384 Breakpoint specific settings\n\
16385 Configure various breakpoint-specific variables such as\n\
16386 pending breakpoint behavior"),
16387                   &breakpoint_set_cmdlist, "set breakpoint ",
16388                   0/*allow-unknown*/, &setlist);
16389   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16390 Breakpoint specific settings\n\
16391 Configure various breakpoint-specific variables such as\n\
16392 pending breakpoint behavior"),
16393                   &breakpoint_show_cmdlist, "show breakpoint ",
16394                   0/*allow-unknown*/, &showlist);
16395
16396   add_setshow_auto_boolean_cmd ("pending", no_class,
16397                                 &pending_break_support, _("\
16398 Set debugger's behavior regarding pending breakpoints."), _("\
16399 Show debugger's behavior regarding pending breakpoints."), _("\
16400 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16401 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16402 an error.  If auto, an unrecognized breakpoint location results in a\n\
16403 user-query to see if a pending breakpoint should be created."),
16404                                 NULL,
16405                                 show_pending_break_support,
16406                                 &breakpoint_set_cmdlist,
16407                                 &breakpoint_show_cmdlist);
16408
16409   pending_break_support = AUTO_BOOLEAN_AUTO;
16410
16411   add_setshow_boolean_cmd ("auto-hw", no_class,
16412                            &automatic_hardware_breakpoints, _("\
16413 Set automatic usage of hardware breakpoints."), _("\
16414 Show automatic usage of hardware breakpoints."), _("\
16415 If set, the debugger will automatically use hardware breakpoints for\n\
16416 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16417 a warning will be emitted for such breakpoints."),
16418                            NULL,
16419                            show_automatic_hardware_breakpoints,
16420                            &breakpoint_set_cmdlist,
16421                            &breakpoint_show_cmdlist);
16422
16423   add_setshow_boolean_cmd ("always-inserted", class_support,
16424                            &always_inserted_mode, _("\
16425 Set mode for inserting breakpoints."), _("\
16426 Show mode for inserting breakpoints."), _("\
16427 When this mode is on, breakpoints are inserted immediately as soon as\n\
16428 they're created, kept inserted even when execution stops, and removed\n\
16429 only when the user deletes them.  When this mode is off (the default),\n\
16430 breakpoints are inserted only when execution continues, and removed\n\
16431 when execution stops."),
16432                                 NULL,
16433                                 &show_always_inserted_mode,
16434                                 &breakpoint_set_cmdlist,
16435                                 &breakpoint_show_cmdlist);
16436
16437   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16438                         condition_evaluation_enums,
16439                         &condition_evaluation_mode_1, _("\
16440 Set mode of breakpoint condition evaluation."), _("\
16441 Show mode of breakpoint condition evaluation."), _("\
16442 When this is set to \"host\", breakpoint conditions will be\n\
16443 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16444 breakpoint conditions will be downloaded to the target (if the target\n\
16445 supports such feature) and conditions will be evaluated on the target's side.\n\
16446 If this is set to \"auto\" (default), this will be automatically set to\n\
16447 \"target\" if it supports condition evaluation, otherwise it will\n\
16448 be set to \"gdb\""),
16449                            &set_condition_evaluation_mode,
16450                            &show_condition_evaluation_mode,
16451                            &breakpoint_set_cmdlist,
16452                            &breakpoint_show_cmdlist);
16453
16454   add_com ("break-range", class_breakpoint, break_range_command, _("\
16455 Set a breakpoint for an address range.\n\
16456 break-range START-LOCATION, END-LOCATION\n\
16457 where START-LOCATION and END-LOCATION can be one of the following:\n\
16458   LINENUM, for that line in the current file,\n\
16459   FILE:LINENUM, for that line in that file,\n\
16460   +OFFSET, for that number of lines after the current line\n\
16461            or the start of the range\n\
16462   FUNCTION, for the first line in that function,\n\
16463   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16464   *ADDRESS, for the instruction at that address.\n\
16465 \n\
16466 The breakpoint will stop execution of the inferior whenever it executes\n\
16467 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16468 range (including START-LOCATION and END-LOCATION)."));
16469
16470   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16471 Set a dynamic printf at specified location.\n\
16472 dprintf location,format string,arg1,arg2,...\n\
16473 location may be a linespec, explicit, or address location.\n"
16474 "\n" LOCATION_HELP_STRING));
16475   set_cmd_completer (c, location_completer);
16476
16477   add_setshow_enum_cmd ("dprintf-style", class_support,
16478                         dprintf_style_enums, &dprintf_style, _("\
16479 Set the style of usage for dynamic printf."), _("\
16480 Show the style of usage for dynamic printf."), _("\
16481 This setting chooses how GDB will do a dynamic printf.\n\
16482 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16483 console, as with the \"printf\" command.\n\
16484 If the value is \"call\", the print is done by calling a function in your\n\
16485 program; by default printf(), but you can choose a different function or\n\
16486 output stream by setting dprintf-function and dprintf-channel."),
16487                         update_dprintf_commands, NULL,
16488                         &setlist, &showlist);
16489
16490   dprintf_function = xstrdup ("printf");
16491   add_setshow_string_cmd ("dprintf-function", class_support,
16492                           &dprintf_function, _("\
16493 Set the function to use for dynamic printf"), _("\
16494 Show the function to use for dynamic printf"), NULL,
16495                           update_dprintf_commands, NULL,
16496                           &setlist, &showlist);
16497
16498   dprintf_channel = xstrdup ("");
16499   add_setshow_string_cmd ("dprintf-channel", class_support,
16500                           &dprintf_channel, _("\
16501 Set the channel to use for dynamic printf"), _("\
16502 Show the channel to use for dynamic printf"), NULL,
16503                           update_dprintf_commands, NULL,
16504                           &setlist, &showlist);
16505
16506   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16507                            &disconnected_dprintf, _("\
16508 Set whether dprintf continues after GDB disconnects."), _("\
16509 Show whether dprintf continues after GDB disconnects."), _("\
16510 Use this to let dprintf commands continue to hit and produce output\n\
16511 even if GDB disconnects or detaches from the target."),
16512                            NULL,
16513                            NULL,
16514                            &setlist, &showlist);
16515
16516   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16517 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16518 (target agent only) This is useful for formatted output in user-defined commands."));
16519
16520   automatic_hardware_breakpoints = 1;
16521
16522   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16523   observer_attach_thread_exit (remove_threaded_breakpoints);
16524 }