Use XCNEW gdbarch_tdep
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 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 "thread-fsm.h"
71 #include "tid-parse.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 #include <algorithm>
83 #include "progspace-and-thread.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_RETHROW,
90   EX_EVENT_CATCH
91 };
92
93 /* Prototypes for local functions.  */
94
95 static void enable_delete_command (char *, int);
96
97 static void enable_once_command (char *, int);
98
99 static void enable_count_command (char *, int);
100
101 static void disable_command (char *, int);
102
103 static void enable_command (char *, int);
104
105 static void map_breakpoint_numbers (const char *,
106                                     void (*) (struct breakpoint *,
107                                               void *),
108                                     void *);
109
110 static void ignore_command (char *, int);
111
112 static int breakpoint_re_set_one (void *);
113
114 static void breakpoint_re_set_default (struct breakpoint *);
115
116 static void
117   create_sals_from_location_default (const struct event_location *location,
118                                      struct linespec_result *canonical,
119                                      enum bptype type_wanted);
120
121 static void create_breakpoints_sal_default (struct gdbarch *,
122                                             struct linespec_result *,
123                                             char *, char *, enum bptype,
124                                             enum bpdisp, int, int,
125                                             int,
126                                             const struct breakpoint_ops *,
127                                             int, int, int, unsigned);
128
129 static void decode_location_default (struct breakpoint *b,
130                                      const struct event_location *location,
131                                      struct program_space *search_pspace,
132                                      struct symtabs_and_lines *sals);
133
134 static void clear_command (char *, int);
135
136 static void catch_command (char *, int);
137
138 static int can_use_hardware_watchpoint (struct value *);
139
140 static void break_command_1 (char *, int, int);
141
142 static void mention (struct breakpoint *);
143
144 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
145                                                                enum bptype,
146                                                                const struct breakpoint_ops *);
147 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
148                                                        const struct symtab_and_line *);
149
150 /* This function is used in gdbtk sources and thus can not be made
151    static.  */
152 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
153                                        struct symtab_and_line,
154                                        enum bptype,
155                                        const struct breakpoint_ops *);
156
157 static struct breakpoint *
158   momentary_breakpoint_from_master (struct breakpoint *orig,
159                                     enum bptype type,
160                                     const struct breakpoint_ops *ops,
161                                     int loc_enabled);
162
163 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
164
165 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
166                                             CORE_ADDR bpaddr,
167                                             enum bptype bptype);
168
169 static void describe_other_breakpoints (struct gdbarch *,
170                                         struct program_space *, CORE_ADDR,
171                                         struct obj_section *, int);
172
173 static int watchpoint_locations_match (struct bp_location *loc1,
174                                        struct bp_location *loc2);
175
176 static int breakpoint_location_address_match (struct bp_location *bl,
177                                               struct address_space *aspace,
178                                               CORE_ADDR addr);
179
180 static int breakpoint_location_address_range_overlap (struct bp_location *,
181                                                       struct address_space *,
182                                                       CORE_ADDR, int);
183
184 static void breakpoints_info (char *, int);
185
186 static void watchpoints_info (char *, int);
187
188 static int breakpoint_1 (char *, int, 
189                          int (*) (const struct breakpoint *));
190
191 static int breakpoint_cond_eval (void *);
192
193 static void cleanup_executing_breakpoints (void *);
194
195 static void commands_command (char *, int);
196
197 static void condition_command (char *, int);
198
199 static int remove_breakpoint (struct bp_location *);
200 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
201
202 static enum print_stop_action print_bp_stop_message (bpstat bs);
203
204 static int watchpoint_check (void *);
205
206 static void maintenance_info_breakpoints (char *, int);
207
208 static int hw_breakpoint_used_count (void);
209
210 static int hw_watchpoint_use_count (struct breakpoint *);
211
212 static int hw_watchpoint_used_count_others (struct breakpoint *except,
213                                             enum bptype type,
214                                             int *other_type_used);
215
216 static void hbreak_command (char *, int);
217
218 static void thbreak_command (char *, int);
219
220 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
221                                     int count);
222
223 static void stop_command (char *arg, int from_tty);
224
225 static void stopin_command (char *arg, int from_tty);
226
227 static void stopat_command (char *arg, int from_tty);
228
229 static void tcatch_command (char *arg, int from_tty);
230
231 static void free_bp_location (struct bp_location *loc);
232 static void incref_bp_location (struct bp_location *loc);
233 static void decref_bp_location (struct bp_location **loc);
234
235 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
236
237 /* update_global_location_list's modes of operation wrt to whether to
238    insert locations now.  */
239 enum ugll_insert_mode
240 {
241   /* Don't insert any breakpoint locations into the inferior, only
242      remove already-inserted locations that no longer should be
243      inserted.  Functions that delete a breakpoint or breakpoints
244      should specify this mode, so that deleting a breakpoint doesn't
245      have the side effect of inserting the locations of other
246      breakpoints that are marked not-inserted, but should_be_inserted
247      returns true on them.
248
249      This behavior is useful is situations close to tear-down -- e.g.,
250      after an exec, while the target still has execution, but
251      breakpoint shadows of the previous executable image should *NOT*
252      be restored to the new image; or before detaching, where the
253      target still has execution and wants to delete breakpoints from
254      GDB's lists, and all breakpoints had already been removed from
255      the inferior.  */
256   UGLL_DONT_INSERT,
257
258   /* May insert breakpoints iff breakpoints_should_be_inserted_now
259      claims breakpoints should be inserted now.  */
260   UGLL_MAY_INSERT,
261
262   /* Insert locations now, irrespective of
263      breakpoints_should_be_inserted_now.  E.g., say all threads are
264      stopped right now, and the user did "continue".  We need to
265      insert breakpoints _before_ resuming the target, but
266      UGLL_MAY_INSERT wouldn't insert them, because
267      breakpoints_should_be_inserted_now returns false at that point,
268      as no thread is running yet.  */
269   UGLL_INSERT
270 };
271
272 static void update_global_location_list (enum ugll_insert_mode);
273
274 static void update_global_location_list_nothrow (enum ugll_insert_mode);
275
276 static int is_hardware_watchpoint (const struct breakpoint *bpt);
277
278 static void insert_breakpoint_locations (void);
279
280 static void tracepoints_info (char *, int);
281
282 static void delete_trace_command (char *, int);
283
284 static void enable_trace_command (char *, int);
285
286 static void disable_trace_command (char *, int);
287
288 static void trace_pass_command (char *, int);
289
290 static void set_tracepoint_count (int num);
291
292 static int is_masked_watchpoint (const struct breakpoint *b);
293
294 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
295
296 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
297    otherwise.  */
298
299 static int strace_marker_p (struct breakpoint *b);
300
301 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
302    that are implemented on top of software or hardware breakpoints
303    (user breakpoints, internal and momentary breakpoints, etc.).  */
304 static struct breakpoint_ops bkpt_base_breakpoint_ops;
305
306 /* Internal breakpoints class type.  */
307 static struct breakpoint_ops internal_breakpoint_ops;
308
309 /* Momentary breakpoints class type.  */
310 static struct breakpoint_ops momentary_breakpoint_ops;
311
312 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
313 static struct breakpoint_ops longjmp_breakpoint_ops;
314
315 /* The breakpoint_ops structure to be used in regular user created
316    breakpoints.  */
317 struct breakpoint_ops bkpt_breakpoint_ops;
318
319 /* Breakpoints set on probes.  */
320 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
321
322 /* Dynamic printf class type.  */
323 struct breakpoint_ops dprintf_breakpoint_ops;
324
325 /* The style in which to perform a dynamic printf.  This is a user
326    option because different output options have different tradeoffs;
327    if GDB does the printing, there is better error handling if there
328    is a problem with any of the arguments, but using an inferior
329    function lets you have special-purpose printers and sending of
330    output to the same place as compiled-in print functions.  */
331
332 static const char dprintf_style_gdb[] = "gdb";
333 static const char dprintf_style_call[] = "call";
334 static const char dprintf_style_agent[] = "agent";
335 static const char *const dprintf_style_enums[] = {
336   dprintf_style_gdb,
337   dprintf_style_call,
338   dprintf_style_agent,
339   NULL
340 };
341 static const char *dprintf_style = dprintf_style_gdb;
342
343 /* The function to use for dynamic printf if the preferred style is to
344    call into the inferior.  The value is simply a string that is
345    copied into the command, so it can be anything that GDB can
346    evaluate to a callable address, not necessarily a function name.  */
347
348 static char *dprintf_function;
349
350 /* The channel to use for dynamic printf if the preferred style is to
351    call into the inferior; if a nonempty string, it will be passed to
352    the call as the first argument, with the format string as the
353    second.  As with the dprintf function, this can be anything that
354    GDB knows how to evaluate, so in addition to common choices like
355    "stderr", this could be an app-specific expression like
356    "mystreams[curlogger]".  */
357
358 static char *dprintf_channel;
359
360 /* True if dprintf commands should continue to operate even if GDB
361    has disconnected.  */
362 static int disconnected_dprintf = 1;
363
364 /* A reference-counted struct command_line.  This lets multiple
365    breakpoints share a single command list.  */
366 struct counted_command_line
367 {
368   /* The reference count.  */
369   int refc;
370
371   /* The command list.  */
372   struct command_line *commands;
373 };
374
375 struct command_line *
376 breakpoint_commands (struct breakpoint *b)
377 {
378   return b->commands ? b->commands->commands : NULL;
379 }
380
381 /* Flag indicating that a command has proceeded the inferior past the
382    current breakpoint.  */
383
384 static int breakpoint_proceeded;
385
386 const char *
387 bpdisp_text (enum bpdisp disp)
388 {
389   /* NOTE: the following values are a part of MI protocol and
390      represent values of 'disp' field returned when inferior stops at
391      a breakpoint.  */
392   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
393
394   return bpdisps[(int) disp];
395 }
396
397 /* Prototypes for exported functions.  */
398 /* If FALSE, gdb will not use hardware support for watchpoints, even
399    if such is available.  */
400 static int can_use_hw_watchpoints;
401
402 static void
403 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
404                              struct cmd_list_element *c,
405                              const char *value)
406 {
407   fprintf_filtered (file,
408                     _("Debugger's willingness to use "
409                       "watchpoint hardware is %s.\n"),
410                     value);
411 }
412
413 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
414    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
415    for unrecognized breakpoint locations.
416    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
417 static enum auto_boolean pending_break_support;
418 static void
419 show_pending_break_support (struct ui_file *file, int from_tty,
420                             struct cmd_list_element *c,
421                             const char *value)
422 {
423   fprintf_filtered (file,
424                     _("Debugger's behavior regarding "
425                       "pending breakpoints is %s.\n"),
426                     value);
427 }
428
429 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
430    set with "break" but falling in read-only memory.
431    If 0, gdb will warn about such breakpoints, but won't automatically
432    use hardware breakpoints.  */
433 static int automatic_hardware_breakpoints;
434 static void
435 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
436                                      struct cmd_list_element *c,
437                                      const char *value)
438 {
439   fprintf_filtered (file,
440                     _("Automatic usage of hardware breakpoints is %s.\n"),
441                     value);
442 }
443
444 /* If on, GDB keeps breakpoints inserted even if the inferior is
445    stopped, and immediately inserts any new breakpoints as soon as
446    they're created.  If off (default), GDB keeps breakpoints off of
447    the target as long as possible.  That is, it delays inserting
448    breakpoints until the next resume, and removes them again when the
449    target fully stops.  This is a bit safer in case GDB crashes while
450    processing user input.  */
451 static int always_inserted_mode = 0;
452
453 static void
454 show_always_inserted_mode (struct ui_file *file, int from_tty,
455                      struct cmd_list_element *c, const char *value)
456 {
457   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
458                     value);
459 }
460
461 /* See breakpoint.h.  */
462
463 int
464 breakpoints_should_be_inserted_now (void)
465 {
466   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
467     {
468       /* If breakpoints are global, they should be inserted even if no
469          thread under gdb's control is running, or even if there are
470          no threads under GDB's control yet.  */
471       return 1;
472     }
473   else if (target_has_execution)
474     {
475       struct thread_info *tp;
476
477       if (always_inserted_mode)
478         {
479           /* The user wants breakpoints inserted even if all threads
480              are stopped.  */
481           return 1;
482         }
483
484       if (threads_are_executing ())
485         return 1;
486
487       /* Don't remove breakpoints yet if, even though all threads are
488          stopped, we still have events to process.  */
489       ALL_NON_EXITED_THREADS (tp)
490         if (tp->resumed
491             && tp->suspend.waitstatus_pending_p)
492           return 1;
493     }
494   return 0;
495 }
496
497 static const char condition_evaluation_both[] = "host or target";
498
499 /* Modes for breakpoint condition evaluation.  */
500 static const char condition_evaluation_auto[] = "auto";
501 static const char condition_evaluation_host[] = "host";
502 static const char condition_evaluation_target[] = "target";
503 static const char *const condition_evaluation_enums[] = {
504   condition_evaluation_auto,
505   condition_evaluation_host,
506   condition_evaluation_target,
507   NULL
508 };
509
510 /* Global that holds the current mode for breakpoint condition evaluation.  */
511 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
512
513 /* Global that we use to display information to the user (gets its value from
514    condition_evaluation_mode_1.  */
515 static const char *condition_evaluation_mode = condition_evaluation_auto;
516
517 /* Translate a condition evaluation mode MODE into either "host"
518    or "target".  This is used mostly to translate from "auto" to the
519    real setting that is being used.  It returns the translated
520    evaluation mode.  */
521
522 static const char *
523 translate_condition_evaluation_mode (const char *mode)
524 {
525   if (mode == condition_evaluation_auto)
526     {
527       if (target_supports_evaluation_of_breakpoint_conditions ())
528         return condition_evaluation_target;
529       else
530         return condition_evaluation_host;
531     }
532   else
533     return mode;
534 }
535
536 /* Discovers what condition_evaluation_auto translates to.  */
537
538 static const char *
539 breakpoint_condition_evaluation_mode (void)
540 {
541   return translate_condition_evaluation_mode (condition_evaluation_mode);
542 }
543
544 /* Return true if GDB should evaluate breakpoint conditions or false
545    otherwise.  */
546
547 static int
548 gdb_evaluates_breakpoint_condition_p (void)
549 {
550   const char *mode = breakpoint_condition_evaluation_mode ();
551
552   return (mode == condition_evaluation_host);
553 }
554
555 void _initialize_breakpoint (void);
556
557 /* Are we executing breakpoint commands?  */
558 static int executing_breakpoint_commands;
559
560 /* Are overlay event breakpoints enabled? */
561 static int overlay_events_enabled;
562
563 /* See description in breakpoint.h. */
564 int target_exact_watchpoints = 0;
565
566 /* Walk the following statement or block through all breakpoints.
567    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
568    current breakpoint.  */
569
570 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
571
572 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
573         for (B = breakpoint_chain;      \
574              B ? (TMP=B->next, 1): 0;   \
575              B = TMP)
576
577 /* Similar iterator for the low-level breakpoints.  SAFE variant is
578    not provided so update_global_location_list must not be called
579    while executing the block of ALL_BP_LOCATIONS.  */
580
581 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
582         for (BP_TMP = bp_locations;                                     \
583              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
584              BP_TMP++)
585
586 /* Iterates through locations with address ADDRESS for the currently selected
587    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
588    to where the loop should start from.
589    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
590    appropriate location to start with.  */
591
592 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
593         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
594              BP_LOCP_TMP = BP_LOCP_START;                               \
595              BP_LOCP_START                                              \
596              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
597              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
598              BP_LOCP_TMP++)
599
600 /* Iterator for tracepoints only.  */
601
602 #define ALL_TRACEPOINTS(B)  \
603   for (B = breakpoint_chain; B; B = B->next)  \
604     if (is_tracepoint (B))
605
606 /* Chains of all breakpoints defined.  */
607
608 struct breakpoint *breakpoint_chain;
609
610 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
611
612 static struct bp_location **bp_locations;
613
614 /* Number of elements of BP_LOCATIONS.  */
615
616 static unsigned bp_locations_count;
617
618 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
619    ADDRESS for the current elements of BP_LOCATIONS which get a valid
620    result from bp_location_has_shadow.  You can use it for roughly
621    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
622    an address you need to read.  */
623
624 static CORE_ADDR bp_locations_placed_address_before_address_max;
625
626 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
627    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
628    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
629    You can use it for roughly limiting the subrange of BP_LOCATIONS to
630    scan for shadow bytes for an address you need to read.  */
631
632 static CORE_ADDR bp_locations_shadow_len_after_address_max;
633
634 /* The locations that no longer correspond to any breakpoint, unlinked
635    from the bp_locations array, but for which a hit may still be
636    reported by a target.  */
637 VEC(bp_location_p) *moribund_locations = NULL;
638
639 /* Number of last breakpoint made.  */
640
641 static int breakpoint_count;
642
643 /* The value of `breakpoint_count' before the last command that
644    created breakpoints.  If the last (break-like) command created more
645    than one breakpoint, then the difference between BREAKPOINT_COUNT
646    and PREV_BREAKPOINT_COUNT is more than one.  */
647 static int prev_breakpoint_count;
648
649 /* Number of last tracepoint made.  */
650
651 static int tracepoint_count;
652
653 static struct cmd_list_element *breakpoint_set_cmdlist;
654 static struct cmd_list_element *breakpoint_show_cmdlist;
655 struct cmd_list_element *save_cmdlist;
656
657 /* See declaration at breakpoint.h.  */
658
659 struct breakpoint *
660 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
661                     void *user_data)
662 {
663   struct breakpoint *b = NULL;
664
665   ALL_BREAKPOINTS (b)
666     {
667       if (func (b, user_data) != 0)
668         break;
669     }
670
671   return b;
672 }
673
674 /* Return whether a breakpoint is an active enabled breakpoint.  */
675 static int
676 breakpoint_enabled (struct breakpoint *b)
677 {
678   return (b->enable_state == bp_enabled);
679 }
680
681 /* Set breakpoint count to NUM.  */
682
683 static void
684 set_breakpoint_count (int num)
685 {
686   prev_breakpoint_count = breakpoint_count;
687   breakpoint_count = num;
688   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
689 }
690
691 /* Used by `start_rbreak_breakpoints' below, to record the current
692    breakpoint count before "rbreak" creates any breakpoint.  */
693 static int rbreak_start_breakpoint_count;
694
695 /* Called at the start an "rbreak" command to record the first
696    breakpoint made.  */
697
698 void
699 start_rbreak_breakpoints (void)
700 {
701   rbreak_start_breakpoint_count = breakpoint_count;
702 }
703
704 /* Called at the end of an "rbreak" command to record the last
705    breakpoint made.  */
706
707 void
708 end_rbreak_breakpoints (void)
709 {
710   prev_breakpoint_count = rbreak_start_breakpoint_count;
711 }
712
713 /* Used in run_command to zero the hit count when a new run starts.  */
714
715 void
716 clear_breakpoint_hit_counts (void)
717 {
718   struct breakpoint *b;
719
720   ALL_BREAKPOINTS (b)
721     b->hit_count = 0;
722 }
723
724 /* Allocate a new counted_command_line with reference count of 1.
725    The new structure owns COMMANDS.  */
726
727 static struct counted_command_line *
728 alloc_counted_command_line (struct command_line *commands)
729 {
730   struct counted_command_line *result = XNEW (struct counted_command_line);
731
732   result->refc = 1;
733   result->commands = commands;
734
735   return result;
736 }
737
738 /* Increment reference count.  This does nothing if CMD is NULL.  */
739
740 static void
741 incref_counted_command_line (struct counted_command_line *cmd)
742 {
743   if (cmd)
744     ++cmd->refc;
745 }
746
747 /* Decrement reference count.  If the reference count reaches 0,
748    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
749    nothing if *CMDP is NULL.  */
750
751 static void
752 decref_counted_command_line (struct counted_command_line **cmdp)
753 {
754   if (*cmdp)
755     {
756       if (--(*cmdp)->refc == 0)
757         {
758           free_command_lines (&(*cmdp)->commands);
759           xfree (*cmdp);
760         }
761       *cmdp = NULL;
762     }
763 }
764
765 /* A cleanup function that calls decref_counted_command_line.  */
766
767 static void
768 do_cleanup_counted_command_line (void *arg)
769 {
770   decref_counted_command_line ((struct counted_command_line **) arg);
771 }
772
773 /* Create a cleanup that calls decref_counted_command_line on the
774    argument.  */
775
776 static struct cleanup *
777 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
778 {
779   return make_cleanup (do_cleanup_counted_command_line, cmdp);
780 }
781
782 \f
783 /* Return the breakpoint with the specified number, or NULL
784    if the number does not refer to an existing breakpoint.  */
785
786 struct breakpoint *
787 get_breakpoint (int num)
788 {
789   struct breakpoint *b;
790
791   ALL_BREAKPOINTS (b)
792     if (b->number == num)
793       return b;
794   
795   return NULL;
796 }
797
798 \f
799
800 /* Mark locations as "conditions have changed" in case the target supports
801    evaluating conditions on its side.  */
802
803 static void
804 mark_breakpoint_modified (struct breakpoint *b)
805 {
806   struct bp_location *loc;
807
808   /* This is only meaningful if the target is
809      evaluating conditions and if the user has
810      opted for condition evaluation on the target's
811      side.  */
812   if (gdb_evaluates_breakpoint_condition_p ()
813       || !target_supports_evaluation_of_breakpoint_conditions ())
814     return;
815
816   if (!is_breakpoint (b))
817     return;
818
819   for (loc = b->loc; loc; loc = loc->next)
820     loc->condition_changed = condition_modified;
821 }
822
823 /* Mark location as "conditions have changed" in case the target supports
824    evaluating conditions on its side.  */
825
826 static void
827 mark_breakpoint_location_modified (struct bp_location *loc)
828 {
829   /* This is only meaningful if the target is
830      evaluating conditions and if the user has
831      opted for condition evaluation on the target's
832      side.  */
833   if (gdb_evaluates_breakpoint_condition_p ()
834       || !target_supports_evaluation_of_breakpoint_conditions ())
835
836     return;
837
838   if (!is_breakpoint (loc->owner))
839     return;
840
841   loc->condition_changed = condition_modified;
842 }
843
844 /* Sets the condition-evaluation mode using the static global
845    condition_evaluation_mode.  */
846
847 static void
848 set_condition_evaluation_mode (char *args, int from_tty,
849                                struct cmd_list_element *c)
850 {
851   const char *old_mode, *new_mode;
852
853   if ((condition_evaluation_mode_1 == condition_evaluation_target)
854       && !target_supports_evaluation_of_breakpoint_conditions ())
855     {
856       condition_evaluation_mode_1 = condition_evaluation_mode;
857       warning (_("Target does not support breakpoint condition evaluation.\n"
858                  "Using host evaluation mode instead."));
859       return;
860     }
861
862   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
863   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
864
865   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
866      settings was "auto".  */
867   condition_evaluation_mode = condition_evaluation_mode_1;
868
869   /* Only update the mode if the user picked a different one.  */
870   if (new_mode != old_mode)
871     {
872       struct bp_location *loc, **loc_tmp;
873       /* If the user switched to a different evaluation mode, we
874          need to synch the changes with the target as follows:
875
876          "host" -> "target": Send all (valid) conditions to the target.
877          "target" -> "host": Remove all the conditions from the target.
878       */
879
880       if (new_mode == condition_evaluation_target)
881         {
882           /* Mark everything modified and synch conditions with the
883              target.  */
884           ALL_BP_LOCATIONS (loc, loc_tmp)
885             mark_breakpoint_location_modified (loc);
886         }
887       else
888         {
889           /* Manually mark non-duplicate locations to synch conditions
890              with the target.  We do this to remove all the conditions the
891              target knows about.  */
892           ALL_BP_LOCATIONS (loc, loc_tmp)
893             if (is_breakpoint (loc->owner) && loc->inserted)
894               loc->needs_update = 1;
895         }
896
897       /* Do the update.  */
898       update_global_location_list (UGLL_MAY_INSERT);
899     }
900
901   return;
902 }
903
904 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
905    what "auto" is translating to.  */
906
907 static void
908 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
909                                 struct cmd_list_element *c, const char *value)
910 {
911   if (condition_evaluation_mode == condition_evaluation_auto)
912     fprintf_filtered (file,
913                       _("Breakpoint condition evaluation "
914                         "mode is %s (currently %s).\n"),
915                       value,
916                       breakpoint_condition_evaluation_mode ());
917   else
918     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
919                       value);
920 }
921
922 /* A comparison function for bp_location AP and BP that is used by
923    bsearch.  This comparison function only cares about addresses, unlike
924    the more general bp_locations_compare function.  */
925
926 static int
927 bp_locations_compare_addrs (const void *ap, const void *bp)
928 {
929   const struct bp_location *a = *(const struct bp_location **) ap;
930   const struct bp_location *b = *(const struct bp_location **) bp;
931
932   if (a->address == b->address)
933     return 0;
934   else
935     return ((a->address > b->address) - (a->address < b->address));
936 }
937
938 /* Helper function to skip all bp_locations with addresses
939    less than ADDRESS.  It returns the first bp_location that
940    is greater than or equal to ADDRESS.  If none is found, just
941    return NULL.  */
942
943 static struct bp_location **
944 get_first_locp_gte_addr (CORE_ADDR address)
945 {
946   struct bp_location dummy_loc;
947   struct bp_location *dummy_locp = &dummy_loc;
948   struct bp_location **locp_found = NULL;
949
950   /* Initialize the dummy location's address field.  */
951   dummy_loc.address = address;
952
953   /* Find a close match to the first location at ADDRESS.  */
954   locp_found = ((struct bp_location **)
955                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
956                          sizeof (struct bp_location **),
957                          bp_locations_compare_addrs));
958
959   /* Nothing was found, nothing left to do.  */
960   if (locp_found == NULL)
961     return NULL;
962
963   /* We may have found a location that is at ADDRESS but is not the first in the
964      location's list.  Go backwards (if possible) and locate the first one.  */
965   while ((locp_found - 1) >= bp_locations
966          && (*(locp_found - 1))->address == address)
967     locp_found--;
968
969   return locp_found;
970 }
971
972 void
973 set_breakpoint_condition (struct breakpoint *b, const char *exp,
974                           int from_tty)
975 {
976   xfree (b->cond_string);
977   b->cond_string = NULL;
978
979   if (is_watchpoint (b))
980     {
981       struct watchpoint *w = (struct watchpoint *) b;
982
983       w->cond_exp.reset ();
984     }
985   else
986     {
987       struct bp_location *loc;
988
989       for (loc = b->loc; loc; loc = loc->next)
990         {
991           loc->cond.reset ();
992
993           /* No need to free the condition agent expression
994              bytecode (if we have one).  We will handle this
995              when we go through update_global_location_list.  */
996         }
997     }
998
999   if (*exp == 0)
1000     {
1001       if (from_tty)
1002         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1003     }
1004   else
1005     {
1006       const char *arg = exp;
1007
1008       /* I don't know if it matters whether this is the string the user
1009          typed in or the decompiled expression.  */
1010       b->cond_string = xstrdup (arg);
1011       b->condition_not_parsed = 0;
1012
1013       if (is_watchpoint (b))
1014         {
1015           struct watchpoint *w = (struct watchpoint *) b;
1016
1017           innermost_block = NULL;
1018           arg = exp;
1019           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1020           if (*arg)
1021             error (_("Junk at end of expression"));
1022           w->cond_exp_valid_block = innermost_block;
1023         }
1024       else
1025         {
1026           struct bp_location *loc;
1027
1028           for (loc = b->loc; loc; loc = loc->next)
1029             {
1030               arg = exp;
1031               loc->cond =
1032                 parse_exp_1 (&arg, loc->address,
1033                              block_for_pc (loc->address), 0);
1034               if (*arg)
1035                 error (_("Junk at end of expression"));
1036             }
1037         }
1038     }
1039   mark_breakpoint_modified (b);
1040
1041   observer_notify_breakpoint_modified (b);
1042 }
1043
1044 /* Completion for the "condition" command.  */
1045
1046 static VEC (char_ptr) *
1047 condition_completer (struct cmd_list_element *cmd,
1048                      const char *text, const char *word)
1049 {
1050   const char *space;
1051
1052   text = skip_spaces_const (text);
1053   space = skip_to_space_const (text);
1054   if (*space == '\0')
1055     {
1056       int len;
1057       struct breakpoint *b;
1058       VEC (char_ptr) *result = NULL;
1059
1060       if (text[0] == '$')
1061         {
1062           /* We don't support completion of history indices.  */
1063           if (isdigit (text[1]))
1064             return NULL;
1065           return complete_internalvar (&text[1]);
1066         }
1067
1068       /* We're completing the breakpoint number.  */
1069       len = strlen (text);
1070
1071       ALL_BREAKPOINTS (b)
1072         {
1073           char number[50];
1074
1075           xsnprintf (number, sizeof (number), "%d", b->number);
1076
1077           if (strncmp (number, text, len) == 0)
1078             VEC_safe_push (char_ptr, result, xstrdup (number));
1079         }
1080
1081       return result;
1082     }
1083
1084   /* We're completing the expression part.  */
1085   text = skip_spaces_const (space);
1086   return expression_completer (cmd, text, word);
1087 }
1088
1089 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1090
1091 static void
1092 condition_command (char *arg, int from_tty)
1093 {
1094   struct breakpoint *b;
1095   char *p;
1096   int bnum;
1097
1098   if (arg == 0)
1099     error_no_arg (_("breakpoint number"));
1100
1101   p = arg;
1102   bnum = get_number (&p);
1103   if (bnum == 0)
1104     error (_("Bad breakpoint argument: '%s'"), arg);
1105
1106   ALL_BREAKPOINTS (b)
1107     if (b->number == bnum)
1108       {
1109         /* Check if this breakpoint has a "stop" method implemented in an
1110            extension language.  This method and conditions entered into GDB
1111            from the CLI are mutually exclusive.  */
1112         const struct extension_language_defn *extlang
1113           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1114
1115         if (extlang != NULL)
1116           {
1117             error (_("Only one stop condition allowed.  There is currently"
1118                      " a %s stop condition defined for this breakpoint."),
1119                    ext_lang_capitalized_name (extlang));
1120           }
1121         set_breakpoint_condition (b, p, from_tty);
1122
1123         if (is_breakpoint (b))
1124           update_global_location_list (UGLL_MAY_INSERT);
1125
1126         return;
1127       }
1128
1129   error (_("No breakpoint number %d."), bnum);
1130 }
1131
1132 /* Check that COMMAND do not contain commands that are suitable
1133    only for tracepoints and not suitable for ordinary breakpoints.
1134    Throw if any such commands is found.  */
1135
1136 static void
1137 check_no_tracepoint_commands (struct command_line *commands)
1138 {
1139   struct command_line *c;
1140
1141   for (c = commands; c; c = c->next)
1142     {
1143       int i;
1144
1145       if (c->control_type == while_stepping_control)
1146         error (_("The 'while-stepping' command can "
1147                  "only be used for tracepoints"));
1148
1149       for (i = 0; i < c->body_count; ++i)
1150         check_no_tracepoint_commands ((c->body_list)[i]);
1151
1152       /* Not that command parsing removes leading whitespace and comment
1153          lines and also empty lines.  So, we only need to check for
1154          command directly.  */
1155       if (strstr (c->line, "collect ") == c->line)
1156         error (_("The 'collect' command can only be used for tracepoints"));
1157
1158       if (strstr (c->line, "teval ") == c->line)
1159         error (_("The 'teval' command can only be used for tracepoints"));
1160     }
1161 }
1162
1163 /* Encapsulate tests for different types of tracepoints.  */
1164
1165 static int
1166 is_tracepoint_type (enum bptype type)
1167 {
1168   return (type == bp_tracepoint
1169           || type == bp_fast_tracepoint
1170           || type == bp_static_tracepoint);
1171 }
1172
1173 int
1174 is_tracepoint (const struct breakpoint *b)
1175 {
1176   return is_tracepoint_type (b->type);
1177 }
1178
1179 /* A helper function that validates that COMMANDS are valid for a
1180    breakpoint.  This function will throw an exception if a problem is
1181    found.  */
1182
1183 static void
1184 validate_commands_for_breakpoint (struct breakpoint *b,
1185                                   struct command_line *commands)
1186 {
1187   if (is_tracepoint (b))
1188     {
1189       struct tracepoint *t = (struct tracepoint *) b;
1190       struct command_line *c;
1191       struct command_line *while_stepping = 0;
1192
1193       /* Reset the while-stepping step count.  The previous commands
1194          might have included a while-stepping action, while the new
1195          ones might not.  */
1196       t->step_count = 0;
1197
1198       /* We need to verify that each top-level element of commands is
1199          valid for tracepoints, that there's at most one
1200          while-stepping element, and that the while-stepping's body
1201          has valid tracing commands excluding nested while-stepping.
1202          We also need to validate the tracepoint action line in the
1203          context of the tracepoint --- validate_actionline actually
1204          has side effects, like setting the tracepoint's
1205          while-stepping STEP_COUNT, in addition to checking if the
1206          collect/teval actions parse and make sense in the
1207          tracepoint's context.  */
1208       for (c = commands; c; c = c->next)
1209         {
1210           if (c->control_type == while_stepping_control)
1211             {
1212               if (b->type == bp_fast_tracepoint)
1213                 error (_("The 'while-stepping' command "
1214                          "cannot be used for fast tracepoint"));
1215               else if (b->type == bp_static_tracepoint)
1216                 error (_("The 'while-stepping' command "
1217                          "cannot be used for static tracepoint"));
1218
1219               if (while_stepping)
1220                 error (_("The 'while-stepping' command "
1221                          "can be used only once"));
1222               else
1223                 while_stepping = c;
1224             }
1225
1226           validate_actionline (c->line, b);
1227         }
1228       if (while_stepping)
1229         {
1230           struct command_line *c2;
1231
1232           gdb_assert (while_stepping->body_count == 1);
1233           c2 = while_stepping->body_list[0];
1234           for (; c2; c2 = c2->next)
1235             {
1236               if (c2->control_type == while_stepping_control)
1237                 error (_("The 'while-stepping' command cannot be nested"));
1238             }
1239         }
1240     }
1241   else
1242     {
1243       check_no_tracepoint_commands (commands);
1244     }
1245 }
1246
1247 /* Return a vector of all the static tracepoints set at ADDR.  The
1248    caller is responsible for releasing the vector.  */
1249
1250 VEC(breakpoint_p) *
1251 static_tracepoints_here (CORE_ADDR addr)
1252 {
1253   struct breakpoint *b;
1254   VEC(breakpoint_p) *found = 0;
1255   struct bp_location *loc;
1256
1257   ALL_BREAKPOINTS (b)
1258     if (b->type == bp_static_tracepoint)
1259       {
1260         for (loc = b->loc; loc; loc = loc->next)
1261           if (loc->address == addr)
1262             VEC_safe_push(breakpoint_p, found, b);
1263       }
1264
1265   return found;
1266 }
1267
1268 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1269    validate that only allowed commands are included.  */
1270
1271 void
1272 breakpoint_set_commands (struct breakpoint *b, 
1273                          command_line_up &&commands)
1274 {
1275   validate_commands_for_breakpoint (b, commands.get ());
1276
1277   decref_counted_command_line (&b->commands);
1278   b->commands = alloc_counted_command_line (commands.release ());
1279   observer_notify_breakpoint_modified (b);
1280 }
1281
1282 /* Set the internal `silent' flag on the breakpoint.  Note that this
1283    is not the same as the "silent" that may appear in the breakpoint's
1284    commands.  */
1285
1286 void
1287 breakpoint_set_silent (struct breakpoint *b, int silent)
1288 {
1289   int old_silent = b->silent;
1290
1291   b->silent = silent;
1292   if (old_silent != silent)
1293     observer_notify_breakpoint_modified (b);
1294 }
1295
1296 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1297    breakpoint work for any thread.  */
1298
1299 void
1300 breakpoint_set_thread (struct breakpoint *b, int thread)
1301 {
1302   int old_thread = b->thread;
1303
1304   b->thread = thread;
1305   if (old_thread != thread)
1306     observer_notify_breakpoint_modified (b);
1307 }
1308
1309 /* Set the task for this breakpoint.  If TASK is 0, make the
1310    breakpoint work for any task.  */
1311
1312 void
1313 breakpoint_set_task (struct breakpoint *b, int task)
1314 {
1315   int old_task = b->task;
1316
1317   b->task = task;
1318   if (old_task != task)
1319     observer_notify_breakpoint_modified (b);
1320 }
1321
1322 void
1323 check_tracepoint_command (char *line, void *closure)
1324 {
1325   struct breakpoint *b = (struct breakpoint *) closure;
1326
1327   validate_actionline (line, b);
1328 }
1329
1330 /* A structure used to pass information through
1331    map_breakpoint_numbers.  */
1332
1333 struct commands_info
1334 {
1335   /* True if the command was typed at a tty.  */
1336   int from_tty;
1337
1338   /* The breakpoint range spec.  */
1339   const char *arg;
1340
1341   /* Non-NULL if the body of the commands are being read from this
1342      already-parsed command.  */
1343   struct command_line *control;
1344
1345   /* The command lines read from the user, or NULL if they have not
1346      yet been read.  */
1347   struct counted_command_line *cmd;
1348 };
1349
1350 /* A callback for map_breakpoint_numbers that sets the commands for
1351    commands_command.  */
1352
1353 static void
1354 do_map_commands_command (struct breakpoint *b, void *data)
1355 {
1356   struct commands_info *info = (struct commands_info *) data;
1357
1358   if (info->cmd == NULL)
1359     {
1360       command_line_up l;
1361
1362       if (info->control != NULL)
1363         l = copy_command_lines (info->control->body_list[0]);
1364       else
1365         {
1366           struct cleanup *old_chain;
1367           char *str;
1368
1369           str = xstrprintf (_("Type commands for breakpoint(s) "
1370                               "%s, one per line."),
1371                             info->arg);
1372
1373           old_chain = make_cleanup (xfree, str);
1374
1375           l = read_command_lines (str,
1376                                   info->from_tty, 1,
1377                                   (is_tracepoint (b)
1378                                    ? check_tracepoint_command : 0),
1379                                   b);
1380
1381           do_cleanups (old_chain);
1382         }
1383
1384       info->cmd = alloc_counted_command_line (l.release ());
1385     }
1386
1387   /* If a breakpoint was on the list more than once, we don't need to
1388      do anything.  */
1389   if (b->commands != info->cmd)
1390     {
1391       validate_commands_for_breakpoint (b, info->cmd->commands);
1392       incref_counted_command_line (info->cmd);
1393       decref_counted_command_line (&b->commands);
1394       b->commands = info->cmd;
1395       observer_notify_breakpoint_modified (b);
1396     }
1397 }
1398
1399 static void
1400 commands_command_1 (const char *arg, int from_tty,
1401                     struct command_line *control)
1402 {
1403   struct cleanup *cleanups;
1404   struct commands_info info;
1405
1406   info.from_tty = from_tty;
1407   info.control = control;
1408   info.cmd = NULL;
1409   /* If we read command lines from the user, then `info' will hold an
1410      extra reference to the commands that we must clean up.  */
1411   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1412
1413   std::string new_arg;
1414
1415   if (arg == NULL || !*arg)
1416     {
1417       if (breakpoint_count - prev_breakpoint_count > 1)
1418         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1419                                  breakpoint_count);
1420       else if (breakpoint_count > 0)
1421         new_arg = string_printf ("%d", breakpoint_count);
1422     }
1423   else
1424     new_arg = arg;
1425
1426   info.arg = new_arg.c_str ();
1427
1428   map_breakpoint_numbers (info.arg, do_map_commands_command, &info);
1429
1430   if (info.cmd == NULL)
1431     error (_("No breakpoints specified."));
1432
1433   do_cleanups (cleanups);
1434 }
1435
1436 static void
1437 commands_command (char *arg, int from_tty)
1438 {
1439   commands_command_1 (arg, from_tty, NULL);
1440 }
1441
1442 /* Like commands_command, but instead of reading the commands from
1443    input stream, takes them from an already parsed command structure.
1444
1445    This is used by cli-script.c to DTRT with breakpoint commands
1446    that are part of if and while bodies.  */
1447 enum command_control_type
1448 commands_from_control_command (const char *arg, struct command_line *cmd)
1449 {
1450   commands_command_1 (arg, 0, cmd);
1451   return simple_control;
1452 }
1453
1454 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1455
1456 static int
1457 bp_location_has_shadow (struct bp_location *bl)
1458 {
1459   if (bl->loc_type != bp_loc_software_breakpoint)
1460     return 0;
1461   if (!bl->inserted)
1462     return 0;
1463   if (bl->target_info.shadow_len == 0)
1464     /* BL isn't valid, or doesn't shadow memory.  */
1465     return 0;
1466   return 1;
1467 }
1468
1469 /* Update BUF, which is LEN bytes read from the target address
1470    MEMADDR, by replacing a memory breakpoint with its shadowed
1471    contents.
1472
1473    If READBUF is not NULL, this buffer must not overlap with the of
1474    the breakpoint location's shadow_contents buffer.  Otherwise, a
1475    failed assertion internal error will be raised.  */
1476
1477 static void
1478 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1479                             const gdb_byte *writebuf_org,
1480                             ULONGEST memaddr, LONGEST len,
1481                             struct bp_target_info *target_info,
1482                             struct gdbarch *gdbarch)
1483 {
1484   /* Now do full processing of the found relevant range of elements.  */
1485   CORE_ADDR bp_addr = 0;
1486   int bp_size = 0;
1487   int bptoffset = 0;
1488
1489   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1490                                  current_program_space->aspace, 0))
1491     {
1492       /* The breakpoint is inserted in a different address space.  */
1493       return;
1494     }
1495
1496   /* Addresses and length of the part of the breakpoint that
1497      we need to copy.  */
1498   bp_addr = target_info->placed_address;
1499   bp_size = target_info->shadow_len;
1500
1501   if (bp_addr + bp_size <= memaddr)
1502     {
1503       /* The breakpoint is entirely before the chunk of memory we are
1504          reading.  */
1505       return;
1506     }
1507
1508   if (bp_addr >= memaddr + len)
1509     {
1510       /* The breakpoint is entirely after the chunk of memory we are
1511          reading.  */
1512       return;
1513     }
1514
1515   /* Offset within shadow_contents.  */
1516   if (bp_addr < memaddr)
1517     {
1518       /* Only copy the second part of the breakpoint.  */
1519       bp_size -= memaddr - bp_addr;
1520       bptoffset = memaddr - bp_addr;
1521       bp_addr = memaddr;
1522     }
1523
1524   if (bp_addr + bp_size > memaddr + len)
1525     {
1526       /* Only copy the first part of the breakpoint.  */
1527       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1528     }
1529
1530   if (readbuf != NULL)
1531     {
1532       /* Verify that the readbuf buffer does not overlap with the
1533          shadow_contents buffer.  */
1534       gdb_assert (target_info->shadow_contents >= readbuf + len
1535                   || readbuf >= (target_info->shadow_contents
1536                                  + target_info->shadow_len));
1537
1538       /* Update the read buffer with this inserted breakpoint's
1539          shadow.  */
1540       memcpy (readbuf + bp_addr - memaddr,
1541               target_info->shadow_contents + bptoffset, bp_size);
1542     }
1543   else
1544     {
1545       const unsigned char *bp;
1546       CORE_ADDR addr = target_info->reqstd_address;
1547       int placed_size;
1548
1549       /* Update the shadow with what we want to write to memory.  */
1550       memcpy (target_info->shadow_contents + bptoffset,
1551               writebuf_org + bp_addr - memaddr, bp_size);
1552
1553       /* Determine appropriate breakpoint contents and size for this
1554          address.  */
1555       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1556
1557       /* Update the final write buffer with this inserted
1558          breakpoint's INSN.  */
1559       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1560     }
1561 }
1562
1563 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1564    by replacing any memory breakpoints with their shadowed contents.
1565
1566    If READBUF is not NULL, this buffer must not overlap with any of
1567    the breakpoint location's shadow_contents buffers.  Otherwise,
1568    a failed assertion internal error will be raised.
1569
1570    The range of shadowed area by each bp_location is:
1571      bl->address - bp_locations_placed_address_before_address_max
1572      up to bl->address + bp_locations_shadow_len_after_address_max
1573    The range we were requested to resolve shadows for is:
1574      memaddr ... memaddr + len
1575    Thus the safe cutoff boundaries for performance optimization are
1576      memaddr + len <= (bl->address
1577                        - bp_locations_placed_address_before_address_max)
1578    and:
1579      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1580
1581 void
1582 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1583                         const gdb_byte *writebuf_org,
1584                         ULONGEST memaddr, LONGEST len)
1585 {
1586   /* Left boundary, right boundary and median element of our binary
1587      search.  */
1588   unsigned bc_l, bc_r, bc;
1589
1590   /* Find BC_L which is a leftmost element which may affect BUF
1591      content.  It is safe to report lower value but a failure to
1592      report higher one.  */
1593
1594   bc_l = 0;
1595   bc_r = bp_locations_count;
1596   while (bc_l + 1 < bc_r)
1597     {
1598       struct bp_location *bl;
1599
1600       bc = (bc_l + bc_r) / 2;
1601       bl = bp_locations[bc];
1602
1603       /* Check first BL->ADDRESS will not overflow due to the added
1604          constant.  Then advance the left boundary only if we are sure
1605          the BC element can in no way affect the BUF content (MEMADDR
1606          to MEMADDR + LEN range).
1607
1608          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1609          offset so that we cannot miss a breakpoint with its shadow
1610          range tail still reaching MEMADDR.  */
1611
1612       if ((bl->address + bp_locations_shadow_len_after_address_max
1613            >= bl->address)
1614           && (bl->address + bp_locations_shadow_len_after_address_max
1615               <= memaddr))
1616         bc_l = bc;
1617       else
1618         bc_r = bc;
1619     }
1620
1621   /* Due to the binary search above, we need to make sure we pick the
1622      first location that's at BC_L's address.  E.g., if there are
1623      multiple locations at the same address, BC_L may end up pointing
1624      at a duplicate location, and miss the "master"/"inserted"
1625      location.  Say, given locations L1, L2 and L3 at addresses A and
1626      B:
1627
1628       L1@A, L2@A, L3@B, ...
1629
1630      BC_L could end up pointing at location L2, while the "master"
1631      location could be L1.  Since the `loc->inserted' flag is only set
1632      on "master" locations, we'd forget to restore the shadow of L1
1633      and L2.  */
1634   while (bc_l > 0
1635          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1636     bc_l--;
1637
1638   /* Now do full processing of the found relevant range of elements.  */
1639
1640   for (bc = bc_l; bc < bp_locations_count; bc++)
1641   {
1642     struct bp_location *bl = bp_locations[bc];
1643
1644     /* bp_location array has BL->OWNER always non-NULL.  */
1645     if (bl->owner->type == bp_none)
1646       warning (_("reading through apparently deleted breakpoint #%d?"),
1647                bl->owner->number);
1648
1649     /* Performance optimization: any further element can no longer affect BUF
1650        content.  */
1651
1652     if (bl->address >= bp_locations_placed_address_before_address_max
1653         && memaddr + len <= (bl->address
1654                              - bp_locations_placed_address_before_address_max))
1655       break;
1656
1657     if (!bp_location_has_shadow (bl))
1658       continue;
1659
1660     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1661                                 memaddr, len, &bl->target_info, bl->gdbarch);
1662   }
1663 }
1664
1665 \f
1666
1667 /* Return true if BPT is either a software breakpoint or a hardware
1668    breakpoint.  */
1669
1670 int
1671 is_breakpoint (const struct breakpoint *bpt)
1672 {
1673   return (bpt->type == bp_breakpoint
1674           || bpt->type == bp_hardware_breakpoint
1675           || bpt->type == bp_dprintf);
1676 }
1677
1678 /* Return true if BPT is of any hardware watchpoint kind.  */
1679
1680 static int
1681 is_hardware_watchpoint (const struct breakpoint *bpt)
1682 {
1683   return (bpt->type == bp_hardware_watchpoint
1684           || bpt->type == bp_read_watchpoint
1685           || bpt->type == bp_access_watchpoint);
1686 }
1687
1688 /* Return true if BPT is of any watchpoint kind, hardware or
1689    software.  */
1690
1691 int
1692 is_watchpoint (const struct breakpoint *bpt)
1693 {
1694   return (is_hardware_watchpoint (bpt)
1695           || bpt->type == bp_watchpoint);
1696 }
1697
1698 /* Returns true if the current thread and its running state are safe
1699    to evaluate or update watchpoint B.  Watchpoints on local
1700    expressions need to be evaluated in the context of the thread that
1701    was current when the watchpoint was created, and, that thread needs
1702    to be stopped to be able to select the correct frame context.
1703    Watchpoints on global expressions can be evaluated on any thread,
1704    and in any state.  It is presently left to the target allowing
1705    memory accesses when threads are running.  */
1706
1707 static int
1708 watchpoint_in_thread_scope (struct watchpoint *b)
1709 {
1710   return (b->base.pspace == current_program_space
1711           && (ptid_equal (b->watchpoint_thread, null_ptid)
1712               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1713                   && !is_executing (inferior_ptid))));
1714 }
1715
1716 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1717    associated bp_watchpoint_scope breakpoint.  */
1718
1719 static void
1720 watchpoint_del_at_next_stop (struct watchpoint *w)
1721 {
1722   struct breakpoint *b = &w->base;
1723
1724   if (b->related_breakpoint != b)
1725     {
1726       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1727       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1728       b->related_breakpoint->disposition = disp_del_at_next_stop;
1729       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1730       b->related_breakpoint = b;
1731     }
1732   b->disposition = disp_del_at_next_stop;
1733 }
1734
1735 /* Extract a bitfield value from value VAL using the bit parameters contained in
1736    watchpoint W.  */
1737
1738 static struct value *
1739 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1740 {
1741   struct value *bit_val;
1742
1743   if (val == NULL)
1744     return NULL;
1745
1746   bit_val = allocate_value (value_type (val));
1747
1748   unpack_value_bitfield (bit_val,
1749                          w->val_bitpos,
1750                          w->val_bitsize,
1751                          value_contents_for_printing (val),
1752                          value_offset (val),
1753                          val);
1754
1755   return bit_val;
1756 }
1757
1758 /* Allocate a dummy location and add it to B, which must be a software
1759    watchpoint.  This is required because even if a software watchpoint
1760    is not watching any memory, bpstat_stop_status requires a location
1761    to be able to report stops.  */
1762
1763 static void
1764 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1765                                             struct program_space *pspace)
1766 {
1767   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1768
1769   b->loc = allocate_bp_location (b);
1770   b->loc->pspace = pspace;
1771   b->loc->address = -1;
1772   b->loc->length = -1;
1773 }
1774
1775 /* Returns true if B is a software watchpoint that is not watching any
1776    memory (e.g., "watch $pc").  */
1777
1778 static int
1779 is_no_memory_software_watchpoint (struct breakpoint *b)
1780 {
1781   return (b->type == bp_watchpoint
1782           && b->loc != NULL
1783           && b->loc->next == NULL
1784           && b->loc->address == -1
1785           && b->loc->length == -1);
1786 }
1787
1788 /* Assuming that B is a watchpoint:
1789    - Reparse watchpoint expression, if REPARSE is non-zero
1790    - Evaluate expression and store the result in B->val
1791    - Evaluate the condition if there is one, and store the result
1792      in b->loc->cond.
1793    - Update the list of values that must be watched in B->loc.
1794
1795    If the watchpoint disposition is disp_del_at_next_stop, then do
1796    nothing.  If this is local watchpoint that is out of scope, delete
1797    it.
1798
1799    Even with `set breakpoint always-inserted on' the watchpoints are
1800    removed + inserted on each stop here.  Normal breakpoints must
1801    never be removed because they might be missed by a running thread
1802    when debugging in non-stop mode.  On the other hand, hardware
1803    watchpoints (is_hardware_watchpoint; processed here) are specific
1804    to each LWP since they are stored in each LWP's hardware debug
1805    registers.  Therefore, such LWP must be stopped first in order to
1806    be able to modify its hardware watchpoints.
1807
1808    Hardware watchpoints must be reset exactly once after being
1809    presented to the user.  It cannot be done sooner, because it would
1810    reset the data used to present the watchpoint hit to the user.  And
1811    it must not be done later because it could display the same single
1812    watchpoint hit during multiple GDB stops.  Note that the latter is
1813    relevant only to the hardware watchpoint types bp_read_watchpoint
1814    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1815    not user-visible - its hit is suppressed if the memory content has
1816    not changed.
1817
1818    The following constraints influence the location where we can reset
1819    hardware watchpoints:
1820
1821    * target_stopped_by_watchpoint and target_stopped_data_address are
1822      called several times when GDB stops.
1823
1824    [linux] 
1825    * Multiple hardware watchpoints can be hit at the same time,
1826      causing GDB to stop.  GDB only presents one hardware watchpoint
1827      hit at a time as the reason for stopping, and all the other hits
1828      are presented later, one after the other, each time the user
1829      requests the execution to be resumed.  Execution is not resumed
1830      for the threads still having pending hit event stored in
1831      LWP_INFO->STATUS.  While the watchpoint is already removed from
1832      the inferior on the first stop the thread hit event is kept being
1833      reported from its cached value by linux_nat_stopped_data_address
1834      until the real thread resume happens after the watchpoint gets
1835      presented and thus its LWP_INFO->STATUS gets reset.
1836
1837    Therefore the hardware watchpoint hit can get safely reset on the
1838    watchpoint removal from inferior.  */
1839
1840 static void
1841 update_watchpoint (struct watchpoint *b, int reparse)
1842 {
1843   int within_current_scope;
1844   struct frame_id saved_frame_id;
1845   int frame_saved;
1846
1847   /* If this is a local watchpoint, we only want to check if the
1848      watchpoint frame is in scope if the current thread is the thread
1849      that was used to create the watchpoint.  */
1850   if (!watchpoint_in_thread_scope (b))
1851     return;
1852
1853   if (b->base.disposition == disp_del_at_next_stop)
1854     return;
1855  
1856   frame_saved = 0;
1857
1858   /* Determine if the watchpoint is within scope.  */
1859   if (b->exp_valid_block == NULL)
1860     within_current_scope = 1;
1861   else
1862     {
1863       struct frame_info *fi = get_current_frame ();
1864       struct gdbarch *frame_arch = get_frame_arch (fi);
1865       CORE_ADDR frame_pc = get_frame_pc (fi);
1866
1867       /* If we're at a point where the stack has been destroyed
1868          (e.g. in a function epilogue), unwinding may not work
1869          properly. Do not attempt to recreate locations at this
1870          point.  See similar comments in watchpoint_check.  */
1871       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1872         return;
1873
1874       /* Save the current frame's ID so we can restore it after
1875          evaluating the watchpoint expression on its own frame.  */
1876       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1877          took a frame parameter, so that we didn't have to change the
1878          selected frame.  */
1879       frame_saved = 1;
1880       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1881
1882       fi = frame_find_by_id (b->watchpoint_frame);
1883       within_current_scope = (fi != NULL);
1884       if (within_current_scope)
1885         select_frame (fi);
1886     }
1887
1888   /* We don't free locations.  They are stored in the bp_location array
1889      and update_global_location_list will eventually delete them and
1890      remove breakpoints if needed.  */
1891   b->base.loc = NULL;
1892
1893   if (within_current_scope && reparse)
1894     {
1895       const char *s;
1896
1897       b->exp.reset ();
1898       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1899       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1900       /* If the meaning of expression itself changed, the old value is
1901          no longer relevant.  We don't want to report a watchpoint hit
1902          to the user when the old value and the new value may actually
1903          be completely different objects.  */
1904       value_free (b->val);
1905       b->val = NULL;
1906       b->val_valid = 0;
1907
1908       /* Note that unlike with breakpoints, the watchpoint's condition
1909          expression is stored in the breakpoint object, not in the
1910          locations (re)created below.  */
1911       if (b->base.cond_string != NULL)
1912         {
1913           b->cond_exp.reset ();
1914
1915           s = b->base.cond_string;
1916           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1917         }
1918     }
1919
1920   /* If we failed to parse the expression, for example because
1921      it refers to a global variable in a not-yet-loaded shared library,
1922      don't try to insert watchpoint.  We don't automatically delete
1923      such watchpoint, though, since failure to parse expression
1924      is different from out-of-scope watchpoint.  */
1925   if (!target_has_execution)
1926     {
1927       /* Without execution, memory can't change.  No use to try and
1928          set watchpoint locations.  The watchpoint will be reset when
1929          the target gains execution, through breakpoint_re_set.  */
1930       if (!can_use_hw_watchpoints)
1931         {
1932           if (b->base.ops->works_in_software_mode (&b->base))
1933             b->base.type = bp_watchpoint;
1934           else
1935             error (_("Can't set read/access watchpoint when "
1936                      "hardware watchpoints are disabled."));
1937         }
1938     }
1939   else if (within_current_scope && b->exp)
1940     {
1941       int pc = 0;
1942       struct value *val_chain, *v, *result, *next;
1943       struct program_space *frame_pspace;
1944
1945       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1946
1947       /* Avoid setting b->val if it's already set.  The meaning of
1948          b->val is 'the last value' user saw, and we should update
1949          it only if we reported that last value to user.  As it
1950          happens, the code that reports it updates b->val directly.
1951          We don't keep track of the memory value for masked
1952          watchpoints.  */
1953       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1954         {
1955           if (b->val_bitsize != 0)
1956             {
1957               v = extract_bitfield_from_watchpoint_value (b, v);
1958               if (v != NULL)
1959                 release_value (v);
1960             }
1961           b->val = v;
1962           b->val_valid = 1;
1963         }
1964
1965       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1966
1967       /* Look at each value on the value chain.  */
1968       for (v = val_chain; v; v = value_next (v))
1969         {
1970           /* If it's a memory location, and GDB actually needed
1971              its contents to evaluate the expression, then we
1972              must watch it.  If the first value returned is
1973              still lazy, that means an error occurred reading it;
1974              watch it anyway in case it becomes readable.  */
1975           if (VALUE_LVAL (v) == lval_memory
1976               && (v == val_chain || ! value_lazy (v)))
1977             {
1978               struct type *vtype = check_typedef (value_type (v));
1979
1980               /* We only watch structs and arrays if user asked
1981                  for it explicitly, never if they just happen to
1982                  appear in the middle of some value chain.  */
1983               if (v == result
1984                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1985                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1986                 {
1987                   CORE_ADDR addr;
1988                   enum target_hw_bp_type type;
1989                   struct bp_location *loc, **tmp;
1990                   int bitpos = 0, bitsize = 0;
1991
1992                   if (value_bitsize (v) != 0)
1993                     {
1994                       /* Extract the bit parameters out from the bitfield
1995                          sub-expression.  */
1996                       bitpos = value_bitpos (v);
1997                       bitsize = value_bitsize (v);
1998                     }
1999                   else if (v == result && b->val_bitsize != 0)
2000                     {
2001                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2002                         lvalue whose bit parameters are saved in the fields
2003                         VAL_BITPOS and VAL_BITSIZE.  */
2004                       bitpos = b->val_bitpos;
2005                       bitsize = b->val_bitsize;
2006                     }
2007
2008                   addr = value_address (v);
2009                   if (bitsize != 0)
2010                     {
2011                       /* Skip the bytes that don't contain the bitfield.  */
2012                       addr += bitpos / 8;
2013                     }
2014
2015                   type = hw_write;
2016                   if (b->base.type == bp_read_watchpoint)
2017                     type = hw_read;
2018                   else if (b->base.type == bp_access_watchpoint)
2019                     type = hw_access;
2020
2021                   loc = allocate_bp_location (&b->base);
2022                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2023                     ;
2024                   *tmp = loc;
2025                   loc->gdbarch = get_type_arch (value_type (v));
2026
2027                   loc->pspace = frame_pspace;
2028                   loc->address = addr;
2029
2030                   if (bitsize != 0)
2031                     {
2032                       /* Just cover the bytes that make up the bitfield.  */
2033                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2034                     }
2035                   else
2036                     loc->length = TYPE_LENGTH (value_type (v));
2037
2038                   loc->watchpoint_type = type;
2039                 }
2040             }
2041         }
2042
2043       /* Change the type of breakpoint between hardware assisted or
2044          an ordinary watchpoint depending on the hardware support
2045          and free hardware slots.  REPARSE is set when the inferior
2046          is started.  */
2047       if (reparse)
2048         {
2049           int reg_cnt;
2050           enum bp_loc_type loc_type;
2051           struct bp_location *bl;
2052
2053           reg_cnt = can_use_hardware_watchpoint (val_chain);
2054
2055           if (reg_cnt)
2056             {
2057               int i, target_resources_ok, other_type_used;
2058               enum bptype type;
2059
2060               /* Use an exact watchpoint when there's only one memory region to be
2061                  watched, and only one debug register is needed to watch it.  */
2062               b->exact = target_exact_watchpoints && reg_cnt == 1;
2063
2064               /* We need to determine how many resources are already
2065                  used for all other hardware watchpoints plus this one
2066                  to see if we still have enough resources to also fit
2067                  this watchpoint in as well.  */
2068
2069               /* If this is a software watchpoint, we try to turn it
2070                  to a hardware one -- count resources as if B was of
2071                  hardware watchpoint type.  */
2072               type = b->base.type;
2073               if (type == bp_watchpoint)
2074                 type = bp_hardware_watchpoint;
2075
2076               /* This watchpoint may or may not have been placed on
2077                  the list yet at this point (it won't be in the list
2078                  if we're trying to create it for the first time,
2079                  through watch_command), so always account for it
2080                  manually.  */
2081
2082               /* Count resources used by all watchpoints except B.  */
2083               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2084
2085               /* Add in the resources needed for B.  */
2086               i += hw_watchpoint_use_count (&b->base);
2087
2088               target_resources_ok
2089                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2090               if (target_resources_ok <= 0)
2091                 {
2092                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2093
2094                   if (target_resources_ok == 0 && !sw_mode)
2095                     error (_("Target does not support this type of "
2096                              "hardware watchpoint."));
2097                   else if (target_resources_ok < 0 && !sw_mode)
2098                     error (_("There are not enough available hardware "
2099                              "resources for this watchpoint."));
2100
2101                   /* Downgrade to software watchpoint.  */
2102                   b->base.type = bp_watchpoint;
2103                 }
2104               else
2105                 {
2106                   /* If this was a software watchpoint, we've just
2107                      found we have enough resources to turn it to a
2108                      hardware watchpoint.  Otherwise, this is a
2109                      nop.  */
2110                   b->base.type = type;
2111                 }
2112             }
2113           else if (!b->base.ops->works_in_software_mode (&b->base))
2114             {
2115               if (!can_use_hw_watchpoints)
2116                 error (_("Can't set read/access watchpoint when "
2117                          "hardware watchpoints are disabled."));
2118               else
2119                 error (_("Expression cannot be implemented with "
2120                          "read/access watchpoint."));
2121             }
2122           else
2123             b->base.type = bp_watchpoint;
2124
2125           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2126                       : bp_loc_hardware_watchpoint);
2127           for (bl = b->base.loc; bl; bl = bl->next)
2128             bl->loc_type = loc_type;
2129         }
2130
2131       for (v = val_chain; v; v = next)
2132         {
2133           next = value_next (v);
2134           if (v != b->val)
2135             value_free (v);
2136         }
2137
2138       /* If a software watchpoint is not watching any memory, then the
2139          above left it without any location set up.  But,
2140          bpstat_stop_status requires a location to be able to report
2141          stops, so make sure there's at least a dummy one.  */
2142       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2143         software_watchpoint_add_no_memory_location (&b->base, frame_pspace);
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, except if the breakpoint is a single-step breakpoint,
2193      and the breakpoint's thread is the thread which is stepping past
2194      a breakpoint.  */
2195   if ((bl->loc_type == bp_loc_software_breakpoint
2196        || bl->loc_type == bp_loc_hardware_breakpoint)
2197       && stepping_past_instruction_at (bl->pspace->aspace,
2198                                        bl->address)
2199       /* The single-step breakpoint may be inserted at the location
2200          we're trying to step if the instruction branches to itself.
2201          However, the instruction won't be executed at all and it may
2202          break the semantics of the instruction, for example, the
2203          instruction is a conditional branch or updates some flags.
2204          We can't fix it unless GDB is able to emulate the instruction
2205          or switch to displaced stepping.  */
2206       && !(bl->owner->type == bp_single_step
2207            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2208     {
2209       if (debug_infrun)
2210         {
2211           fprintf_unfiltered (gdb_stdlog,
2212                               "infrun: skipping breakpoint: "
2213                               "stepping past insn at: %s\n",
2214                               paddress (bl->gdbarch, bl->address));
2215         }
2216       return 0;
2217     }
2218
2219   /* Don't insert watchpoints if we're trying to step past the
2220      instruction that triggered one.  */
2221   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2222       && stepping_past_nonsteppable_watchpoint ())
2223     {
2224       if (debug_infrun)
2225         {
2226           fprintf_unfiltered (gdb_stdlog,
2227                               "infrun: stepping past non-steppable watchpoint. "
2228                               "skipping watchpoint at %s:%d\n",
2229                               paddress (bl->gdbarch, bl->address),
2230                               bl->length);
2231         }
2232       return 0;
2233     }
2234
2235   return 1;
2236 }
2237
2238 /* Same as should_be_inserted but does the check assuming
2239    that the location is not duplicated.  */
2240
2241 static int
2242 unduplicated_should_be_inserted (struct bp_location *bl)
2243 {
2244   int result;
2245   const int save_duplicate = bl->duplicate;
2246
2247   bl->duplicate = 0;
2248   result = should_be_inserted (bl);
2249   bl->duplicate = save_duplicate;
2250   return result;
2251 }
2252
2253 /* Parses a conditional described by an expression COND into an
2254    agent expression bytecode suitable for evaluation
2255    by the bytecode interpreter.  Return NULL if there was
2256    any error during parsing.  */
2257
2258 static agent_expr_up
2259 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2260 {
2261   if (cond == NULL)
2262     return NULL;
2263
2264   agent_expr_up aexpr;
2265
2266   /* We don't want to stop processing, so catch any errors
2267      that may show up.  */
2268   TRY
2269     {
2270       aexpr = gen_eval_for_expr (scope, cond);
2271     }
2272
2273   CATCH (ex, RETURN_MASK_ERROR)
2274     {
2275       /* If we got here, it means the condition could not be parsed to a valid
2276          bytecode expression and thus can't be evaluated on the target's side.
2277          It's no use iterating through the conditions.  */
2278     }
2279   END_CATCH
2280
2281   /* We have a valid agent expression.  */
2282   return aexpr;
2283 }
2284
2285 /* Based on location BL, create a list of breakpoint conditions to be
2286    passed on to the target.  If we have duplicated locations with different
2287    conditions, we will add such conditions to the list.  The idea is that the
2288    target will evaluate the list of conditions and will only notify GDB when
2289    one of them is true.  */
2290
2291 static void
2292 build_target_condition_list (struct bp_location *bl)
2293 {
2294   struct bp_location **locp = NULL, **loc2p;
2295   int null_condition_or_parse_error = 0;
2296   int modified = bl->needs_update;
2297   struct bp_location *loc;
2298
2299   /* Release conditions left over from a previous insert.  */
2300   bl->target_info.conditions.clear ();
2301
2302   /* This is only meaningful if the target is
2303      evaluating conditions and if the user has
2304      opted for condition evaluation on the target's
2305      side.  */
2306   if (gdb_evaluates_breakpoint_condition_p ()
2307       || !target_supports_evaluation_of_breakpoint_conditions ())
2308     return;
2309
2310   /* Do a first pass to check for locations with no assigned
2311      conditions or conditions that fail to parse to a valid agent expression
2312      bytecode.  If any of these happen, then it's no use to send conditions
2313      to the target since this location will always trigger and generate a
2314      response back to GDB.  */
2315   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2316     {
2317       loc = (*loc2p);
2318       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2319         {
2320           if (modified)
2321             {
2322               /* Re-parse the conditions since something changed.  In that
2323                  case we already freed the condition bytecodes (see
2324                  force_breakpoint_reinsertion).  We just
2325                  need to parse the condition to bytecodes again.  */
2326               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2327                                                         loc->cond.get ());
2328             }
2329
2330           /* If we have a NULL bytecode expression, it means something
2331              went wrong or we have a null condition expression.  */
2332           if (!loc->cond_bytecode)
2333             {
2334               null_condition_or_parse_error = 1;
2335               break;
2336             }
2337         }
2338     }
2339
2340   /* If any of these happened, it means we will have to evaluate the conditions
2341      for the location's address on gdb's side.  It is no use keeping bytecodes
2342      for all the other duplicate locations, thus we free all of them here.
2343
2344      This is so we have a finer control over which locations' conditions are
2345      being evaluated by GDB or the remote stub.  */
2346   if (null_condition_or_parse_error)
2347     {
2348       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2349         {
2350           loc = (*loc2p);
2351           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2352             {
2353               /* Only go as far as the first NULL bytecode is
2354                  located.  */
2355               if (!loc->cond_bytecode)
2356                 return;
2357
2358               loc->cond_bytecode.reset ();
2359             }
2360         }
2361     }
2362
2363   /* No NULL conditions or failed bytecode generation.  Build a condition list
2364      for this location's address.  */
2365   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2366     {
2367       loc = (*loc2p);
2368       if (loc->cond
2369           && is_breakpoint (loc->owner)
2370           && loc->pspace->num == bl->pspace->num
2371           && loc->owner->enable_state == bp_enabled
2372           && loc->enabled)
2373         {
2374           /* Add the condition to the vector.  This will be used later
2375              to send the conditions to the target.  */
2376           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2377         }
2378     }
2379
2380   return;
2381 }
2382
2383 /* Parses a command described by string CMD into an agent expression
2384    bytecode suitable for evaluation by the bytecode interpreter.
2385    Return NULL if there was any error during parsing.  */
2386
2387 static agent_expr_up
2388 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2389 {
2390   struct cleanup *old_cleanups = 0;
2391   struct expression **argvec;
2392   const char *cmdrest;
2393   const char *format_start, *format_end;
2394   struct format_piece *fpieces;
2395   int nargs;
2396   struct gdbarch *gdbarch = get_current_arch ();
2397
2398   if (cmd == NULL)
2399     return NULL;
2400
2401   cmdrest = cmd;
2402
2403   if (*cmdrest == ',')
2404     ++cmdrest;
2405   cmdrest = skip_spaces_const (cmdrest);
2406
2407   if (*cmdrest++ != '"')
2408     error (_("No format string following the location"));
2409
2410   format_start = cmdrest;
2411
2412   fpieces = parse_format_string (&cmdrest);
2413
2414   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2415
2416   format_end = cmdrest;
2417
2418   if (*cmdrest++ != '"')
2419     error (_("Bad format string, non-terminated '\"'."));
2420   
2421   cmdrest = skip_spaces_const (cmdrest);
2422
2423   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2424     error (_("Invalid argument syntax"));
2425
2426   if (*cmdrest == ',')
2427     cmdrest++;
2428   cmdrest = skip_spaces_const (cmdrest);
2429
2430   /* For each argument, make an expression.  */
2431
2432   argvec = (struct expression **) alloca (strlen (cmd)
2433                                          * sizeof (struct expression *));
2434
2435   nargs = 0;
2436   while (*cmdrest != '\0')
2437     {
2438       const char *cmd1;
2439
2440       cmd1 = cmdrest;
2441       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2442       argvec[nargs++] = expr.release ();
2443       cmdrest = cmd1;
2444       if (*cmdrest == ',')
2445         ++cmdrest;
2446     }
2447
2448   agent_expr_up aexpr;
2449
2450   /* We don't want to stop processing, so catch any errors
2451      that may show up.  */
2452   TRY
2453     {
2454       aexpr = gen_printf (scope, gdbarch, 0, 0,
2455                           format_start, format_end - format_start,
2456                           fpieces, nargs, argvec);
2457     }
2458   CATCH (ex, RETURN_MASK_ERROR)
2459     {
2460       /* If we got here, it means the command could not be parsed to a valid
2461          bytecode expression and thus can't be evaluated on the target's side.
2462          It's no use iterating through the other commands.  */
2463     }
2464   END_CATCH
2465
2466   do_cleanups (old_cleanups);
2467
2468   /* We have a valid agent expression, return it.  */
2469   return aexpr;
2470 }
2471
2472 /* Based on location BL, create a list of breakpoint commands to be
2473    passed on to the target.  If we have duplicated locations with
2474    different commands, we will add any such to the list.  */
2475
2476 static void
2477 build_target_command_list (struct bp_location *bl)
2478 {
2479   struct bp_location **locp = NULL, **loc2p;
2480   int null_command_or_parse_error = 0;
2481   int modified = bl->needs_update;
2482   struct bp_location *loc;
2483
2484   /* Clear commands left over from a previous insert.  */
2485   bl->target_info.tcommands.clear ();
2486
2487   if (!target_can_run_breakpoint_commands ())
2488     return;
2489
2490   /* For now, limit to agent-style dprintf breakpoints.  */
2491   if (dprintf_style != dprintf_style_agent)
2492     return;
2493
2494   /* For now, if we have any duplicate location that isn't a dprintf,
2495      don't install the target-side commands, as that would make the
2496      breakpoint not be reported to the core, and we'd lose
2497      control.  */
2498   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2499     {
2500       loc = (*loc2p);
2501       if (is_breakpoint (loc->owner)
2502           && loc->pspace->num == bl->pspace->num
2503           && loc->owner->type != bp_dprintf)
2504         return;
2505     }
2506
2507   /* Do a first pass to check for locations with no assigned
2508      conditions or conditions that fail to parse to a valid agent expression
2509      bytecode.  If any of these happen, then it's no use to send conditions
2510      to the target since this location will always trigger and generate a
2511      response back to GDB.  */
2512   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2513     {
2514       loc = (*loc2p);
2515       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2516         {
2517           if (modified)
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               loc->cmd_bytecode
2524                 = parse_cmd_to_aexpr (bl->address,
2525                                       loc->owner->extra_string);
2526             }
2527
2528           /* If we have a NULL bytecode expression, it means something
2529              went wrong or we have a null command expression.  */
2530           if (!loc->cmd_bytecode)
2531             {
2532               null_command_or_parse_error = 1;
2533               break;
2534             }
2535         }
2536     }
2537
2538   /* If anything failed, then we're not doing target-side commands,
2539      and so clean up.  */
2540   if (null_command_or_parse_error)
2541     {
2542       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2543         {
2544           loc = (*loc2p);
2545           if (is_breakpoint (loc->owner)
2546               && loc->pspace->num == bl->pspace->num)
2547             {
2548               /* Only go as far as the first NULL bytecode is
2549                  located.  */
2550               if (loc->cmd_bytecode == NULL)
2551                 return;
2552
2553               loc->cmd_bytecode.reset ();
2554             }
2555         }
2556     }
2557
2558   /* No NULL commands or failed bytecode generation.  Build a command list
2559      for this location's address.  */
2560   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2561     {
2562       loc = (*loc2p);
2563       if (loc->owner->extra_string
2564           && is_breakpoint (loc->owner)
2565           && loc->pspace->num == bl->pspace->num
2566           && loc->owner->enable_state == bp_enabled
2567           && loc->enabled)
2568         {
2569           /* Add the command to the vector.  This will be used later
2570              to send the commands to the target.  */
2571           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2572         }
2573     }
2574
2575   bl->target_info.persist = 0;
2576   /* Maybe flag this location as persistent.  */
2577   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2578     bl->target_info.persist = 1;
2579 }
2580
2581 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2582    of breakpoint according to ADDR except single-step breakpoint.
2583    Get the kind of single-step breakpoint according to the current
2584    registers state.  */
2585
2586 static int
2587 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2588 {
2589   if (bl->owner->type == bp_single_step)
2590     {
2591       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2592       struct regcache *regcache;
2593
2594       regcache = get_thread_regcache (thr->ptid);
2595
2596       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2597                                                          regcache, addr);
2598     }
2599   else
2600     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2601 }
2602
2603 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2604    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2605    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2606    Returns 0 for success, 1 if the bp_location type is not supported or
2607    -1 for failure.
2608
2609    NOTE drow/2003-09-09: This routine could be broken down to an
2610    object-style method for each breakpoint or catchpoint type.  */
2611 static int
2612 insert_bp_location (struct bp_location *bl,
2613                     struct ui_file *tmp_error_stream,
2614                     int *disabled_breaks,
2615                     int *hw_breakpoint_error,
2616                     int *hw_bp_error_explained_already)
2617 {
2618   enum errors bp_err = GDB_NO_ERROR;
2619   const char *bp_err_message = NULL;
2620
2621   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2622     return 0;
2623
2624   /* Note we don't initialize bl->target_info, as that wipes out
2625      the breakpoint location's shadow_contents if the breakpoint
2626      is still inserted at that location.  This in turn breaks
2627      target_read_memory which depends on these buffers when
2628      a memory read is requested at the breakpoint location:
2629      Once the target_info has been wiped, we fail to see that
2630      we have a breakpoint inserted at that address and thus
2631      read the breakpoint instead of returning the data saved in
2632      the breakpoint location's shadow contents.  */
2633   bl->target_info.reqstd_address = bl->address;
2634   bl->target_info.placed_address_space = bl->pspace->aspace;
2635   bl->target_info.length = bl->length;
2636
2637   /* When working with target-side conditions, we must pass all the conditions
2638      for the same breakpoint address down to the target since GDB will not
2639      insert those locations.  With a list of breakpoint conditions, the target
2640      can decide when to stop and notify GDB.  */
2641
2642   if (is_breakpoint (bl->owner))
2643     {
2644       build_target_condition_list (bl);
2645       build_target_command_list (bl);
2646       /* Reset the modification marker.  */
2647       bl->needs_update = 0;
2648     }
2649
2650   if (bl->loc_type == bp_loc_software_breakpoint
2651       || bl->loc_type == bp_loc_hardware_breakpoint)
2652     {
2653       if (bl->owner->type != bp_hardware_breakpoint)
2654         {
2655           /* If the explicitly specified breakpoint type
2656              is not hardware breakpoint, check the memory map to see
2657              if the breakpoint address is in read only memory or not.
2658
2659              Two important cases are:
2660              - location type is not hardware breakpoint, memory
2661              is readonly.  We change the type of the location to
2662              hardware breakpoint.
2663              - location type is hardware breakpoint, memory is
2664              read-write.  This means we've previously made the
2665              location hardware one, but then the memory map changed,
2666              so we undo.
2667              
2668              When breakpoints are removed, remove_breakpoints will use
2669              location types we've just set here, the only possible
2670              problem is that memory map has changed during running
2671              program, but it's not going to work anyway with current
2672              gdb.  */
2673           struct mem_region *mr 
2674             = lookup_mem_region (bl->target_info.reqstd_address);
2675           
2676           if (mr)
2677             {
2678               if (automatic_hardware_breakpoints)
2679                 {
2680                   enum bp_loc_type new_type;
2681                   
2682                   if (mr->attrib.mode != MEM_RW)
2683                     new_type = bp_loc_hardware_breakpoint;
2684                   else 
2685                     new_type = bp_loc_software_breakpoint;
2686                   
2687                   if (new_type != bl->loc_type)
2688                     {
2689                       static int said = 0;
2690
2691                       bl->loc_type = new_type;
2692                       if (!said)
2693                         {
2694                           fprintf_filtered (gdb_stdout,
2695                                             _("Note: automatically using "
2696                                               "hardware breakpoints for "
2697                                               "read-only addresses.\n"));
2698                           said = 1;
2699                         }
2700                     }
2701                 }
2702               else if (bl->loc_type == bp_loc_software_breakpoint
2703                        && mr->attrib.mode != MEM_RW)
2704                 {
2705                   fprintf_unfiltered (tmp_error_stream,
2706                                       _("Cannot insert breakpoint %d.\n"
2707                                         "Cannot set software breakpoint "
2708                                         "at read-only address %s\n"),
2709                                       bl->owner->number,
2710                                       paddress (bl->gdbarch, bl->address));
2711                   return 1;
2712                 }
2713             }
2714         }
2715         
2716       /* First check to see if we have to handle an overlay.  */
2717       if (overlay_debugging == ovly_off
2718           || bl->section == NULL
2719           || !(section_is_overlay (bl->section)))
2720         {
2721           /* No overlay handling: just set the breakpoint.  */
2722           TRY
2723             {
2724               int val;
2725
2726               val = bl->owner->ops->insert_location (bl);
2727               if (val)
2728                 bp_err = GENERIC_ERROR;
2729             }
2730           CATCH (e, RETURN_MASK_ALL)
2731             {
2732               bp_err = e.error;
2733               bp_err_message = e.message;
2734             }
2735           END_CATCH
2736         }
2737       else
2738         {
2739           /* This breakpoint is in an overlay section.
2740              Shall we set a breakpoint at the LMA?  */
2741           if (!overlay_events_enabled)
2742             {
2743               /* Yes -- overlay event support is not active, 
2744                  so we must try to set a breakpoint at the LMA.
2745                  This will not work for a hardware breakpoint.  */
2746               if (bl->loc_type == bp_loc_hardware_breakpoint)
2747                 warning (_("hardware breakpoint %d not supported in overlay!"),
2748                          bl->owner->number);
2749               else
2750                 {
2751                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2752                                                              bl->section);
2753                   /* Set a software (trap) breakpoint at the LMA.  */
2754                   bl->overlay_target_info = bl->target_info;
2755                   bl->overlay_target_info.reqstd_address = addr;
2756
2757                   /* No overlay handling: just set the breakpoint.  */
2758                   TRY
2759                     {
2760                       int val;
2761
2762                       bl->overlay_target_info.kind
2763                         = breakpoint_kind (bl, &addr);
2764                       bl->overlay_target_info.placed_address = addr;
2765                       val = target_insert_breakpoint (bl->gdbarch,
2766                                                       &bl->overlay_target_info);
2767                       if (val)
2768                         bp_err = GENERIC_ERROR;
2769                     }
2770                   CATCH (e, RETURN_MASK_ALL)
2771                     {
2772                       bp_err = e.error;
2773                       bp_err_message = e.message;
2774                     }
2775                   END_CATCH
2776
2777                   if (bp_err != GDB_NO_ERROR)
2778                     fprintf_unfiltered (tmp_error_stream,
2779                                         "Overlay breakpoint %d "
2780                                         "failed: in ROM?\n",
2781                                         bl->owner->number);
2782                 }
2783             }
2784           /* Shall we set a breakpoint at the VMA? */
2785           if (section_is_mapped (bl->section))
2786             {
2787               /* Yes.  This overlay section is mapped into memory.  */
2788               TRY
2789                 {
2790                   int val;
2791
2792                   val = bl->owner->ops->insert_location (bl);
2793                   if (val)
2794                     bp_err = GENERIC_ERROR;
2795                 }
2796               CATCH (e, RETURN_MASK_ALL)
2797                 {
2798                   bp_err = e.error;
2799                   bp_err_message = e.message;
2800                 }
2801               END_CATCH
2802             }
2803           else
2804             {
2805               /* No.  This breakpoint will not be inserted.  
2806                  No error, but do not mark the bp as 'inserted'.  */
2807               return 0;
2808             }
2809         }
2810
2811       if (bp_err != GDB_NO_ERROR)
2812         {
2813           /* Can't set the breakpoint.  */
2814
2815           /* In some cases, we might not be able to insert a
2816              breakpoint in a shared library that has already been
2817              removed, but we have not yet processed the shlib unload
2818              event.  Unfortunately, some targets that implement
2819              breakpoint insertion themselves can't tell why the
2820              breakpoint insertion failed (e.g., the remote target
2821              doesn't define error codes), so we must treat generic
2822              errors as memory errors.  */
2823           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2824               && bl->loc_type == bp_loc_software_breakpoint
2825               && (solib_name_from_address (bl->pspace, bl->address)
2826                   || shared_objfile_contains_address_p (bl->pspace,
2827                                                         bl->address)))
2828             {
2829               /* See also: disable_breakpoints_in_shlibs.  */
2830               bl->shlib_disabled = 1;
2831               observer_notify_breakpoint_modified (bl->owner);
2832               if (!*disabled_breaks)
2833                 {
2834                   fprintf_unfiltered (tmp_error_stream, 
2835                                       "Cannot insert breakpoint %d.\n", 
2836                                       bl->owner->number);
2837                   fprintf_unfiltered (tmp_error_stream, 
2838                                       "Temporarily disabling shared "
2839                                       "library breakpoints:\n");
2840                 }
2841               *disabled_breaks = 1;
2842               fprintf_unfiltered (tmp_error_stream,
2843                                   "breakpoint #%d\n", bl->owner->number);
2844               return 0;
2845             }
2846           else
2847             {
2848               if (bl->loc_type == bp_loc_hardware_breakpoint)
2849                 {
2850                   *hw_breakpoint_error = 1;
2851                   *hw_bp_error_explained_already = bp_err_message != NULL;
2852                   fprintf_unfiltered (tmp_error_stream,
2853                                       "Cannot insert hardware breakpoint %d%s",
2854                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2855                   if (bp_err_message != NULL)
2856                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2857                 }
2858               else
2859                 {
2860                   if (bp_err_message == NULL)
2861                     {
2862                       char *message
2863                         = memory_error_message (TARGET_XFER_E_IO,
2864                                                 bl->gdbarch, bl->address);
2865                       struct cleanup *old_chain = make_cleanup (xfree, message);
2866
2867                       fprintf_unfiltered (tmp_error_stream,
2868                                           "Cannot insert breakpoint %d.\n"
2869                                           "%s\n",
2870                                           bl->owner->number, message);
2871                       do_cleanups (old_chain);
2872                     }
2873                   else
2874                     {
2875                       fprintf_unfiltered (tmp_error_stream,
2876                                           "Cannot insert breakpoint %d: %s\n",
2877                                           bl->owner->number,
2878                                           bp_err_message);
2879                     }
2880                 }
2881               return 1;
2882
2883             }
2884         }
2885       else
2886         bl->inserted = 1;
2887
2888       return 0;
2889     }
2890
2891   else if (bl->loc_type == bp_loc_hardware_watchpoint
2892            /* NOTE drow/2003-09-08: This state only exists for removing
2893               watchpoints.  It's not clear that it's necessary...  */
2894            && bl->owner->disposition != disp_del_at_next_stop)
2895     {
2896       int val;
2897
2898       gdb_assert (bl->owner->ops != NULL
2899                   && bl->owner->ops->insert_location != NULL);
2900
2901       val = bl->owner->ops->insert_location (bl);
2902
2903       /* If trying to set a read-watchpoint, and it turns out it's not
2904          supported, try emulating one with an access watchpoint.  */
2905       if (val == 1 && bl->watchpoint_type == hw_read)
2906         {
2907           struct bp_location *loc, **loc_temp;
2908
2909           /* But don't try to insert it, if there's already another
2910              hw_access location that would be considered a duplicate
2911              of this one.  */
2912           ALL_BP_LOCATIONS (loc, loc_temp)
2913             if (loc != bl
2914                 && loc->watchpoint_type == hw_access
2915                 && watchpoint_locations_match (bl, loc))
2916               {
2917                 bl->duplicate = 1;
2918                 bl->inserted = 1;
2919                 bl->target_info = loc->target_info;
2920                 bl->watchpoint_type = hw_access;
2921                 val = 0;
2922                 break;
2923               }
2924
2925           if (val == 1)
2926             {
2927               bl->watchpoint_type = hw_access;
2928               val = bl->owner->ops->insert_location (bl);
2929
2930               if (val)
2931                 /* Back to the original value.  */
2932                 bl->watchpoint_type = hw_read;
2933             }
2934         }
2935
2936       bl->inserted = (val == 0);
2937     }
2938
2939   else if (bl->owner->type == bp_catchpoint)
2940     {
2941       int val;
2942
2943       gdb_assert (bl->owner->ops != NULL
2944                   && bl->owner->ops->insert_location != NULL);
2945
2946       val = bl->owner->ops->insert_location (bl);
2947       if (val)
2948         {
2949           bl->owner->enable_state = bp_disabled;
2950
2951           if (val == 1)
2952             warning (_("\
2953 Error inserting catchpoint %d: Your system does not support this type\n\
2954 of catchpoint."), bl->owner->number);
2955           else
2956             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2957         }
2958
2959       bl->inserted = (val == 0);
2960
2961       /* We've already printed an error message if there was a problem
2962          inserting this catchpoint, and we've disabled the catchpoint,
2963          so just return success.  */
2964       return 0;
2965     }
2966
2967   return 0;
2968 }
2969
2970 /* This function is called when program space PSPACE is about to be
2971    deleted.  It takes care of updating breakpoints to not reference
2972    PSPACE anymore.  */
2973
2974 void
2975 breakpoint_program_space_exit (struct program_space *pspace)
2976 {
2977   struct breakpoint *b, *b_temp;
2978   struct bp_location *loc, **loc_temp;
2979
2980   /* Remove any breakpoint that was set through this program space.  */
2981   ALL_BREAKPOINTS_SAFE (b, b_temp)
2982     {
2983       if (b->pspace == pspace)
2984         delete_breakpoint (b);
2985     }
2986
2987   /* Breakpoints set through other program spaces could have locations
2988      bound to PSPACE as well.  Remove those.  */
2989   ALL_BP_LOCATIONS (loc, loc_temp)
2990     {
2991       struct bp_location *tmp;
2992
2993       if (loc->pspace == pspace)
2994         {
2995           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2996           if (loc->owner->loc == loc)
2997             loc->owner->loc = loc->next;
2998           else
2999             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3000               if (tmp->next == loc)
3001                 {
3002                   tmp->next = loc->next;
3003                   break;
3004                 }
3005         }
3006     }
3007
3008   /* Now update the global location list to permanently delete the
3009      removed locations above.  */
3010   update_global_location_list (UGLL_DONT_INSERT);
3011 }
3012
3013 /* Make sure all breakpoints are inserted in inferior.
3014    Throws exception on any error.
3015    A breakpoint that is already inserted won't be inserted
3016    again, so calling this function twice is safe.  */
3017 void
3018 insert_breakpoints (void)
3019 {
3020   struct breakpoint *bpt;
3021
3022   ALL_BREAKPOINTS (bpt)
3023     if (is_hardware_watchpoint (bpt))
3024       {
3025         struct watchpoint *w = (struct watchpoint *) bpt;
3026
3027         update_watchpoint (w, 0 /* don't reparse.  */);
3028       }
3029
3030   /* Updating watchpoints creates new locations, so update the global
3031      location list.  Explicitly tell ugll to insert locations and
3032      ignore breakpoints_always_inserted_mode.  */
3033   update_global_location_list (UGLL_INSERT);
3034 }
3035
3036 /* Invoke CALLBACK for each of bp_location.  */
3037
3038 void
3039 iterate_over_bp_locations (walk_bp_location_callback callback)
3040 {
3041   struct bp_location *loc, **loc_tmp;
3042
3043   ALL_BP_LOCATIONS (loc, loc_tmp)
3044     {
3045       callback (loc, NULL);
3046     }
3047 }
3048
3049 /* This is used when we need to synch breakpoint conditions between GDB and the
3050    target.  It is the case with deleting and disabling of breakpoints when using
3051    always-inserted mode.  */
3052
3053 static void
3054 update_inserted_breakpoint_locations (void)
3055 {
3056   struct bp_location *bl, **blp_tmp;
3057   int error_flag = 0;
3058   int val = 0;
3059   int disabled_breaks = 0;
3060   int hw_breakpoint_error = 0;
3061   int hw_bp_details_reported = 0;
3062
3063   string_file tmp_error_stream;
3064
3065   /* Explicitly mark the warning -- this will only be printed if
3066      there was an error.  */
3067   tmp_error_stream.puts ("Warning:\n");
3068
3069   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3070
3071   ALL_BP_LOCATIONS (bl, blp_tmp)
3072     {
3073       /* We only want to update software breakpoints and hardware
3074          breakpoints.  */
3075       if (!is_breakpoint (bl->owner))
3076         continue;
3077
3078       /* We only want to update locations that are already inserted
3079          and need updating.  This is to avoid unwanted insertion during
3080          deletion of breakpoints.  */
3081       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3082         continue;
3083
3084       switch_to_program_space_and_thread (bl->pspace);
3085
3086       /* For targets that support global breakpoints, there's no need
3087          to select an inferior to insert breakpoint to.  In fact, even
3088          if we aren't attached to any process yet, we should still
3089          insert breakpoints.  */
3090       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3091           && ptid_equal (inferior_ptid, null_ptid))
3092         continue;
3093
3094       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3095                                     &hw_breakpoint_error, &hw_bp_details_reported);
3096       if (val)
3097         error_flag = val;
3098     }
3099
3100   if (error_flag)
3101     {
3102       target_terminal_ours_for_output ();
3103       error_stream (tmp_error_stream);
3104     }
3105 }
3106
3107 /* Used when starting or continuing the program.  */
3108
3109 static void
3110 insert_breakpoint_locations (void)
3111 {
3112   struct breakpoint *bpt;
3113   struct bp_location *bl, **blp_tmp;
3114   int error_flag = 0;
3115   int val = 0;
3116   int disabled_breaks = 0;
3117   int hw_breakpoint_error = 0;
3118   int hw_bp_error_explained_already = 0;
3119
3120   string_file tmp_error_stream;
3121
3122   /* Explicitly mark the warning -- this will only be printed if
3123      there was an error.  */
3124   tmp_error_stream.puts ("Warning:\n");
3125
3126   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3127
3128   ALL_BP_LOCATIONS (bl, blp_tmp)
3129     {
3130       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3131         continue;
3132
3133       /* There is no point inserting thread-specific breakpoints if
3134          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3135          has BL->OWNER always non-NULL.  */
3136       if (bl->owner->thread != -1
3137           && !valid_global_thread_id (bl->owner->thread))
3138         continue;
3139
3140       switch_to_program_space_and_thread (bl->pspace);
3141
3142       /* For targets that support global breakpoints, there's no need
3143          to select an inferior to insert breakpoint to.  In fact, even
3144          if we aren't attached to any process yet, we should still
3145          insert breakpoints.  */
3146       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3147           && ptid_equal (inferior_ptid, null_ptid))
3148         continue;
3149
3150       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3151                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3152       if (val)
3153         error_flag = val;
3154     }
3155
3156   /* If we failed to insert all locations of a watchpoint, remove
3157      them, as half-inserted watchpoint is of limited use.  */
3158   ALL_BREAKPOINTS (bpt)  
3159     {
3160       int some_failed = 0;
3161       struct bp_location *loc;
3162
3163       if (!is_hardware_watchpoint (bpt))
3164         continue;
3165
3166       if (!breakpoint_enabled (bpt))
3167         continue;
3168
3169       if (bpt->disposition == disp_del_at_next_stop)
3170         continue;
3171       
3172       for (loc = bpt->loc; loc; loc = loc->next)
3173         if (!loc->inserted && should_be_inserted (loc))
3174           {
3175             some_failed = 1;
3176             break;
3177           }
3178       if (some_failed)
3179         {
3180           for (loc = bpt->loc; loc; loc = loc->next)
3181             if (loc->inserted)
3182               remove_breakpoint (loc);
3183
3184           hw_breakpoint_error = 1;
3185           tmp_error_stream.printf ("Could not insert "
3186                                    "hardware watchpoint %d.\n",
3187                                    bpt->number);
3188           error_flag = -1;
3189         }
3190     }
3191
3192   if (error_flag)
3193     {
3194       /* If a hardware breakpoint or watchpoint was inserted, add a
3195          message about possibly exhausted resources.  */
3196       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3197         {
3198           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3199 You may have requested too many hardware breakpoints/watchpoints.\n");
3200         }
3201       target_terminal_ours_for_output ();
3202       error_stream (tmp_error_stream);
3203     }
3204 }
3205
3206 /* Used when the program stops.
3207    Returns zero if successful, or non-zero if there was a problem
3208    removing a breakpoint location.  */
3209
3210 int
3211 remove_breakpoints (void)
3212 {
3213   struct bp_location *bl, **blp_tmp;
3214   int val = 0;
3215
3216   ALL_BP_LOCATIONS (bl, blp_tmp)
3217   {
3218     if (bl->inserted && !is_tracepoint (bl->owner))
3219       val |= remove_breakpoint (bl);
3220   }
3221   return val;
3222 }
3223
3224 /* When a thread exits, remove breakpoints that are related to
3225    that thread.  */
3226
3227 static void
3228 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3229 {
3230   struct breakpoint *b, *b_tmp;
3231
3232   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3233     {
3234       if (b->thread == tp->global_num && user_breakpoint_p (b))
3235         {
3236           b->disposition = disp_del_at_next_stop;
3237
3238           printf_filtered (_("\
3239 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3240                            b->number, print_thread_id (tp));
3241
3242           /* Hide it from the user.  */
3243           b->number = 0;
3244        }
3245     }
3246 }
3247
3248 /* Remove breakpoints of process PID.  */
3249
3250 int
3251 remove_breakpoints_pid (int pid)
3252 {
3253   struct bp_location *bl, **blp_tmp;
3254   int val;
3255   struct inferior *inf = find_inferior_pid (pid);
3256
3257   ALL_BP_LOCATIONS (bl, blp_tmp)
3258   {
3259     if (bl->pspace != inf->pspace)
3260       continue;
3261
3262     if (bl->inserted && !bl->target_info.persist)
3263       {
3264         val = remove_breakpoint (bl);
3265         if (val != 0)
3266           return val;
3267       }
3268   }
3269   return 0;
3270 }
3271
3272 int
3273 reattach_breakpoints (int pid)
3274 {
3275   struct cleanup *old_chain;
3276   struct bp_location *bl, **blp_tmp;
3277   int val;
3278   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3279   struct inferior *inf;
3280   struct thread_info *tp;
3281
3282   tp = any_live_thread_of_process (pid);
3283   if (tp == NULL)
3284     return 1;
3285
3286   inf = find_inferior_pid (pid);
3287   old_chain = save_inferior_ptid ();
3288
3289   inferior_ptid = tp->ptid;
3290
3291   string_file tmp_error_stream;
3292
3293   ALL_BP_LOCATIONS (bl, blp_tmp)
3294   {
3295     if (bl->pspace != inf->pspace)
3296       continue;
3297
3298     if (bl->inserted)
3299       {
3300         bl->inserted = 0;
3301         val = insert_bp_location (bl, &tmp_error_stream, &dummy1, &dummy2, &dummy3);
3302         if (val != 0)
3303           {
3304             do_cleanups (old_chain);
3305             return val;
3306           }
3307       }
3308   }
3309   do_cleanups (old_chain);
3310   return 0;
3311 }
3312
3313 static int internal_breakpoint_number = -1;
3314
3315 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3316    If INTERNAL is non-zero, the breakpoint number will be populated
3317    from internal_breakpoint_number and that variable decremented.
3318    Otherwise the breakpoint number will be populated from
3319    breakpoint_count and that value incremented.  Internal breakpoints
3320    do not set the internal var bpnum.  */
3321 static void
3322 set_breakpoint_number (int internal, struct breakpoint *b)
3323 {
3324   if (internal)
3325     b->number = internal_breakpoint_number--;
3326   else
3327     {
3328       set_breakpoint_count (breakpoint_count + 1);
3329       b->number = breakpoint_count;
3330     }
3331 }
3332
3333 static struct breakpoint *
3334 create_internal_breakpoint (struct gdbarch *gdbarch,
3335                             CORE_ADDR address, enum bptype type,
3336                             const struct breakpoint_ops *ops)
3337 {
3338   struct symtab_and_line sal;
3339   struct breakpoint *b;
3340
3341   init_sal (&sal);              /* Initialize to zeroes.  */
3342
3343   sal.pc = address;
3344   sal.section = find_pc_overlay (sal.pc);
3345   sal.pspace = current_program_space;
3346
3347   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3348   b->number = internal_breakpoint_number--;
3349   b->disposition = disp_donttouch;
3350
3351   return b;
3352 }
3353
3354 static const char *const longjmp_names[] =
3355   {
3356     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3357   };
3358 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3359
3360 /* Per-objfile data private to breakpoint.c.  */
3361 struct breakpoint_objfile_data
3362 {
3363   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3364   struct bound_minimal_symbol overlay_msym;
3365
3366   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3367   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3368
3369   /* True if we have looked for longjmp probes.  */
3370   int longjmp_searched;
3371
3372   /* SystemTap probe points for longjmp (if any).  */
3373   VEC (probe_p) *longjmp_probes;
3374
3375   /* Minimal symbol for "std::terminate()" (if any).  */
3376   struct bound_minimal_symbol terminate_msym;
3377
3378   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3379   struct bound_minimal_symbol exception_msym;
3380
3381   /* True if we have looked for exception probes.  */
3382   int exception_searched;
3383
3384   /* SystemTap probe points for unwinding (if any).  */
3385   VEC (probe_p) *exception_probes;
3386 };
3387
3388 static const struct objfile_data *breakpoint_objfile_key;
3389
3390 /* Minimal symbol not found sentinel.  */
3391 static struct minimal_symbol msym_not_found;
3392
3393 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3394
3395 static int
3396 msym_not_found_p (const struct minimal_symbol *msym)
3397 {
3398   return msym == &msym_not_found;
3399 }
3400
3401 /* Return per-objfile data needed by breakpoint.c.
3402    Allocate the data if necessary.  */
3403
3404 static struct breakpoint_objfile_data *
3405 get_breakpoint_objfile_data (struct objfile *objfile)
3406 {
3407   struct breakpoint_objfile_data *bp_objfile_data;
3408
3409   bp_objfile_data = ((struct breakpoint_objfile_data *)
3410                      objfile_data (objfile, breakpoint_objfile_key));
3411   if (bp_objfile_data == NULL)
3412     {
3413       bp_objfile_data =
3414         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3415
3416       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3417       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3418     }
3419   return bp_objfile_data;
3420 }
3421
3422 static void
3423 free_breakpoint_probes (struct objfile *obj, void *data)
3424 {
3425   struct breakpoint_objfile_data *bp_objfile_data
3426     = (struct breakpoint_objfile_data *) data;
3427
3428   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3429   VEC_free (probe_p, bp_objfile_data->exception_probes);
3430 }
3431
3432 static void
3433 create_overlay_event_breakpoint (void)
3434 {
3435   struct objfile *objfile;
3436   const char *const func_name = "_ovly_debug_event";
3437
3438   ALL_OBJFILES (objfile)
3439     {
3440       struct breakpoint *b;
3441       struct breakpoint_objfile_data *bp_objfile_data;
3442       CORE_ADDR addr;
3443       struct explicit_location explicit_loc;
3444
3445       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3446
3447       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3448         continue;
3449
3450       if (bp_objfile_data->overlay_msym.minsym == NULL)
3451         {
3452           struct bound_minimal_symbol m;
3453
3454           m = lookup_minimal_symbol_text (func_name, objfile);
3455           if (m.minsym == NULL)
3456             {
3457               /* Avoid future lookups in this objfile.  */
3458               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3459               continue;
3460             }
3461           bp_objfile_data->overlay_msym = m;
3462         }
3463
3464       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3465       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3466                                       bp_overlay_event,
3467                                       &internal_breakpoint_ops);
3468       initialize_explicit_location (&explicit_loc);
3469       explicit_loc.function_name = ASTRDUP (func_name);
3470       b->location = new_explicit_location (&explicit_loc);
3471
3472       if (overlay_debugging == ovly_auto)
3473         {
3474           b->enable_state = bp_enabled;
3475           overlay_events_enabled = 1;
3476         }
3477       else
3478        {
3479          b->enable_state = bp_disabled;
3480          overlay_events_enabled = 0;
3481        }
3482     }
3483 }
3484
3485 static void
3486 create_longjmp_master_breakpoint (void)
3487 {
3488   struct program_space *pspace;
3489
3490   scoped_restore_current_program_space restore_pspace;
3491
3492   ALL_PSPACES (pspace)
3493   {
3494     struct objfile *objfile;
3495
3496     set_current_program_space (pspace);
3497
3498     ALL_OBJFILES (objfile)
3499     {
3500       int i;
3501       struct gdbarch *gdbarch;
3502       struct breakpoint_objfile_data *bp_objfile_data;
3503
3504       gdbarch = get_objfile_arch (objfile);
3505
3506       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3507
3508       if (!bp_objfile_data->longjmp_searched)
3509         {
3510           VEC (probe_p) *ret;
3511
3512           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3513           if (ret != NULL)
3514             {
3515               /* We are only interested in checking one element.  */
3516               struct probe *p = VEC_index (probe_p, ret, 0);
3517
3518               if (!can_evaluate_probe_arguments (p))
3519                 {
3520                   /* We cannot use the probe interface here, because it does
3521                      not know how to evaluate arguments.  */
3522                   VEC_free (probe_p, ret);
3523                   ret = NULL;
3524                 }
3525             }
3526           bp_objfile_data->longjmp_probes = ret;
3527           bp_objfile_data->longjmp_searched = 1;
3528         }
3529
3530       if (bp_objfile_data->longjmp_probes != NULL)
3531         {
3532           int i;
3533           struct probe *probe;
3534           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3535
3536           for (i = 0;
3537                VEC_iterate (probe_p,
3538                             bp_objfile_data->longjmp_probes,
3539                             i, probe);
3540                ++i)
3541             {
3542               struct breakpoint *b;
3543
3544               b = create_internal_breakpoint (gdbarch,
3545                                               get_probe_address (probe,
3546                                                                  objfile),
3547                                               bp_longjmp_master,
3548                                               &internal_breakpoint_ops);
3549               b->location = new_probe_location ("-probe-stap libc:longjmp");
3550               b->enable_state = bp_disabled;
3551             }
3552
3553           continue;
3554         }
3555
3556       if (!gdbarch_get_longjmp_target_p (gdbarch))
3557         continue;
3558
3559       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3560         {
3561           struct breakpoint *b;
3562           const char *func_name;
3563           CORE_ADDR addr;
3564           struct explicit_location explicit_loc;
3565
3566           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3567             continue;
3568
3569           func_name = longjmp_names[i];
3570           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3571             {
3572               struct bound_minimal_symbol m;
3573
3574               m = lookup_minimal_symbol_text (func_name, objfile);
3575               if (m.minsym == NULL)
3576                 {
3577                   /* Prevent future lookups in this objfile.  */
3578                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3579                   continue;
3580                 }
3581               bp_objfile_data->longjmp_msym[i] = m;
3582             }
3583
3584           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3585           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3586                                           &internal_breakpoint_ops);
3587           initialize_explicit_location (&explicit_loc);
3588           explicit_loc.function_name = ASTRDUP (func_name);
3589           b->location = new_explicit_location (&explicit_loc);
3590           b->enable_state = bp_disabled;
3591         }
3592     }
3593   }
3594 }
3595
3596 /* Create a master std::terminate breakpoint.  */
3597 static void
3598 create_std_terminate_master_breakpoint (void)
3599 {
3600   struct program_space *pspace;
3601   const char *const func_name = "std::terminate()";
3602
3603   scoped_restore_current_program_space restore_pspace;
3604
3605   ALL_PSPACES (pspace)
3606   {
3607     struct objfile *objfile;
3608     CORE_ADDR addr;
3609
3610     set_current_program_space (pspace);
3611
3612     ALL_OBJFILES (objfile)
3613     {
3614       struct breakpoint *b;
3615       struct breakpoint_objfile_data *bp_objfile_data;
3616       struct explicit_location explicit_loc;
3617
3618       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3619
3620       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3621         continue;
3622
3623       if (bp_objfile_data->terminate_msym.minsym == NULL)
3624         {
3625           struct bound_minimal_symbol m;
3626
3627           m = lookup_minimal_symbol (func_name, NULL, objfile);
3628           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3629                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3630             {
3631               /* Prevent future lookups in this objfile.  */
3632               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3633               continue;
3634             }
3635           bp_objfile_data->terminate_msym = m;
3636         }
3637
3638       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3639       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3640                                       bp_std_terminate_master,
3641                                       &internal_breakpoint_ops);
3642       initialize_explicit_location (&explicit_loc);
3643       explicit_loc.function_name = ASTRDUP (func_name);
3644       b->location = new_explicit_location (&explicit_loc);
3645       b->enable_state = bp_disabled;
3646     }
3647   }
3648 }
3649
3650 /* Install a master breakpoint on the unwinder's debug hook.  */
3651
3652 static void
3653 create_exception_master_breakpoint (void)
3654 {
3655   struct objfile *objfile;
3656   const char *const func_name = "_Unwind_DebugHook";
3657
3658   ALL_OBJFILES (objfile)
3659     {
3660       struct breakpoint *b;
3661       struct gdbarch *gdbarch;
3662       struct breakpoint_objfile_data *bp_objfile_data;
3663       CORE_ADDR addr;
3664       struct explicit_location explicit_loc;
3665
3666       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3667
3668       /* We prefer the SystemTap probe point if it exists.  */
3669       if (!bp_objfile_data->exception_searched)
3670         {
3671           VEC (probe_p) *ret;
3672
3673           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3674
3675           if (ret != NULL)
3676             {
3677               /* We are only interested in checking one element.  */
3678               struct probe *p = VEC_index (probe_p, ret, 0);
3679
3680               if (!can_evaluate_probe_arguments (p))
3681                 {
3682                   /* We cannot use the probe interface here, because it does
3683                      not know how to evaluate arguments.  */
3684                   VEC_free (probe_p, ret);
3685                   ret = NULL;
3686                 }
3687             }
3688           bp_objfile_data->exception_probes = ret;
3689           bp_objfile_data->exception_searched = 1;
3690         }
3691
3692       if (bp_objfile_data->exception_probes != NULL)
3693         {
3694           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3695           int i;
3696           struct probe *probe;
3697
3698           for (i = 0;
3699                VEC_iterate (probe_p,
3700                             bp_objfile_data->exception_probes,
3701                             i, probe);
3702                ++i)
3703             {
3704               struct breakpoint *b;
3705
3706               b = create_internal_breakpoint (gdbarch,
3707                                               get_probe_address (probe,
3708                                                                  objfile),
3709                                               bp_exception_master,
3710                                               &internal_breakpoint_ops);
3711               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3712               b->enable_state = bp_disabled;
3713             }
3714
3715           continue;
3716         }
3717
3718       /* Otherwise, try the hook function.  */
3719
3720       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3721         continue;
3722
3723       gdbarch = get_objfile_arch (objfile);
3724
3725       if (bp_objfile_data->exception_msym.minsym == NULL)
3726         {
3727           struct bound_minimal_symbol debug_hook;
3728
3729           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3730           if (debug_hook.minsym == NULL)
3731             {
3732               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3733               continue;
3734             }
3735
3736           bp_objfile_data->exception_msym = debug_hook;
3737         }
3738
3739       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3740       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3741                                                  &current_target);
3742       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3743                                       &internal_breakpoint_ops);
3744       initialize_explicit_location (&explicit_loc);
3745       explicit_loc.function_name = ASTRDUP (func_name);
3746       b->location = new_explicit_location (&explicit_loc);
3747       b->enable_state = bp_disabled;
3748     }
3749 }
3750
3751 /* Does B have a location spec?  */
3752
3753 static int
3754 breakpoint_event_location_empty_p (const struct breakpoint *b)
3755 {
3756   return b->location != NULL && event_location_empty_p (b->location.get ());
3757 }
3758
3759 void
3760 update_breakpoints_after_exec (void)
3761 {
3762   struct breakpoint *b, *b_tmp;
3763   struct bp_location *bploc, **bplocp_tmp;
3764
3765   /* We're about to delete breakpoints from GDB's lists.  If the
3766      INSERTED flag is true, GDB will try to lift the breakpoints by
3767      writing the breakpoints' "shadow contents" back into memory.  The
3768      "shadow contents" are NOT valid after an exec, so GDB should not
3769      do that.  Instead, the target is responsible from marking
3770      breakpoints out as soon as it detects an exec.  We don't do that
3771      here instead, because there may be other attempts to delete
3772      breakpoints after detecting an exec and before reaching here.  */
3773   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3774     if (bploc->pspace == current_program_space)
3775       gdb_assert (!bploc->inserted);
3776
3777   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3778   {
3779     if (b->pspace != current_program_space)
3780       continue;
3781
3782     /* Solib breakpoints must be explicitly reset after an exec().  */
3783     if (b->type == bp_shlib_event)
3784       {
3785         delete_breakpoint (b);
3786         continue;
3787       }
3788
3789     /* JIT breakpoints must be explicitly reset after an exec().  */
3790     if (b->type == bp_jit_event)
3791       {
3792         delete_breakpoint (b);
3793         continue;
3794       }
3795
3796     /* Thread event breakpoints must be set anew after an exec(),
3797        as must overlay event and longjmp master breakpoints.  */
3798     if (b->type == bp_thread_event || b->type == bp_overlay_event
3799         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3800         || b->type == bp_exception_master)
3801       {
3802         delete_breakpoint (b);
3803         continue;
3804       }
3805
3806     /* Step-resume breakpoints are meaningless after an exec().  */
3807     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3808       {
3809         delete_breakpoint (b);
3810         continue;
3811       }
3812
3813     /* Just like single-step breakpoints.  */
3814     if (b->type == bp_single_step)
3815       {
3816         delete_breakpoint (b);
3817         continue;
3818       }
3819
3820     /* Longjmp and longjmp-resume breakpoints are also meaningless
3821        after an exec.  */
3822     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3823         || b->type == bp_longjmp_call_dummy
3824         || b->type == bp_exception || b->type == bp_exception_resume)
3825       {
3826         delete_breakpoint (b);
3827         continue;
3828       }
3829
3830     if (b->type == bp_catchpoint)
3831       {
3832         /* For now, none of the bp_catchpoint breakpoints need to
3833            do anything at this point.  In the future, if some of
3834            the catchpoints need to something, we will need to add
3835            a new method, and call this method from here.  */
3836         continue;
3837       }
3838
3839     /* bp_finish is a special case.  The only way we ought to be able
3840        to see one of these when an exec() has happened, is if the user
3841        caught a vfork, and then said "finish".  Ordinarily a finish just
3842        carries them to the call-site of the current callee, by setting
3843        a temporary bp there and resuming.  But in this case, the finish
3844        will carry them entirely through the vfork & exec.
3845
3846        We don't want to allow a bp_finish to remain inserted now.  But
3847        we can't safely delete it, 'cause finish_command has a handle to
3848        the bp on a bpstat, and will later want to delete it.  There's a
3849        chance (and I've seen it happen) that if we delete the bp_finish
3850        here, that its storage will get reused by the time finish_command
3851        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3852        We really must allow finish_command to delete a bp_finish.
3853
3854        In the absence of a general solution for the "how do we know
3855        it's safe to delete something others may have handles to?"
3856        problem, what we'll do here is just uninsert the bp_finish, and
3857        let finish_command delete it.
3858
3859        (We know the bp_finish is "doomed" in the sense that it's
3860        momentary, and will be deleted as soon as finish_command sees
3861        the inferior stopped.  So it doesn't matter that the bp's
3862        address is probably bogus in the new a.out, unlike e.g., the
3863        solib breakpoints.)  */
3864
3865     if (b->type == bp_finish)
3866       {
3867         continue;
3868       }
3869
3870     /* Without a symbolic address, we have little hope of the
3871        pre-exec() address meaning the same thing in the post-exec()
3872        a.out.  */
3873     if (breakpoint_event_location_empty_p (b))
3874       {
3875         delete_breakpoint (b);
3876         continue;
3877       }
3878   }
3879 }
3880
3881 int
3882 detach_breakpoints (ptid_t ptid)
3883 {
3884   struct bp_location *bl, **blp_tmp;
3885   int val = 0;
3886   struct cleanup *old_chain = save_inferior_ptid ();
3887   struct inferior *inf = current_inferior ();
3888
3889   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3890     error (_("Cannot detach breakpoints of inferior_ptid"));
3891
3892   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3893   inferior_ptid = ptid;
3894   ALL_BP_LOCATIONS (bl, blp_tmp)
3895   {
3896     if (bl->pspace != inf->pspace)
3897       continue;
3898
3899     /* This function must physically remove breakpoints locations
3900        from the specified ptid, without modifying the breakpoint
3901        package's state.  Locations of type bp_loc_other are only
3902        maintained at GDB side.  So, there is no need to remove
3903        these bp_loc_other locations.  Moreover, removing these
3904        would modify the breakpoint package's state.  */
3905     if (bl->loc_type == bp_loc_other)
3906       continue;
3907
3908     if (bl->inserted)
3909       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3910   }
3911
3912   do_cleanups (old_chain);
3913   return val;
3914 }
3915
3916 /* Remove the breakpoint location BL from the current address space.
3917    Note that this is used to detach breakpoints from a child fork.
3918    When we get here, the child isn't in the inferior list, and neither
3919    do we have objects to represent its address space --- we should
3920    *not* look at bl->pspace->aspace here.  */
3921
3922 static int
3923 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3924 {
3925   int val;
3926
3927   /* BL is never in moribund_locations by our callers.  */
3928   gdb_assert (bl->owner != NULL);
3929
3930   /* The type of none suggests that owner is actually deleted.
3931      This should not ever happen.  */
3932   gdb_assert (bl->owner->type != bp_none);
3933
3934   if (bl->loc_type == bp_loc_software_breakpoint
3935       || bl->loc_type == bp_loc_hardware_breakpoint)
3936     {
3937       /* "Normal" instruction breakpoint: either the standard
3938          trap-instruction bp (bp_breakpoint), or a
3939          bp_hardware_breakpoint.  */
3940
3941       /* First check to see if we have to handle an overlay.  */
3942       if (overlay_debugging == ovly_off
3943           || bl->section == NULL
3944           || !(section_is_overlay (bl->section)))
3945         {
3946           /* No overlay handling: just remove the breakpoint.  */
3947
3948           /* If we're trying to uninsert a memory breakpoint that we
3949              know is set in a dynamic object that is marked
3950              shlib_disabled, then either the dynamic object was
3951              removed with "remove-symbol-file" or with
3952              "nosharedlibrary".  In the former case, we don't know
3953              whether another dynamic object might have loaded over the
3954              breakpoint's address -- the user might well let us know
3955              about it next with add-symbol-file (the whole point of
3956              add-symbol-file is letting the user manually maintain a
3957              list of dynamically loaded objects).  If we have the
3958              breakpoint's shadow memory, that is, this is a software
3959              breakpoint managed by GDB, check whether the breakpoint
3960              is still inserted in memory, to avoid overwriting wrong
3961              code with stale saved shadow contents.  Note that HW
3962              breakpoints don't have shadow memory, as they're
3963              implemented using a mechanism that is not dependent on
3964              being able to modify the target's memory, and as such
3965              they should always be removed.  */
3966           if (bl->shlib_disabled
3967               && bl->target_info.shadow_len != 0
3968               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3969             val = 0;
3970           else
3971             val = bl->owner->ops->remove_location (bl, reason);
3972         }
3973       else
3974         {
3975           /* This breakpoint is in an overlay section.
3976              Did we set a breakpoint at the LMA?  */
3977           if (!overlay_events_enabled)
3978               {
3979                 /* Yes -- overlay event support is not active, so we
3980                    should have set a breakpoint at the LMA.  Remove it.  
3981                 */
3982                 /* Ignore any failures: if the LMA is in ROM, we will
3983                    have already warned when we failed to insert it.  */
3984                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3985                   target_remove_hw_breakpoint (bl->gdbarch,
3986                                                &bl->overlay_target_info);
3987                 else
3988                   target_remove_breakpoint (bl->gdbarch,
3989                                             &bl->overlay_target_info,
3990                                             reason);
3991               }
3992           /* Did we set a breakpoint at the VMA? 
3993              If so, we will have marked the breakpoint 'inserted'.  */
3994           if (bl->inserted)
3995             {
3996               /* Yes -- remove it.  Previously we did not bother to
3997                  remove the breakpoint if the section had been
3998                  unmapped, but let's not rely on that being safe.  We
3999                  don't know what the overlay manager might do.  */
4000
4001               /* However, we should remove *software* breakpoints only
4002                  if the section is still mapped, or else we overwrite
4003                  wrong code with the saved shadow contents.  */
4004               if (bl->loc_type == bp_loc_hardware_breakpoint
4005                   || section_is_mapped (bl->section))
4006                 val = bl->owner->ops->remove_location (bl, reason);
4007               else
4008                 val = 0;
4009             }
4010           else
4011             {
4012               /* No -- not inserted, so no need to remove.  No error.  */
4013               val = 0;
4014             }
4015         }
4016
4017       /* In some cases, we might not be able to remove a breakpoint in
4018          a shared library that has already been removed, but we have
4019          not yet processed the shlib unload event.  Similarly for an
4020          unloaded add-symbol-file object - the user might not yet have
4021          had the chance to remove-symbol-file it.  shlib_disabled will
4022          be set if the library/object has already been removed, but
4023          the breakpoint hasn't been uninserted yet, e.g., after
4024          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4025          always-inserted mode.  */
4026       if (val
4027           && (bl->loc_type == bp_loc_software_breakpoint
4028               && (bl->shlib_disabled
4029                   || solib_name_from_address (bl->pspace, bl->address)
4030                   || shared_objfile_contains_address_p (bl->pspace,
4031                                                         bl->address))))
4032         val = 0;
4033
4034       if (val)
4035         return val;
4036       bl->inserted = (reason == DETACH_BREAKPOINT);
4037     }
4038   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4039     {
4040       gdb_assert (bl->owner->ops != NULL
4041                   && bl->owner->ops->remove_location != NULL);
4042
4043       bl->inserted = (reason == DETACH_BREAKPOINT);
4044       bl->owner->ops->remove_location (bl, reason);
4045
4046       /* Failure to remove any of the hardware watchpoints comes here.  */
4047       if (reason == REMOVE_BREAKPOINT && bl->inserted)
4048         warning (_("Could not remove hardware watchpoint %d."),
4049                  bl->owner->number);
4050     }
4051   else if (bl->owner->type == bp_catchpoint
4052            && breakpoint_enabled (bl->owner)
4053            && !bl->duplicate)
4054     {
4055       gdb_assert (bl->owner->ops != NULL
4056                   && bl->owner->ops->remove_location != NULL);
4057
4058       val = bl->owner->ops->remove_location (bl, reason);
4059       if (val)
4060         return val;
4061
4062       bl->inserted = (reason == DETACH_BREAKPOINT);
4063     }
4064
4065   return 0;
4066 }
4067
4068 static int
4069 remove_breakpoint (struct bp_location *bl)
4070 {
4071   /* BL is never in moribund_locations by our callers.  */
4072   gdb_assert (bl->owner != NULL);
4073
4074   /* The type of none suggests that owner is actually deleted.
4075      This should not ever happen.  */
4076   gdb_assert (bl->owner->type != bp_none);
4077
4078   scoped_restore_current_pspace_and_thread restore_pspace_thread;
4079
4080   switch_to_program_space_and_thread (bl->pspace);
4081
4082   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4083 }
4084
4085 /* Clear the "inserted" flag in all breakpoints.  */
4086
4087 void
4088 mark_breakpoints_out (void)
4089 {
4090   struct bp_location *bl, **blp_tmp;
4091
4092   ALL_BP_LOCATIONS (bl, blp_tmp)
4093     if (bl->pspace == current_program_space)
4094       bl->inserted = 0;
4095 }
4096
4097 /* Clear the "inserted" flag in all breakpoints and delete any
4098    breakpoints which should go away between runs of the program.
4099
4100    Plus other such housekeeping that has to be done for breakpoints
4101    between runs.
4102
4103    Note: this function gets called at the end of a run (by
4104    generic_mourn_inferior) and when a run begins (by
4105    init_wait_for_inferior).  */
4106
4107
4108
4109 void
4110 breakpoint_init_inferior (enum inf_context context)
4111 {
4112   struct breakpoint *b, *b_tmp;
4113   struct bp_location *bl;
4114   int ix;
4115   struct program_space *pspace = current_program_space;
4116
4117   /* If breakpoint locations are shared across processes, then there's
4118      nothing to do.  */
4119   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4120     return;
4121
4122   mark_breakpoints_out ();
4123
4124   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4125   {
4126     if (b->loc && b->loc->pspace != pspace)
4127       continue;
4128
4129     switch (b->type)
4130       {
4131       case bp_call_dummy:
4132       case bp_longjmp_call_dummy:
4133
4134         /* If the call dummy breakpoint is at the entry point it will
4135            cause problems when the inferior is rerun, so we better get
4136            rid of it.  */
4137
4138       case bp_watchpoint_scope:
4139
4140         /* Also get rid of scope breakpoints.  */
4141
4142       case bp_shlib_event:
4143
4144         /* Also remove solib event breakpoints.  Their addresses may
4145            have changed since the last time we ran the program.
4146            Actually we may now be debugging against different target;
4147            and so the solib backend that installed this breakpoint may
4148            not be used in by the target.  E.g.,
4149
4150            (gdb) file prog-linux
4151            (gdb) run               # native linux target
4152            ...
4153            (gdb) kill
4154            (gdb) file prog-win.exe
4155            (gdb) tar rem :9999     # remote Windows gdbserver.
4156         */
4157
4158       case bp_step_resume:
4159
4160         /* Also remove step-resume breakpoints.  */
4161
4162       case bp_single_step:
4163
4164         /* Also remove single-step breakpoints.  */
4165
4166         delete_breakpoint (b);
4167         break;
4168
4169       case bp_watchpoint:
4170       case bp_hardware_watchpoint:
4171       case bp_read_watchpoint:
4172       case bp_access_watchpoint:
4173         {
4174           struct watchpoint *w = (struct watchpoint *) b;
4175
4176           /* Likewise for watchpoints on local expressions.  */
4177           if (w->exp_valid_block != NULL)
4178             delete_breakpoint (b);
4179           else
4180             {
4181               /* Get rid of existing locations, which are no longer
4182                  valid.  New ones will be created in
4183                  update_watchpoint, when the inferior is restarted.
4184                  The next update_global_location_list call will
4185                  garbage collect them.  */
4186               b->loc = NULL;
4187
4188               if (context == inf_starting)
4189                 {
4190                   /* Reset val field to force reread of starting value in
4191                      insert_breakpoints.  */
4192                   if (w->val)
4193                     value_free (w->val);
4194                   w->val = NULL;
4195                   w->val_valid = 0;
4196                 }
4197             }
4198         }
4199         break;
4200       default:
4201         break;
4202       }
4203   }
4204
4205   /* Get rid of the moribund locations.  */
4206   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4207     decref_bp_location (&bl);
4208   VEC_free (bp_location_p, moribund_locations);
4209 }
4210
4211 /* These functions concern about actual breakpoints inserted in the
4212    target --- to e.g. check if we need to do decr_pc adjustment or if
4213    we need to hop over the bkpt --- so we check for address space
4214    match, not program space.  */
4215
4216 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4217    exists at PC.  It returns ordinary_breakpoint_here if it's an
4218    ordinary breakpoint, or permanent_breakpoint_here if it's a
4219    permanent breakpoint.
4220    - When continuing from a location with an ordinary breakpoint, we
4221      actually single step once before calling insert_breakpoints.
4222    - When continuing from a location with a permanent breakpoint, we
4223      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4224      the target, to advance the PC past the breakpoint.  */
4225
4226 enum breakpoint_here
4227 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4228 {
4229   struct bp_location *bl, **blp_tmp;
4230   int any_breakpoint_here = 0;
4231
4232   ALL_BP_LOCATIONS (bl, blp_tmp)
4233     {
4234       if (bl->loc_type != bp_loc_software_breakpoint
4235           && bl->loc_type != bp_loc_hardware_breakpoint)
4236         continue;
4237
4238       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4239       if ((breakpoint_enabled (bl->owner)
4240            || bl->permanent)
4241           && breakpoint_location_address_match (bl, aspace, pc))
4242         {
4243           if (overlay_debugging 
4244               && section_is_overlay (bl->section)
4245               && !section_is_mapped (bl->section))
4246             continue;           /* unmapped overlay -- can't be a match */
4247           else if (bl->permanent)
4248             return permanent_breakpoint_here;
4249           else
4250             any_breakpoint_here = 1;
4251         }
4252     }
4253
4254   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4255 }
4256
4257 /* See breakpoint.h.  */
4258
4259 int
4260 breakpoint_in_range_p (struct address_space *aspace,
4261                        CORE_ADDR addr, ULONGEST len)
4262 {
4263   struct bp_location *bl, **blp_tmp;
4264
4265   ALL_BP_LOCATIONS (bl, blp_tmp)
4266     {
4267       if (bl->loc_type != bp_loc_software_breakpoint
4268           && bl->loc_type != bp_loc_hardware_breakpoint)
4269         continue;
4270
4271       if ((breakpoint_enabled (bl->owner)
4272            || bl->permanent)
4273           && breakpoint_location_address_range_overlap (bl, aspace,
4274                                                         addr, len))
4275         {
4276           if (overlay_debugging
4277               && section_is_overlay (bl->section)
4278               && !section_is_mapped (bl->section))
4279             {
4280               /* Unmapped overlay -- can't be a match.  */
4281               continue;
4282             }
4283
4284           return 1;
4285         }
4286     }
4287
4288   return 0;
4289 }
4290
4291 /* Return true if there's a moribund breakpoint at PC.  */
4292
4293 int
4294 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4295 {
4296   struct bp_location *loc;
4297   int ix;
4298
4299   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4300     if (breakpoint_location_address_match (loc, aspace, pc))
4301       return 1;
4302
4303   return 0;
4304 }
4305
4306 /* Returns non-zero iff BL is inserted at PC, in address space
4307    ASPACE.  */
4308
4309 static int
4310 bp_location_inserted_here_p (struct bp_location *bl,
4311                              struct address_space *aspace, CORE_ADDR pc)
4312 {
4313   if (bl->inserted
4314       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4315                                    aspace, pc))
4316     {
4317       if (overlay_debugging
4318           && section_is_overlay (bl->section)
4319           && !section_is_mapped (bl->section))
4320         return 0;               /* unmapped overlay -- can't be a match */
4321       else
4322         return 1;
4323     }
4324   return 0;
4325 }
4326
4327 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4328
4329 int
4330 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4331 {
4332   struct bp_location **blp, **blp_tmp = NULL;
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_software_breakpoint
4339           && bl->loc_type != bp_loc_hardware_breakpoint)
4340         continue;
4341
4342       if (bp_location_inserted_here_p (bl, aspace, pc))
4343         return 1;
4344     }
4345   return 0;
4346 }
4347
4348 /* This function returns non-zero iff there is a software breakpoint
4349    inserted at PC.  */
4350
4351 int
4352 software_breakpoint_inserted_here_p (struct address_space *aspace,
4353                                      CORE_ADDR pc)
4354 {
4355   struct bp_location **blp, **blp_tmp = NULL;
4356
4357   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4358     {
4359       struct bp_location *bl = *blp;
4360
4361       if (bl->loc_type != bp_loc_software_breakpoint)
4362         continue;
4363
4364       if (bp_location_inserted_here_p (bl, aspace, pc))
4365         return 1;
4366     }
4367
4368   return 0;
4369 }
4370
4371 /* See breakpoint.h.  */
4372
4373 int
4374 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4375                                      CORE_ADDR pc)
4376 {
4377   struct bp_location **blp, **blp_tmp = NULL;
4378
4379   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4380     {
4381       struct bp_location *bl = *blp;
4382
4383       if (bl->loc_type != bp_loc_hardware_breakpoint)
4384         continue;
4385
4386       if (bp_location_inserted_here_p (bl, aspace, pc))
4387         return 1;
4388     }
4389
4390   return 0;
4391 }
4392
4393 int
4394 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4395                                        CORE_ADDR addr, ULONGEST len)
4396 {
4397   struct breakpoint *bpt;
4398
4399   ALL_BREAKPOINTS (bpt)
4400     {
4401       struct bp_location *loc;
4402
4403       if (bpt->type != bp_hardware_watchpoint
4404           && bpt->type != bp_access_watchpoint)
4405         continue;
4406
4407       if (!breakpoint_enabled (bpt))
4408         continue;
4409
4410       for (loc = bpt->loc; loc; loc = loc->next)
4411         if (loc->pspace->aspace == aspace && loc->inserted)
4412           {
4413             CORE_ADDR l, h;
4414
4415             /* Check for intersection.  */
4416             l = std::max<CORE_ADDR> (loc->address, addr);
4417             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4418             if (l < h)
4419               return 1;
4420           }
4421     }
4422   return 0;
4423 }
4424 \f
4425
4426 /* bpstat stuff.  External routines' interfaces are documented
4427    in breakpoint.h.  */
4428
4429 int
4430 is_catchpoint (struct breakpoint *ep)
4431 {
4432   return (ep->type == bp_catchpoint);
4433 }
4434
4435 /* Frees any storage that is part of a bpstat.  Does not walk the
4436    'next' chain.  */
4437
4438 static void
4439 bpstat_free (bpstat bs)
4440 {
4441   if (bs->old_val != NULL)
4442     value_free (bs->old_val);
4443   decref_counted_command_line (&bs->commands);
4444   decref_bp_location (&bs->bp_location_at);
4445   xfree (bs);
4446 }
4447
4448 /* Clear a bpstat so that it says we are not at any breakpoint.
4449    Also free any storage that is part of a bpstat.  */
4450
4451 void
4452 bpstat_clear (bpstat *bsp)
4453 {
4454   bpstat p;
4455   bpstat q;
4456
4457   if (bsp == 0)
4458     return;
4459   p = *bsp;
4460   while (p != NULL)
4461     {
4462       q = p->next;
4463       bpstat_free (p);
4464       p = q;
4465     }
4466   *bsp = NULL;
4467 }
4468
4469 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4470    is part of the bpstat is copied as well.  */
4471
4472 bpstat
4473 bpstat_copy (bpstat bs)
4474 {
4475   bpstat p = NULL;
4476   bpstat tmp;
4477   bpstat retval = NULL;
4478
4479   if (bs == NULL)
4480     return bs;
4481
4482   for (; bs != NULL; bs = bs->next)
4483     {
4484       tmp = (bpstat) xmalloc (sizeof (*tmp));
4485       memcpy (tmp, bs, sizeof (*tmp));
4486       incref_counted_command_line (tmp->commands);
4487       incref_bp_location (tmp->bp_location_at);
4488       if (bs->old_val != NULL)
4489         {
4490           tmp->old_val = value_copy (bs->old_val);
4491           release_value (tmp->old_val);
4492         }
4493
4494       if (p == NULL)
4495         /* This is the first thing in the chain.  */
4496         retval = tmp;
4497       else
4498         p->next = tmp;
4499       p = tmp;
4500     }
4501   p->next = NULL;
4502   return retval;
4503 }
4504
4505 /* Find the bpstat associated with this breakpoint.  */
4506
4507 bpstat
4508 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4509 {
4510   if (bsp == NULL)
4511     return NULL;
4512
4513   for (; bsp != NULL; bsp = bsp->next)
4514     {
4515       if (bsp->breakpoint_at == breakpoint)
4516         return bsp;
4517     }
4518   return NULL;
4519 }
4520
4521 /* See breakpoint.h.  */
4522
4523 int
4524 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4525 {
4526   for (; bsp != NULL; bsp = bsp->next)
4527     {
4528       if (bsp->breakpoint_at == NULL)
4529         {
4530           /* A moribund location can never explain a signal other than
4531              GDB_SIGNAL_TRAP.  */
4532           if (sig == GDB_SIGNAL_TRAP)
4533             return 1;
4534         }
4535       else
4536         {
4537           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4538                                                         sig))
4539             return 1;
4540         }
4541     }
4542
4543   return 0;
4544 }
4545
4546 /* Put in *NUM the breakpoint number of the first breakpoint we are
4547    stopped at.  *BSP upon return is a bpstat which points to the
4548    remaining breakpoints stopped at (but which is not guaranteed to be
4549    good for anything but further calls to bpstat_num).
4550
4551    Return 0 if passed a bpstat which does not indicate any breakpoints.
4552    Return -1 if stopped at a breakpoint that has been deleted since
4553    we set it.
4554    Return 1 otherwise.  */
4555
4556 int
4557 bpstat_num (bpstat *bsp, int *num)
4558 {
4559   struct breakpoint *b;
4560
4561   if ((*bsp) == NULL)
4562     return 0;                   /* No more breakpoint values */
4563
4564   /* We assume we'll never have several bpstats that correspond to a
4565      single breakpoint -- otherwise, this function might return the
4566      same number more than once and this will look ugly.  */
4567   b = (*bsp)->breakpoint_at;
4568   *bsp = (*bsp)->next;
4569   if (b == NULL)
4570     return -1;                  /* breakpoint that's been deleted since */
4571
4572   *num = b->number;             /* We have its number */
4573   return 1;
4574 }
4575
4576 /* See breakpoint.h.  */
4577
4578 void
4579 bpstat_clear_actions (void)
4580 {
4581   struct thread_info *tp;
4582   bpstat bs;
4583
4584   if (ptid_equal (inferior_ptid, null_ptid))
4585     return;
4586
4587   tp = find_thread_ptid (inferior_ptid);
4588   if (tp == NULL)
4589     return;
4590
4591   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4592     {
4593       decref_counted_command_line (&bs->commands);
4594
4595       if (bs->old_val != NULL)
4596         {
4597           value_free (bs->old_val);
4598           bs->old_val = NULL;
4599         }
4600     }
4601 }
4602
4603 /* Called when a command is about to proceed the inferior.  */
4604
4605 static void
4606 breakpoint_about_to_proceed (void)
4607 {
4608   if (!ptid_equal (inferior_ptid, null_ptid))
4609     {
4610       struct thread_info *tp = inferior_thread ();
4611
4612       /* Allow inferior function calls in breakpoint commands to not
4613          interrupt the command list.  When the call finishes
4614          successfully, the inferior will be standing at the same
4615          breakpoint as if nothing happened.  */
4616       if (tp->control.in_infcall)
4617         return;
4618     }
4619
4620   breakpoint_proceeded = 1;
4621 }
4622
4623 /* Stub for cleaning up our state if we error-out of a breakpoint
4624    command.  */
4625 static void
4626 cleanup_executing_breakpoints (void *ignore)
4627 {
4628   executing_breakpoint_commands = 0;
4629 }
4630
4631 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4632    or its equivalent.  */
4633
4634 static int
4635 command_line_is_silent (struct command_line *cmd)
4636 {
4637   return cmd && (strcmp ("silent", cmd->line) == 0);
4638 }
4639
4640 /* Execute all the commands associated with all the breakpoints at
4641    this location.  Any of these commands could cause the process to
4642    proceed beyond this point, etc.  We look out for such changes by
4643    checking the global "breakpoint_proceeded" after each command.
4644
4645    Returns true if a breakpoint command resumed the inferior.  In that
4646    case, it is the caller's responsibility to recall it again with the
4647    bpstat of the current thread.  */
4648
4649 static int
4650 bpstat_do_actions_1 (bpstat *bsp)
4651 {
4652   bpstat bs;
4653   struct cleanup *old_chain;
4654   int again = 0;
4655
4656   /* Avoid endless recursion if a `source' command is contained
4657      in bs->commands.  */
4658   if (executing_breakpoint_commands)
4659     return 0;
4660
4661   executing_breakpoint_commands = 1;
4662   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4663
4664   scoped_restore preventer = prevent_dont_repeat ();
4665
4666   /* This pointer will iterate over the list of bpstat's.  */
4667   bs = *bsp;
4668
4669   breakpoint_proceeded = 0;
4670   for (; bs != NULL; bs = bs->next)
4671     {
4672       struct counted_command_line *ccmd;
4673       struct command_line *cmd;
4674       struct cleanup *this_cmd_tree_chain;
4675
4676       /* Take ownership of the BSP's command tree, if it has one.
4677
4678          The command tree could legitimately contain commands like
4679          'step' and 'next', which call clear_proceed_status, which
4680          frees stop_bpstat's command tree.  To make sure this doesn't
4681          free the tree we're executing out from under us, we need to
4682          take ownership of the tree ourselves.  Since a given bpstat's
4683          commands are only executed once, we don't need to copy it; we
4684          can clear the pointer in the bpstat, and make sure we free
4685          the tree when we're done.  */
4686       ccmd = bs->commands;
4687       bs->commands = NULL;
4688       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4689       cmd = ccmd ? ccmd->commands : NULL;
4690       if (command_line_is_silent (cmd))
4691         {
4692           /* The action has been already done by bpstat_stop_status.  */
4693           cmd = cmd->next;
4694         }
4695
4696       while (cmd != NULL)
4697         {
4698           execute_control_command (cmd);
4699
4700           if (breakpoint_proceeded)
4701             break;
4702           else
4703             cmd = cmd->next;
4704         }
4705
4706       /* We can free this command tree now.  */
4707       do_cleanups (this_cmd_tree_chain);
4708
4709       if (breakpoint_proceeded)
4710         {
4711           if (current_ui->async)
4712             /* If we are in async mode, then the target might be still
4713                running, not stopped at any breakpoint, so nothing for
4714                us to do here -- just return to the event loop.  */
4715             ;
4716           else
4717             /* In sync mode, when execute_control_command returns
4718                we're already standing on the next breakpoint.
4719                Breakpoint commands for that stop were not run, since
4720                execute_command does not run breakpoint commands --
4721                only command_line_handler does, but that one is not
4722                involved in execution of breakpoint commands.  So, we
4723                can now execute breakpoint commands.  It should be
4724                noted that making execute_command do bpstat actions is
4725                not an option -- in this case we'll have recursive
4726                invocation of bpstat for each breakpoint with a
4727                command, and can easily blow up GDB stack.  Instead, we
4728                return true, which will trigger the caller to recall us
4729                with the new stop_bpstat.  */
4730             again = 1;
4731           break;
4732         }
4733     }
4734   do_cleanups (old_chain);
4735   return again;
4736 }
4737
4738 void
4739 bpstat_do_actions (void)
4740 {
4741   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4742
4743   /* Do any commands attached to breakpoint we are stopped at.  */
4744   while (!ptid_equal (inferior_ptid, null_ptid)
4745          && target_has_execution
4746          && !is_exited (inferior_ptid)
4747          && !is_executing (inferior_ptid))
4748     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4749        and only return when it is stopped at the next breakpoint, we
4750        keep doing breakpoint actions until it returns false to
4751        indicate the inferior was not resumed.  */
4752     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4753       break;
4754
4755   discard_cleanups (cleanup_if_error);
4756 }
4757
4758 /* Print out the (old or new) value associated with a watchpoint.  */
4759
4760 static void
4761 watchpoint_value_print (struct value *val, struct ui_file *stream)
4762 {
4763   if (val == NULL)
4764     fprintf_unfiltered (stream, _("<unreadable>"));
4765   else
4766     {
4767       struct value_print_options opts;
4768       get_user_print_options (&opts);
4769       value_print (val, stream, &opts);
4770     }
4771 }
4772
4773 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4774    debugging multiple threads.  */
4775
4776 void
4777 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4778 {
4779   if (uiout->is_mi_like_p ())
4780     return;
4781
4782   uiout->text ("\n");
4783
4784   if (show_thread_that_caused_stop ())
4785     {
4786       const char *name;
4787       struct thread_info *thr = inferior_thread ();
4788
4789       uiout->text ("Thread ");
4790       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4791
4792       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4793       if (name != NULL)
4794         {
4795           uiout->text (" \"");
4796           uiout->field_fmt ("name", "%s", name);
4797           uiout->text ("\"");
4798         }
4799
4800       uiout->text (" hit ");
4801     }
4802 }
4803
4804 /* Generic routine for printing messages indicating why we
4805    stopped.  The behavior of this function depends on the value
4806    'print_it' in the bpstat structure.  Under some circumstances we
4807    may decide not to print anything here and delegate the task to
4808    normal_stop().  */
4809
4810 static enum print_stop_action
4811 print_bp_stop_message (bpstat bs)
4812 {
4813   switch (bs->print_it)
4814     {
4815     case print_it_noop:
4816       /* Nothing should be printed for this bpstat entry.  */
4817       return PRINT_UNKNOWN;
4818       break;
4819
4820     case print_it_done:
4821       /* We still want to print the frame, but we already printed the
4822          relevant messages.  */
4823       return PRINT_SRC_AND_LOC;
4824       break;
4825
4826     case print_it_normal:
4827       {
4828         struct breakpoint *b = bs->breakpoint_at;
4829
4830         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4831            which has since been deleted.  */
4832         if (b == NULL)
4833           return PRINT_UNKNOWN;
4834
4835         /* Normal case.  Call the breakpoint's print_it method.  */
4836         return b->ops->print_it (bs);
4837       }
4838       break;
4839
4840     default:
4841       internal_error (__FILE__, __LINE__,
4842                       _("print_bp_stop_message: unrecognized enum value"));
4843       break;
4844     }
4845 }
4846
4847 /* A helper function that prints a shared library stopped event.  */
4848
4849 static void
4850 print_solib_event (int is_catchpoint)
4851 {
4852   int any_deleted
4853     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4854   int any_added
4855     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4856
4857   if (!is_catchpoint)
4858     {
4859       if (any_added || any_deleted)
4860         current_uiout->text (_("Stopped due to shared library event:\n"));
4861       else
4862         current_uiout->text (_("Stopped due to shared library event (no "
4863                                "libraries added or removed)\n"));
4864     }
4865
4866   if (current_uiout->is_mi_like_p ())
4867     current_uiout->field_string ("reason",
4868                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4869
4870   if (any_deleted)
4871     {
4872       char *name;
4873       int ix;
4874
4875       current_uiout->text (_("  Inferior unloaded "));
4876       ui_out_emit_list list_emitter (current_uiout, "removed");
4877       for (ix = 0;
4878            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4879                         ix, name);
4880            ++ix)
4881         {
4882           if (ix > 0)
4883             current_uiout->text ("    ");
4884           current_uiout->field_string ("library", name);
4885           current_uiout->text ("\n");
4886         }
4887     }
4888
4889   if (any_added)
4890     {
4891       struct so_list *iter;
4892       int ix;
4893
4894       current_uiout->text (_("  Inferior loaded "));
4895       ui_out_emit_list list_emitter (current_uiout, "added");
4896       for (ix = 0;
4897            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4898                         ix, iter);
4899            ++ix)
4900         {
4901           if (ix > 0)
4902             current_uiout->text ("    ");
4903           current_uiout->field_string ("library", iter->so_name);
4904           current_uiout->text ("\n");
4905         }
4906     }
4907 }
4908
4909 /* Print a message indicating what happened.  This is called from
4910    normal_stop().  The input to this routine is the head of the bpstat
4911    list - a list of the eventpoints that caused this stop.  KIND is
4912    the target_waitkind for the stopping event.  This
4913    routine calls the generic print routine for printing a message
4914    about reasons for stopping.  This will print (for example) the
4915    "Breakpoint n," part of the output.  The return value of this
4916    routine is one of:
4917
4918    PRINT_UNKNOWN: Means we printed nothing.
4919    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4920    code to print the location.  An example is 
4921    "Breakpoint 1, " which should be followed by
4922    the location.
4923    PRINT_SRC_ONLY: Means we printed something, but there is no need
4924    to also print the location part of the message.
4925    An example is the catch/throw messages, which
4926    don't require a location appended to the end.
4927    PRINT_NOTHING: We have done some printing and we don't need any 
4928    further info to be printed.  */
4929
4930 enum print_stop_action
4931 bpstat_print (bpstat bs, int kind)
4932 {
4933   enum print_stop_action val;
4934
4935   /* Maybe another breakpoint in the chain caused us to stop.
4936      (Currently all watchpoints go on the bpstat whether hit or not.
4937      That probably could (should) be changed, provided care is taken
4938      with respect to bpstat_explains_signal).  */
4939   for (; bs; bs = bs->next)
4940     {
4941       val = print_bp_stop_message (bs);
4942       if (val == PRINT_SRC_ONLY 
4943           || val == PRINT_SRC_AND_LOC 
4944           || val == PRINT_NOTHING)
4945         return val;
4946     }
4947
4948   /* If we had hit a shared library event breakpoint,
4949      print_bp_stop_message would print out this message.  If we hit an
4950      OS-level shared library event, do the same thing.  */
4951   if (kind == TARGET_WAITKIND_LOADED)
4952     {
4953       print_solib_event (0);
4954       return PRINT_NOTHING;
4955     }
4956
4957   /* We reached the end of the chain, or we got a null BS to start
4958      with and nothing was printed.  */
4959   return PRINT_UNKNOWN;
4960 }
4961
4962 /* Evaluate the expression EXP and return 1 if value is zero.
4963    This returns the inverse of the condition because it is called
4964    from catch_errors which returns 0 if an exception happened, and if an
4965    exception happens we want execution to stop.
4966    The argument is a "struct expression *" that has been cast to a
4967    "void *" to make it pass through catch_errors.  */
4968
4969 static int
4970 breakpoint_cond_eval (void *exp)
4971 {
4972   struct value *mark = value_mark ();
4973   int i = !value_true (evaluate_expression ((struct expression *) exp));
4974
4975   value_free_to_mark (mark);
4976   return i;
4977 }
4978
4979 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4980
4981 static bpstat
4982 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4983 {
4984   bpstat bs;
4985
4986   bs = (bpstat) xmalloc (sizeof (*bs));
4987   bs->next = NULL;
4988   **bs_link_pointer = bs;
4989   *bs_link_pointer = &bs->next;
4990   bs->breakpoint_at = bl->owner;
4991   bs->bp_location_at = bl;
4992   incref_bp_location (bl);
4993   /* If the condition is false, etc., don't do the commands.  */
4994   bs->commands = NULL;
4995   bs->old_val = NULL;
4996   bs->print_it = print_it_normal;
4997   return bs;
4998 }
4999 \f
5000 /* The target has stopped with waitstatus WS.  Check if any hardware
5001    watchpoints have triggered, according to the target.  */
5002
5003 int
5004 watchpoints_triggered (struct target_waitstatus *ws)
5005 {
5006   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
5007   CORE_ADDR addr;
5008   struct breakpoint *b;
5009
5010   if (!stopped_by_watchpoint)
5011     {
5012       /* We were not stopped by a watchpoint.  Mark all watchpoints
5013          as not triggered.  */
5014       ALL_BREAKPOINTS (b)
5015         if (is_hardware_watchpoint (b))
5016           {
5017             struct watchpoint *w = (struct watchpoint *) b;
5018
5019             w->watchpoint_triggered = watch_triggered_no;
5020           }
5021
5022       return 0;
5023     }
5024
5025   if (!target_stopped_data_address (&current_target, &addr))
5026     {
5027       /* We were stopped by a watchpoint, but we don't know where.
5028          Mark all watchpoints as unknown.  */
5029       ALL_BREAKPOINTS (b)
5030         if (is_hardware_watchpoint (b))
5031           {
5032             struct watchpoint *w = (struct watchpoint *) b;
5033
5034             w->watchpoint_triggered = watch_triggered_unknown;
5035           }
5036
5037       return 1;
5038     }
5039
5040   /* The target could report the data address.  Mark watchpoints
5041      affected by this data address as triggered, and all others as not
5042      triggered.  */
5043
5044   ALL_BREAKPOINTS (b)
5045     if (is_hardware_watchpoint (b))
5046       {
5047         struct watchpoint *w = (struct watchpoint *) b;
5048         struct bp_location *loc;
5049
5050         w->watchpoint_triggered = watch_triggered_no;
5051         for (loc = b->loc; loc; loc = loc->next)
5052           {
5053             if (is_masked_watchpoint (b))
5054               {
5055                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5056                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5057
5058                 if (newaddr == start)
5059                   {
5060                     w->watchpoint_triggered = watch_triggered_yes;
5061                     break;
5062                   }
5063               }
5064             /* Exact match not required.  Within range is sufficient.  */
5065             else if (target_watchpoint_addr_within_range (&current_target,
5066                                                          addr, loc->address,
5067                                                          loc->length))
5068               {
5069                 w->watchpoint_triggered = watch_triggered_yes;
5070                 break;
5071               }
5072           }
5073       }
5074
5075   return 1;
5076 }
5077
5078 /* Possible return values for watchpoint_check (this can't be an enum
5079    because of check_errors).  */
5080 /* The watchpoint has been deleted.  */
5081 #define WP_DELETED 1
5082 /* The value has changed.  */
5083 #define WP_VALUE_CHANGED 2
5084 /* The value has not changed.  */
5085 #define WP_VALUE_NOT_CHANGED 3
5086 /* Ignore this watchpoint, no matter if the value changed or not.  */
5087 #define WP_IGNORE 4
5088
5089 #define BP_TEMPFLAG 1
5090 #define BP_HARDWAREFLAG 2
5091
5092 /* Evaluate watchpoint condition expression and check if its value
5093    changed.
5094
5095    P should be a pointer to struct bpstat, but is defined as a void *
5096    in order for this function to be usable with catch_errors.  */
5097
5098 static int
5099 watchpoint_check (void *p)
5100 {
5101   bpstat bs = (bpstat) p;
5102   struct watchpoint *b;
5103   struct frame_info *fr;
5104   int within_current_scope;
5105
5106   /* BS is built from an existing struct breakpoint.  */
5107   gdb_assert (bs->breakpoint_at != NULL);
5108   b = (struct watchpoint *) bs->breakpoint_at;
5109
5110   /* If this is a local watchpoint, we only want to check if the
5111      watchpoint frame is in scope if the current thread is the thread
5112      that was used to create the watchpoint.  */
5113   if (!watchpoint_in_thread_scope (b))
5114     return WP_IGNORE;
5115
5116   if (b->exp_valid_block == NULL)
5117     within_current_scope = 1;
5118   else
5119     {
5120       struct frame_info *frame = get_current_frame ();
5121       struct gdbarch *frame_arch = get_frame_arch (frame);
5122       CORE_ADDR frame_pc = get_frame_pc (frame);
5123
5124       /* stack_frame_destroyed_p() returns a non-zero value if we're
5125          still in the function but the stack frame has already been
5126          invalidated.  Since we can't rely on the values of local
5127          variables after the stack has been destroyed, we are treating
5128          the watchpoint in that state as `not changed' without further
5129          checking.  Don't mark watchpoints as changed if the current
5130          frame is in an epilogue - even if they are in some other
5131          frame, our view of the stack is likely to be wrong and
5132          frame_find_by_id could error out.  */
5133       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5134         return WP_IGNORE;
5135
5136       fr = frame_find_by_id (b->watchpoint_frame);
5137       within_current_scope = (fr != NULL);
5138
5139       /* If we've gotten confused in the unwinder, we might have
5140          returned a frame that can't describe this variable.  */
5141       if (within_current_scope)
5142         {
5143           struct symbol *function;
5144
5145           function = get_frame_function (fr);
5146           if (function == NULL
5147               || !contained_in (b->exp_valid_block,
5148                                 SYMBOL_BLOCK_VALUE (function)))
5149             within_current_scope = 0;
5150         }
5151
5152       if (within_current_scope)
5153         /* If we end up stopping, the current frame will get selected
5154            in normal_stop.  So this call to select_frame won't affect
5155            the user.  */
5156         select_frame (fr);
5157     }
5158
5159   if (within_current_scope)
5160     {
5161       /* We use value_{,free_to_}mark because it could be a *long*
5162          time before we return to the command level and call
5163          free_all_values.  We can't call free_all_values because we
5164          might be in the middle of evaluating a function call.  */
5165
5166       int pc = 0;
5167       struct value *mark;
5168       struct value *new_val;
5169
5170       if (is_masked_watchpoint (&b->base))
5171         /* Since we don't know the exact trigger address (from
5172            stopped_data_address), just tell the user we've triggered
5173            a mask watchpoint.  */
5174         return WP_VALUE_CHANGED;
5175
5176       mark = value_mark ();
5177       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
5178
5179       if (b->val_bitsize != 0)
5180         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5181
5182       /* We use value_equal_contents instead of value_equal because
5183          the latter coerces an array to a pointer, thus comparing just
5184          the address of the array instead of its contents.  This is
5185          not what we want.  */
5186       if ((b->val != NULL) != (new_val != NULL)
5187           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5188         {
5189           if (new_val != NULL)
5190             {
5191               release_value (new_val);
5192               value_free_to_mark (mark);
5193             }
5194           bs->old_val = b->val;
5195           b->val = new_val;
5196           b->val_valid = 1;
5197           return WP_VALUE_CHANGED;
5198         }
5199       else
5200         {
5201           /* Nothing changed.  */
5202           value_free_to_mark (mark);
5203           return WP_VALUE_NOT_CHANGED;
5204         }
5205     }
5206   else
5207     {
5208       /* This seems like the only logical thing to do because
5209          if we temporarily ignored the watchpoint, then when
5210          we reenter the block in which it is valid it contains
5211          garbage (in the case of a function, it may have two
5212          garbage values, one before and one after the prologue).
5213          So we can't even detect the first assignment to it and
5214          watch after that (since the garbage may or may not equal
5215          the first value assigned).  */
5216       /* We print all the stop information in
5217          breakpoint_ops->print_it, but in this case, by the time we
5218          call breakpoint_ops->print_it this bp will be deleted
5219          already.  So we have no choice but print the information
5220          here.  */
5221
5222       SWITCH_THRU_ALL_UIS ()
5223         {
5224           struct ui_out *uiout = current_uiout;
5225
5226           if (uiout->is_mi_like_p ())
5227             uiout->field_string
5228               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5229           uiout->text ("\nWatchpoint ");
5230           uiout->field_int ("wpnum", b->base.number);
5231           uiout->text (" deleted because the program has left the block in\n"
5232                        "which its expression is valid.\n");
5233         }
5234
5235       /* Make sure the watchpoint's commands aren't executed.  */
5236       decref_counted_command_line (&b->base.commands);
5237       watchpoint_del_at_next_stop (b);
5238
5239       return WP_DELETED;
5240     }
5241 }
5242
5243 /* Return true if it looks like target has stopped due to hitting
5244    breakpoint location BL.  This function does not check if we should
5245    stop, only if BL explains the stop.  */
5246
5247 static int
5248 bpstat_check_location (const struct bp_location *bl,
5249                        struct address_space *aspace, CORE_ADDR bp_addr,
5250                        const struct target_waitstatus *ws)
5251 {
5252   struct breakpoint *b = bl->owner;
5253
5254   /* BL is from an existing breakpoint.  */
5255   gdb_assert (b != NULL);
5256
5257   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5258 }
5259
5260 /* Determine if the watched values have actually changed, and we
5261    should stop.  If not, set BS->stop to 0.  */
5262
5263 static void
5264 bpstat_check_watchpoint (bpstat bs)
5265 {
5266   const struct bp_location *bl;
5267   struct watchpoint *b;
5268
5269   /* BS is built for existing struct breakpoint.  */
5270   bl = bs->bp_location_at;
5271   gdb_assert (bl != NULL);
5272   b = (struct watchpoint *) bs->breakpoint_at;
5273   gdb_assert (b != NULL);
5274
5275     {
5276       int must_check_value = 0;
5277       
5278       if (b->base.type == bp_watchpoint)
5279         /* For a software watchpoint, we must always check the
5280            watched value.  */
5281         must_check_value = 1;
5282       else if (b->watchpoint_triggered == watch_triggered_yes)
5283         /* We have a hardware watchpoint (read, write, or access)
5284            and the target earlier reported an address watched by
5285            this watchpoint.  */
5286         must_check_value = 1;
5287       else if (b->watchpoint_triggered == watch_triggered_unknown
5288                && b->base.type == bp_hardware_watchpoint)
5289         /* We were stopped by a hardware watchpoint, but the target could
5290            not report the data address.  We must check the watchpoint's
5291            value.  Access and read watchpoints are out of luck; without
5292            a data address, we can't figure it out.  */
5293         must_check_value = 1;
5294
5295       if (must_check_value)
5296         {
5297           char *message
5298             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5299                           b->base.number);
5300           struct cleanup *cleanups = make_cleanup (xfree, message);
5301           int e = catch_errors (watchpoint_check, bs, message,
5302                                 RETURN_MASK_ALL);
5303           do_cleanups (cleanups);
5304           switch (e)
5305             {
5306             case WP_DELETED:
5307               /* We've already printed what needs to be printed.  */
5308               bs->print_it = print_it_done;
5309               /* Stop.  */
5310               break;
5311             case WP_IGNORE:
5312               bs->print_it = print_it_noop;
5313               bs->stop = 0;
5314               break;
5315             case WP_VALUE_CHANGED:
5316               if (b->base.type == bp_read_watchpoint)
5317                 {
5318                   /* There are two cases to consider here:
5319
5320                      1. We're watching the triggered memory for reads.
5321                      In that case, trust the target, and always report
5322                      the watchpoint hit to the user.  Even though
5323                      reads don't cause value changes, the value may
5324                      have changed since the last time it was read, and
5325                      since we're not trapping writes, we will not see
5326                      those, and as such we should ignore our notion of
5327                      old value.
5328
5329                      2. We're watching the triggered memory for both
5330                      reads and writes.  There are two ways this may
5331                      happen:
5332
5333                      2.1. This is a target that can't break on data
5334                      reads only, but can break on accesses (reads or
5335                      writes), such as e.g., x86.  We detect this case
5336                      at the time we try to insert read watchpoints.
5337
5338                      2.2. Otherwise, the target supports read
5339                      watchpoints, but, the user set an access or write
5340                      watchpoint watching the same memory as this read
5341                      watchpoint.
5342
5343                      If we're watching memory writes as well as reads,
5344                      ignore watchpoint hits when we find that the
5345                      value hasn't changed, as reads don't cause
5346                      changes.  This still gives false positives when
5347                      the program writes the same value to memory as
5348                      what there was already in memory (we will confuse
5349                      it for a read), but it's much better than
5350                      nothing.  */
5351
5352                   int other_write_watchpoint = 0;
5353
5354                   if (bl->watchpoint_type == hw_read)
5355                     {
5356                       struct breakpoint *other_b;
5357
5358                       ALL_BREAKPOINTS (other_b)
5359                         if (other_b->type == bp_hardware_watchpoint
5360                             || other_b->type == bp_access_watchpoint)
5361                           {
5362                             struct watchpoint *other_w =
5363                               (struct watchpoint *) other_b;
5364
5365                             if (other_w->watchpoint_triggered
5366                                 == watch_triggered_yes)
5367                               {
5368                                 other_write_watchpoint = 1;
5369                                 break;
5370                               }
5371                           }
5372                     }
5373
5374                   if (other_write_watchpoint
5375                       || bl->watchpoint_type == hw_access)
5376                     {
5377                       /* We're watching the same memory for writes,
5378                          and the value changed since the last time we
5379                          updated it, so this trap must be for a write.
5380                          Ignore it.  */
5381                       bs->print_it = print_it_noop;
5382                       bs->stop = 0;
5383                     }
5384                 }
5385               break;
5386             case WP_VALUE_NOT_CHANGED:
5387               if (b->base.type == bp_hardware_watchpoint
5388                   || b->base.type == bp_watchpoint)
5389                 {
5390                   /* Don't stop: write watchpoints shouldn't fire if
5391                      the value hasn't changed.  */
5392                   bs->print_it = print_it_noop;
5393                   bs->stop = 0;
5394                 }
5395               /* Stop.  */
5396               break;
5397             default:
5398               /* Can't happen.  */
5399             case 0:
5400               /* Error from catch_errors.  */
5401               {
5402                 SWITCH_THRU_ALL_UIS ()
5403                   {
5404                     printf_filtered (_("Watchpoint %d deleted.\n"),
5405                                      b->base.number);
5406                   }
5407                 watchpoint_del_at_next_stop (b);
5408                 /* We've already printed what needs to be printed.  */
5409                 bs->print_it = print_it_done;
5410               }
5411               break;
5412             }
5413         }
5414       else      /* must_check_value == 0 */
5415         {
5416           /* This is a case where some watchpoint(s) triggered, but
5417              not at the address of this watchpoint, or else no
5418              watchpoint triggered after all.  So don't print
5419              anything for this watchpoint.  */
5420           bs->print_it = print_it_noop;
5421           bs->stop = 0;
5422         }
5423     }
5424 }
5425
5426 /* For breakpoints that are currently marked as telling gdb to stop,
5427    check conditions (condition proper, frame, thread and ignore count)
5428    of breakpoint referred to by BS.  If we should not stop for this
5429    breakpoint, set BS->stop to 0.  */
5430
5431 static void
5432 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5433 {
5434   const struct bp_location *bl;
5435   struct breakpoint *b;
5436   int value_is_zero = 0;
5437   struct expression *cond;
5438
5439   gdb_assert (bs->stop);
5440
5441   /* BS is built for existing struct breakpoint.  */
5442   bl = bs->bp_location_at;
5443   gdb_assert (bl != NULL);
5444   b = bs->breakpoint_at;
5445   gdb_assert (b != NULL);
5446
5447   /* Even if the target evaluated the condition on its end and notified GDB, we
5448      need to do so again since GDB does not know if we stopped due to a
5449      breakpoint or a single step breakpoint.  */
5450
5451   if (frame_id_p (b->frame_id)
5452       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5453     {
5454       bs->stop = 0;
5455       return;
5456     }
5457
5458   /* If this is a thread/task-specific breakpoint, don't waste cpu
5459      evaluating the condition if this isn't the specified
5460      thread/task.  */
5461   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5462       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5463
5464     {
5465       bs->stop = 0;
5466       return;
5467     }
5468
5469   /* Evaluate extension language breakpoints that have a "stop" method
5470      implemented.  */
5471   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5472
5473   if (is_watchpoint (b))
5474     {
5475       struct watchpoint *w = (struct watchpoint *) b;
5476
5477       cond = w->cond_exp.get ();
5478     }
5479   else
5480     cond = bl->cond.get ();
5481
5482   if (cond && b->disposition != disp_del_at_next_stop)
5483     {
5484       int within_current_scope = 1;
5485       struct watchpoint * w;
5486
5487       /* We use value_mark and value_free_to_mark because it could
5488          be a long time before we return to the command level and
5489          call free_all_values.  We can't call free_all_values
5490          because we might be in the middle of evaluating a
5491          function call.  */
5492       struct value *mark = value_mark ();
5493
5494       if (is_watchpoint (b))
5495         w = (struct watchpoint *) b;
5496       else
5497         w = NULL;
5498
5499       /* Need to select the frame, with all that implies so that
5500          the conditions will have the right context.  Because we
5501          use the frame, we will not see an inlined function's
5502          variables when we arrive at a breakpoint at the start
5503          of the inlined function; the current frame will be the
5504          call site.  */
5505       if (w == NULL || w->cond_exp_valid_block == NULL)
5506         select_frame (get_current_frame ());
5507       else
5508         {
5509           struct frame_info *frame;
5510
5511           /* For local watchpoint expressions, which particular
5512              instance of a local is being watched matters, so we
5513              keep track of the frame to evaluate the expression
5514              in.  To evaluate the condition however, it doesn't
5515              really matter which instantiation of the function
5516              where the condition makes sense triggers the
5517              watchpoint.  This allows an expression like "watch
5518              global if q > 10" set in `func', catch writes to
5519              global on all threads that call `func', or catch
5520              writes on all recursive calls of `func' by a single
5521              thread.  We simply always evaluate the condition in
5522              the innermost frame that's executing where it makes
5523              sense to evaluate the condition.  It seems
5524              intuitive.  */
5525           frame = block_innermost_frame (w->cond_exp_valid_block);
5526           if (frame != NULL)
5527             select_frame (frame);
5528           else
5529             within_current_scope = 0;
5530         }
5531       if (within_current_scope)
5532         value_is_zero
5533           = catch_errors (breakpoint_cond_eval, cond,
5534                           "Error in testing breakpoint condition:\n",
5535                           RETURN_MASK_ALL);
5536       else
5537         {
5538           warning (_("Watchpoint condition cannot be tested "
5539                      "in the current scope"));
5540           /* If we failed to set the right context for this
5541              watchpoint, unconditionally report it.  */
5542           value_is_zero = 0;
5543         }
5544       /* FIXME-someday, should give breakpoint #.  */
5545       value_free_to_mark (mark);
5546     }
5547
5548   if (cond && value_is_zero)
5549     {
5550       bs->stop = 0;
5551     }
5552   else if (b->ignore_count > 0)
5553     {
5554       b->ignore_count--;
5555       bs->stop = 0;
5556       /* Increase the hit count even though we don't stop.  */
5557       ++(b->hit_count);
5558       observer_notify_breakpoint_modified (b);
5559     }   
5560 }
5561
5562 /* Returns true if we need to track moribund locations of LOC's type
5563    on the current target.  */
5564
5565 static int
5566 need_moribund_for_location_type (struct bp_location *loc)
5567 {
5568   return ((loc->loc_type == bp_loc_software_breakpoint
5569            && !target_supports_stopped_by_sw_breakpoint ())
5570           || (loc->loc_type == bp_loc_hardware_breakpoint
5571               && !target_supports_stopped_by_hw_breakpoint ()));
5572 }
5573
5574
5575 /* Get a bpstat associated with having just stopped at address
5576    BP_ADDR in thread PTID.
5577
5578    Determine whether we stopped at a breakpoint, etc, or whether we
5579    don't understand this stop.  Result is a chain of bpstat's such
5580    that:
5581
5582    if we don't understand the stop, the result is a null pointer.
5583
5584    if we understand why we stopped, the result is not null.
5585
5586    Each element of the chain refers to a particular breakpoint or
5587    watchpoint at which we have stopped.  (We may have stopped for
5588    several reasons concurrently.)
5589
5590    Each element of the chain has valid next, breakpoint_at,
5591    commands, FIXME??? fields.  */
5592
5593 bpstat
5594 bpstat_stop_status (struct address_space *aspace,
5595                     CORE_ADDR bp_addr, ptid_t ptid,
5596                     const struct target_waitstatus *ws)
5597 {
5598   struct breakpoint *b = NULL;
5599   struct bp_location *bl;
5600   struct bp_location *loc;
5601   /* First item of allocated bpstat's.  */
5602   bpstat bs_head = NULL, *bs_link = &bs_head;
5603   /* Pointer to the last thing in the chain currently.  */
5604   bpstat bs;
5605   int ix;
5606   int need_remove_insert;
5607   int removed_any;
5608
5609   /* First, build the bpstat chain with locations that explain a
5610      target stop, while being careful to not set the target running,
5611      as that may invalidate locations (in particular watchpoint
5612      locations are recreated).  Resuming will happen here with
5613      breakpoint conditions or watchpoint expressions that include
5614      inferior function calls.  */
5615
5616   ALL_BREAKPOINTS (b)
5617     {
5618       if (!breakpoint_enabled (b))
5619         continue;
5620
5621       for (bl = b->loc; bl != NULL; bl = bl->next)
5622         {
5623           /* For hardware watchpoints, we look only at the first
5624              location.  The watchpoint_check function will work on the
5625              entire expression, not the individual locations.  For
5626              read watchpoints, the watchpoints_triggered function has
5627              checked all locations already.  */
5628           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5629             break;
5630
5631           if (!bl->enabled || bl->shlib_disabled)
5632             continue;
5633
5634           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5635             continue;
5636
5637           /* Come here if it's a watchpoint, or if the break address
5638              matches.  */
5639
5640           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5641                                                    explain stop.  */
5642
5643           /* Assume we stop.  Should we find a watchpoint that is not
5644              actually triggered, or if the condition of the breakpoint
5645              evaluates as false, we'll reset 'stop' to 0.  */
5646           bs->stop = 1;
5647           bs->print = 1;
5648
5649           /* If this is a scope breakpoint, mark the associated
5650              watchpoint as triggered so that we will handle the
5651              out-of-scope event.  We'll get to the watchpoint next
5652              iteration.  */
5653           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5654             {
5655               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5656
5657               w->watchpoint_triggered = watch_triggered_yes;
5658             }
5659         }
5660     }
5661
5662   /* Check if a moribund breakpoint explains the stop.  */
5663   if (!target_supports_stopped_by_sw_breakpoint ()
5664       || !target_supports_stopped_by_hw_breakpoint ())
5665     {
5666       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5667         {
5668           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5669               && need_moribund_for_location_type (loc))
5670             {
5671               bs = bpstat_alloc (loc, &bs_link);
5672               /* For hits of moribund locations, we should just proceed.  */
5673               bs->stop = 0;
5674               bs->print = 0;
5675               bs->print_it = print_it_noop;
5676             }
5677         }
5678     }
5679
5680   /* A bit of special processing for shlib breakpoints.  We need to
5681      process solib loading here, so that the lists of loaded and
5682      unloaded libraries are correct before we handle "catch load" and
5683      "catch unload".  */
5684   for (bs = bs_head; bs != NULL; bs = bs->next)
5685     {
5686       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5687         {
5688           handle_solib_event ();
5689           break;
5690         }
5691     }
5692
5693   /* Now go through the locations that caused the target to stop, and
5694      check whether we're interested in reporting this stop to higher
5695      layers, or whether we should resume the target transparently.  */
5696
5697   removed_any = 0;
5698
5699   for (bs = bs_head; bs != NULL; bs = bs->next)
5700     {
5701       if (!bs->stop)
5702         continue;
5703
5704       b = bs->breakpoint_at;
5705       b->ops->check_status (bs);
5706       if (bs->stop)
5707         {
5708           bpstat_check_breakpoint_conditions (bs, ptid);
5709
5710           if (bs->stop)
5711             {
5712               ++(b->hit_count);
5713               observer_notify_breakpoint_modified (b);
5714
5715               /* We will stop here.  */
5716               if (b->disposition == disp_disable)
5717                 {
5718                   --(b->enable_count);
5719                   if (b->enable_count <= 0)
5720                     b->enable_state = bp_disabled;
5721                   removed_any = 1;
5722                 }
5723               if (b->silent)
5724                 bs->print = 0;
5725               bs->commands = b->commands;
5726               incref_counted_command_line (bs->commands);
5727               if (command_line_is_silent (bs->commands
5728                                           ? bs->commands->commands : NULL))
5729                 bs->print = 0;
5730
5731               b->ops->after_condition_true (bs);
5732             }
5733
5734         }
5735
5736       /* Print nothing for this entry if we don't stop or don't
5737          print.  */
5738       if (!bs->stop || !bs->print)
5739         bs->print_it = print_it_noop;
5740     }
5741
5742   /* If we aren't stopping, the value of some hardware watchpoint may
5743      not have changed, but the intermediate memory locations we are
5744      watching may have.  Don't bother if we're stopping; this will get
5745      done later.  */
5746   need_remove_insert = 0;
5747   if (! bpstat_causes_stop (bs_head))
5748     for (bs = bs_head; bs != NULL; bs = bs->next)
5749       if (!bs->stop
5750           && bs->breakpoint_at
5751           && is_hardware_watchpoint (bs->breakpoint_at))
5752         {
5753           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5754
5755           update_watchpoint (w, 0 /* don't reparse.  */);
5756           need_remove_insert = 1;
5757         }
5758
5759   if (need_remove_insert)
5760     update_global_location_list (UGLL_MAY_INSERT);
5761   else if (removed_any)
5762     update_global_location_list (UGLL_DONT_INSERT);
5763
5764   return bs_head;
5765 }
5766
5767 static void
5768 handle_jit_event (void)
5769 {
5770   struct frame_info *frame;
5771   struct gdbarch *gdbarch;
5772
5773   if (debug_infrun)
5774     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5775
5776   /* Switch terminal for any messages produced by
5777      breakpoint_re_set.  */
5778   target_terminal_ours_for_output ();
5779
5780   frame = get_current_frame ();
5781   gdbarch = get_frame_arch (frame);
5782
5783   jit_event_handler (gdbarch);
5784
5785   target_terminal_inferior ();
5786 }
5787
5788 /* Prepare WHAT final decision for infrun.  */
5789
5790 /* Decide what infrun needs to do with this bpstat.  */
5791
5792 struct bpstat_what
5793 bpstat_what (bpstat bs_head)
5794 {
5795   struct bpstat_what retval;
5796   bpstat bs;
5797
5798   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5799   retval.call_dummy = STOP_NONE;
5800   retval.is_longjmp = 0;
5801
5802   for (bs = bs_head; bs != NULL; bs = bs->next)
5803     {
5804       /* Extract this BS's action.  After processing each BS, we check
5805          if its action overrides all we've seem so far.  */
5806       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5807       enum bptype bptype;
5808
5809       if (bs->breakpoint_at == NULL)
5810         {
5811           /* I suspect this can happen if it was a momentary
5812              breakpoint which has since been deleted.  */
5813           bptype = bp_none;
5814         }
5815       else
5816         bptype = bs->breakpoint_at->type;
5817
5818       switch (bptype)
5819         {
5820         case bp_none:
5821           break;
5822         case bp_breakpoint:
5823         case bp_hardware_breakpoint:
5824         case bp_single_step:
5825         case bp_until:
5826         case bp_finish:
5827         case bp_shlib_event:
5828           if (bs->stop)
5829             {
5830               if (bs->print)
5831                 this_action = BPSTAT_WHAT_STOP_NOISY;
5832               else
5833                 this_action = BPSTAT_WHAT_STOP_SILENT;
5834             }
5835           else
5836             this_action = BPSTAT_WHAT_SINGLE;
5837           break;
5838         case bp_watchpoint:
5839         case bp_hardware_watchpoint:
5840         case bp_read_watchpoint:
5841         case bp_access_watchpoint:
5842           if (bs->stop)
5843             {
5844               if (bs->print)
5845                 this_action = BPSTAT_WHAT_STOP_NOISY;
5846               else
5847                 this_action = BPSTAT_WHAT_STOP_SILENT;
5848             }
5849           else
5850             {
5851               /* There was a watchpoint, but we're not stopping.
5852                  This requires no further action.  */
5853             }
5854           break;
5855         case bp_longjmp:
5856         case bp_longjmp_call_dummy:
5857         case bp_exception:
5858           if (bs->stop)
5859             {
5860               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5861               retval.is_longjmp = bptype != bp_exception;
5862             }
5863           else
5864             this_action = BPSTAT_WHAT_SINGLE;
5865           break;
5866         case bp_longjmp_resume:
5867         case bp_exception_resume:
5868           if (bs->stop)
5869             {
5870               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5871               retval.is_longjmp = bptype == bp_longjmp_resume;
5872             }
5873           else
5874             this_action = BPSTAT_WHAT_SINGLE;
5875           break;
5876         case bp_step_resume:
5877           if (bs->stop)
5878             this_action = BPSTAT_WHAT_STEP_RESUME;
5879           else
5880             {
5881               /* It is for the wrong frame.  */
5882               this_action = BPSTAT_WHAT_SINGLE;
5883             }
5884           break;
5885         case bp_hp_step_resume:
5886           if (bs->stop)
5887             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5888           else
5889             {
5890               /* It is for the wrong frame.  */
5891               this_action = BPSTAT_WHAT_SINGLE;
5892             }
5893           break;
5894         case bp_watchpoint_scope:
5895         case bp_thread_event:
5896         case bp_overlay_event:
5897         case bp_longjmp_master:
5898         case bp_std_terminate_master:
5899         case bp_exception_master:
5900           this_action = BPSTAT_WHAT_SINGLE;
5901           break;
5902         case bp_catchpoint:
5903           if (bs->stop)
5904             {
5905               if (bs->print)
5906                 this_action = BPSTAT_WHAT_STOP_NOISY;
5907               else
5908                 this_action = BPSTAT_WHAT_STOP_SILENT;
5909             }
5910           else
5911             {
5912               /* There was a catchpoint, but we're not stopping.
5913                  This requires no further action.  */
5914             }
5915           break;
5916         case bp_jit_event:
5917           this_action = BPSTAT_WHAT_SINGLE;
5918           break;
5919         case bp_call_dummy:
5920           /* Make sure the action is stop (silent or noisy),
5921              so infrun.c pops the dummy frame.  */
5922           retval.call_dummy = STOP_STACK_DUMMY;
5923           this_action = BPSTAT_WHAT_STOP_SILENT;
5924           break;
5925         case bp_std_terminate:
5926           /* Make sure the action is stop (silent or noisy),
5927              so infrun.c pops the dummy frame.  */
5928           retval.call_dummy = STOP_STD_TERMINATE;
5929           this_action = BPSTAT_WHAT_STOP_SILENT;
5930           break;
5931         case bp_tracepoint:
5932         case bp_fast_tracepoint:
5933         case bp_static_tracepoint:
5934           /* Tracepoint hits should not be reported back to GDB, and
5935              if one got through somehow, it should have been filtered
5936              out already.  */
5937           internal_error (__FILE__, __LINE__,
5938                           _("bpstat_what: tracepoint encountered"));
5939           break;
5940         case bp_gnu_ifunc_resolver:
5941           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5942           this_action = BPSTAT_WHAT_SINGLE;
5943           break;
5944         case bp_gnu_ifunc_resolver_return:
5945           /* The breakpoint will be removed, execution will restart from the
5946              PC of the former breakpoint.  */
5947           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5948           break;
5949
5950         case bp_dprintf:
5951           if (bs->stop)
5952             this_action = BPSTAT_WHAT_STOP_SILENT;
5953           else
5954             this_action = BPSTAT_WHAT_SINGLE;
5955           break;
5956
5957         default:
5958           internal_error (__FILE__, __LINE__,
5959                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5960         }
5961
5962       retval.main_action = std::max (retval.main_action, this_action);
5963     }
5964
5965   return retval;
5966 }
5967
5968 void
5969 bpstat_run_callbacks (bpstat bs_head)
5970 {
5971   bpstat bs;
5972
5973   for (bs = bs_head; bs != NULL; bs = bs->next)
5974     {
5975       struct breakpoint *b = bs->breakpoint_at;
5976
5977       if (b == NULL)
5978         continue;
5979       switch (b->type)
5980         {
5981         case bp_jit_event:
5982           handle_jit_event ();
5983           break;
5984         case bp_gnu_ifunc_resolver:
5985           gnu_ifunc_resolver_stop (b);
5986           break;
5987         case bp_gnu_ifunc_resolver_return:
5988           gnu_ifunc_resolver_return_stop (b);
5989           break;
5990         }
5991     }
5992 }
5993
5994 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5995    without hardware support).  This isn't related to a specific bpstat,
5996    just to things like whether watchpoints are set.  */
5997
5998 int
5999 bpstat_should_step (void)
6000 {
6001   struct breakpoint *b;
6002
6003   ALL_BREAKPOINTS (b)
6004     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6005       return 1;
6006   return 0;
6007 }
6008
6009 int
6010 bpstat_causes_stop (bpstat bs)
6011 {
6012   for (; bs != NULL; bs = bs->next)
6013     if (bs->stop)
6014       return 1;
6015
6016   return 0;
6017 }
6018
6019 \f
6020
6021 /* Compute a string of spaces suitable to indent the next line
6022    so it starts at the position corresponding to the table column
6023    named COL_NAME in the currently active table of UIOUT.  */
6024
6025 static char *
6026 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6027 {
6028   static char wrap_indent[80];
6029   int i, total_width, width, align;
6030   const char *text;
6031
6032   total_width = 0;
6033   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6034     {
6035       if (strcmp (text, col_name) == 0)
6036         {
6037           gdb_assert (total_width < sizeof wrap_indent);
6038           memset (wrap_indent, ' ', total_width);
6039           wrap_indent[total_width] = 0;
6040
6041           return wrap_indent;
6042         }
6043
6044       total_width += width + 1;
6045     }
6046
6047   return NULL;
6048 }
6049
6050 /* Determine if the locations of this breakpoint will have their conditions
6051    evaluated by the target, host or a mix of both.  Returns the following:
6052
6053     "host": Host evals condition.
6054     "host or target": Host or Target evals condition.
6055     "target": Target evals condition.
6056 */
6057
6058 static const char *
6059 bp_condition_evaluator (struct breakpoint *b)
6060 {
6061   struct bp_location *bl;
6062   char host_evals = 0;
6063   char target_evals = 0;
6064
6065   if (!b)
6066     return NULL;
6067
6068   if (!is_breakpoint (b))
6069     return NULL;
6070
6071   if (gdb_evaluates_breakpoint_condition_p ()
6072       || !target_supports_evaluation_of_breakpoint_conditions ())
6073     return condition_evaluation_host;
6074
6075   for (bl = b->loc; bl; bl = bl->next)
6076     {
6077       if (bl->cond_bytecode)
6078         target_evals++;
6079       else
6080         host_evals++;
6081     }
6082
6083   if (host_evals && target_evals)
6084     return condition_evaluation_both;
6085   else if (target_evals)
6086     return condition_evaluation_target;
6087   else
6088     return condition_evaluation_host;
6089 }
6090
6091 /* Determine the breakpoint location's condition evaluator.  This is
6092    similar to bp_condition_evaluator, but for locations.  */
6093
6094 static const char *
6095 bp_location_condition_evaluator (struct bp_location *bl)
6096 {
6097   if (bl && !is_breakpoint (bl->owner))
6098     return NULL;
6099
6100   if (gdb_evaluates_breakpoint_condition_p ()
6101       || !target_supports_evaluation_of_breakpoint_conditions ())
6102     return condition_evaluation_host;
6103
6104   if (bl && bl->cond_bytecode)
6105     return condition_evaluation_target;
6106   else
6107     return condition_evaluation_host;
6108 }
6109
6110 /* Print the LOC location out of the list of B->LOC locations.  */
6111
6112 static void
6113 print_breakpoint_location (struct breakpoint *b,
6114                            struct bp_location *loc)
6115 {
6116   struct ui_out *uiout = current_uiout;
6117
6118   scoped_restore_current_program_space restore_pspace;
6119
6120   if (loc != NULL && loc->shlib_disabled)
6121     loc = NULL;
6122
6123   if (loc != NULL)
6124     set_current_program_space (loc->pspace);
6125
6126   if (b->display_canonical)
6127     uiout->field_string ("what", event_location_to_string (b->location.get ()));
6128   else if (loc && loc->symtab)
6129     {
6130       struct symbol *sym 
6131         = find_pc_sect_function (loc->address, loc->section);
6132       if (sym)
6133         {
6134           uiout->text ("in ");
6135           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
6136           uiout->text (" ");
6137           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6138           uiout->text ("at ");
6139         }
6140       uiout->field_string ("file",
6141                            symtab_to_filename_for_display (loc->symtab));
6142       uiout->text (":");
6143
6144       if (uiout->is_mi_like_p ())
6145         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6146       
6147       uiout->field_int ("line", loc->line_number);
6148     }
6149   else if (loc)
6150     {
6151       string_file stb;
6152
6153       print_address_symbolic (loc->gdbarch, loc->address, &stb,
6154                               demangle, "");
6155       uiout->field_stream ("at", stb);
6156     }
6157   else
6158     {
6159       uiout->field_string ("pending",
6160                            event_location_to_string (b->location.get ()));
6161       /* If extra_string is available, it could be holding a condition
6162          or dprintf arguments.  In either case, make sure it is printed,
6163          too, but only for non-MI streams.  */
6164       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6165         {
6166           if (b->type == bp_dprintf)
6167             uiout->text (",");
6168           else
6169             uiout->text (" ");
6170           uiout->text (b->extra_string);
6171         }
6172     }
6173
6174   if (loc && is_breakpoint (b)
6175       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6176       && bp_condition_evaluator (b) == condition_evaluation_both)
6177     {
6178       uiout->text (" (");
6179       uiout->field_string ("evaluated-by",
6180                            bp_location_condition_evaluator (loc));
6181       uiout->text (")");
6182     }
6183 }
6184
6185 static const char *
6186 bptype_string (enum bptype type)
6187 {
6188   struct ep_type_description
6189     {
6190       enum bptype type;
6191       const char *description;
6192     };
6193   static struct ep_type_description bptypes[] =
6194   {
6195     {bp_none, "?deleted?"},
6196     {bp_breakpoint, "breakpoint"},
6197     {bp_hardware_breakpoint, "hw breakpoint"},
6198     {bp_single_step, "sw single-step"},
6199     {bp_until, "until"},
6200     {bp_finish, "finish"},
6201     {bp_watchpoint, "watchpoint"},
6202     {bp_hardware_watchpoint, "hw watchpoint"},
6203     {bp_read_watchpoint, "read watchpoint"},
6204     {bp_access_watchpoint, "acc watchpoint"},
6205     {bp_longjmp, "longjmp"},
6206     {bp_longjmp_resume, "longjmp resume"},
6207     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6208     {bp_exception, "exception"},
6209     {bp_exception_resume, "exception resume"},
6210     {bp_step_resume, "step resume"},
6211     {bp_hp_step_resume, "high-priority step resume"},
6212     {bp_watchpoint_scope, "watchpoint scope"},
6213     {bp_call_dummy, "call dummy"},
6214     {bp_std_terminate, "std::terminate"},
6215     {bp_shlib_event, "shlib events"},
6216     {bp_thread_event, "thread events"},
6217     {bp_overlay_event, "overlay events"},
6218     {bp_longjmp_master, "longjmp master"},
6219     {bp_std_terminate_master, "std::terminate master"},
6220     {bp_exception_master, "exception master"},
6221     {bp_catchpoint, "catchpoint"},
6222     {bp_tracepoint, "tracepoint"},
6223     {bp_fast_tracepoint, "fast tracepoint"},
6224     {bp_static_tracepoint, "static tracepoint"},
6225     {bp_dprintf, "dprintf"},
6226     {bp_jit_event, "jit events"},
6227     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6228     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6229   };
6230
6231   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6232       || ((int) type != bptypes[(int) type].type))
6233     internal_error (__FILE__, __LINE__,
6234                     _("bptypes table does not describe type #%d."),
6235                     (int) type);
6236
6237   return bptypes[(int) type].description;
6238 }
6239
6240 /* For MI, output a field named 'thread-groups' with a list as the value.
6241    For CLI, prefix the list with the string 'inf'. */
6242
6243 static void
6244 output_thread_groups (struct ui_out *uiout,
6245                       const char *field_name,
6246                       VEC(int) *inf_num,
6247                       int mi_only)
6248 {
6249   int is_mi = uiout->is_mi_like_p ();
6250   int inf;
6251   int i;
6252
6253   /* For backward compatibility, don't display inferiors in CLI unless
6254      there are several.  Always display them for MI. */
6255   if (!is_mi && mi_only)
6256     return;
6257
6258   ui_out_emit_list list_emitter (uiout, field_name);
6259
6260   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6261     {
6262       if (is_mi)
6263         {
6264           char mi_group[10];
6265
6266           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6267           uiout->field_string (NULL, mi_group);
6268         }
6269       else
6270         {
6271           if (i == 0)
6272             uiout->text (" inf ");
6273           else
6274             uiout->text (", ");
6275         
6276           uiout->text (plongest (inf));
6277         }
6278     }
6279 }
6280
6281 /* Print B to gdb_stdout.  */
6282
6283 static void
6284 print_one_breakpoint_location (struct breakpoint *b,
6285                                struct bp_location *loc,
6286                                int loc_number,
6287                                struct bp_location **last_loc,
6288                                int allflag)
6289 {
6290   struct command_line *l;
6291   static char bpenables[] = "nynny";
6292
6293   struct ui_out *uiout = current_uiout;
6294   int header_of_multiple = 0;
6295   int part_of_multiple = (loc != NULL);
6296   struct value_print_options opts;
6297
6298   get_user_print_options (&opts);
6299
6300   gdb_assert (!loc || loc_number != 0);
6301   /* See comment in print_one_breakpoint concerning treatment of
6302      breakpoints with single disabled location.  */
6303   if (loc == NULL 
6304       && (b->loc != NULL 
6305           && (b->loc->next != NULL || !b->loc->enabled)))
6306     header_of_multiple = 1;
6307   if (loc == NULL)
6308     loc = b->loc;
6309
6310   annotate_record ();
6311
6312   /* 1 */
6313   annotate_field (0);
6314   if (part_of_multiple)
6315     {
6316       char *formatted;
6317       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6318       uiout->field_string ("number", formatted);
6319       xfree (formatted);
6320     }
6321   else
6322     {
6323       uiout->field_int ("number", b->number);
6324     }
6325
6326   /* 2 */
6327   annotate_field (1);
6328   if (part_of_multiple)
6329     uiout->field_skip ("type");
6330   else
6331     uiout->field_string ("type", bptype_string (b->type));
6332
6333   /* 3 */
6334   annotate_field (2);
6335   if (part_of_multiple)
6336     uiout->field_skip ("disp");
6337   else
6338     uiout->field_string ("disp", bpdisp_text (b->disposition));
6339
6340
6341   /* 4 */
6342   annotate_field (3);
6343   if (part_of_multiple)
6344     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6345   else
6346     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6347   uiout->spaces (2);
6348
6349   
6350   /* 5 and 6 */
6351   if (b->ops != NULL && b->ops->print_one != NULL)
6352     {
6353       /* Although the print_one can possibly print all locations,
6354          calling it here is not likely to get any nice result.  So,
6355          make sure there's just one location.  */
6356       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6357       b->ops->print_one (b, last_loc);
6358     }
6359   else
6360     switch (b->type)
6361       {
6362       case bp_none:
6363         internal_error (__FILE__, __LINE__,
6364                         _("print_one_breakpoint: bp_none encountered\n"));
6365         break;
6366
6367       case bp_watchpoint:
6368       case bp_hardware_watchpoint:
6369       case bp_read_watchpoint:
6370       case bp_access_watchpoint:
6371         {
6372           struct watchpoint *w = (struct watchpoint *) b;
6373
6374           /* Field 4, the address, is omitted (which makes the columns
6375              not line up too nicely with the headers, but the effect
6376              is relatively readable).  */
6377           if (opts.addressprint)
6378             uiout->field_skip ("addr");
6379           annotate_field (5);
6380           uiout->field_string ("what", w->exp_string);
6381         }
6382         break;
6383
6384       case bp_breakpoint:
6385       case bp_hardware_breakpoint:
6386       case bp_single_step:
6387       case bp_until:
6388       case bp_finish:
6389       case bp_longjmp:
6390       case bp_longjmp_resume:
6391       case bp_longjmp_call_dummy:
6392       case bp_exception:
6393       case bp_exception_resume:
6394       case bp_step_resume:
6395       case bp_hp_step_resume:
6396       case bp_watchpoint_scope:
6397       case bp_call_dummy:
6398       case bp_std_terminate:
6399       case bp_shlib_event:
6400       case bp_thread_event:
6401       case bp_overlay_event:
6402       case bp_longjmp_master:
6403       case bp_std_terminate_master:
6404       case bp_exception_master:
6405       case bp_tracepoint:
6406       case bp_fast_tracepoint:
6407       case bp_static_tracepoint:
6408       case bp_dprintf:
6409       case bp_jit_event:
6410       case bp_gnu_ifunc_resolver:
6411       case bp_gnu_ifunc_resolver_return:
6412         if (opts.addressprint)
6413           {
6414             annotate_field (4);
6415             if (header_of_multiple)
6416               uiout->field_string ("addr", "<MULTIPLE>");
6417             else if (b->loc == NULL || loc->shlib_disabled)
6418               uiout->field_string ("addr", "<PENDING>");
6419             else
6420               uiout->field_core_addr ("addr",
6421                                       loc->gdbarch, loc->address);
6422           }
6423         annotate_field (5);
6424         if (!header_of_multiple)
6425           print_breakpoint_location (b, loc);
6426         if (b->loc)
6427           *last_loc = b->loc;
6428         break;
6429       }
6430
6431
6432   if (loc != NULL && !header_of_multiple)
6433     {
6434       struct inferior *inf;
6435       VEC(int) *inf_num = NULL;
6436       int mi_only = 1;
6437
6438       ALL_INFERIORS (inf)
6439         {
6440           if (inf->pspace == loc->pspace)
6441             VEC_safe_push (int, inf_num, inf->num);
6442         }
6443
6444         /* For backward compatibility, don't display inferiors in CLI unless
6445            there are several.  Always display for MI. */
6446         if (allflag
6447             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6448                 && (number_of_program_spaces () > 1
6449                     || number_of_inferiors () > 1)
6450                 /* LOC is for existing B, it cannot be in
6451                    moribund_locations and thus having NULL OWNER.  */
6452                 && loc->owner->type != bp_catchpoint))
6453         mi_only = 0;
6454       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6455       VEC_free (int, inf_num);
6456     }
6457
6458   if (!part_of_multiple)
6459     {
6460       if (b->thread != -1)
6461         {
6462           /* FIXME: This seems to be redundant and lost here; see the
6463              "stop only in" line a little further down.  */
6464           uiout->text (" thread ");
6465           uiout->field_int ("thread", b->thread);
6466         }
6467       else if (b->task != 0)
6468         {
6469           uiout->text (" task ");
6470           uiout->field_int ("task", b->task);
6471         }
6472     }
6473
6474   uiout->text ("\n");
6475
6476   if (!part_of_multiple)
6477     b->ops->print_one_detail (b, uiout);
6478
6479   if (part_of_multiple && frame_id_p (b->frame_id))
6480     {
6481       annotate_field (6);
6482       uiout->text ("\tstop only in stack frame at ");
6483       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6484          the frame ID.  */
6485       uiout->field_core_addr ("frame",
6486                               b->gdbarch, b->frame_id.stack_addr);
6487       uiout->text ("\n");
6488     }
6489   
6490   if (!part_of_multiple && b->cond_string)
6491     {
6492       annotate_field (7);
6493       if (is_tracepoint (b))
6494         uiout->text ("\ttrace only if ");
6495       else
6496         uiout->text ("\tstop only if ");
6497       uiout->field_string ("cond", b->cond_string);
6498
6499       /* Print whether the target is doing the breakpoint's condition
6500          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6501       if (is_breakpoint (b)
6502           && breakpoint_condition_evaluation_mode ()
6503           == condition_evaluation_target)
6504         {
6505           uiout->text (" (");
6506           uiout->field_string ("evaluated-by",
6507                                bp_condition_evaluator (b));
6508           uiout->text (" evals)");
6509         }
6510       uiout->text ("\n");
6511     }
6512
6513   if (!part_of_multiple && b->thread != -1)
6514     {
6515       /* FIXME should make an annotation for this.  */
6516       uiout->text ("\tstop only in thread ");
6517       if (uiout->is_mi_like_p ())
6518         uiout->field_int ("thread", b->thread);
6519       else
6520         {
6521           struct thread_info *thr = find_thread_global_id (b->thread);
6522
6523           uiout->field_string ("thread", print_thread_id (thr));
6524         }
6525       uiout->text ("\n");
6526     }
6527   
6528   if (!part_of_multiple)
6529     {
6530       if (b->hit_count)
6531         {
6532           /* FIXME should make an annotation for this.  */
6533           if (is_catchpoint (b))
6534             uiout->text ("\tcatchpoint");
6535           else if (is_tracepoint (b))
6536             uiout->text ("\ttracepoint");
6537           else
6538             uiout->text ("\tbreakpoint");
6539           uiout->text (" already hit ");
6540           uiout->field_int ("times", b->hit_count);
6541           if (b->hit_count == 1)
6542             uiout->text (" time\n");
6543           else
6544             uiout->text (" times\n");
6545         }
6546       else
6547         {
6548           /* Output the count also if it is zero, but only if this is mi.  */
6549           if (uiout->is_mi_like_p ())
6550             uiout->field_int ("times", b->hit_count);
6551         }
6552     }
6553
6554   if (!part_of_multiple && b->ignore_count)
6555     {
6556       annotate_field (8);
6557       uiout->text ("\tignore next ");
6558       uiout->field_int ("ignore", b->ignore_count);
6559       uiout->text (" hits\n");
6560     }
6561
6562   /* Note that an enable count of 1 corresponds to "enable once"
6563      behavior, which is reported by the combination of enablement and
6564      disposition, so we don't need to mention it here.  */
6565   if (!part_of_multiple && b->enable_count > 1)
6566     {
6567       annotate_field (8);
6568       uiout->text ("\tdisable after ");
6569       /* Tweak the wording to clarify that ignore and enable counts
6570          are distinct, and have additive effect.  */
6571       if (b->ignore_count)
6572         uiout->text ("additional ");
6573       else
6574         uiout->text ("next ");
6575       uiout->field_int ("enable", b->enable_count);
6576       uiout->text (" hits\n");
6577     }
6578
6579   if (!part_of_multiple && is_tracepoint (b))
6580     {
6581       struct tracepoint *tp = (struct tracepoint *) b;
6582
6583       if (tp->traceframe_usage)
6584         {
6585           uiout->text ("\ttrace buffer usage ");
6586           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6587           uiout->text (" bytes\n");
6588         }
6589     }
6590
6591   l = b->commands ? b->commands->commands : NULL;
6592   if (!part_of_multiple && l)
6593     {
6594       annotate_field (9);
6595       ui_out_emit_tuple tuple_emitter (uiout, "script");
6596       print_command_lines (uiout, l, 4);
6597     }
6598
6599   if (is_tracepoint (b))
6600     {
6601       struct tracepoint *t = (struct tracepoint *) b;
6602
6603       if (!part_of_multiple && t->pass_count)
6604         {
6605           annotate_field (10);
6606           uiout->text ("\tpass count ");
6607           uiout->field_int ("pass", t->pass_count);
6608           uiout->text (" \n");
6609         }
6610
6611       /* Don't display it when tracepoint or tracepoint location is
6612          pending.   */
6613       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6614         {
6615           annotate_field (11);
6616
6617           if (uiout->is_mi_like_p ())
6618             uiout->field_string ("installed",
6619                                  loc->inserted ? "y" : "n");
6620           else
6621             {
6622               if (loc->inserted)
6623                 uiout->text ("\t");
6624               else
6625                 uiout->text ("\tnot ");
6626               uiout->text ("installed on target\n");
6627             }
6628         }
6629     }
6630
6631   if (uiout->is_mi_like_p () && !part_of_multiple)
6632     {
6633       if (is_watchpoint (b))
6634         {
6635           struct watchpoint *w = (struct watchpoint *) b;
6636
6637           uiout->field_string ("original-location", w->exp_string);
6638         }
6639       else if (b->location != NULL
6640                && event_location_to_string (b->location.get ()) != NULL)
6641         uiout->field_string ("original-location",
6642                              event_location_to_string (b->location.get ()));
6643     }
6644 }
6645
6646 static void
6647 print_one_breakpoint (struct breakpoint *b,
6648                       struct bp_location **last_loc, 
6649                       int allflag)
6650 {
6651   struct ui_out *uiout = current_uiout;
6652
6653   {
6654     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6655
6656     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6657   }
6658
6659   /* If this breakpoint has custom print function,
6660      it's already printed.  Otherwise, print individual
6661      locations, if any.  */
6662   if (b->ops == NULL || b->ops->print_one == NULL)
6663     {
6664       /* If breakpoint has a single location that is disabled, we
6665          print it as if it had several locations, since otherwise it's
6666          hard to represent "breakpoint enabled, location disabled"
6667          situation.
6668
6669          Note that while hardware watchpoints have several locations
6670          internally, that's not a property exposed to user.  */
6671       if (b->loc 
6672           && !is_hardware_watchpoint (b)
6673           && (b->loc->next || !b->loc->enabled))
6674         {
6675           struct bp_location *loc;
6676           int n = 1;
6677
6678           for (loc = b->loc; loc; loc = loc->next, ++n)
6679             {
6680               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6681               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6682             }
6683         }
6684     }
6685 }
6686
6687 static int
6688 breakpoint_address_bits (struct breakpoint *b)
6689 {
6690   int print_address_bits = 0;
6691   struct bp_location *loc;
6692
6693   /* Software watchpoints that aren't watching memory don't have an
6694      address to print.  */
6695   if (is_no_memory_software_watchpoint (b))
6696     return 0;
6697
6698   for (loc = b->loc; loc; loc = loc->next)
6699     {
6700       int addr_bit;
6701
6702       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6703       if (addr_bit > print_address_bits)
6704         print_address_bits = addr_bit;
6705     }
6706
6707   return print_address_bits;
6708 }
6709
6710 struct captured_breakpoint_query_args
6711   {
6712     int bnum;
6713   };
6714
6715 static int
6716 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6717 {
6718   struct captured_breakpoint_query_args *args
6719     = (struct captured_breakpoint_query_args *) data;
6720   struct breakpoint *b;
6721   struct bp_location *dummy_loc = NULL;
6722
6723   ALL_BREAKPOINTS (b)
6724     {
6725       if (args->bnum == b->number)
6726         {
6727           print_one_breakpoint (b, &dummy_loc, 0);
6728           return GDB_RC_OK;
6729         }
6730     }
6731   return GDB_RC_NONE;
6732 }
6733
6734 enum gdb_rc
6735 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6736                       char **error_message)
6737 {
6738   struct captured_breakpoint_query_args args;
6739
6740   args.bnum = bnum;
6741   /* For the moment we don't trust print_one_breakpoint() to not throw
6742      an error.  */
6743   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6744                                  error_message, RETURN_MASK_ALL) < 0)
6745     return GDB_RC_FAIL;
6746   else
6747     return GDB_RC_OK;
6748 }
6749
6750 /* Return true if this breakpoint was set by the user, false if it is
6751    internal or momentary.  */
6752
6753 int
6754 user_breakpoint_p (struct breakpoint *b)
6755 {
6756   return b->number > 0;
6757 }
6758
6759 /* See breakpoint.h.  */
6760
6761 int
6762 pending_breakpoint_p (struct breakpoint *b)
6763 {
6764   return b->loc == NULL;
6765 }
6766
6767 /* Print information on user settable breakpoint (watchpoint, etc)
6768    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6769    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6770    FILTER is non-NULL, call it on each breakpoint and only include the
6771    ones for which it returns non-zero.  Return the total number of
6772    breakpoints listed.  */
6773
6774 static int
6775 breakpoint_1 (char *args, int allflag, 
6776               int (*filter) (const struct breakpoint *))
6777 {
6778   struct breakpoint *b;
6779   struct bp_location *last_loc = NULL;
6780   int nr_printable_breakpoints;
6781   struct cleanup *bkpttbl_chain;
6782   struct value_print_options opts;
6783   int print_address_bits = 0;
6784   int print_type_col_width = 14;
6785   struct ui_out *uiout = current_uiout;
6786
6787   get_user_print_options (&opts);
6788
6789   /* Compute the number of rows in the table, as well as the size
6790      required for address fields.  */
6791   nr_printable_breakpoints = 0;
6792   ALL_BREAKPOINTS (b)
6793     {
6794       /* If we have a filter, only list the breakpoints it accepts.  */
6795       if (filter && !filter (b))
6796         continue;
6797
6798       /* If we have an "args" string, it is a list of breakpoints to 
6799          accept.  Skip the others.  */
6800       if (args != NULL && *args != '\0')
6801         {
6802           if (allflag && parse_and_eval_long (args) != b->number)
6803             continue;
6804           if (!allflag && !number_is_in_list (args, b->number))
6805             continue;
6806         }
6807
6808       if (allflag || user_breakpoint_p (b))
6809         {
6810           int addr_bit, type_len;
6811
6812           addr_bit = breakpoint_address_bits (b);
6813           if (addr_bit > print_address_bits)
6814             print_address_bits = addr_bit;
6815
6816           type_len = strlen (bptype_string (b->type));
6817           if (type_len > print_type_col_width)
6818             print_type_col_width = type_len;
6819
6820           nr_printable_breakpoints++;
6821         }
6822     }
6823
6824   if (opts.addressprint)
6825     bkpttbl_chain 
6826       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6827                                              nr_printable_breakpoints,
6828                                              "BreakpointTable");
6829   else
6830     bkpttbl_chain 
6831       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6832                                              nr_printable_breakpoints,
6833                                              "BreakpointTable");
6834
6835   if (nr_printable_breakpoints > 0)
6836     annotate_breakpoints_headers ();
6837   if (nr_printable_breakpoints > 0)
6838     annotate_field (0);
6839   uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6840   if (nr_printable_breakpoints > 0)
6841     annotate_field (1);
6842   uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6843   if (nr_printable_breakpoints > 0)
6844     annotate_field (2);
6845   uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6846   if (nr_printable_breakpoints > 0)
6847     annotate_field (3);
6848   uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6849   if (opts.addressprint)
6850     {
6851       if (nr_printable_breakpoints > 0)
6852         annotate_field (4);
6853       if (print_address_bits <= 32)
6854         uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6855       else
6856         uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6857     }
6858   if (nr_printable_breakpoints > 0)
6859     annotate_field (5);
6860   uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6861   uiout->table_body ();
6862   if (nr_printable_breakpoints > 0)
6863     annotate_breakpoints_table ();
6864
6865   ALL_BREAKPOINTS (b)
6866     {
6867       QUIT;
6868       /* If we have a filter, only list the breakpoints it accepts.  */
6869       if (filter && !filter (b))
6870         continue;
6871
6872       /* If we have an "args" string, it is a list of breakpoints to 
6873          accept.  Skip the others.  */
6874
6875       if (args != NULL && *args != '\0')
6876         {
6877           if (allflag)  /* maintenance info breakpoint */
6878             {
6879               if (parse_and_eval_long (args) != b->number)
6880                 continue;
6881             }
6882           else          /* all others */
6883             {
6884               if (!number_is_in_list (args, b->number))
6885                 continue;
6886             }
6887         }
6888       /* We only print out user settable breakpoints unless the
6889          allflag is set.  */
6890       if (allflag || user_breakpoint_p (b))
6891         print_one_breakpoint (b, &last_loc, allflag);
6892     }
6893
6894   do_cleanups (bkpttbl_chain);
6895
6896   if (nr_printable_breakpoints == 0)
6897     {
6898       /* If there's a filter, let the caller decide how to report
6899          empty list.  */
6900       if (!filter)
6901         {
6902           if (args == NULL || *args == '\0')
6903             uiout->message ("No breakpoints or watchpoints.\n");
6904           else
6905             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6906                             args);
6907         }
6908     }
6909   else
6910     {
6911       if (last_loc && !server_command)
6912         set_next_address (last_loc->gdbarch, last_loc->address);
6913     }
6914
6915   /* FIXME?  Should this be moved up so that it is only called when
6916      there have been breakpoints? */
6917   annotate_breakpoints_table_end ();
6918
6919   return nr_printable_breakpoints;
6920 }
6921
6922 /* Display the value of default-collect in a way that is generally
6923    compatible with the breakpoint list.  */
6924
6925 static void
6926 default_collect_info (void)
6927 {
6928   struct ui_out *uiout = current_uiout;
6929
6930   /* If it has no value (which is frequently the case), say nothing; a
6931      message like "No default-collect." gets in user's face when it's
6932      not wanted.  */
6933   if (!*default_collect)
6934     return;
6935
6936   /* The following phrase lines up nicely with per-tracepoint collect
6937      actions.  */
6938   uiout->text ("default collect ");
6939   uiout->field_string ("default-collect", default_collect);
6940   uiout->text (" \n");
6941 }
6942   
6943 static void
6944 breakpoints_info (char *args, int from_tty)
6945 {
6946   breakpoint_1 (args, 0, NULL);
6947
6948   default_collect_info ();
6949 }
6950
6951 static void
6952 watchpoints_info (char *args, int from_tty)
6953 {
6954   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6955   struct ui_out *uiout = current_uiout;
6956
6957   if (num_printed == 0)
6958     {
6959       if (args == NULL || *args == '\0')
6960         uiout->message ("No watchpoints.\n");
6961       else
6962         uiout->message ("No watchpoint matching '%s'.\n", args);
6963     }
6964 }
6965
6966 static void
6967 maintenance_info_breakpoints (char *args, int from_tty)
6968 {
6969   breakpoint_1 (args, 1, NULL);
6970
6971   default_collect_info ();
6972 }
6973
6974 static int
6975 breakpoint_has_pc (struct breakpoint *b,
6976                    struct program_space *pspace,
6977                    CORE_ADDR pc, struct obj_section *section)
6978 {
6979   struct bp_location *bl = b->loc;
6980
6981   for (; bl; bl = bl->next)
6982     {
6983       if (bl->pspace == pspace
6984           && bl->address == pc
6985           && (!overlay_debugging || bl->section == section))
6986         return 1;         
6987     }
6988   return 0;
6989 }
6990
6991 /* Print a message describing any user-breakpoints set at PC.  This
6992    concerns with logical breakpoints, so we match program spaces, not
6993    address spaces.  */
6994
6995 static void
6996 describe_other_breakpoints (struct gdbarch *gdbarch,
6997                             struct program_space *pspace, CORE_ADDR pc,
6998                             struct obj_section *section, int thread)
6999 {
7000   int others = 0;
7001   struct breakpoint *b;
7002
7003   ALL_BREAKPOINTS (b)
7004     others += (user_breakpoint_p (b)
7005                && breakpoint_has_pc (b, pspace, pc, section));
7006   if (others > 0)
7007     {
7008       if (others == 1)
7009         printf_filtered (_("Note: breakpoint "));
7010       else /* if (others == ???) */
7011         printf_filtered (_("Note: breakpoints "));
7012       ALL_BREAKPOINTS (b)
7013         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7014           {
7015             others--;
7016             printf_filtered ("%d", b->number);
7017             if (b->thread == -1 && thread != -1)
7018               printf_filtered (" (all threads)");
7019             else if (b->thread != -1)
7020               printf_filtered (" (thread %d)", b->thread);
7021             printf_filtered ("%s%s ",
7022                              ((b->enable_state == bp_disabled
7023                                || b->enable_state == bp_call_disabled)
7024                               ? " (disabled)"
7025                               : ""),
7026                              (others > 1) ? "," 
7027                              : ((others == 1) ? " and" : ""));
7028           }
7029       printf_filtered (_("also set at pc "));
7030       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
7031       printf_filtered (".\n");
7032     }
7033 }
7034 \f
7035
7036 /* Return true iff it is meaningful to use the address member of
7037    BPT locations.  For some breakpoint types, the locations' address members
7038    are irrelevant and it makes no sense to attempt to compare them to other
7039    addresses (or use them for any other purpose either).
7040
7041    More specifically, each of the following breakpoint types will
7042    always have a zero valued location address and we don't want to mark
7043    breakpoints of any of these types to be a duplicate of an actual
7044    breakpoint location at address zero:
7045
7046       bp_watchpoint
7047       bp_catchpoint
7048
7049 */
7050
7051 static int
7052 breakpoint_address_is_meaningful (struct breakpoint *bpt)
7053 {
7054   enum bptype type = bpt->type;
7055
7056   return (type != bp_watchpoint && type != bp_catchpoint);
7057 }
7058
7059 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7060    true if LOC1 and LOC2 represent the same watchpoint location.  */
7061
7062 static int
7063 watchpoint_locations_match (struct bp_location *loc1, 
7064                             struct bp_location *loc2)
7065 {
7066   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7067   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7068
7069   /* Both of them must exist.  */
7070   gdb_assert (w1 != NULL);
7071   gdb_assert (w2 != NULL);
7072
7073   /* If the target can evaluate the condition expression in hardware,
7074      then we we need to insert both watchpoints even if they are at
7075      the same place.  Otherwise the watchpoint will only trigger when
7076      the condition of whichever watchpoint was inserted evaluates to
7077      true, not giving a chance for GDB to check the condition of the
7078      other watchpoint.  */
7079   if ((w1->cond_exp
7080        && target_can_accel_watchpoint_condition (loc1->address, 
7081                                                  loc1->length,
7082                                                  loc1->watchpoint_type,
7083                                                  w1->cond_exp.get ()))
7084       || (w2->cond_exp
7085           && target_can_accel_watchpoint_condition (loc2->address, 
7086                                                     loc2->length,
7087                                                     loc2->watchpoint_type,
7088                                                     w2->cond_exp.get ())))
7089     return 0;
7090
7091   /* Note that this checks the owner's type, not the location's.  In
7092      case the target does not support read watchpoints, but does
7093      support access watchpoints, we'll have bp_read_watchpoint
7094      watchpoints with hw_access locations.  Those should be considered
7095      duplicates of hw_read locations.  The hw_read locations will
7096      become hw_access locations later.  */
7097   return (loc1->owner->type == loc2->owner->type
7098           && loc1->pspace->aspace == loc2->pspace->aspace
7099           && loc1->address == loc2->address
7100           && loc1->length == loc2->length);
7101 }
7102
7103 /* See breakpoint.h.  */
7104
7105 int
7106 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7107                           struct address_space *aspace2, CORE_ADDR addr2)
7108 {
7109   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7110            || aspace1 == aspace2)
7111           && addr1 == addr2);
7112 }
7113
7114 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7115    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7116    matches ASPACE2.  On targets that have global breakpoints, the address
7117    space doesn't really matter.  */
7118
7119 static int
7120 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7121                                 int len1, struct address_space *aspace2,
7122                                 CORE_ADDR addr2)
7123 {
7124   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7125            || aspace1 == aspace2)
7126           && addr2 >= addr1 && addr2 < addr1 + len1);
7127 }
7128
7129 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7130    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7131    matches the breakpoint's address space.  On targets that have global
7132    breakpoints, the address space doesn't really matter.  */
7133
7134 static int
7135 breakpoint_location_address_match (struct bp_location *bl,
7136                                    struct address_space *aspace,
7137                                    CORE_ADDR addr)
7138 {
7139   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7140                                     aspace, addr)
7141           || (bl->length
7142               && breakpoint_address_match_range (bl->pspace->aspace,
7143                                                  bl->address, bl->length,
7144                                                  aspace, addr)));
7145 }
7146
7147 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7148    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7149    match happens only if ASPACE matches the breakpoint's address
7150    space.  On targets that have global breakpoints, the address space
7151    doesn't really matter.  */
7152
7153 static int
7154 breakpoint_location_address_range_overlap (struct bp_location *bl,
7155                                            struct address_space *aspace,
7156                                            CORE_ADDR addr, int len)
7157 {
7158   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7159       || bl->pspace->aspace == aspace)
7160     {
7161       int bl_len = bl->length != 0 ? bl->length : 1;
7162
7163       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7164         return 1;
7165     }
7166   return 0;
7167 }
7168
7169 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7170    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7171    true, otherwise returns false.  */
7172
7173 static int
7174 tracepoint_locations_match (struct bp_location *loc1,
7175                             struct bp_location *loc2)
7176 {
7177   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7178     /* Since tracepoint locations are never duplicated with others', tracepoint
7179        locations at the same address of different tracepoints are regarded as
7180        different locations.  */
7181     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7182   else
7183     return 0;
7184 }
7185
7186 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7187    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7188    represent the same location.  */
7189
7190 static int
7191 breakpoint_locations_match (struct bp_location *loc1, 
7192                             struct bp_location *loc2)
7193 {
7194   int hw_point1, hw_point2;
7195
7196   /* Both of them must not be in moribund_locations.  */
7197   gdb_assert (loc1->owner != NULL);
7198   gdb_assert (loc2->owner != NULL);
7199
7200   hw_point1 = is_hardware_watchpoint (loc1->owner);
7201   hw_point2 = is_hardware_watchpoint (loc2->owner);
7202
7203   if (hw_point1 != hw_point2)
7204     return 0;
7205   else if (hw_point1)
7206     return watchpoint_locations_match (loc1, loc2);
7207   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7208     return tracepoint_locations_match (loc1, loc2);
7209   else
7210     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7211     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7212                                      loc2->pspace->aspace, loc2->address)
7213             && loc1->length == loc2->length);
7214 }
7215
7216 static void
7217 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7218                                int bnum, int have_bnum)
7219 {
7220   /* The longest string possibly returned by hex_string_custom
7221      is 50 chars.  These must be at least that big for safety.  */
7222   char astr1[64];
7223   char astr2[64];
7224
7225   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7226   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7227   if (have_bnum)
7228     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7229              bnum, astr1, astr2);
7230   else
7231     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7232 }
7233
7234 /* Adjust a breakpoint's address to account for architectural
7235    constraints on breakpoint placement.  Return the adjusted address.
7236    Note: Very few targets require this kind of adjustment.  For most
7237    targets, this function is simply the identity function.  */
7238
7239 static CORE_ADDR
7240 adjust_breakpoint_address (struct gdbarch *gdbarch,
7241                            CORE_ADDR bpaddr, enum bptype bptype)
7242 {
7243   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7244     {
7245       /* Very few targets need any kind of breakpoint adjustment.  */
7246       return bpaddr;
7247     }
7248   else if (bptype == bp_watchpoint
7249            || bptype == bp_hardware_watchpoint
7250            || bptype == bp_read_watchpoint
7251            || bptype == bp_access_watchpoint
7252            || bptype == bp_catchpoint)
7253     {
7254       /* Watchpoints and the various bp_catch_* eventpoints should not
7255          have their addresses modified.  */
7256       return bpaddr;
7257     }
7258   else if (bptype == bp_single_step)
7259     {
7260       /* Single-step breakpoints should not have their addresses
7261          modified.  If there's any architectural constrain that
7262          applies to this address, then it should have already been
7263          taken into account when the breakpoint was created in the
7264          first place.  If we didn't do this, stepping through e.g.,
7265          Thumb-2 IT blocks would break.  */
7266       return bpaddr;
7267     }
7268   else
7269     {
7270       CORE_ADDR adjusted_bpaddr;
7271
7272       /* Some targets have architectural constraints on the placement
7273          of breakpoint instructions.  Obtain the adjusted address.  */
7274       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7275
7276       /* An adjusted breakpoint address can significantly alter
7277          a user's expectations.  Print a warning if an adjustment
7278          is required.  */
7279       if (adjusted_bpaddr != bpaddr)
7280         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7281
7282       return adjusted_bpaddr;
7283     }
7284 }
7285
7286 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7287 {
7288   bp_location *loc = this;
7289
7290   gdb_assert (ops != NULL);
7291
7292   loc->ops = ops;
7293   loc->owner = owner;
7294   loc->cond_bytecode = NULL;
7295   loc->shlib_disabled = 0;
7296   loc->enabled = 1;
7297
7298   switch (owner->type)
7299     {
7300     case bp_breakpoint:
7301     case bp_single_step:
7302     case bp_until:
7303     case bp_finish:
7304     case bp_longjmp:
7305     case bp_longjmp_resume:
7306     case bp_longjmp_call_dummy:
7307     case bp_exception:
7308     case bp_exception_resume:
7309     case bp_step_resume:
7310     case bp_hp_step_resume:
7311     case bp_watchpoint_scope:
7312     case bp_call_dummy:
7313     case bp_std_terminate:
7314     case bp_shlib_event:
7315     case bp_thread_event:
7316     case bp_overlay_event:
7317     case bp_jit_event:
7318     case bp_longjmp_master:
7319     case bp_std_terminate_master:
7320     case bp_exception_master:
7321     case bp_gnu_ifunc_resolver:
7322     case bp_gnu_ifunc_resolver_return:
7323     case bp_dprintf:
7324       loc->loc_type = bp_loc_software_breakpoint;
7325       mark_breakpoint_location_modified (loc);
7326       break;
7327     case bp_hardware_breakpoint:
7328       loc->loc_type = bp_loc_hardware_breakpoint;
7329       mark_breakpoint_location_modified (loc);
7330       break;
7331     case bp_hardware_watchpoint:
7332     case bp_read_watchpoint:
7333     case bp_access_watchpoint:
7334       loc->loc_type = bp_loc_hardware_watchpoint;
7335       break;
7336     case bp_watchpoint:
7337     case bp_catchpoint:
7338     case bp_tracepoint:
7339     case bp_fast_tracepoint:
7340     case bp_static_tracepoint:
7341       loc->loc_type = bp_loc_other;
7342       break;
7343     default:
7344       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7345     }
7346
7347   loc->refc = 1;
7348 }
7349
7350 /* Allocate a struct bp_location.  */
7351
7352 static struct bp_location *
7353 allocate_bp_location (struct breakpoint *bpt)
7354 {
7355   return bpt->ops->allocate_location (bpt);
7356 }
7357
7358 static void
7359 free_bp_location (struct bp_location *loc)
7360 {
7361   loc->ops->dtor (loc);
7362   delete loc;
7363 }
7364
7365 /* Increment reference count.  */
7366
7367 static void
7368 incref_bp_location (struct bp_location *bl)
7369 {
7370   ++bl->refc;
7371 }
7372
7373 /* Decrement reference count.  If the reference count reaches 0,
7374    destroy the bp_location.  Sets *BLP to NULL.  */
7375
7376 static void
7377 decref_bp_location (struct bp_location **blp)
7378 {
7379   gdb_assert ((*blp)->refc > 0);
7380
7381   if (--(*blp)->refc == 0)
7382     free_bp_location (*blp);
7383   *blp = NULL;
7384 }
7385
7386 /* Add breakpoint B at the end of the global breakpoint chain.  */
7387
7388 static void
7389 add_to_breakpoint_chain (struct breakpoint *b)
7390 {
7391   struct breakpoint *b1;
7392
7393   /* Add this breakpoint to the end of the chain so that a list of
7394      breakpoints will come out in order of increasing numbers.  */
7395
7396   b1 = breakpoint_chain;
7397   if (b1 == 0)
7398     breakpoint_chain = b;
7399   else
7400     {
7401       while (b1->next)
7402         b1 = b1->next;
7403       b1->next = b;
7404     }
7405 }
7406
7407 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7408
7409 static void
7410 init_raw_breakpoint_without_location (struct breakpoint *b,
7411                                       struct gdbarch *gdbarch,
7412                                       enum bptype bptype,
7413                                       const struct breakpoint_ops *ops)
7414 {
7415   gdb_assert (ops != NULL);
7416
7417   b->ops = ops;
7418   b->type = bptype;
7419   b->gdbarch = gdbarch;
7420   b->language = current_language->la_language;
7421   b->input_radix = input_radix;
7422   b->related_breakpoint = b;
7423 }
7424
7425 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7426    that has type BPTYPE and has no locations as yet.  */
7427
7428 static struct breakpoint *
7429 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7430                                      enum bptype bptype,
7431                                      const struct breakpoint_ops *ops)
7432 {
7433   struct breakpoint *b = new breakpoint ();
7434
7435   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7436   add_to_breakpoint_chain (b);
7437   return b;
7438 }
7439
7440 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7441    resolutions should be made as the user specified the location explicitly
7442    enough.  */
7443
7444 static void
7445 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7446 {
7447   gdb_assert (loc->owner != NULL);
7448
7449   if (loc->owner->type == bp_breakpoint
7450       || loc->owner->type == bp_hardware_breakpoint
7451       || is_tracepoint (loc->owner))
7452     {
7453       int is_gnu_ifunc;
7454       const char *function_name;
7455       CORE_ADDR func_addr;
7456
7457       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7458                                           &func_addr, NULL, &is_gnu_ifunc);
7459
7460       if (is_gnu_ifunc && !explicit_loc)
7461         {
7462           struct breakpoint *b = loc->owner;
7463
7464           gdb_assert (loc->pspace == current_program_space);
7465           if (gnu_ifunc_resolve_name (function_name,
7466                                       &loc->requested_address))
7467             {
7468               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7469               loc->address = adjust_breakpoint_address (loc->gdbarch,
7470                                                         loc->requested_address,
7471                                                         b->type);
7472             }
7473           else if (b->type == bp_breakpoint && b->loc == loc
7474                    && loc->next == NULL && b->related_breakpoint == b)
7475             {
7476               /* Create only the whole new breakpoint of this type but do not
7477                  mess more complicated breakpoints with multiple locations.  */
7478               b->type = bp_gnu_ifunc_resolver;
7479               /* Remember the resolver's address for use by the return
7480                  breakpoint.  */
7481               loc->related_address = func_addr;
7482             }
7483         }
7484
7485       if (function_name)
7486         loc->function_name = xstrdup (function_name);
7487     }
7488 }
7489
7490 /* Attempt to determine architecture of location identified by SAL.  */
7491 struct gdbarch *
7492 get_sal_arch (struct symtab_and_line sal)
7493 {
7494   if (sal.section)
7495     return get_objfile_arch (sal.section->objfile);
7496   if (sal.symtab)
7497     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7498
7499   return NULL;
7500 }
7501
7502 /* Low level routine for partially initializing a breakpoint of type
7503    BPTYPE.  The newly created breakpoint's address, section, source
7504    file name, and line number are provided by SAL.
7505
7506    It is expected that the caller will complete the initialization of
7507    the newly created breakpoint struct as well as output any status
7508    information regarding the creation of a new breakpoint.  */
7509
7510 static void
7511 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7512                      struct symtab_and_line sal, enum bptype bptype,
7513                      const struct breakpoint_ops *ops)
7514 {
7515   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7516
7517   add_location_to_breakpoint (b, &sal);
7518
7519   if (bptype != bp_catchpoint)
7520     gdb_assert (sal.pspace != NULL);
7521
7522   /* Store the program space that was used to set the breakpoint,
7523      except for ordinary breakpoints, which are independent of the
7524      program space.  */
7525   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7526     b->pspace = sal.pspace;
7527 }
7528
7529 /* set_raw_breakpoint is a low level routine for allocating and
7530    partially initializing a breakpoint of type BPTYPE.  The newly
7531    created breakpoint's address, section, source file name, and line
7532    number are provided by SAL.  The newly created and partially
7533    initialized breakpoint is added to the breakpoint chain and
7534    is also returned as the value of this function.
7535
7536    It is expected that the caller will complete the initialization of
7537    the newly created breakpoint struct as well as output any status
7538    information regarding the creation of a new breakpoint.  In
7539    particular, set_raw_breakpoint does NOT set the breakpoint
7540    number!  Care should be taken to not allow an error to occur
7541    prior to completing the initialization of the breakpoint.  If this
7542    should happen, a bogus breakpoint will be left on the chain.  */
7543
7544 struct breakpoint *
7545 set_raw_breakpoint (struct gdbarch *gdbarch,
7546                     struct symtab_and_line sal, enum bptype bptype,
7547                     const struct breakpoint_ops *ops)
7548 {
7549   struct breakpoint *b = new breakpoint ();
7550
7551   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7552   add_to_breakpoint_chain (b);
7553   return b;
7554 }
7555
7556 /* Call this routine when stepping and nexting to enable a breakpoint
7557    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7558    initiated the operation.  */
7559
7560 void
7561 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7562 {
7563   struct breakpoint *b, *b_tmp;
7564   int thread = tp->global_num;
7565
7566   /* To avoid having to rescan all objfile symbols at every step,
7567      we maintain a list of continually-inserted but always disabled
7568      longjmp "master" breakpoints.  Here, we simply create momentary
7569      clones of those and enable them for the requested thread.  */
7570   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7571     if (b->pspace == current_program_space
7572         && (b->type == bp_longjmp_master
7573             || b->type == bp_exception_master))
7574       {
7575         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7576         struct breakpoint *clone;
7577
7578         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7579            after their removal.  */
7580         clone = momentary_breakpoint_from_master (b, type,
7581                                                   &longjmp_breakpoint_ops, 1);
7582         clone->thread = thread;
7583       }
7584
7585   tp->initiating_frame = frame;
7586 }
7587
7588 /* Delete all longjmp breakpoints from THREAD.  */
7589 void
7590 delete_longjmp_breakpoint (int thread)
7591 {
7592   struct breakpoint *b, *b_tmp;
7593
7594   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7595     if (b->type == bp_longjmp || b->type == bp_exception)
7596       {
7597         if (b->thread == thread)
7598           delete_breakpoint (b);
7599       }
7600 }
7601
7602 void
7603 delete_longjmp_breakpoint_at_next_stop (int thread)
7604 {
7605   struct breakpoint *b, *b_tmp;
7606
7607   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7608     if (b->type == bp_longjmp || b->type == bp_exception)
7609       {
7610         if (b->thread == thread)
7611           b->disposition = disp_del_at_next_stop;
7612       }
7613 }
7614
7615 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7616    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7617    pointer to any of them.  Return NULL if this system cannot place longjmp
7618    breakpoints.  */
7619
7620 struct breakpoint *
7621 set_longjmp_breakpoint_for_call_dummy (void)
7622 {
7623   struct breakpoint *b, *retval = NULL;
7624
7625   ALL_BREAKPOINTS (b)
7626     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7627       {
7628         struct breakpoint *new_b;
7629
7630         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7631                                                   &momentary_breakpoint_ops,
7632                                                   1);
7633         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7634
7635         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7636
7637         gdb_assert (new_b->related_breakpoint == new_b);
7638         if (retval == NULL)
7639           retval = new_b;
7640         new_b->related_breakpoint = retval;
7641         while (retval->related_breakpoint != new_b->related_breakpoint)
7642           retval = retval->related_breakpoint;
7643         retval->related_breakpoint = new_b;
7644       }
7645
7646   return retval;
7647 }
7648
7649 /* Verify all existing dummy frames and their associated breakpoints for
7650    TP.  Remove those which can no longer be found in the current frame
7651    stack.
7652
7653    You should call this function only at places where it is safe to currently
7654    unwind the whole stack.  Failed stack unwind would discard live dummy
7655    frames.  */
7656
7657 void
7658 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7659 {
7660   struct breakpoint *b, *b_tmp;
7661
7662   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7663     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7664       {
7665         struct breakpoint *dummy_b = b->related_breakpoint;
7666
7667         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7668           dummy_b = dummy_b->related_breakpoint;
7669         if (dummy_b->type != bp_call_dummy
7670             || frame_find_by_id (dummy_b->frame_id) != NULL)
7671           continue;
7672         
7673         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7674
7675         while (b->related_breakpoint != b)
7676           {
7677             if (b_tmp == b->related_breakpoint)
7678               b_tmp = b->related_breakpoint->next;
7679             delete_breakpoint (b->related_breakpoint);
7680           }
7681         delete_breakpoint (b);
7682       }
7683 }
7684
7685 void
7686 enable_overlay_breakpoints (void)
7687 {
7688   struct breakpoint *b;
7689
7690   ALL_BREAKPOINTS (b)
7691     if (b->type == bp_overlay_event)
7692     {
7693       b->enable_state = bp_enabled;
7694       update_global_location_list (UGLL_MAY_INSERT);
7695       overlay_events_enabled = 1;
7696     }
7697 }
7698
7699 void
7700 disable_overlay_breakpoints (void)
7701 {
7702   struct breakpoint *b;
7703
7704   ALL_BREAKPOINTS (b)
7705     if (b->type == bp_overlay_event)
7706     {
7707       b->enable_state = bp_disabled;
7708       update_global_location_list (UGLL_DONT_INSERT);
7709       overlay_events_enabled = 0;
7710     }
7711 }
7712
7713 /* Set an active std::terminate breakpoint for each std::terminate
7714    master breakpoint.  */
7715 void
7716 set_std_terminate_breakpoint (void)
7717 {
7718   struct breakpoint *b, *b_tmp;
7719
7720   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7721     if (b->pspace == current_program_space
7722         && b->type == bp_std_terminate_master)
7723       {
7724         momentary_breakpoint_from_master (b, bp_std_terminate,
7725                                           &momentary_breakpoint_ops, 1);
7726       }
7727 }
7728
7729 /* Delete all the std::terminate breakpoints.  */
7730 void
7731 delete_std_terminate_breakpoint (void)
7732 {
7733   struct breakpoint *b, *b_tmp;
7734
7735   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7736     if (b->type == bp_std_terminate)
7737       delete_breakpoint (b);
7738 }
7739
7740 struct breakpoint *
7741 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7742 {
7743   struct breakpoint *b;
7744
7745   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7746                                   &internal_breakpoint_ops);
7747
7748   b->enable_state = bp_enabled;
7749   /* location has to be used or breakpoint_re_set will delete me.  */
7750   b->location = new_address_location (b->loc->address, NULL, 0);
7751
7752   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7753
7754   return b;
7755 }
7756
7757 struct lang_and_radix
7758   {
7759     enum language lang;
7760     int radix;
7761   };
7762
7763 /* Create a breakpoint for JIT code registration and unregistration.  */
7764
7765 struct breakpoint *
7766 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7767 {
7768   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7769                                      &internal_breakpoint_ops);
7770 }
7771
7772 /* Remove JIT code registration and unregistration breakpoint(s).  */
7773
7774 void
7775 remove_jit_event_breakpoints (void)
7776 {
7777   struct breakpoint *b, *b_tmp;
7778
7779   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7780     if (b->type == bp_jit_event
7781         && b->loc->pspace == current_program_space)
7782       delete_breakpoint (b);
7783 }
7784
7785 void
7786 remove_solib_event_breakpoints (void)
7787 {
7788   struct breakpoint *b, *b_tmp;
7789
7790   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7791     if (b->type == bp_shlib_event
7792         && b->loc->pspace == current_program_space)
7793       delete_breakpoint (b);
7794 }
7795
7796 /* See breakpoint.h.  */
7797
7798 void
7799 remove_solib_event_breakpoints_at_next_stop (void)
7800 {
7801   struct breakpoint *b, *b_tmp;
7802
7803   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7804     if (b->type == bp_shlib_event
7805         && b->loc->pspace == current_program_space)
7806       b->disposition = disp_del_at_next_stop;
7807 }
7808
7809 /* Helper for create_solib_event_breakpoint /
7810    create_and_insert_solib_event_breakpoint.  Allows specifying which
7811    INSERT_MODE to pass through to update_global_location_list.  */
7812
7813 static struct breakpoint *
7814 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7815                                  enum ugll_insert_mode insert_mode)
7816 {
7817   struct breakpoint *b;
7818
7819   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7820                                   &internal_breakpoint_ops);
7821   update_global_location_list_nothrow (insert_mode);
7822   return b;
7823 }
7824
7825 struct breakpoint *
7826 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7827 {
7828   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7829 }
7830
7831 /* See breakpoint.h.  */
7832
7833 struct breakpoint *
7834 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7835 {
7836   struct breakpoint *b;
7837
7838   /* Explicitly tell update_global_location_list to insert
7839      locations.  */
7840   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7841   if (!b->loc->inserted)
7842     {
7843       delete_breakpoint (b);
7844       return NULL;
7845     }
7846   return b;
7847 }
7848
7849 /* Disable any breakpoints that are on code in shared libraries.  Only
7850    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7851
7852 void
7853 disable_breakpoints_in_shlibs (void)
7854 {
7855   struct bp_location *loc, **locp_tmp;
7856
7857   ALL_BP_LOCATIONS (loc, locp_tmp)
7858   {
7859     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7860     struct breakpoint *b = loc->owner;
7861
7862     /* We apply the check to all breakpoints, including disabled for
7863        those with loc->duplicate set.  This is so that when breakpoint
7864        becomes enabled, or the duplicate is removed, gdb will try to
7865        insert all breakpoints.  If we don't set shlib_disabled here,
7866        we'll try to insert those breakpoints and fail.  */
7867     if (((b->type == bp_breakpoint)
7868          || (b->type == bp_jit_event)
7869          || (b->type == bp_hardware_breakpoint)
7870          || (is_tracepoint (b)))
7871         && loc->pspace == current_program_space
7872         && !loc->shlib_disabled
7873         && solib_name_from_address (loc->pspace, loc->address)
7874         )
7875       {
7876         loc->shlib_disabled = 1;
7877       }
7878   }
7879 }
7880
7881 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7882    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7883    disabled ones can just stay disabled.  */
7884
7885 static void
7886 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7887 {
7888   struct bp_location *loc, **locp_tmp;
7889   int disabled_shlib_breaks = 0;
7890
7891   ALL_BP_LOCATIONS (loc, locp_tmp)
7892   {
7893     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7894     struct breakpoint *b = loc->owner;
7895
7896     if (solib->pspace == loc->pspace
7897         && !loc->shlib_disabled
7898         && (((b->type == bp_breakpoint
7899               || b->type == bp_jit_event
7900               || b->type == bp_hardware_breakpoint)
7901              && (loc->loc_type == bp_loc_hardware_breakpoint
7902                  || loc->loc_type == bp_loc_software_breakpoint))
7903             || is_tracepoint (b))
7904         && solib_contains_address_p (solib, loc->address))
7905       {
7906         loc->shlib_disabled = 1;
7907         /* At this point, we cannot rely on remove_breakpoint
7908            succeeding so we must mark the breakpoint as not inserted
7909            to prevent future errors occurring in remove_breakpoints.  */
7910         loc->inserted = 0;
7911
7912         /* This may cause duplicate notifications for the same breakpoint.  */
7913         observer_notify_breakpoint_modified (b);
7914
7915         if (!disabled_shlib_breaks)
7916           {
7917             target_terminal_ours_for_output ();
7918             warning (_("Temporarily disabling breakpoints "
7919                        "for unloaded shared library \"%s\""),
7920                      solib->so_name);
7921           }
7922         disabled_shlib_breaks = 1;
7923       }
7924   }
7925 }
7926
7927 /* Disable any breakpoints and tracepoints in OBJFILE upon
7928    notification of free_objfile.  Only apply to enabled breakpoints,
7929    disabled ones can just stay disabled.  */
7930
7931 static void
7932 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7933 {
7934   struct breakpoint *b;
7935
7936   if (objfile == NULL)
7937     return;
7938
7939   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7940      managed by the user with add-symbol-file/remove-symbol-file.
7941      Similarly to how breakpoints in shared libraries are handled in
7942      response to "nosharedlibrary", mark breakpoints in such modules
7943      shlib_disabled so they end up uninserted on the next global
7944      location list update.  Shared libraries not loaded by the user
7945      aren't handled here -- they're already handled in
7946      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7947      solib_unloaded observer.  We skip objfiles that are not
7948      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7949      main objfile).  */
7950   if ((objfile->flags & OBJF_SHARED) == 0
7951       || (objfile->flags & OBJF_USERLOADED) == 0)
7952     return;
7953
7954   ALL_BREAKPOINTS (b)
7955     {
7956       struct bp_location *loc;
7957       int bp_modified = 0;
7958
7959       if (!is_breakpoint (b) && !is_tracepoint (b))
7960         continue;
7961
7962       for (loc = b->loc; loc != NULL; loc = loc->next)
7963         {
7964           CORE_ADDR loc_addr = loc->address;
7965
7966           if (loc->loc_type != bp_loc_hardware_breakpoint
7967               && loc->loc_type != bp_loc_software_breakpoint)
7968             continue;
7969
7970           if (loc->shlib_disabled != 0)
7971             continue;
7972
7973           if (objfile->pspace != loc->pspace)
7974             continue;
7975
7976           if (loc->loc_type != bp_loc_hardware_breakpoint
7977               && loc->loc_type != bp_loc_software_breakpoint)
7978             continue;
7979
7980           if (is_addr_in_objfile (loc_addr, objfile))
7981             {
7982               loc->shlib_disabled = 1;
7983               /* At this point, we don't know whether the object was
7984                  unmapped from the inferior or not, so leave the
7985                  inserted flag alone.  We'll handle failure to
7986                  uninsert quietly, in case the object was indeed
7987                  unmapped.  */
7988
7989               mark_breakpoint_location_modified (loc);
7990
7991               bp_modified = 1;
7992             }
7993         }
7994
7995       if (bp_modified)
7996         observer_notify_breakpoint_modified (b);
7997     }
7998 }
7999
8000 /* FORK & VFORK catchpoints.  */
8001
8002 /* An instance of this type is used to represent a fork or vfork
8003    catchpoint.  It includes a "struct breakpoint" as a kind of base
8004    class; users downcast to "struct breakpoint *" when needed.  A
8005    breakpoint is really of this type iff its ops pointer points to
8006    CATCH_FORK_BREAKPOINT_OPS.  */
8007
8008 struct fork_catchpoint
8009 {
8010   /* The base class.  */
8011   struct breakpoint base;
8012
8013   /* Process id of a child process whose forking triggered this
8014      catchpoint.  This field is only valid immediately after this
8015      catchpoint has triggered.  */
8016   ptid_t forked_inferior_pid;
8017 };
8018
8019 /* Implement the "insert" breakpoint_ops method for fork
8020    catchpoints.  */
8021
8022 static int
8023 insert_catch_fork (struct bp_location *bl)
8024 {
8025   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
8026 }
8027
8028 /* Implement the "remove" breakpoint_ops method for fork
8029    catchpoints.  */
8030
8031 static int
8032 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
8033 {
8034   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
8035 }
8036
8037 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
8038    catchpoints.  */
8039
8040 static int
8041 breakpoint_hit_catch_fork (const struct bp_location *bl,
8042                            struct address_space *aspace, CORE_ADDR bp_addr,
8043                            const struct target_waitstatus *ws)
8044 {
8045   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8046
8047   if (ws->kind != TARGET_WAITKIND_FORKED)
8048     return 0;
8049
8050   c->forked_inferior_pid = ws->value.related_pid;
8051   return 1;
8052 }
8053
8054 /* Implement the "print_it" breakpoint_ops method for fork
8055    catchpoints.  */
8056
8057 static enum print_stop_action
8058 print_it_catch_fork (bpstat bs)
8059 {
8060   struct ui_out *uiout = current_uiout;
8061   struct breakpoint *b = bs->breakpoint_at;
8062   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8063
8064   annotate_catchpoint (b->number);
8065   maybe_print_thread_hit_breakpoint (uiout);
8066   if (b->disposition == disp_del)
8067     uiout->text ("Temporary catchpoint ");
8068   else
8069     uiout->text ("Catchpoint ");
8070   if (uiout->is_mi_like_p ())
8071     {
8072       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
8073       uiout->field_string ("disp", bpdisp_text (b->disposition));
8074     }
8075   uiout->field_int ("bkptno", b->number);
8076   uiout->text (" (forked process ");
8077   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8078   uiout->text ("), ");
8079   return PRINT_SRC_AND_LOC;
8080 }
8081
8082 /* Implement the "print_one" breakpoint_ops method for fork
8083    catchpoints.  */
8084
8085 static void
8086 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8087 {
8088   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8089   struct value_print_options opts;
8090   struct ui_out *uiout = current_uiout;
8091
8092   get_user_print_options (&opts);
8093
8094   /* Field 4, the address, is omitted (which makes the columns not
8095      line up too nicely with the headers, but the effect is relatively
8096      readable).  */
8097   if (opts.addressprint)
8098     uiout->field_skip ("addr");
8099   annotate_field (5);
8100   uiout->text ("fork");
8101   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8102     {
8103       uiout->text (", process ");
8104       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8105       uiout->spaces (1);
8106     }
8107
8108   if (uiout->is_mi_like_p ())
8109     uiout->field_string ("catch-type", "fork");
8110 }
8111
8112 /* Implement the "print_mention" breakpoint_ops method for fork
8113    catchpoints.  */
8114
8115 static void
8116 print_mention_catch_fork (struct breakpoint *b)
8117 {
8118   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8119 }
8120
8121 /* Implement the "print_recreate" breakpoint_ops method for fork
8122    catchpoints.  */
8123
8124 static void
8125 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8126 {
8127   fprintf_unfiltered (fp, "catch fork");
8128   print_recreate_thread (b, fp);
8129 }
8130
8131 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8132
8133 static struct breakpoint_ops catch_fork_breakpoint_ops;
8134
8135 /* Implement the "insert" breakpoint_ops method for vfork
8136    catchpoints.  */
8137
8138 static int
8139 insert_catch_vfork (struct bp_location *bl)
8140 {
8141   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8142 }
8143
8144 /* Implement the "remove" breakpoint_ops method for vfork
8145    catchpoints.  */
8146
8147 static int
8148 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
8149 {
8150   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8151 }
8152
8153 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8154    catchpoints.  */
8155
8156 static int
8157 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8158                             struct address_space *aspace, CORE_ADDR bp_addr,
8159                             const struct target_waitstatus *ws)
8160 {
8161   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8162
8163   if (ws->kind != TARGET_WAITKIND_VFORKED)
8164     return 0;
8165
8166   c->forked_inferior_pid = ws->value.related_pid;
8167   return 1;
8168 }
8169
8170 /* Implement the "print_it" breakpoint_ops method for vfork
8171    catchpoints.  */
8172
8173 static enum print_stop_action
8174 print_it_catch_vfork (bpstat bs)
8175 {
8176   struct ui_out *uiout = current_uiout;
8177   struct breakpoint *b = bs->breakpoint_at;
8178   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8179
8180   annotate_catchpoint (b->number);
8181   maybe_print_thread_hit_breakpoint (uiout);
8182   if (b->disposition == disp_del)
8183     uiout->text ("Temporary catchpoint ");
8184   else
8185     uiout->text ("Catchpoint ");
8186   if (uiout->is_mi_like_p ())
8187     {
8188       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
8189       uiout->field_string ("disp", bpdisp_text (b->disposition));
8190     }
8191   uiout->field_int ("bkptno", b->number);
8192   uiout->text (" (vforked process ");
8193   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8194   uiout->text ("), ");
8195   return PRINT_SRC_AND_LOC;
8196 }
8197
8198 /* Implement the "print_one" breakpoint_ops method for vfork
8199    catchpoints.  */
8200
8201 static void
8202 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8203 {
8204   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8205   struct value_print_options opts;
8206   struct ui_out *uiout = current_uiout;
8207
8208   get_user_print_options (&opts);
8209   /* Field 4, the address, is omitted (which makes the columns not
8210      line up too nicely with the headers, but the effect is relatively
8211      readable).  */
8212   if (opts.addressprint)
8213     uiout->field_skip ("addr");
8214   annotate_field (5);
8215   uiout->text ("vfork");
8216   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8217     {
8218       uiout->text (", process ");
8219       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8220       uiout->spaces (1);
8221     }
8222
8223   if (uiout->is_mi_like_p ())
8224     uiout->field_string ("catch-type", "vfork");
8225 }
8226
8227 /* Implement the "print_mention" breakpoint_ops method for vfork
8228    catchpoints.  */
8229
8230 static void
8231 print_mention_catch_vfork (struct breakpoint *b)
8232 {
8233   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8234 }
8235
8236 /* Implement the "print_recreate" breakpoint_ops method for vfork
8237    catchpoints.  */
8238
8239 static void
8240 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8241 {
8242   fprintf_unfiltered (fp, "catch vfork");
8243   print_recreate_thread (b, fp);
8244 }
8245
8246 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8247
8248 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8249
8250 /* An instance of this type is used to represent an solib catchpoint.
8251    It includes a "struct breakpoint" as a kind of base class; users
8252    downcast to "struct breakpoint *" when needed.  A breakpoint is
8253    really of this type iff its ops pointer points to
8254    CATCH_SOLIB_BREAKPOINT_OPS.  */
8255
8256 struct solib_catchpoint
8257 {
8258   /* The base class.  */
8259   struct breakpoint base;
8260
8261   /* True for "catch load", false for "catch unload".  */
8262   unsigned char is_load;
8263
8264   /* Regular expression to match, if any.  COMPILED is only valid when
8265      REGEX is non-NULL.  */
8266   char *regex;
8267   regex_t compiled;
8268 };
8269
8270 static void
8271 dtor_catch_solib (struct breakpoint *b)
8272 {
8273   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8274
8275   if (self->regex)
8276     regfree (&self->compiled);
8277   xfree (self->regex);
8278
8279   base_breakpoint_ops.dtor (b);
8280 }
8281
8282 static int
8283 insert_catch_solib (struct bp_location *ignore)
8284 {
8285   return 0;
8286 }
8287
8288 static int
8289 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8290 {
8291   return 0;
8292 }
8293
8294 static int
8295 breakpoint_hit_catch_solib (const struct bp_location *bl,
8296                             struct address_space *aspace,
8297                             CORE_ADDR bp_addr,
8298                             const struct target_waitstatus *ws)
8299 {
8300   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8301   struct breakpoint *other;
8302
8303   if (ws->kind == TARGET_WAITKIND_LOADED)
8304     return 1;
8305
8306   ALL_BREAKPOINTS (other)
8307   {
8308     struct bp_location *other_bl;
8309
8310     if (other == bl->owner)
8311       continue;
8312
8313     if (other->type != bp_shlib_event)
8314       continue;
8315
8316     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8317       continue;
8318
8319     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8320       {
8321         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8322           return 1;
8323       }
8324   }
8325
8326   return 0;
8327 }
8328
8329 static void
8330 check_status_catch_solib (struct bpstats *bs)
8331 {
8332   struct solib_catchpoint *self
8333     = (struct solib_catchpoint *) bs->breakpoint_at;
8334   int ix;
8335
8336   if (self->is_load)
8337     {
8338       struct so_list *iter;
8339
8340       for (ix = 0;
8341            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8342                         ix, iter);
8343            ++ix)
8344         {
8345           if (!self->regex
8346               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8347             return;
8348         }
8349     }
8350   else
8351     {
8352       char *iter;
8353
8354       for (ix = 0;
8355            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8356                         ix, iter);
8357            ++ix)
8358         {
8359           if (!self->regex
8360               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8361             return;
8362         }
8363     }
8364
8365   bs->stop = 0;
8366   bs->print_it = print_it_noop;
8367 }
8368
8369 static enum print_stop_action
8370 print_it_catch_solib (bpstat bs)
8371 {
8372   struct breakpoint *b = bs->breakpoint_at;
8373   struct ui_out *uiout = current_uiout;
8374
8375   annotate_catchpoint (b->number);
8376   maybe_print_thread_hit_breakpoint (uiout);
8377   if (b->disposition == disp_del)
8378     uiout->text ("Temporary catchpoint ");
8379   else
8380     uiout->text ("Catchpoint ");
8381   uiout->field_int ("bkptno", b->number);
8382   uiout->text ("\n");
8383   if (uiout->is_mi_like_p ())
8384     uiout->field_string ("disp", bpdisp_text (b->disposition));
8385   print_solib_event (1);
8386   return PRINT_SRC_AND_LOC;
8387 }
8388
8389 static void
8390 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8391 {
8392   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8393   struct value_print_options opts;
8394   struct ui_out *uiout = current_uiout;
8395   char *msg;
8396
8397   get_user_print_options (&opts);
8398   /* Field 4, the address, is omitted (which makes the columns not
8399      line up too nicely with the headers, but the effect is relatively
8400      readable).  */
8401   if (opts.addressprint)
8402     {
8403       annotate_field (4);
8404       uiout->field_skip ("addr");
8405     }
8406
8407   annotate_field (5);
8408   if (self->is_load)
8409     {
8410       if (self->regex)
8411         msg = xstrprintf (_("load of library matching %s"), self->regex);
8412       else
8413         msg = xstrdup (_("load of library"));
8414     }
8415   else
8416     {
8417       if (self->regex)
8418         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8419       else
8420         msg = xstrdup (_("unload of library"));
8421     }
8422   uiout->field_string ("what", msg);
8423   xfree (msg);
8424
8425   if (uiout->is_mi_like_p ())
8426     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8427 }
8428
8429 static void
8430 print_mention_catch_solib (struct breakpoint *b)
8431 {
8432   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8433
8434   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8435                    self->is_load ? "load" : "unload");
8436 }
8437
8438 static void
8439 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8440 {
8441   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8442
8443   fprintf_unfiltered (fp, "%s %s",
8444                       b->disposition == disp_del ? "tcatch" : "catch",
8445                       self->is_load ? "load" : "unload");
8446   if (self->regex)
8447     fprintf_unfiltered (fp, " %s", self->regex);
8448   fprintf_unfiltered (fp, "\n");
8449 }
8450
8451 static struct breakpoint_ops catch_solib_breakpoint_ops;
8452
8453 /* Shared helper function (MI and CLI) for creating and installing
8454    a shared object event catchpoint.  If IS_LOAD is non-zero then
8455    the events to be caught are load events, otherwise they are
8456    unload events.  If IS_TEMP is non-zero the catchpoint is a
8457    temporary one.  If ENABLED is non-zero the catchpoint is
8458    created in an enabled state.  */
8459
8460 void
8461 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8462 {
8463   struct solib_catchpoint *c;
8464   struct gdbarch *gdbarch = get_current_arch ();
8465   struct cleanup *cleanup;
8466
8467   if (!arg)
8468     arg = "";
8469   arg = skip_spaces_const (arg);
8470
8471   c = new solib_catchpoint ();
8472   cleanup = make_cleanup (xfree, c);
8473
8474   if (*arg != '\0')
8475     {
8476       int errcode;
8477
8478       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8479       if (errcode != 0)
8480         {
8481           char *err = get_regcomp_error (errcode, &c->compiled);
8482
8483           make_cleanup (xfree, err);
8484           error (_("Invalid regexp (%s): %s"), err, arg);
8485         }
8486       c->regex = xstrdup (arg);
8487     }
8488
8489   c->is_load = is_load;
8490   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8491                    &catch_solib_breakpoint_ops);
8492
8493   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8494
8495   discard_cleanups (cleanup);
8496   install_breakpoint (0, &c->base, 1);
8497 }
8498
8499 /* A helper function that does all the work for "catch load" and
8500    "catch unload".  */
8501
8502 static void
8503 catch_load_or_unload (char *arg, int from_tty, int is_load,
8504                       struct cmd_list_element *command)
8505 {
8506   int tempflag;
8507   const int enabled = 1;
8508
8509   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8510
8511   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8512 }
8513
8514 static void
8515 catch_load_command_1 (char *arg, int from_tty,
8516                       struct cmd_list_element *command)
8517 {
8518   catch_load_or_unload (arg, from_tty, 1, command);
8519 }
8520
8521 static void
8522 catch_unload_command_1 (char *arg, int from_tty,
8523                         struct cmd_list_element *command)
8524 {
8525   catch_load_or_unload (arg, from_tty, 0, command);
8526 }
8527
8528 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8529    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8530    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8531    the breakpoint_ops structure associated to the catchpoint.  */
8532
8533 void
8534 init_catchpoint (struct breakpoint *b,
8535                  struct gdbarch *gdbarch, int tempflag,
8536                  const char *cond_string,
8537                  const struct breakpoint_ops *ops)
8538 {
8539   struct symtab_and_line sal;
8540
8541   init_sal (&sal);
8542   sal.pspace = current_program_space;
8543
8544   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8545
8546   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8547   b->disposition = tempflag ? disp_del : disp_donttouch;
8548 }
8549
8550 void
8551 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8552 {
8553   add_to_breakpoint_chain (b);
8554   set_breakpoint_number (internal, b);
8555   if (is_tracepoint (b))
8556     set_tracepoint_count (breakpoint_count);
8557   if (!internal)
8558     mention (b);
8559   observer_notify_breakpoint_created (b);
8560
8561   if (update_gll)
8562     update_global_location_list (UGLL_MAY_INSERT);
8563 }
8564
8565 static void
8566 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8567                                     int tempflag, const char *cond_string,
8568                                     const struct breakpoint_ops *ops)
8569 {
8570   struct fork_catchpoint *c = new fork_catchpoint ();
8571
8572   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8573
8574   c->forked_inferior_pid = null_ptid;
8575
8576   install_breakpoint (0, &c->base, 1);
8577 }
8578
8579 /* Exec catchpoints.  */
8580
8581 /* An instance of this type is used to represent an exec catchpoint.
8582    It includes a "struct breakpoint" as a kind of base class; users
8583    downcast to "struct breakpoint *" when needed.  A breakpoint is
8584    really of this type iff its ops pointer points to
8585    CATCH_EXEC_BREAKPOINT_OPS.  */
8586
8587 struct exec_catchpoint
8588 {
8589   /* The base class.  */
8590   struct breakpoint base;
8591
8592   /* Filename of a program whose exec triggered this catchpoint.
8593      This field is only valid immediately after this catchpoint has
8594      triggered.  */
8595   char *exec_pathname;
8596 };
8597
8598 /* Implement the "dtor" breakpoint_ops method for exec
8599    catchpoints.  */
8600
8601 static void
8602 dtor_catch_exec (struct breakpoint *b)
8603 {
8604   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8605
8606   xfree (c->exec_pathname);
8607
8608   base_breakpoint_ops.dtor (b);
8609 }
8610
8611 static int
8612 insert_catch_exec (struct bp_location *bl)
8613 {
8614   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8615 }
8616
8617 static int
8618 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8619 {
8620   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8621 }
8622
8623 static int
8624 breakpoint_hit_catch_exec (const struct bp_location *bl,
8625                            struct address_space *aspace, CORE_ADDR bp_addr,
8626                            const struct target_waitstatus *ws)
8627 {
8628   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8629
8630   if (ws->kind != TARGET_WAITKIND_EXECD)
8631     return 0;
8632
8633   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8634   return 1;
8635 }
8636
8637 static enum print_stop_action
8638 print_it_catch_exec (bpstat bs)
8639 {
8640   struct ui_out *uiout = current_uiout;
8641   struct breakpoint *b = bs->breakpoint_at;
8642   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8643
8644   annotate_catchpoint (b->number);
8645   maybe_print_thread_hit_breakpoint (uiout);
8646   if (b->disposition == disp_del)
8647     uiout->text ("Temporary catchpoint ");
8648   else
8649     uiout->text ("Catchpoint ");
8650   if (uiout->is_mi_like_p ())
8651     {
8652       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8653       uiout->field_string ("disp", bpdisp_text (b->disposition));
8654     }
8655   uiout->field_int ("bkptno", b->number);
8656   uiout->text (" (exec'd ");
8657   uiout->field_string ("new-exec", c->exec_pathname);
8658   uiout->text ("), ");
8659
8660   return PRINT_SRC_AND_LOC;
8661 }
8662
8663 static void
8664 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8665 {
8666   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8667   struct value_print_options opts;
8668   struct ui_out *uiout = current_uiout;
8669
8670   get_user_print_options (&opts);
8671
8672   /* Field 4, the address, is omitted (which makes the columns
8673      not line up too nicely with the headers, but the effect
8674      is relatively readable).  */
8675   if (opts.addressprint)
8676     uiout->field_skip ("addr");
8677   annotate_field (5);
8678   uiout->text ("exec");
8679   if (c->exec_pathname != NULL)
8680     {
8681       uiout->text (", program \"");
8682       uiout->field_string ("what", c->exec_pathname);
8683       uiout->text ("\" ");
8684     }
8685
8686   if (uiout->is_mi_like_p ())
8687     uiout->field_string ("catch-type", "exec");
8688 }
8689
8690 static void
8691 print_mention_catch_exec (struct breakpoint *b)
8692 {
8693   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8694 }
8695
8696 /* Implement the "print_recreate" breakpoint_ops method for exec
8697    catchpoints.  */
8698
8699 static void
8700 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8701 {
8702   fprintf_unfiltered (fp, "catch exec");
8703   print_recreate_thread (b, fp);
8704 }
8705
8706 static struct breakpoint_ops catch_exec_breakpoint_ops;
8707
8708 static int
8709 hw_breakpoint_used_count (void)
8710 {
8711   int i = 0;
8712   struct breakpoint *b;
8713   struct bp_location *bl;
8714
8715   ALL_BREAKPOINTS (b)
8716   {
8717     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8718       for (bl = b->loc; bl; bl = bl->next)
8719         {
8720           /* Special types of hardware breakpoints may use more than
8721              one register.  */
8722           i += b->ops->resources_needed (bl);
8723         }
8724   }
8725
8726   return i;
8727 }
8728
8729 /* Returns the resources B would use if it were a hardware
8730    watchpoint.  */
8731
8732 static int
8733 hw_watchpoint_use_count (struct breakpoint *b)
8734 {
8735   int i = 0;
8736   struct bp_location *bl;
8737
8738   if (!breakpoint_enabled (b))
8739     return 0;
8740
8741   for (bl = b->loc; bl; bl = bl->next)
8742     {
8743       /* Special types of hardware watchpoints may use more than
8744          one register.  */
8745       i += b->ops->resources_needed (bl);
8746     }
8747
8748   return i;
8749 }
8750
8751 /* Returns the sum the used resources of all hardware watchpoints of
8752    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8753    the sum of the used resources of all hardware watchpoints of other
8754    types _not_ TYPE.  */
8755
8756 static int
8757 hw_watchpoint_used_count_others (struct breakpoint *except,
8758                                  enum bptype type, int *other_type_used)
8759 {
8760   int i = 0;
8761   struct breakpoint *b;
8762
8763   *other_type_used = 0;
8764   ALL_BREAKPOINTS (b)
8765     {
8766       if (b == except)
8767         continue;
8768       if (!breakpoint_enabled (b))
8769         continue;
8770
8771       if (b->type == type)
8772         i += hw_watchpoint_use_count (b);
8773       else if (is_hardware_watchpoint (b))
8774         *other_type_used = 1;
8775     }
8776
8777   return i;
8778 }
8779
8780 void
8781 disable_watchpoints_before_interactive_call_start (void)
8782 {
8783   struct breakpoint *b;
8784
8785   ALL_BREAKPOINTS (b)
8786   {
8787     if (is_watchpoint (b) && breakpoint_enabled (b))
8788       {
8789         b->enable_state = bp_call_disabled;
8790         update_global_location_list (UGLL_DONT_INSERT);
8791       }
8792   }
8793 }
8794
8795 void
8796 enable_watchpoints_after_interactive_call_stop (void)
8797 {
8798   struct breakpoint *b;
8799
8800   ALL_BREAKPOINTS (b)
8801   {
8802     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8803       {
8804         b->enable_state = bp_enabled;
8805         update_global_location_list (UGLL_MAY_INSERT);
8806       }
8807   }
8808 }
8809
8810 void
8811 disable_breakpoints_before_startup (void)
8812 {
8813   current_program_space->executing_startup = 1;
8814   update_global_location_list (UGLL_DONT_INSERT);
8815 }
8816
8817 void
8818 enable_breakpoints_after_startup (void)
8819 {
8820   current_program_space->executing_startup = 0;
8821   breakpoint_re_set ();
8822 }
8823
8824 /* Create a new single-step breakpoint for thread THREAD, with no
8825    locations.  */
8826
8827 static struct breakpoint *
8828 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8829 {
8830   struct breakpoint *b = new breakpoint ();
8831
8832   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8833                                         &momentary_breakpoint_ops);
8834
8835   b->disposition = disp_donttouch;
8836   b->frame_id = null_frame_id;
8837
8838   b->thread = thread;
8839   gdb_assert (b->thread != 0);
8840
8841   add_to_breakpoint_chain (b);
8842
8843   return b;
8844 }
8845
8846 /* Set a momentary breakpoint of type TYPE at address specified by
8847    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8848    frame.  */
8849
8850 struct breakpoint *
8851 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8852                           struct frame_id frame_id, enum bptype type)
8853 {
8854   struct breakpoint *b;
8855
8856   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8857      tail-called one.  */
8858   gdb_assert (!frame_id_artificial_p (frame_id));
8859
8860   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8861   b->enable_state = bp_enabled;
8862   b->disposition = disp_donttouch;
8863   b->frame_id = frame_id;
8864
8865   /* If we're debugging a multi-threaded program, then we want
8866      momentary breakpoints to be active in only a single thread of
8867      control.  */
8868   if (in_thread_list (inferior_ptid))
8869     b->thread = ptid_to_global_thread_id (inferior_ptid);
8870
8871   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8872
8873   return b;
8874 }
8875
8876 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8877    The new breakpoint will have type TYPE, use OPS as its
8878    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8879
8880 static struct breakpoint *
8881 momentary_breakpoint_from_master (struct breakpoint *orig,
8882                                   enum bptype type,
8883                                   const struct breakpoint_ops *ops,
8884                                   int loc_enabled)
8885 {
8886   struct breakpoint *copy;
8887
8888   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8889   copy->loc = allocate_bp_location (copy);
8890   set_breakpoint_location_function (copy->loc, 1);
8891
8892   copy->loc->gdbarch = orig->loc->gdbarch;
8893   copy->loc->requested_address = orig->loc->requested_address;
8894   copy->loc->address = orig->loc->address;
8895   copy->loc->section = orig->loc->section;
8896   copy->loc->pspace = orig->loc->pspace;
8897   copy->loc->probe = orig->loc->probe;
8898   copy->loc->line_number = orig->loc->line_number;
8899   copy->loc->symtab = orig->loc->symtab;
8900   copy->loc->enabled = loc_enabled;
8901   copy->frame_id = orig->frame_id;
8902   copy->thread = orig->thread;
8903   copy->pspace = orig->pspace;
8904
8905   copy->enable_state = bp_enabled;
8906   copy->disposition = disp_donttouch;
8907   copy->number = internal_breakpoint_number--;
8908
8909   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8910   return copy;
8911 }
8912
8913 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8914    ORIG is NULL.  */
8915
8916 struct breakpoint *
8917 clone_momentary_breakpoint (struct breakpoint *orig)
8918 {
8919   /* If there's nothing to clone, then return nothing.  */
8920   if (orig == NULL)
8921     return NULL;
8922
8923   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8924 }
8925
8926 struct breakpoint *
8927 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8928                                 enum bptype type)
8929 {
8930   struct symtab_and_line sal;
8931
8932   sal = find_pc_line (pc, 0);
8933   sal.pc = pc;
8934   sal.section = find_pc_overlay (pc);
8935   sal.explicit_pc = 1;
8936
8937   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8938 }
8939 \f
8940
8941 /* Tell the user we have just set a breakpoint B.  */
8942
8943 static void
8944 mention (struct breakpoint *b)
8945 {
8946   b->ops->print_mention (b);
8947   if (current_uiout->is_mi_like_p ())
8948     return;
8949   printf_filtered ("\n");
8950 }
8951 \f
8952
8953 static int bp_loc_is_permanent (struct bp_location *loc);
8954
8955 static struct bp_location *
8956 add_location_to_breakpoint (struct breakpoint *b,
8957                             const struct symtab_and_line *sal)
8958 {
8959   struct bp_location *loc, **tmp;
8960   CORE_ADDR adjusted_address;
8961   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8962
8963   if (loc_gdbarch == NULL)
8964     loc_gdbarch = b->gdbarch;
8965
8966   /* Adjust the breakpoint's address prior to allocating a location.
8967      Once we call allocate_bp_location(), that mostly uninitialized
8968      location will be placed on the location chain.  Adjustment of the
8969      breakpoint may cause target_read_memory() to be called and we do
8970      not want its scan of the location chain to find a breakpoint and
8971      location that's only been partially initialized.  */
8972   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8973                                                 sal->pc, b->type);
8974
8975   /* Sort the locations by their ADDRESS.  */
8976   loc = allocate_bp_location (b);
8977   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8978        tmp = &((*tmp)->next))
8979     ;
8980   loc->next = *tmp;
8981   *tmp = loc;
8982
8983   loc->requested_address = sal->pc;
8984   loc->address = adjusted_address;
8985   loc->pspace = sal->pspace;
8986   loc->probe.probe = sal->probe;
8987   loc->probe.objfile = sal->objfile;
8988   gdb_assert (loc->pspace != NULL);
8989   loc->section = sal->section;
8990   loc->gdbarch = loc_gdbarch;
8991   loc->line_number = sal->line;
8992   loc->symtab = sal->symtab;
8993
8994   set_breakpoint_location_function (loc,
8995                                     sal->explicit_pc || sal->explicit_line);
8996
8997   /* While by definition, permanent breakpoints are already present in the
8998      code, we don't mark the location as inserted.  Normally one would expect
8999      that GDB could rely on that breakpoint instruction to stop the program,
9000      thus removing the need to insert its own breakpoint, except that executing
9001      the breakpoint instruction can kill the target instead of reporting a
9002      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
9003      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
9004      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
9005      breakpoint be inserted normally results in QEMU knowing about the GDB
9006      breakpoint, and thus trap before the breakpoint instruction is executed.
9007      (If GDB later needs to continue execution past the permanent breakpoint,
9008      it manually increments the PC, thus avoiding executing the breakpoint
9009      instruction.)  */
9010   if (bp_loc_is_permanent (loc))
9011     loc->permanent = 1;
9012
9013   return loc;
9014 }
9015 \f
9016
9017 /* See breakpoint.h.  */
9018
9019 int
9020 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9021 {
9022   int len;
9023   CORE_ADDR addr;
9024   const gdb_byte *bpoint;
9025   gdb_byte *target_mem;
9026   struct cleanup *cleanup;
9027   int retval = 0;
9028
9029   addr = address;
9030   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9031
9032   /* Software breakpoints unsupported?  */
9033   if (bpoint == NULL)
9034     return 0;
9035
9036   target_mem = (gdb_byte *) alloca (len);
9037
9038   /* Enable the automatic memory restoration from breakpoints while
9039      we read the memory.  Otherwise we could say about our temporary
9040      breakpoints they are permanent.  */
9041   cleanup = make_show_memory_breakpoints_cleanup (0);
9042
9043   if (target_read_memory (address, target_mem, len) == 0
9044       && memcmp (target_mem, bpoint, len) == 0)
9045     retval = 1;
9046
9047   do_cleanups (cleanup);
9048
9049   return retval;
9050 }
9051
9052 /* Return 1 if LOC is pointing to a permanent breakpoint,
9053    return 0 otherwise.  */
9054
9055 static int
9056 bp_loc_is_permanent (struct bp_location *loc)
9057 {
9058   gdb_assert (loc != NULL);
9059
9060   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9061      attempt to read from the addresses the locations of these breakpoint types
9062      point to.  program_breakpoint_here_p, below, will attempt to read
9063      memory.  */
9064   if (!breakpoint_address_is_meaningful (loc->owner))
9065     return 0;
9066
9067   scoped_restore_current_pspace_and_thread restore_pspace_thread;
9068   switch_to_program_space_and_thread (loc->pspace);
9069   return program_breakpoint_here_p (loc->gdbarch, loc->address);
9070 }
9071
9072 /* Build a command list for the dprintf corresponding to the current
9073    settings of the dprintf style options.  */
9074
9075 static void
9076 update_dprintf_command_list (struct breakpoint *b)
9077 {
9078   char *dprintf_args = b->extra_string;
9079   char *printf_line = NULL;
9080
9081   if (!dprintf_args)
9082     return;
9083
9084   dprintf_args = skip_spaces (dprintf_args);
9085
9086   /* Allow a comma, as it may have terminated a location, but don't
9087      insist on it.  */
9088   if (*dprintf_args == ',')
9089     ++dprintf_args;
9090   dprintf_args = skip_spaces (dprintf_args);
9091
9092   if (*dprintf_args != '"')
9093     error (_("Bad format string, missing '\"'."));
9094
9095   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9096     printf_line = xstrprintf ("printf %s", dprintf_args);
9097   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9098     {
9099       if (!dprintf_function)
9100         error (_("No function supplied for dprintf call"));
9101
9102       if (dprintf_channel && strlen (dprintf_channel) > 0)
9103         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9104                                   dprintf_function,
9105                                   dprintf_channel,
9106                                   dprintf_args);
9107       else
9108         printf_line = xstrprintf ("call (void) %s (%s)",
9109                                   dprintf_function,
9110                                   dprintf_args);
9111     }
9112   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9113     {
9114       if (target_can_run_breakpoint_commands ())
9115         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9116       else
9117         {
9118           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9119           printf_line = xstrprintf ("printf %s", dprintf_args);
9120         }
9121     }
9122   else
9123     internal_error (__FILE__, __LINE__,
9124                     _("Invalid dprintf style."));
9125
9126   gdb_assert (printf_line != NULL);
9127   /* Manufacture a printf sequence.  */
9128   {
9129     struct command_line *printf_cmd_line = XNEW (struct command_line);
9130
9131     printf_cmd_line->control_type = simple_control;
9132     printf_cmd_line->body_count = 0;
9133     printf_cmd_line->body_list = NULL;
9134     printf_cmd_line->next = NULL;
9135     printf_cmd_line->line = printf_line;
9136
9137     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
9138   }
9139 }
9140
9141 /* Update all dprintf commands, making their command lists reflect
9142    current style settings.  */
9143
9144 static void
9145 update_dprintf_commands (char *args, int from_tty,
9146                          struct cmd_list_element *c)
9147 {
9148   struct breakpoint *b;
9149
9150   ALL_BREAKPOINTS (b)
9151     {
9152       if (b->type == bp_dprintf)
9153         update_dprintf_command_list (b);
9154     }
9155 }
9156
9157 /* Create a breakpoint with SAL as location.  Use LOCATION
9158    as a description of the location, and COND_STRING
9159    as condition expression.  If LOCATION is NULL then create an
9160    "address location" from the address in the SAL.  */
9161
9162 static void
9163 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9164                      struct symtabs_and_lines sals,
9165                      event_location_up &&location,
9166                      char *filter, char *cond_string,
9167                      char *extra_string,
9168                      enum bptype type, enum bpdisp disposition,
9169                      int thread, int task, int ignore_count,
9170                      const struct breakpoint_ops *ops, int from_tty,
9171                      int enabled, int internal, unsigned flags,
9172                      int display_canonical)
9173 {
9174   int i;
9175
9176   if (type == bp_hardware_breakpoint)
9177     {
9178       int target_resources_ok;
9179
9180       i = hw_breakpoint_used_count ();
9181       target_resources_ok =
9182         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9183                                             i + 1, 0);
9184       if (target_resources_ok == 0)
9185         error (_("No hardware breakpoint support in the target."));
9186       else if (target_resources_ok < 0)
9187         error (_("Hardware breakpoints used exceeds limit."));
9188     }
9189
9190   gdb_assert (sals.nelts > 0);
9191
9192   for (i = 0; i < sals.nelts; ++i)
9193     {
9194       struct symtab_and_line sal = sals.sals[i];
9195       struct bp_location *loc;
9196
9197       if (from_tty)
9198         {
9199           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9200           if (!loc_gdbarch)
9201             loc_gdbarch = gdbarch;
9202
9203           describe_other_breakpoints (loc_gdbarch,
9204                                       sal.pspace, sal.pc, sal.section, thread);
9205         }
9206
9207       if (i == 0)
9208         {
9209           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9210           b->thread = thread;
9211           b->task = task;
9212
9213           b->cond_string = cond_string;
9214           b->extra_string = extra_string;
9215           b->ignore_count = ignore_count;
9216           b->enable_state = enabled ? bp_enabled : bp_disabled;
9217           b->disposition = disposition;
9218
9219           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9220             b->loc->inserted = 1;
9221
9222           if (type == bp_static_tracepoint)
9223             {
9224               struct tracepoint *t = (struct tracepoint *) b;
9225               struct static_tracepoint_marker marker;
9226
9227               if (strace_marker_p (b))
9228                 {
9229                   /* We already know the marker exists, otherwise, we
9230                      wouldn't see a sal for it.  */
9231                   const char *p
9232                     = &event_location_to_string (b->location.get ())[3];
9233                   const char *endp;
9234                   char *marker_str;
9235
9236                   p = skip_spaces_const (p);
9237
9238                   endp = skip_to_space_const (p);
9239
9240                   marker_str = savestring (p, endp - p);
9241                   t->static_trace_marker_id = marker_str;
9242
9243                   printf_filtered (_("Probed static tracepoint "
9244                                      "marker \"%s\"\n"),
9245                                    t->static_trace_marker_id);
9246                 }
9247               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9248                 {
9249                   t->static_trace_marker_id = xstrdup (marker.str_id);
9250                   release_static_tracepoint_marker (&marker);
9251
9252                   printf_filtered (_("Probed static tracepoint "
9253                                      "marker \"%s\"\n"),
9254                                    t->static_trace_marker_id);
9255                 }
9256               else
9257                 warning (_("Couldn't determine the static "
9258                            "tracepoint marker to probe"));
9259             }
9260
9261           loc = b->loc;
9262         }
9263       else
9264         {
9265           loc = add_location_to_breakpoint (b, &sal);
9266           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9267             loc->inserted = 1;
9268         }
9269
9270       if (b->cond_string)
9271         {
9272           const char *arg = b->cond_string;
9273
9274           loc->cond = parse_exp_1 (&arg, loc->address,
9275                                    block_for_pc (loc->address), 0);
9276           if (*arg)
9277               error (_("Garbage '%s' follows condition"), arg);
9278         }
9279
9280       /* Dynamic printf requires and uses additional arguments on the
9281          command line, otherwise it's an error.  */
9282       if (type == bp_dprintf)
9283         {
9284           if (b->extra_string)
9285             update_dprintf_command_list (b);
9286           else
9287             error (_("Format string required"));
9288         }
9289       else if (b->extra_string)
9290         error (_("Garbage '%s' at end of command"), b->extra_string);
9291     }
9292
9293   b->display_canonical = display_canonical;
9294   if (location != NULL)
9295     b->location = std::move (location);
9296   else
9297     b->location = new_address_location (b->loc->address, NULL, 0);
9298   b->filter = filter;
9299 }
9300
9301 static void
9302 create_breakpoint_sal (struct gdbarch *gdbarch,
9303                        struct symtabs_and_lines sals,
9304                        event_location_up &&location,
9305                        char *filter, char *cond_string,
9306                        char *extra_string,
9307                        enum bptype type, enum bpdisp disposition,
9308                        int thread, int task, int ignore_count,
9309                        const struct breakpoint_ops *ops, int from_tty,
9310                        int enabled, int internal, unsigned flags,
9311                        int display_canonical)
9312 {
9313   struct breakpoint *b;
9314   struct cleanup *old_chain;
9315
9316   if (is_tracepoint_type (type))
9317     {
9318       struct tracepoint *t;
9319
9320       t = new tracepoint ();
9321       b = &t->base;
9322     }
9323   else
9324     b = new breakpoint ();
9325
9326   old_chain = make_cleanup (xfree, b);
9327
9328   init_breakpoint_sal (b, gdbarch,
9329                        sals, std::move (location),
9330                        filter, cond_string, extra_string,
9331                        type, disposition,
9332                        thread, task, ignore_count,
9333                        ops, from_tty,
9334                        enabled, internal, flags,
9335                        display_canonical);
9336   discard_cleanups (old_chain);
9337
9338   install_breakpoint (internal, b, 0);
9339 }
9340
9341 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9342    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9343    value.  COND_STRING, if not NULL, specified the condition to be
9344    used for all breakpoints.  Essentially the only case where
9345    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9346    function.  In that case, it's still not possible to specify
9347    separate conditions for different overloaded functions, so
9348    we take just a single condition string.
9349    
9350    NOTE: If the function succeeds, the caller is expected to cleanup
9351    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9352    array contents).  If the function fails (error() is called), the
9353    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9354    COND and SALS arrays and each of those arrays contents.  */
9355
9356 static void
9357 create_breakpoints_sal (struct gdbarch *gdbarch,
9358                         struct linespec_result *canonical,
9359                         char *cond_string, char *extra_string,
9360                         enum bptype type, enum bpdisp disposition,
9361                         int thread, int task, int ignore_count,
9362                         const struct breakpoint_ops *ops, int from_tty,
9363                         int enabled, int internal, unsigned flags)
9364 {
9365   int i;
9366   struct linespec_sals *lsal;
9367
9368   if (canonical->pre_expanded)
9369     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9370
9371   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9372     {
9373       /* Note that 'location' can be NULL in the case of a plain
9374          'break', without arguments.  */
9375       event_location_up location
9376         = (canonical->location != NULL
9377            ? copy_event_location (canonical->location.get ()) : NULL);
9378       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9379
9380       make_cleanup (xfree, filter_string);
9381       create_breakpoint_sal (gdbarch, lsal->sals,
9382                              std::move (location),
9383                              filter_string,
9384                              cond_string, extra_string,
9385                              type, disposition,
9386                              thread, task, ignore_count, ops,
9387                              from_tty, enabled, internal, flags,
9388                              canonical->special_display);
9389     }
9390 }
9391
9392 /* Parse LOCATION which is assumed to be a SAL specification possibly
9393    followed by conditionals.  On return, SALS contains an array of SAL
9394    addresses found.  LOCATION points to the end of the SAL (for
9395    linespec locations).
9396
9397    The array and the line spec strings are allocated on the heap, it is
9398    the caller's responsibility to free them.  */
9399
9400 static void
9401 parse_breakpoint_sals (const struct event_location *location,
9402                        struct linespec_result *canonical)
9403 {
9404   struct symtab_and_line cursal;
9405
9406   if (event_location_type (location) == LINESPEC_LOCATION)
9407     {
9408       const char *address = get_linespec_location (location);
9409
9410       if (address == NULL)
9411         {
9412           /* The last displayed codepoint, if it's valid, is our default
9413              breakpoint address.  */
9414           if (last_displayed_sal_is_valid ())
9415             {
9416               struct linespec_sals lsal;
9417               struct symtab_and_line sal;
9418               CORE_ADDR pc;
9419
9420               init_sal (&sal);          /* Initialize to zeroes.  */
9421               lsal.sals.sals = XNEW (struct symtab_and_line);
9422
9423               /* Set sal's pspace, pc, symtab, and line to the values
9424                  corresponding to the last call to print_frame_info.
9425                  Be sure to reinitialize LINE with NOTCURRENT == 0
9426                  as the breakpoint line number is inappropriate otherwise.
9427                  find_pc_line would adjust PC, re-set it back.  */
9428               get_last_displayed_sal (&sal);
9429               pc = sal.pc;
9430               sal = find_pc_line (pc, 0);
9431
9432               /* "break" without arguments is equivalent to "break *PC"
9433                  where PC is the last displayed codepoint's address.  So
9434                  make sure to set sal.explicit_pc to prevent GDB from
9435                  trying to expand the list of sals to include all other
9436                  instances with the same symtab and line.  */
9437               sal.pc = pc;
9438               sal.explicit_pc = 1;
9439
9440               lsal.sals.sals[0] = sal;
9441               lsal.sals.nelts = 1;
9442               lsal.canonical = NULL;
9443
9444               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9445               return;
9446             }
9447           else
9448             error (_("No default breakpoint address now."));
9449         }
9450     }
9451
9452   /* Force almost all breakpoints to be in terms of the
9453      current_source_symtab (which is decode_line_1's default).
9454      This should produce the results we want almost all of the
9455      time while leaving default_breakpoint_* alone.
9456
9457      ObjC: However, don't match an Objective-C method name which
9458      may have a '+' or '-' succeeded by a '['.  */
9459   cursal = get_current_source_symtab_and_line ();
9460   if (last_displayed_sal_is_valid ())
9461     {
9462       const char *address = NULL;
9463
9464       if (event_location_type (location) == LINESPEC_LOCATION)
9465         address = get_linespec_location (location);
9466
9467       if (!cursal.symtab
9468           || (address != NULL
9469               && strchr ("+-", address[0]) != NULL
9470               && address[1] != '['))
9471         {
9472           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9473                             get_last_displayed_symtab (),
9474                             get_last_displayed_line (),
9475                             canonical, NULL, NULL);
9476           return;
9477         }
9478     }
9479
9480   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9481                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9482 }
9483
9484
9485 /* Convert each SAL into a real PC.  Verify that the PC can be
9486    inserted as a breakpoint.  If it can't throw an error.  */
9487
9488 static void
9489 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9490 {    
9491   int i;
9492
9493   for (i = 0; i < sals->nelts; i++)
9494     resolve_sal_pc (&sals->sals[i]);
9495 }
9496
9497 /* Fast tracepoints may have restrictions on valid locations.  For
9498    instance, a fast tracepoint using a jump instead of a trap will
9499    likely have to overwrite more bytes than a trap would, and so can
9500    only be placed where the instruction is longer than the jump, or a
9501    multi-instruction sequence does not have a jump into the middle of
9502    it, etc.  */
9503
9504 static void
9505 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9506                             struct symtabs_and_lines *sals)
9507 {
9508   int i, rslt;
9509   struct symtab_and_line *sal;
9510   char *msg;
9511   struct cleanup *old_chain;
9512
9513   for (i = 0; i < sals->nelts; i++)
9514     {
9515       struct gdbarch *sarch;
9516
9517       sal = &sals->sals[i];
9518
9519       sarch = get_sal_arch (*sal);
9520       /* We fall back to GDBARCH if there is no architecture
9521          associated with SAL.  */
9522       if (sarch == NULL)
9523         sarch = gdbarch;
9524       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9525       old_chain = make_cleanup (xfree, msg);
9526
9527       if (!rslt)
9528         error (_("May not have a fast tracepoint at %s%s"),
9529                paddress (sarch, sal->pc), (msg ? msg : ""));
9530
9531       do_cleanups (old_chain);
9532     }
9533 }
9534
9535 /* Given TOK, a string specification of condition and thread, as
9536    accepted by the 'break' command, extract the condition
9537    string and thread number and set *COND_STRING and *THREAD.
9538    PC identifies the context at which the condition should be parsed.
9539    If no condition is found, *COND_STRING is set to NULL.
9540    If no thread is found, *THREAD is set to -1.  */
9541
9542 static void
9543 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9544                            char **cond_string, int *thread, int *task,
9545                            char **rest)
9546 {
9547   *cond_string = NULL;
9548   *thread = -1;
9549   *task = 0;
9550   *rest = NULL;
9551
9552   while (tok && *tok)
9553     {
9554       const char *end_tok;
9555       int toklen;
9556       const char *cond_start = NULL;
9557       const char *cond_end = NULL;
9558
9559       tok = skip_spaces_const (tok);
9560
9561       if ((*tok == '"' || *tok == ',') && rest)
9562         {
9563           *rest = savestring (tok, strlen (tok));
9564           return;
9565         }
9566
9567       end_tok = skip_to_space_const (tok);
9568
9569       toklen = end_tok - tok;
9570
9571       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9572         {
9573           tok = cond_start = end_tok + 1;
9574           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9575           cond_end = tok;
9576           *cond_string = savestring (cond_start, cond_end - cond_start);
9577         }
9578       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9579         {
9580           const char *tmptok;
9581           struct thread_info *thr;
9582
9583           tok = end_tok + 1;
9584           thr = parse_thread_id (tok, &tmptok);
9585           if (tok == tmptok)
9586             error (_("Junk after thread keyword."));
9587           *thread = thr->global_num;
9588           tok = tmptok;
9589         }
9590       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9591         {
9592           char *tmptok;
9593
9594           tok = end_tok + 1;
9595           *task = strtol (tok, &tmptok, 0);
9596           if (tok == tmptok)
9597             error (_("Junk after task keyword."));
9598           if (!valid_task_id (*task))
9599             error (_("Unknown task %d."), *task);
9600           tok = tmptok;
9601         }
9602       else if (rest)
9603         {
9604           *rest = savestring (tok, strlen (tok));
9605           return;
9606         }
9607       else
9608         error (_("Junk at end of arguments."));
9609     }
9610 }
9611
9612 /* Decode a static tracepoint marker spec.  */
9613
9614 static struct symtabs_and_lines
9615 decode_static_tracepoint_spec (const char **arg_p)
9616 {
9617   VEC(static_tracepoint_marker_p) *markers = NULL;
9618   struct symtabs_and_lines sals;
9619   struct cleanup *old_chain;
9620   const char *p = &(*arg_p)[3];
9621   const char *endp;
9622   char *marker_str;
9623   int i;
9624
9625   p = skip_spaces_const (p);
9626
9627   endp = skip_to_space_const (p);
9628
9629   marker_str = savestring (p, endp - p);
9630   old_chain = make_cleanup (xfree, marker_str);
9631
9632   markers = target_static_tracepoint_markers_by_strid (marker_str);
9633   if (VEC_empty(static_tracepoint_marker_p, markers))
9634     error (_("No known static tracepoint marker named %s"), marker_str);
9635
9636   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9637   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9638
9639   for (i = 0; i < sals.nelts; i++)
9640     {
9641       struct static_tracepoint_marker *marker;
9642
9643       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9644
9645       init_sal (&sals.sals[i]);
9646
9647       sals.sals[i] = find_pc_line (marker->address, 0);
9648       sals.sals[i].pc = marker->address;
9649
9650       release_static_tracepoint_marker (marker);
9651     }
9652
9653   do_cleanups (old_chain);
9654
9655   *arg_p = endp;
9656   return sals;
9657 }
9658
9659 /* See breakpoint.h.  */
9660
9661 int
9662 create_breakpoint (struct gdbarch *gdbarch,
9663                    const struct event_location *location, char *cond_string,
9664                    int thread, char *extra_string,
9665                    int parse_extra,
9666                    int tempflag, enum bptype type_wanted,
9667                    int ignore_count,
9668                    enum auto_boolean pending_break_support,
9669                    const struct breakpoint_ops *ops,
9670                    int from_tty, int enabled, int internal,
9671                    unsigned flags)
9672 {
9673   struct linespec_result canonical;
9674   struct cleanup *bkpt_chain = NULL;
9675   int pending = 0;
9676   int task = 0;
9677   int prev_bkpt_count = breakpoint_count;
9678
9679   gdb_assert (ops != NULL);
9680
9681   /* If extra_string isn't useful, set it to NULL.  */
9682   if (extra_string != NULL && *extra_string == '\0')
9683     extra_string = NULL;
9684
9685   TRY
9686     {
9687       ops->create_sals_from_location (location, &canonical, type_wanted);
9688     }
9689   CATCH (e, RETURN_MASK_ERROR)
9690     {
9691       /* If caller is interested in rc value from parse, set
9692          value.  */
9693       if (e.error == NOT_FOUND_ERROR)
9694         {
9695           /* If pending breakpoint support is turned off, throw
9696              error.  */
9697
9698           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9699             throw_exception (e);
9700
9701           exception_print (gdb_stderr, e);
9702
9703           /* If pending breakpoint support is auto query and the user
9704              selects no, then simply return the error code.  */
9705           if (pending_break_support == AUTO_BOOLEAN_AUTO
9706               && !nquery (_("Make %s pending on future shared library load? "),
9707                           bptype_string (type_wanted)))
9708             return 0;
9709
9710           /* At this point, either the user was queried about setting
9711              a pending breakpoint and selected yes, or pending
9712              breakpoint behavior is on and thus a pending breakpoint
9713              is defaulted on behalf of the user.  */
9714           pending = 1;
9715         }
9716       else
9717         throw_exception (e);
9718     }
9719   END_CATCH
9720
9721   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9722     return 0;
9723
9724   /* ----------------------------- SNIP -----------------------------
9725      Anything added to the cleanup chain beyond this point is assumed
9726      to be part of a breakpoint.  If the breakpoint create succeeds
9727      then the memory is not reclaimed.  */
9728   bkpt_chain = make_cleanup (null_cleanup, 0);
9729
9730   /* Resolve all line numbers to PC's and verify that the addresses
9731      are ok for the target.  */
9732   if (!pending)
9733     {
9734       int ix;
9735       struct linespec_sals *iter;
9736
9737       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9738         breakpoint_sals_to_pc (&iter->sals);
9739     }
9740
9741   /* Fast tracepoints may have additional restrictions on location.  */
9742   if (!pending && type_wanted == bp_fast_tracepoint)
9743     {
9744       int ix;
9745       struct linespec_sals *iter;
9746
9747       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9748         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9749     }
9750
9751   /* Verify that condition can be parsed, before setting any
9752      breakpoints.  Allocate a separate condition expression for each
9753      breakpoint.  */
9754   if (!pending)
9755     {
9756       if (parse_extra)
9757         {
9758           char *rest;
9759           struct linespec_sals *lsal;
9760
9761           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9762
9763           /* Here we only parse 'arg' to separate condition
9764              from thread number, so parsing in context of first
9765              sal is OK.  When setting the breakpoint we'll
9766              re-parse it in context of each sal.  */
9767
9768           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9769                                      &cond_string, &thread, &task, &rest);
9770           if (cond_string)
9771             make_cleanup (xfree, cond_string);
9772           if (rest)
9773             make_cleanup (xfree, rest);
9774           if (rest)
9775             extra_string = rest;
9776           else
9777             extra_string = NULL;
9778         }
9779       else
9780         {
9781           if (type_wanted != bp_dprintf
9782               && extra_string != NULL && *extra_string != '\0')
9783                 error (_("Garbage '%s' at end of location"), extra_string);
9784
9785           /* Create a private copy of condition string.  */
9786           if (cond_string)
9787             {
9788               cond_string = xstrdup (cond_string);
9789               make_cleanup (xfree, cond_string);
9790             }
9791           /* Create a private copy of any extra string.  */
9792           if (extra_string)
9793             {
9794               extra_string = xstrdup (extra_string);
9795               make_cleanup (xfree, extra_string);
9796             }
9797         }
9798
9799       ops->create_breakpoints_sal (gdbarch, &canonical,
9800                                    cond_string, extra_string, type_wanted,
9801                                    tempflag ? disp_del : disp_donttouch,
9802                                    thread, task, ignore_count, ops,
9803                                    from_tty, enabled, internal, flags);
9804     }
9805   else
9806     {
9807       struct breakpoint *b;
9808
9809       if (is_tracepoint_type (type_wanted))
9810         {
9811           struct tracepoint *t;
9812
9813           t = new tracepoint ();
9814           b = &t->base;
9815         }
9816       else
9817         b = new breakpoint ();
9818
9819       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9820       b->location = copy_event_location (location);
9821
9822       if (parse_extra)
9823         b->cond_string = NULL;
9824       else
9825         {
9826           /* Create a private copy of condition string.  */
9827           if (cond_string)
9828             {
9829               cond_string = xstrdup (cond_string);
9830               make_cleanup (xfree, cond_string);
9831             }
9832           b->cond_string = cond_string;
9833           b->thread = thread;
9834         }
9835
9836       /* Create a private copy of any extra string.  */
9837       if (extra_string != NULL)
9838         {
9839           extra_string = xstrdup (extra_string);
9840           make_cleanup (xfree, extra_string);
9841         }
9842       b->extra_string = extra_string;
9843       b->ignore_count = ignore_count;
9844       b->disposition = tempflag ? disp_del : disp_donttouch;
9845       b->condition_not_parsed = 1;
9846       b->enable_state = enabled ? bp_enabled : bp_disabled;
9847       if ((type_wanted != bp_breakpoint
9848            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9849         b->pspace = current_program_space;
9850
9851       install_breakpoint (internal, b, 0);
9852     }
9853   
9854   if (VEC_length (linespec_sals, canonical.sals) > 1)
9855     {
9856       warning (_("Multiple breakpoints were set.\nUse the "
9857                  "\"delete\" command to delete unwanted breakpoints."));
9858       prev_breakpoint_count = prev_bkpt_count;
9859     }
9860
9861   /* That's it.  Discard the cleanups for data inserted into the
9862      breakpoint.  */
9863   discard_cleanups (bkpt_chain);
9864
9865   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9866   update_global_location_list (UGLL_MAY_INSERT);
9867
9868   return 1;
9869 }
9870
9871 /* Set a breakpoint.
9872    ARG is a string describing breakpoint address,
9873    condition, and thread.
9874    FLAG specifies if a breakpoint is hardware on,
9875    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9876    and BP_TEMPFLAG.  */
9877
9878 static void
9879 break_command_1 (char *arg, int flag, int from_tty)
9880 {
9881   int tempflag = flag & BP_TEMPFLAG;
9882   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9883                              ? bp_hardware_breakpoint
9884                              : bp_breakpoint);
9885   struct breakpoint_ops *ops;
9886
9887   event_location_up location = string_to_event_location (&arg, current_language);
9888
9889   /* Matching breakpoints on probes.  */
9890   if (location != NULL
9891       && event_location_type (location.get ()) == PROBE_LOCATION)
9892     ops = &bkpt_probe_breakpoint_ops;
9893   else
9894     ops = &bkpt_breakpoint_ops;
9895
9896   create_breakpoint (get_current_arch (),
9897                      location.get (),
9898                      NULL, 0, arg, 1 /* parse arg */,
9899                      tempflag, type_wanted,
9900                      0 /* Ignore count */,
9901                      pending_break_support,
9902                      ops,
9903                      from_tty,
9904                      1 /* enabled */,
9905                      0 /* internal */,
9906                      0);
9907 }
9908
9909 /* Helper function for break_command_1 and disassemble_command.  */
9910
9911 void
9912 resolve_sal_pc (struct symtab_and_line *sal)
9913 {
9914   CORE_ADDR pc;
9915
9916   if (sal->pc == 0 && sal->symtab != NULL)
9917     {
9918       if (!find_line_pc (sal->symtab, sal->line, &pc))
9919         error (_("No line %d in file \"%s\"."),
9920                sal->line, symtab_to_filename_for_display (sal->symtab));
9921       sal->pc = pc;
9922
9923       /* If this SAL corresponds to a breakpoint inserted using a line
9924          number, then skip the function prologue if necessary.  */
9925       if (sal->explicit_line)
9926         skip_prologue_sal (sal);
9927     }
9928
9929   if (sal->section == 0 && sal->symtab != NULL)
9930     {
9931       const struct blockvector *bv;
9932       const struct block *b;
9933       struct symbol *sym;
9934
9935       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9936                                     SYMTAB_COMPUNIT (sal->symtab));
9937       if (bv != NULL)
9938         {
9939           sym = block_linkage_function (b);
9940           if (sym != NULL)
9941             {
9942               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9943               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9944                                                  sym);
9945             }
9946           else
9947             {
9948               /* It really is worthwhile to have the section, so we'll
9949                  just have to look harder. This case can be executed
9950                  if we have line numbers but no functions (as can
9951                  happen in assembly source).  */
9952
9953               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9954               switch_to_program_space_and_thread (sal->pspace);
9955
9956               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9957               if (msym.minsym)
9958                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9959             }
9960         }
9961     }
9962 }
9963
9964 void
9965 break_command (char *arg, int from_tty)
9966 {
9967   break_command_1 (arg, 0, from_tty);
9968 }
9969
9970 void
9971 tbreak_command (char *arg, int from_tty)
9972 {
9973   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9974 }
9975
9976 static void
9977 hbreak_command (char *arg, int from_tty)
9978 {
9979   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9980 }
9981
9982 static void
9983 thbreak_command (char *arg, int from_tty)
9984 {
9985   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9986 }
9987
9988 static void
9989 stop_command (char *arg, int from_tty)
9990 {
9991   printf_filtered (_("Specify the type of breakpoint to set.\n\
9992 Usage: stop in <function | address>\n\
9993        stop at <line>\n"));
9994 }
9995
9996 static void
9997 stopin_command (char *arg, int from_tty)
9998 {
9999   int badInput = 0;
10000
10001   if (arg == (char *) NULL)
10002     badInput = 1;
10003   else if (*arg != '*')
10004     {
10005       char *argptr = arg;
10006       int hasColon = 0;
10007
10008       /* Look for a ':'.  If this is a line number specification, then
10009          say it is bad, otherwise, it should be an address or
10010          function/method name.  */
10011       while (*argptr && !hasColon)
10012         {
10013           hasColon = (*argptr == ':');
10014           argptr++;
10015         }
10016
10017       if (hasColon)
10018         badInput = (*argptr != ':');    /* Not a class::method */
10019       else
10020         badInput = isdigit (*arg);      /* a simple line number */
10021     }
10022
10023   if (badInput)
10024     printf_filtered (_("Usage: stop in <function | address>\n"));
10025   else
10026     break_command_1 (arg, 0, from_tty);
10027 }
10028
10029 static void
10030 stopat_command (char *arg, int from_tty)
10031 {
10032   int badInput = 0;
10033
10034   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10035     badInput = 1;
10036   else
10037     {
10038       char *argptr = arg;
10039       int hasColon = 0;
10040
10041       /* Look for a ':'.  If there is a '::' then get out, otherwise
10042          it is probably a line number.  */
10043       while (*argptr && !hasColon)
10044         {
10045           hasColon = (*argptr == ':');
10046           argptr++;
10047         }
10048
10049       if (hasColon)
10050         badInput = (*argptr == ':');    /* we have class::method */
10051       else
10052         badInput = !isdigit (*arg);     /* not a line number */
10053     }
10054
10055   if (badInput)
10056     printf_filtered (_("Usage: stop at <line>\n"));
10057   else
10058     break_command_1 (arg, 0, from_tty);
10059 }
10060
10061 /* The dynamic printf command is mostly like a regular breakpoint, but
10062    with a prewired command list consisting of a single output command,
10063    built from extra arguments supplied on the dprintf command
10064    line.  */
10065
10066 static void
10067 dprintf_command (char *arg, int from_tty)
10068 {
10069   event_location_up location = string_to_event_location (&arg, current_language);
10070
10071   /* If non-NULL, ARG should have been advanced past the location;
10072      the next character must be ','.  */
10073   if (arg != NULL)
10074     {
10075       if (arg[0] != ',' || arg[1] == '\0')
10076         error (_("Format string required"));
10077       else
10078         {
10079           /* Skip the comma.  */
10080           ++arg;
10081         }
10082     }
10083
10084   create_breakpoint (get_current_arch (),
10085                      location.get (),
10086                      NULL, 0, arg, 1 /* parse arg */,
10087                      0, bp_dprintf,
10088                      0 /* Ignore count */,
10089                      pending_break_support,
10090                      &dprintf_breakpoint_ops,
10091                      from_tty,
10092                      1 /* enabled */,
10093                      0 /* internal */,
10094                      0);
10095 }
10096
10097 static void
10098 agent_printf_command (char *arg, int from_tty)
10099 {
10100   error (_("May only run agent-printf on the target"));
10101 }
10102
10103 /* Implement the "breakpoint_hit" breakpoint_ops method for
10104    ranged breakpoints.  */
10105
10106 static int
10107 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10108                                   struct address_space *aspace,
10109                                   CORE_ADDR bp_addr,
10110                                   const struct target_waitstatus *ws)
10111 {
10112   if (ws->kind != TARGET_WAITKIND_STOPPED
10113       || ws->value.sig != GDB_SIGNAL_TRAP)
10114     return 0;
10115
10116   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10117                                          bl->length, aspace, bp_addr);
10118 }
10119
10120 /* Implement the "resources_needed" breakpoint_ops method for
10121    ranged breakpoints.  */
10122
10123 static int
10124 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10125 {
10126   return target_ranged_break_num_registers ();
10127 }
10128
10129 /* Implement the "print_it" breakpoint_ops method for
10130    ranged breakpoints.  */
10131
10132 static enum print_stop_action
10133 print_it_ranged_breakpoint (bpstat bs)
10134 {
10135   struct breakpoint *b = bs->breakpoint_at;
10136   struct bp_location *bl = b->loc;
10137   struct ui_out *uiout = current_uiout;
10138
10139   gdb_assert (b->type == bp_hardware_breakpoint);
10140
10141   /* Ranged breakpoints have only one location.  */
10142   gdb_assert (bl && bl->next == NULL);
10143
10144   annotate_breakpoint (b->number);
10145
10146   maybe_print_thread_hit_breakpoint (uiout);
10147
10148   if (b->disposition == disp_del)
10149     uiout->text ("Temporary ranged breakpoint ");
10150   else
10151     uiout->text ("Ranged breakpoint ");
10152   if (uiout->is_mi_like_p ())
10153     {
10154       uiout->field_string ("reason",
10155                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10156       uiout->field_string ("disp", bpdisp_text (b->disposition));
10157     }
10158   uiout->field_int ("bkptno", b->number);
10159   uiout->text (", ");
10160
10161   return PRINT_SRC_AND_LOC;
10162 }
10163
10164 /* Implement the "print_one" breakpoint_ops method for
10165    ranged breakpoints.  */
10166
10167 static void
10168 print_one_ranged_breakpoint (struct breakpoint *b,
10169                              struct bp_location **last_loc)
10170 {
10171   struct bp_location *bl = b->loc;
10172   struct value_print_options opts;
10173   struct ui_out *uiout = current_uiout;
10174
10175   /* Ranged breakpoints have only one location.  */
10176   gdb_assert (bl && bl->next == NULL);
10177
10178   get_user_print_options (&opts);
10179
10180   if (opts.addressprint)
10181     /* We don't print the address range here, it will be printed later
10182        by print_one_detail_ranged_breakpoint.  */
10183     uiout->field_skip ("addr");
10184   annotate_field (5);
10185   print_breakpoint_location (b, bl);
10186   *last_loc = bl;
10187 }
10188
10189 /* Implement the "print_one_detail" breakpoint_ops method for
10190    ranged breakpoints.  */
10191
10192 static void
10193 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10194                                     struct ui_out *uiout)
10195 {
10196   CORE_ADDR address_start, address_end;
10197   struct bp_location *bl = b->loc;
10198   string_file stb;
10199
10200   gdb_assert (bl);
10201
10202   address_start = bl->address;
10203   address_end = address_start + bl->length - 1;
10204
10205   uiout->text ("\taddress range: ");
10206   stb.printf ("[%s, %s]",
10207               print_core_address (bl->gdbarch, address_start),
10208               print_core_address (bl->gdbarch, address_end));
10209   uiout->field_stream ("addr", stb);
10210   uiout->text ("\n");
10211 }
10212
10213 /* Implement the "print_mention" breakpoint_ops method for
10214    ranged breakpoints.  */
10215
10216 static void
10217 print_mention_ranged_breakpoint (struct breakpoint *b)
10218 {
10219   struct bp_location *bl = b->loc;
10220   struct ui_out *uiout = current_uiout;
10221
10222   gdb_assert (bl);
10223   gdb_assert (b->type == bp_hardware_breakpoint);
10224
10225   if (uiout->is_mi_like_p ())
10226     return;
10227
10228   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10229                    b->number, paddress (bl->gdbarch, bl->address),
10230                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10231 }
10232
10233 /* Implement the "print_recreate" breakpoint_ops method for
10234    ranged breakpoints.  */
10235
10236 static void
10237 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10238 {
10239   fprintf_unfiltered (fp, "break-range %s, %s",
10240                       event_location_to_string (b->location.get ()),
10241                       event_location_to_string (b->location_range_end.get ()));
10242   print_recreate_thread (b, fp);
10243 }
10244
10245 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10246
10247 static struct breakpoint_ops ranged_breakpoint_ops;
10248
10249 /* Find the address where the end of the breakpoint range should be
10250    placed, given the SAL of the end of the range.  This is so that if
10251    the user provides a line number, the end of the range is set to the
10252    last instruction of the given line.  */
10253
10254 static CORE_ADDR
10255 find_breakpoint_range_end (struct symtab_and_line sal)
10256 {
10257   CORE_ADDR end;
10258
10259   /* If the user provided a PC value, use it.  Otherwise,
10260      find the address of the end of the given location.  */
10261   if (sal.explicit_pc)
10262     end = sal.pc;
10263   else
10264     {
10265       int ret;
10266       CORE_ADDR start;
10267
10268       ret = find_line_pc_range (sal, &start, &end);
10269       if (!ret)
10270         error (_("Could not find location of the end of the range."));
10271
10272       /* find_line_pc_range returns the start of the next line.  */
10273       end--;
10274     }
10275
10276   return end;
10277 }
10278
10279 /* Implement the "break-range" CLI command.  */
10280
10281 static void
10282 break_range_command (char *arg, int from_tty)
10283 {
10284   char *arg_start, *addr_string_start;
10285   struct linespec_result canonical_start, canonical_end;
10286   int bp_count, can_use_bp, length;
10287   CORE_ADDR end;
10288   struct breakpoint *b;
10289   struct symtab_and_line sal_start, sal_end;
10290   struct cleanup *cleanup_bkpt;
10291   struct linespec_sals *lsal_start, *lsal_end;
10292
10293   /* We don't support software ranged breakpoints.  */
10294   if (target_ranged_break_num_registers () < 0)
10295     error (_("This target does not support hardware ranged breakpoints."));
10296
10297   bp_count = hw_breakpoint_used_count ();
10298   bp_count += target_ranged_break_num_registers ();
10299   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10300                                                    bp_count, 0);
10301   if (can_use_bp < 0)
10302     error (_("Hardware breakpoints used exceeds limit."));
10303
10304   arg = skip_spaces (arg);
10305   if (arg == NULL || arg[0] == '\0')
10306     error(_("No address range specified."));
10307
10308   arg_start = arg;
10309   event_location_up start_location = string_to_event_location (&arg,
10310                                                                current_language);
10311   parse_breakpoint_sals (start_location.get (), &canonical_start);
10312
10313   if (arg[0] != ',')
10314     error (_("Too few arguments."));
10315   else if (VEC_empty (linespec_sals, canonical_start.sals))
10316     error (_("Could not find location of the beginning of the range."));
10317
10318   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10319
10320   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10321       || lsal_start->sals.nelts != 1)
10322     error (_("Cannot create a ranged breakpoint with multiple locations."));
10323
10324   sal_start = lsal_start->sals.sals[0];
10325   addr_string_start = savestring (arg_start, arg - arg_start);
10326   cleanup_bkpt = make_cleanup (xfree, addr_string_start);
10327
10328   arg++;        /* Skip the comma.  */
10329   arg = skip_spaces (arg);
10330
10331   /* Parse the end location.  */
10332
10333   arg_start = arg;
10334
10335   /* We call decode_line_full directly here instead of using
10336      parse_breakpoint_sals because we need to specify the start location's
10337      symtab and line as the default symtab and line for the end of the
10338      range.  This makes it possible to have ranges like "foo.c:27, +14",
10339      where +14 means 14 lines from the start location.  */
10340   event_location_up end_location = string_to_event_location (&arg,
10341                                                              current_language);
10342   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10343                     sal_start.symtab, sal_start.line,
10344                     &canonical_end, NULL, NULL);
10345
10346   if (VEC_empty (linespec_sals, canonical_end.sals))
10347     error (_("Could not find location of the end of the range."));
10348
10349   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10350   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10351       || lsal_end->sals.nelts != 1)
10352     error (_("Cannot create a ranged breakpoint with multiple locations."));
10353
10354   sal_end = lsal_end->sals.sals[0];
10355
10356   end = find_breakpoint_range_end (sal_end);
10357   if (sal_start.pc > end)
10358     error (_("Invalid address range, end precedes start."));
10359
10360   length = end - sal_start.pc + 1;
10361   if (length < 0)
10362     /* Length overflowed.  */
10363     error (_("Address range too large."));
10364   else if (length == 1)
10365     {
10366       /* This range is simple enough to be handled by
10367          the `hbreak' command.  */
10368       hbreak_command (addr_string_start, 1);
10369
10370       do_cleanups (cleanup_bkpt);
10371
10372       return;
10373     }
10374
10375   /* Now set up the breakpoint.  */
10376   b = set_raw_breakpoint (get_current_arch (), sal_start,
10377                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10378   set_breakpoint_count (breakpoint_count + 1);
10379   b->number = breakpoint_count;
10380   b->disposition = disp_donttouch;
10381   b->location = std::move (start_location);
10382   b->location_range_end = std::move (end_location);
10383   b->loc->length = length;
10384
10385   do_cleanups (cleanup_bkpt);
10386
10387   mention (b);
10388   observer_notify_breakpoint_created (b);
10389   update_global_location_list (UGLL_MAY_INSERT);
10390 }
10391
10392 /*  Return non-zero if EXP is verified as constant.  Returned zero
10393     means EXP is variable.  Also the constant detection may fail for
10394     some constant expressions and in such case still falsely return
10395     zero.  */
10396
10397 static int
10398 watchpoint_exp_is_const (const struct expression *exp)
10399 {
10400   int i = exp->nelts;
10401
10402   while (i > 0)
10403     {
10404       int oplenp, argsp;
10405
10406       /* We are only interested in the descriptor of each element.  */
10407       operator_length (exp, i, &oplenp, &argsp);
10408       i -= oplenp;
10409
10410       switch (exp->elts[i].opcode)
10411         {
10412         case BINOP_ADD:
10413         case BINOP_SUB:
10414         case BINOP_MUL:
10415         case BINOP_DIV:
10416         case BINOP_REM:
10417         case BINOP_MOD:
10418         case BINOP_LSH:
10419         case BINOP_RSH:
10420         case BINOP_LOGICAL_AND:
10421         case BINOP_LOGICAL_OR:
10422         case BINOP_BITWISE_AND:
10423         case BINOP_BITWISE_IOR:
10424         case BINOP_BITWISE_XOR:
10425         case BINOP_EQUAL:
10426         case BINOP_NOTEQUAL:
10427         case BINOP_LESS:
10428         case BINOP_GTR:
10429         case BINOP_LEQ:
10430         case BINOP_GEQ:
10431         case BINOP_REPEAT:
10432         case BINOP_COMMA:
10433         case BINOP_EXP:
10434         case BINOP_MIN:
10435         case BINOP_MAX:
10436         case BINOP_INTDIV:
10437         case BINOP_CONCAT:
10438         case TERNOP_COND:
10439         case TERNOP_SLICE:
10440
10441         case OP_LONG:
10442         case OP_DOUBLE:
10443         case OP_DECFLOAT:
10444         case OP_LAST:
10445         case OP_COMPLEX:
10446         case OP_STRING:
10447         case OP_ARRAY:
10448         case OP_TYPE:
10449         case OP_TYPEOF:
10450         case OP_DECLTYPE:
10451         case OP_TYPEID:
10452         case OP_NAME:
10453         case OP_OBJC_NSSTRING:
10454
10455         case UNOP_NEG:
10456         case UNOP_LOGICAL_NOT:
10457         case UNOP_COMPLEMENT:
10458         case UNOP_ADDR:
10459         case UNOP_HIGH:
10460         case UNOP_CAST:
10461
10462         case UNOP_CAST_TYPE:
10463         case UNOP_REINTERPRET_CAST:
10464         case UNOP_DYNAMIC_CAST:
10465           /* Unary, binary and ternary operators: We have to check
10466              their operands.  If they are constant, then so is the
10467              result of that operation.  For instance, if A and B are
10468              determined to be constants, then so is "A + B".
10469
10470              UNOP_IND is one exception to the rule above, because the
10471              value of *ADDR is not necessarily a constant, even when
10472              ADDR is.  */
10473           break;
10474
10475         case OP_VAR_VALUE:
10476           /* Check whether the associated symbol is a constant.
10477
10478              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10479              possible that a buggy compiler could mark a variable as
10480              constant even when it is not, and TYPE_CONST would return
10481              true in this case, while SYMBOL_CLASS wouldn't.
10482
10483              We also have to check for function symbols because they
10484              are always constant.  */
10485           {
10486             struct symbol *s = exp->elts[i + 2].symbol;
10487
10488             if (SYMBOL_CLASS (s) != LOC_BLOCK
10489                 && SYMBOL_CLASS (s) != LOC_CONST
10490                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10491               return 0;
10492             break;
10493           }
10494
10495         /* The default action is to return 0 because we are using
10496            the optimistic approach here: If we don't know something,
10497            then it is not a constant.  */
10498         default:
10499           return 0;
10500         }
10501     }
10502
10503   return 1;
10504 }
10505
10506 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10507
10508 static void
10509 dtor_watchpoint (struct breakpoint *self)
10510 {
10511   struct watchpoint *w = (struct watchpoint *) self;
10512
10513   xfree (w->exp_string);
10514   xfree (w->exp_string_reparse);
10515   value_free (w->val);
10516
10517   base_breakpoint_ops.dtor (self);
10518 }
10519
10520 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10521
10522 static void
10523 re_set_watchpoint (struct breakpoint *b)
10524 {
10525   struct watchpoint *w = (struct watchpoint *) b;
10526
10527   /* Watchpoint can be either on expression using entirely global
10528      variables, or it can be on local variables.
10529
10530      Watchpoints of the first kind are never auto-deleted, and even
10531      persist across program restarts.  Since they can use variables
10532      from shared libraries, we need to reparse expression as libraries
10533      are loaded and unloaded.
10534
10535      Watchpoints on local variables can also change meaning as result
10536      of solib event.  For example, if a watchpoint uses both a local
10537      and a global variables in expression, it's a local watchpoint,
10538      but unloading of a shared library will make the expression
10539      invalid.  This is not a very common use case, but we still
10540      re-evaluate expression, to avoid surprises to the user.
10541
10542      Note that for local watchpoints, we re-evaluate it only if
10543      watchpoints frame id is still valid.  If it's not, it means the
10544      watchpoint is out of scope and will be deleted soon.  In fact,
10545      I'm not sure we'll ever be called in this case.
10546
10547      If a local watchpoint's frame id is still valid, then
10548      w->exp_valid_block is likewise valid, and we can safely use it.
10549
10550      Don't do anything about disabled watchpoints, since they will be
10551      reevaluated again when enabled.  */
10552   update_watchpoint (w, 1 /* reparse */);
10553 }
10554
10555 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10556
10557 static int
10558 insert_watchpoint (struct bp_location *bl)
10559 {
10560   struct watchpoint *w = (struct watchpoint *) bl->owner;
10561   int length = w->exact ? 1 : bl->length;
10562
10563   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10564                                    w->cond_exp.get ());
10565 }
10566
10567 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10568
10569 static int
10570 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10571 {
10572   struct watchpoint *w = (struct watchpoint *) bl->owner;
10573   int length = w->exact ? 1 : bl->length;
10574
10575   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10576                                    w->cond_exp.get ());
10577 }
10578
10579 static int
10580 breakpoint_hit_watchpoint (const struct bp_location *bl,
10581                            struct address_space *aspace, CORE_ADDR bp_addr,
10582                            const struct target_waitstatus *ws)
10583 {
10584   struct breakpoint *b = bl->owner;
10585   struct watchpoint *w = (struct watchpoint *) b;
10586
10587   /* Continuable hardware watchpoints are treated as non-existent if the
10588      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10589      some data address).  Otherwise gdb won't stop on a break instruction
10590      in the code (not from a breakpoint) when a hardware watchpoint has
10591      been defined.  Also skip watchpoints which we know did not trigger
10592      (did not match the data address).  */
10593   if (is_hardware_watchpoint (b)
10594       && w->watchpoint_triggered == watch_triggered_no)
10595     return 0;
10596
10597   return 1;
10598 }
10599
10600 static void
10601 check_status_watchpoint (bpstat bs)
10602 {
10603   gdb_assert (is_watchpoint (bs->breakpoint_at));
10604
10605   bpstat_check_watchpoint (bs);
10606 }
10607
10608 /* Implement the "resources_needed" breakpoint_ops method for
10609    hardware watchpoints.  */
10610
10611 static int
10612 resources_needed_watchpoint (const struct bp_location *bl)
10613 {
10614   struct watchpoint *w = (struct watchpoint *) bl->owner;
10615   int length = w->exact? 1 : bl->length;
10616
10617   return target_region_ok_for_hw_watchpoint (bl->address, length);
10618 }
10619
10620 /* Implement the "works_in_software_mode" breakpoint_ops method for
10621    hardware watchpoints.  */
10622
10623 static int
10624 works_in_software_mode_watchpoint (const struct breakpoint *b)
10625 {
10626   /* Read and access watchpoints only work with hardware support.  */
10627   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10628 }
10629
10630 static enum print_stop_action
10631 print_it_watchpoint (bpstat bs)
10632 {
10633   struct cleanup *old_chain;
10634   struct breakpoint *b;
10635   enum print_stop_action result;
10636   struct watchpoint *w;
10637   struct ui_out *uiout = current_uiout;
10638
10639   gdb_assert (bs->bp_location_at != NULL);
10640
10641   b = bs->breakpoint_at;
10642   w = (struct watchpoint *) b;
10643
10644   old_chain = make_cleanup (null_cleanup, NULL);
10645
10646   annotate_watchpoint (b->number);
10647   maybe_print_thread_hit_breakpoint (uiout);
10648
10649   string_file stb;
10650
10651   switch (b->type)
10652     {
10653     case bp_watchpoint:
10654     case bp_hardware_watchpoint:
10655       if (uiout->is_mi_like_p ())
10656         uiout->field_string
10657           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10658       mention (b);
10659       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10660       uiout->text ("\nOld value = ");
10661       watchpoint_value_print (bs->old_val, &stb);
10662       uiout->field_stream ("old", stb);
10663       uiout->text ("\nNew value = ");
10664       watchpoint_value_print (w->val, &stb);
10665       uiout->field_stream ("new", stb);
10666       uiout->text ("\n");
10667       /* More than one watchpoint may have been triggered.  */
10668       result = PRINT_UNKNOWN;
10669       break;
10670
10671     case bp_read_watchpoint:
10672       if (uiout->is_mi_like_p ())
10673         uiout->field_string
10674           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10675       mention (b);
10676       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10677       uiout->text ("\nValue = ");
10678       watchpoint_value_print (w->val, &stb);
10679       uiout->field_stream ("value", stb);
10680       uiout->text ("\n");
10681       result = PRINT_UNKNOWN;
10682       break;
10683
10684     case bp_access_watchpoint:
10685       if (bs->old_val != NULL)
10686         {
10687           if (uiout->is_mi_like_p ())
10688             uiout->field_string
10689               ("reason",
10690                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10691           mention (b);
10692           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10693           uiout->text ("\nOld value = ");
10694           watchpoint_value_print (bs->old_val, &stb);
10695           uiout->field_stream ("old", stb);
10696           uiout->text ("\nNew value = ");
10697         }
10698       else
10699         {
10700           mention (b);
10701           if (uiout->is_mi_like_p ())
10702             uiout->field_string
10703               ("reason",
10704                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10705           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10706           uiout->text ("\nValue = ");
10707         }
10708       watchpoint_value_print (w->val, &stb);
10709       uiout->field_stream ("new", stb);
10710       uiout->text ("\n");
10711       result = PRINT_UNKNOWN;
10712       break;
10713     default:
10714       result = PRINT_UNKNOWN;
10715     }
10716
10717   do_cleanups (old_chain);
10718   return result;
10719 }
10720
10721 /* Implement the "print_mention" breakpoint_ops method for hardware
10722    watchpoints.  */
10723
10724 static void
10725 print_mention_watchpoint (struct breakpoint *b)
10726 {
10727   struct watchpoint *w = (struct watchpoint *) b;
10728   struct ui_out *uiout = current_uiout;
10729   const char *tuple_name;
10730
10731   switch (b->type)
10732     {
10733     case bp_watchpoint:
10734       uiout->text ("Watchpoint ");
10735       tuple_name = "wpt";
10736       break;
10737     case bp_hardware_watchpoint:
10738       uiout->text ("Hardware watchpoint ");
10739       tuple_name = "wpt";
10740       break;
10741     case bp_read_watchpoint:
10742       uiout->text ("Hardware read watchpoint ");
10743       tuple_name = "hw-rwpt";
10744       break;
10745     case bp_access_watchpoint:
10746       uiout->text ("Hardware access (read/write) watchpoint ");
10747       tuple_name = "hw-awpt";
10748       break;
10749     default:
10750       internal_error (__FILE__, __LINE__,
10751                       _("Invalid hardware watchpoint type."));
10752     }
10753
10754   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10755   uiout->field_int ("number", b->number);
10756   uiout->text (": ");
10757   uiout->field_string ("exp", w->exp_string);
10758 }
10759
10760 /* Implement the "print_recreate" breakpoint_ops method for
10761    watchpoints.  */
10762
10763 static void
10764 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10765 {
10766   struct watchpoint *w = (struct watchpoint *) b;
10767
10768   switch (b->type)
10769     {
10770     case bp_watchpoint:
10771     case bp_hardware_watchpoint:
10772       fprintf_unfiltered (fp, "watch");
10773       break;
10774     case bp_read_watchpoint:
10775       fprintf_unfiltered (fp, "rwatch");
10776       break;
10777     case bp_access_watchpoint:
10778       fprintf_unfiltered (fp, "awatch");
10779       break;
10780     default:
10781       internal_error (__FILE__, __LINE__,
10782                       _("Invalid watchpoint type."));
10783     }
10784
10785   fprintf_unfiltered (fp, " %s", w->exp_string);
10786   print_recreate_thread (b, fp);
10787 }
10788
10789 /* Implement the "explains_signal" breakpoint_ops method for
10790    watchpoints.  */
10791
10792 static int
10793 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10794 {
10795   /* A software watchpoint cannot cause a signal other than
10796      GDB_SIGNAL_TRAP.  */
10797   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10798     return 0;
10799
10800   return 1;
10801 }
10802
10803 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10804
10805 static struct breakpoint_ops watchpoint_breakpoint_ops;
10806
10807 /* Implement the "insert" breakpoint_ops method for
10808    masked hardware watchpoints.  */
10809
10810 static int
10811 insert_masked_watchpoint (struct bp_location *bl)
10812 {
10813   struct watchpoint *w = (struct watchpoint *) bl->owner;
10814
10815   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10816                                         bl->watchpoint_type);
10817 }
10818
10819 /* Implement the "remove" breakpoint_ops method for
10820    masked hardware watchpoints.  */
10821
10822 static int
10823 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10824 {
10825   struct watchpoint *w = (struct watchpoint *) bl->owner;
10826
10827   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10828                                         bl->watchpoint_type);
10829 }
10830
10831 /* Implement the "resources_needed" breakpoint_ops method for
10832    masked hardware watchpoints.  */
10833
10834 static int
10835 resources_needed_masked_watchpoint (const struct bp_location *bl)
10836 {
10837   struct watchpoint *w = (struct watchpoint *) bl->owner;
10838
10839   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10840 }
10841
10842 /* Implement the "works_in_software_mode" breakpoint_ops method for
10843    masked hardware watchpoints.  */
10844
10845 static int
10846 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10847 {
10848   return 0;
10849 }
10850
10851 /* Implement the "print_it" breakpoint_ops method for
10852    masked hardware watchpoints.  */
10853
10854 static enum print_stop_action
10855 print_it_masked_watchpoint (bpstat bs)
10856 {
10857   struct breakpoint *b = bs->breakpoint_at;
10858   struct ui_out *uiout = current_uiout;
10859
10860   /* Masked watchpoints have only one location.  */
10861   gdb_assert (b->loc && b->loc->next == NULL);
10862
10863   annotate_watchpoint (b->number);
10864   maybe_print_thread_hit_breakpoint (uiout);
10865
10866   switch (b->type)
10867     {
10868     case bp_hardware_watchpoint:
10869       if (uiout->is_mi_like_p ())
10870         uiout->field_string
10871           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10872       break;
10873
10874     case bp_read_watchpoint:
10875       if (uiout->is_mi_like_p ())
10876         uiout->field_string
10877           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10878       break;
10879
10880     case bp_access_watchpoint:
10881       if (uiout->is_mi_like_p ())
10882         uiout->field_string
10883           ("reason",
10884            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10885       break;
10886     default:
10887       internal_error (__FILE__, __LINE__,
10888                       _("Invalid hardware watchpoint type."));
10889     }
10890
10891   mention (b);
10892   uiout->text (_("\n\
10893 Check the underlying instruction at PC for the memory\n\
10894 address and value which triggered this watchpoint.\n"));
10895   uiout->text ("\n");
10896
10897   /* More than one watchpoint may have been triggered.  */
10898   return PRINT_UNKNOWN;
10899 }
10900
10901 /* Implement the "print_one_detail" breakpoint_ops method for
10902    masked hardware watchpoints.  */
10903
10904 static void
10905 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10906                                     struct ui_out *uiout)
10907 {
10908   struct watchpoint *w = (struct watchpoint *) b;
10909
10910   /* Masked watchpoints have only one location.  */
10911   gdb_assert (b->loc && b->loc->next == NULL);
10912
10913   uiout->text ("\tmask ");
10914   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10915   uiout->text ("\n");
10916 }
10917
10918 /* Implement the "print_mention" breakpoint_ops method for
10919    masked hardware watchpoints.  */
10920
10921 static void
10922 print_mention_masked_watchpoint (struct breakpoint *b)
10923 {
10924   struct watchpoint *w = (struct watchpoint *) b;
10925   struct ui_out *uiout = current_uiout;
10926   const char *tuple_name;
10927
10928   switch (b->type)
10929     {
10930     case bp_hardware_watchpoint:
10931       uiout->text ("Masked hardware watchpoint ");
10932       tuple_name = "wpt";
10933       break;
10934     case bp_read_watchpoint:
10935       uiout->text ("Masked hardware read watchpoint ");
10936       tuple_name = "hw-rwpt";
10937       break;
10938     case bp_access_watchpoint:
10939       uiout->text ("Masked hardware access (read/write) watchpoint ");
10940       tuple_name = "hw-awpt";
10941       break;
10942     default:
10943       internal_error (__FILE__, __LINE__,
10944                       _("Invalid hardware watchpoint type."));
10945     }
10946
10947   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10948   uiout->field_int ("number", b->number);
10949   uiout->text (": ");
10950   uiout->field_string ("exp", w->exp_string);
10951 }
10952
10953 /* Implement the "print_recreate" breakpoint_ops method for
10954    masked hardware watchpoints.  */
10955
10956 static void
10957 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10958 {
10959   struct watchpoint *w = (struct watchpoint *) b;
10960   char tmp[40];
10961
10962   switch (b->type)
10963     {
10964     case bp_hardware_watchpoint:
10965       fprintf_unfiltered (fp, "watch");
10966       break;
10967     case bp_read_watchpoint:
10968       fprintf_unfiltered (fp, "rwatch");
10969       break;
10970     case bp_access_watchpoint:
10971       fprintf_unfiltered (fp, "awatch");
10972       break;
10973     default:
10974       internal_error (__FILE__, __LINE__,
10975                       _("Invalid hardware watchpoint type."));
10976     }
10977
10978   sprintf_vma (tmp, w->hw_wp_mask);
10979   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10980   print_recreate_thread (b, fp);
10981 }
10982
10983 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10984
10985 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10986
10987 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10988
10989 static int
10990 is_masked_watchpoint (const struct breakpoint *b)
10991 {
10992   return b->ops == &masked_watchpoint_breakpoint_ops;
10993 }
10994
10995 /* accessflag:  hw_write:  watch write, 
10996                 hw_read:   watch read, 
10997                 hw_access: watch access (read or write) */
10998 static void
10999 watch_command_1 (const char *arg, int accessflag, int from_tty,
11000                  int just_location, int internal)
11001 {
11002   struct breakpoint *b, *scope_breakpoint = NULL;
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   const char *exp_start = NULL;
11007   const char *exp_end = NULL;
11008   const char *tok, *end_tok;
11009   int toklen = -1;
11010   const char *cond_start = NULL;
11011   const char *cond_end = NULL;
11012   enum bptype bp_type;
11013   int thread = -1;
11014   int pc = 0;
11015   /* Flag to indicate whether we are going to use masks for
11016      the hardware watchpoint.  */
11017   int use_mask = 0;
11018   CORE_ADDR mask = 0;
11019   struct watchpoint *w;
11020   char *expression;
11021   struct cleanup *back_to;
11022
11023   /* Make sure that we actually have parameters to parse.  */
11024   if (arg != NULL && arg[0] != '\0')
11025     {
11026       const char *value_start;
11027
11028       exp_end = arg + strlen (arg);
11029
11030       /* Look for "parameter value" pairs at the end
11031          of the arguments string.  */
11032       for (tok = exp_end - 1; tok > arg; tok--)
11033         {
11034           /* Skip whitespace at the end of the argument list.  */
11035           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11036             tok--;
11037
11038           /* Find the beginning of the last token.
11039              This is the value of the parameter.  */
11040           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11041             tok--;
11042           value_start = tok + 1;
11043
11044           /* Skip whitespace.  */
11045           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11046             tok--;
11047
11048           end_tok = tok;
11049
11050           /* Find the beginning of the second to last token.
11051              This is the parameter itself.  */
11052           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11053             tok--;
11054           tok++;
11055           toklen = end_tok - tok + 1;
11056
11057           if (toklen == 6 && startswith (tok, "thread"))
11058             {
11059               struct thread_info *thr;
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               const 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               thr = parse_thread_id (value_start, &endp);
11070
11071               /* Check if the user provided a valid thread ID.  */
11072               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11073                 invalid_thread_id_error (value_start);
11074
11075               thread = thr->global_num;
11076             }
11077           else if (toklen == 4 && startswith (tok, "mask"))
11078             {
11079               /* We've found a "mask" token, which means the user wants to
11080                  create a hardware watchpoint that is going to have the mask
11081                  facility.  */
11082               struct value *mask_value, *mark;
11083
11084               if (use_mask)
11085                 error(_("You can specify only one mask."));
11086
11087               use_mask = just_location = 1;
11088
11089               mark = value_mark ();
11090               mask_value = parse_to_comma_and_eval (&value_start);
11091               mask = value_as_address (mask_value);
11092               value_free_to_mark (mark);
11093             }
11094           else
11095             /* We didn't recognize what we found.  We should stop here.  */
11096             break;
11097
11098           /* Truncate the string and get rid of the "parameter value" pair before
11099              the arguments string is parsed by the parse_exp_1 function.  */
11100           exp_end = tok;
11101         }
11102     }
11103   else
11104     exp_end = arg;
11105
11106   /* Parse the rest of the arguments.  From here on out, everything
11107      is in terms of a newly allocated string instead of the original
11108      ARG.  */
11109   innermost_block = NULL;
11110   expression = savestring (arg, exp_end - arg);
11111   back_to = make_cleanup (xfree, expression);
11112   exp_start = arg = expression;
11113   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
11114   exp_end = arg;
11115   /* Remove trailing whitespace from the expression before saving it.
11116      This makes the eventual display of the expression string a bit
11117      prettier.  */
11118   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11119     --exp_end;
11120
11121   /* Checking if the expression is not constant.  */
11122   if (watchpoint_exp_is_const (exp.get ()))
11123     {
11124       int len;
11125
11126       len = exp_end - exp_start;
11127       while (len > 0 && isspace (exp_start[len - 1]))
11128         len--;
11129       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11130     }
11131
11132   exp_valid_block = innermost_block;
11133   mark = value_mark ();
11134   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
11135
11136   if (val != NULL && just_location)
11137     {
11138       saved_bitpos = value_bitpos (val);
11139       saved_bitsize = value_bitsize (val);
11140     }
11141
11142   if (just_location)
11143     {
11144       int ret;
11145
11146       exp_valid_block = NULL;
11147       val = value_addr (result);
11148       release_value (val);
11149       value_free_to_mark (mark);
11150
11151       if (use_mask)
11152         {
11153           ret = target_masked_watch_num_registers (value_as_address (val),
11154                                                    mask);
11155           if (ret == -1)
11156             error (_("This target does not support masked watchpoints."));
11157           else if (ret == -2)
11158             error (_("Invalid mask or memory region."));
11159         }
11160     }
11161   else if (val != NULL)
11162     release_value (val);
11163
11164   tok = skip_spaces_const (arg);
11165   end_tok = skip_to_space_const (tok);
11166
11167   toklen = end_tok - tok;
11168   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11169     {
11170       innermost_block = NULL;
11171       tok = cond_start = end_tok + 1;
11172       parse_exp_1 (&tok, 0, 0, 0);
11173
11174       /* The watchpoint expression may not be local, but the condition
11175          may still be.  E.g.: `watch global if local > 0'.  */
11176       cond_exp_valid_block = innermost_block;
11177
11178       cond_end = tok;
11179     }
11180   if (*tok)
11181     error (_("Junk at end of command."));
11182
11183   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
11184
11185   /* Save this because create_internal_breakpoint below invalidates
11186      'wp_frame'.  */
11187   frame_id watchpoint_frame = get_frame_id (wp_frame);
11188
11189   /* If the expression is "local", then set up a "watchpoint scope"
11190      breakpoint at the point where we've left the scope of the watchpoint
11191      expression.  Create the scope breakpoint before the watchpoint, so
11192      that we will encounter it first in bpstat_stop_status.  */
11193   if (exp_valid_block != NULL && wp_frame != NULL)
11194     {
11195       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
11196
11197       if (frame_id_p (caller_frame_id))
11198         {
11199           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
11200           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
11201
11202           scope_breakpoint
11203             = create_internal_breakpoint (caller_arch, caller_pc,
11204                                           bp_watchpoint_scope,
11205                                           &momentary_breakpoint_ops);
11206
11207           /* create_internal_breakpoint could invalidate WP_FRAME.  */
11208           wp_frame = NULL;
11209
11210           scope_breakpoint->enable_state = bp_enabled;
11211
11212           /* Automatically delete the breakpoint when it hits.  */
11213           scope_breakpoint->disposition = disp_del;
11214
11215           /* Only break in the proper frame (help with recursion).  */
11216           scope_breakpoint->frame_id = caller_frame_id;
11217
11218           /* Set the address at which we will stop.  */
11219           scope_breakpoint->loc->gdbarch = caller_arch;
11220           scope_breakpoint->loc->requested_address = caller_pc;
11221           scope_breakpoint->loc->address
11222             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11223                                          scope_breakpoint->loc->requested_address,
11224                                          scope_breakpoint->type);
11225         }
11226     }
11227
11228   /* Now set up the breakpoint.  We create all watchpoints as hardware
11229      watchpoints here even if hardware watchpoints are turned off, a call
11230      to update_watchpoint later in this function will cause the type to
11231      drop back to bp_watchpoint (software watchpoint) if required.  */
11232
11233   if (accessflag == hw_read)
11234     bp_type = bp_read_watchpoint;
11235   else if (accessflag == hw_access)
11236     bp_type = bp_access_watchpoint;
11237   else
11238     bp_type = bp_hardware_watchpoint;
11239
11240   w = new watchpoint ();
11241   b = &w->base;
11242   if (use_mask)
11243     init_raw_breakpoint_without_location (b, NULL, bp_type,
11244                                           &masked_watchpoint_breakpoint_ops);
11245   else
11246     init_raw_breakpoint_without_location (b, NULL, bp_type,
11247                                           &watchpoint_breakpoint_ops);
11248   b->thread = thread;
11249   b->disposition = disp_donttouch;
11250   b->pspace = current_program_space;
11251   w->exp = std::move (exp);
11252   w->exp_valid_block = exp_valid_block;
11253   w->cond_exp_valid_block = cond_exp_valid_block;
11254   if (just_location)
11255     {
11256       struct type *t = value_type (val);
11257       CORE_ADDR addr = value_as_address (val);
11258
11259       w->exp_string_reparse
11260         = current_language->la_watch_location_expression (t, addr).release ();
11261
11262       w->exp_string = xstrprintf ("-location %.*s",
11263                                   (int) (exp_end - exp_start), exp_start);
11264     }
11265   else
11266     w->exp_string = savestring (exp_start, exp_end - exp_start);
11267
11268   if (use_mask)
11269     {
11270       w->hw_wp_mask = mask;
11271     }
11272   else
11273     {
11274       w->val = val;
11275       w->val_bitpos = saved_bitpos;
11276       w->val_bitsize = saved_bitsize;
11277       w->val_valid = 1;
11278     }
11279
11280   if (cond_start)
11281     b->cond_string = savestring (cond_start, cond_end - cond_start);
11282   else
11283     b->cond_string = 0;
11284
11285   if (frame_id_p (watchpoint_frame))
11286     {
11287       w->watchpoint_frame = watchpoint_frame;
11288       w->watchpoint_thread = inferior_ptid;
11289     }
11290   else
11291     {
11292       w->watchpoint_frame = null_frame_id;
11293       w->watchpoint_thread = null_ptid;
11294     }
11295
11296   if (scope_breakpoint != NULL)
11297     {
11298       /* The scope breakpoint is related to the watchpoint.  We will
11299          need to act on them together.  */
11300       b->related_breakpoint = scope_breakpoint;
11301       scope_breakpoint->related_breakpoint = b;
11302     }
11303
11304   if (!just_location)
11305     value_free_to_mark (mark);
11306
11307   TRY
11308     {
11309       /* Finally update the new watchpoint.  This creates the locations
11310          that should be inserted.  */
11311       update_watchpoint (w, 1);
11312     }
11313   CATCH (e, RETURN_MASK_ALL)
11314     {
11315       delete_breakpoint (b);
11316       throw_exception (e);
11317     }
11318   END_CATCH
11319
11320   install_breakpoint (internal, b, 1);
11321   do_cleanups (back_to);
11322 }
11323
11324 /* Return count of debug registers needed to watch the given expression.
11325    If the watchpoint cannot be handled in hardware return zero.  */
11326
11327 static int
11328 can_use_hardware_watchpoint (struct value *v)
11329 {
11330   int found_memory_cnt = 0;
11331   struct value *head = v;
11332
11333   /* Did the user specifically forbid us to use hardware watchpoints? */
11334   if (!can_use_hw_watchpoints)
11335     return 0;
11336
11337   /* Make sure that the value of the expression depends only upon
11338      memory contents, and values computed from them within GDB.  If we
11339      find any register references or function calls, we can't use a
11340      hardware watchpoint.
11341
11342      The idea here is that evaluating an expression generates a series
11343      of values, one holding the value of every subexpression.  (The
11344      expression a*b+c has five subexpressions: a, b, a*b, c, and
11345      a*b+c.)  GDB's values hold almost enough information to establish
11346      the criteria given above --- they identify memory lvalues,
11347      register lvalues, computed values, etcetera.  So we can evaluate
11348      the expression, and then scan the chain of values that leaves
11349      behind to decide whether we can detect any possible change to the
11350      expression's final value using only hardware watchpoints.
11351
11352      However, I don't think that the values returned by inferior
11353      function calls are special in any way.  So this function may not
11354      notice that an expression involving an inferior function call
11355      can't be watched with hardware watchpoints.  FIXME.  */
11356   for (; v; v = value_next (v))
11357     {
11358       if (VALUE_LVAL (v) == lval_memory)
11359         {
11360           if (v != head && value_lazy (v))
11361             /* A lazy memory lvalue in the chain is one that GDB never
11362                needed to fetch; we either just used its address (e.g.,
11363                `a' in `a.b') or we never needed it at all (e.g., `a'
11364                in `a,b').  This doesn't apply to HEAD; if that is
11365                lazy then it was not readable, but watch it anyway.  */
11366             ;
11367           else
11368             {
11369               /* Ahh, memory we actually used!  Check if we can cover
11370                  it with hardware watchpoints.  */
11371               struct type *vtype = check_typedef (value_type (v));
11372
11373               /* We only watch structs and arrays if user asked for it
11374                  explicitly, never if they just happen to appear in a
11375                  middle of some value chain.  */
11376               if (v == head
11377                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11378                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11379                 {
11380                   CORE_ADDR vaddr = value_address (v);
11381                   int len;
11382                   int num_regs;
11383
11384                   len = (target_exact_watchpoints
11385                          && is_scalar_type_recursive (vtype))?
11386                     1 : TYPE_LENGTH (value_type (v));
11387
11388                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11389                   if (!num_regs)
11390                     return 0;
11391                   else
11392                     found_memory_cnt += num_regs;
11393                 }
11394             }
11395         }
11396       else if (VALUE_LVAL (v) != not_lval
11397                && deprecated_value_modifiable (v) == 0)
11398         return 0;       /* These are values from the history (e.g., $1).  */
11399       else if (VALUE_LVAL (v) == lval_register)
11400         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11401     }
11402
11403   /* The expression itself looks suitable for using a hardware
11404      watchpoint, but give the target machine a chance to reject it.  */
11405   return found_memory_cnt;
11406 }
11407
11408 void
11409 watch_command_wrapper (char *arg, int from_tty, int internal)
11410 {
11411   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11412 }
11413
11414 /* A helper function that looks for the "-location" argument and then
11415    calls watch_command_1.  */
11416
11417 static void
11418 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11419 {
11420   int just_location = 0;
11421
11422   if (arg
11423       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11424           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11425     {
11426       arg = skip_spaces (arg);
11427       just_location = 1;
11428     }
11429
11430   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11431 }
11432
11433 static void
11434 watch_command (char *arg, int from_tty)
11435 {
11436   watch_maybe_just_location (arg, hw_write, from_tty);
11437 }
11438
11439 void
11440 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11441 {
11442   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11443 }
11444
11445 static void
11446 rwatch_command (char *arg, int from_tty)
11447 {
11448   watch_maybe_just_location (arg, hw_read, from_tty);
11449 }
11450
11451 void
11452 awatch_command_wrapper (char *arg, int from_tty, int internal)
11453 {
11454   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11455 }
11456
11457 static void
11458 awatch_command (char *arg, int from_tty)
11459 {
11460   watch_maybe_just_location (arg, hw_access, from_tty);
11461 }
11462 \f
11463
11464 /* Data for the FSM that manages the until(location)/advance commands
11465    in infcmd.c.  Here because it uses the mechanisms of
11466    breakpoints.  */
11467
11468 struct until_break_fsm
11469 {
11470   /* The base class.  */
11471   struct thread_fsm thread_fsm;
11472
11473   /* The thread that as current when the command was executed.  */
11474   int thread;
11475
11476   /* The breakpoint set at the destination location.  */
11477   struct breakpoint *location_breakpoint;
11478
11479   /* Breakpoint set at the return address in the caller frame.  May be
11480      NULL.  */
11481   struct breakpoint *caller_breakpoint;
11482 };
11483
11484 static void until_break_fsm_clean_up (struct thread_fsm *self,
11485                                       struct thread_info *thread);
11486 static int until_break_fsm_should_stop (struct thread_fsm *self,
11487                                         struct thread_info *thread);
11488 static enum async_reply_reason
11489   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11490
11491 /* until_break_fsm's vtable.  */
11492
11493 static struct thread_fsm_ops until_break_fsm_ops =
11494 {
11495   NULL, /* dtor */
11496   until_break_fsm_clean_up,
11497   until_break_fsm_should_stop,
11498   NULL, /* return_value */
11499   until_break_fsm_async_reply_reason,
11500 };
11501
11502 /* Allocate a new until_break_command_fsm.  */
11503
11504 static struct until_break_fsm *
11505 new_until_break_fsm (struct interp *cmd_interp, int thread,
11506                      struct breakpoint *location_breakpoint,
11507                      struct breakpoint *caller_breakpoint)
11508 {
11509   struct until_break_fsm *sm;
11510
11511   sm = XCNEW (struct until_break_fsm);
11512   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11513
11514   sm->thread = thread;
11515   sm->location_breakpoint = location_breakpoint;
11516   sm->caller_breakpoint = caller_breakpoint;
11517
11518   return sm;
11519 }
11520
11521 /* Implementation of the 'should_stop' FSM method for the
11522    until(location)/advance commands.  */
11523
11524 static int
11525 until_break_fsm_should_stop (struct thread_fsm *self,
11526                              struct thread_info *tp)
11527 {
11528   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11529
11530   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11531                               sm->location_breakpoint) != NULL
11532       || (sm->caller_breakpoint != NULL
11533           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11534                                      sm->caller_breakpoint) != NULL))
11535     thread_fsm_set_finished (self);
11536
11537   return 1;
11538 }
11539
11540 /* Implementation of the 'clean_up' FSM method for the
11541    until(location)/advance commands.  */
11542
11543 static void
11544 until_break_fsm_clean_up (struct thread_fsm *self,
11545                           struct thread_info *thread)
11546 {
11547   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11548
11549   /* Clean up our temporary breakpoints.  */
11550   if (sm->location_breakpoint != NULL)
11551     {
11552       delete_breakpoint (sm->location_breakpoint);
11553       sm->location_breakpoint = NULL;
11554     }
11555   if (sm->caller_breakpoint != NULL)
11556     {
11557       delete_breakpoint (sm->caller_breakpoint);
11558       sm->caller_breakpoint = NULL;
11559     }
11560   delete_longjmp_breakpoint (sm->thread);
11561 }
11562
11563 /* Implementation of the 'async_reply_reason' FSM method for the
11564    until(location)/advance commands.  */
11565
11566 static enum async_reply_reason
11567 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11568 {
11569   return EXEC_ASYNC_LOCATION_REACHED;
11570 }
11571
11572 void
11573 until_break_command (char *arg, int from_tty, int anywhere)
11574 {
11575   struct symtabs_and_lines sals;
11576   struct symtab_and_line sal;
11577   struct frame_info *frame;
11578   struct gdbarch *frame_gdbarch;
11579   struct frame_id stack_frame_id;
11580   struct frame_id caller_frame_id;
11581   struct breakpoint *location_breakpoint;
11582   struct breakpoint *caller_breakpoint = NULL;
11583   struct cleanup *old_chain;
11584   int thread;
11585   struct thread_info *tp;
11586   struct until_break_fsm *sm;
11587
11588   clear_proceed_status (0);
11589
11590   /* Set a breakpoint where the user wants it and at return from
11591      this function.  */
11592
11593   event_location_up location = string_to_event_location (&arg, current_language);
11594
11595   if (last_displayed_sal_is_valid ())
11596     sals = decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11597                           get_last_displayed_symtab (),
11598                           get_last_displayed_line ());
11599   else
11600     sals = decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11601                           NULL, (struct symtab *) NULL, 0);
11602
11603   if (sals.nelts != 1)
11604     error (_("Couldn't get information on specified line."));
11605
11606   sal = sals.sals[0];
11607   xfree (sals.sals);    /* malloc'd, so freed.  */
11608
11609   if (*arg)
11610     error (_("Junk at end of arguments."));
11611
11612   resolve_sal_pc (&sal);
11613
11614   tp = inferior_thread ();
11615   thread = tp->global_num;
11616
11617   old_chain = make_cleanup (null_cleanup, NULL);
11618
11619   /* Note linespec handling above invalidates the frame chain.
11620      Installing a breakpoint also invalidates the frame chain (as it
11621      may need to switch threads), so do any frame handling before
11622      that.  */
11623
11624   frame = get_selected_frame (NULL);
11625   frame_gdbarch = get_frame_arch (frame);
11626   stack_frame_id = get_stack_frame_id (frame);
11627   caller_frame_id = frame_unwind_caller_id (frame);
11628
11629   /* Keep within the current frame, or in frames called by the current
11630      one.  */
11631
11632   if (frame_id_p (caller_frame_id))
11633     {
11634       struct symtab_and_line sal2;
11635       struct gdbarch *caller_gdbarch;
11636
11637       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11638       sal2.pc = frame_unwind_caller_pc (frame);
11639       caller_gdbarch = frame_unwind_caller_arch (frame);
11640       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11641                                                     sal2,
11642                                                     caller_frame_id,
11643                                                     bp_until);
11644       make_cleanup_delete_breakpoint (caller_breakpoint);
11645
11646       set_longjmp_breakpoint (tp, caller_frame_id);
11647       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11648     }
11649
11650   /* set_momentary_breakpoint could invalidate FRAME.  */
11651   frame = NULL;
11652
11653   if (anywhere)
11654     /* If the user told us to continue until a specified location,
11655        we don't specify a frame at which we need to stop.  */
11656     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11657                                                     null_frame_id, bp_until);
11658   else
11659     /* Otherwise, specify the selected frame, because we want to stop
11660        only at the very same frame.  */
11661     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11662                                                     stack_frame_id, bp_until);
11663   make_cleanup_delete_breakpoint (location_breakpoint);
11664
11665   sm = new_until_break_fsm (command_interp (), tp->global_num,
11666                             location_breakpoint, caller_breakpoint);
11667   tp->thread_fsm = &sm->thread_fsm;
11668
11669   discard_cleanups (old_chain);
11670
11671   proceed (-1, GDB_SIGNAL_DEFAULT);
11672 }
11673
11674 /* This function attempts to parse an optional "if <cond>" clause
11675    from the arg string.  If one is not found, it returns NULL.
11676
11677    Else, it returns a pointer to the condition string.  (It does not
11678    attempt to evaluate the string against a particular block.)  And,
11679    it updates arg to point to the first character following the parsed
11680    if clause in the arg string.  */
11681
11682 const char *
11683 ep_parse_optional_if_clause (const char **arg)
11684 {
11685   const char *cond_string;
11686
11687   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11688     return NULL;
11689
11690   /* Skip the "if" keyword.  */
11691   (*arg) += 2;
11692
11693   /* Skip any extra leading whitespace, and record the start of the
11694      condition string.  */
11695   *arg = skip_spaces_const (*arg);
11696   cond_string = *arg;
11697
11698   /* Assume that the condition occupies the remainder of the arg
11699      string.  */
11700   (*arg) += strlen (cond_string);
11701
11702   return cond_string;
11703 }
11704
11705 /* Commands to deal with catching events, such as signals, exceptions,
11706    process start/exit, etc.  */
11707
11708 typedef enum
11709 {
11710   catch_fork_temporary, catch_vfork_temporary,
11711   catch_fork_permanent, catch_vfork_permanent
11712 }
11713 catch_fork_kind;
11714
11715 static void
11716 catch_fork_command_1 (char *arg_entry, int from_tty,
11717                       struct cmd_list_element *command)
11718 {
11719   const char *arg = arg_entry;
11720   struct gdbarch *gdbarch = get_current_arch ();
11721   const char *cond_string = NULL;
11722   catch_fork_kind fork_kind;
11723   int tempflag;
11724
11725   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11726   tempflag = (fork_kind == catch_fork_temporary
11727               || fork_kind == catch_vfork_temporary);
11728
11729   if (!arg)
11730     arg = "";
11731   arg = skip_spaces_const (arg);
11732
11733   /* The allowed syntax is:
11734      catch [v]fork
11735      catch [v]fork if <cond>
11736
11737      First, check if there's an if clause.  */
11738   cond_string = ep_parse_optional_if_clause (&arg);
11739
11740   if ((*arg != '\0') && !isspace (*arg))
11741     error (_("Junk at end of arguments."));
11742
11743   /* If this target supports it, create a fork or vfork catchpoint
11744      and enable reporting of such events.  */
11745   switch (fork_kind)
11746     {
11747     case catch_fork_temporary:
11748     case catch_fork_permanent:
11749       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11750                                           &catch_fork_breakpoint_ops);
11751       break;
11752     case catch_vfork_temporary:
11753     case catch_vfork_permanent:
11754       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11755                                           &catch_vfork_breakpoint_ops);
11756       break;
11757     default:
11758       error (_("unsupported or unknown fork kind; cannot catch it"));
11759       break;
11760     }
11761 }
11762
11763 static void
11764 catch_exec_command_1 (char *arg_entry, int from_tty,
11765                       struct cmd_list_element *command)
11766 {
11767   const char *arg = arg_entry;
11768   struct exec_catchpoint *c;
11769   struct gdbarch *gdbarch = get_current_arch ();
11770   int tempflag;
11771   const char *cond_string = NULL;
11772
11773   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11774
11775   if (!arg)
11776     arg = "";
11777   arg = skip_spaces_const (arg);
11778
11779   /* The allowed syntax is:
11780      catch exec
11781      catch exec if <cond>
11782
11783      First, check if there's an if clause.  */
11784   cond_string = ep_parse_optional_if_clause (&arg);
11785
11786   if ((*arg != '\0') && !isspace (*arg))
11787     error (_("Junk at end of arguments."));
11788
11789   c = new exec_catchpoint ();
11790   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11791                    &catch_exec_breakpoint_ops);
11792   c->exec_pathname = NULL;
11793
11794   install_breakpoint (0, &c->base, 1);
11795 }
11796
11797 void
11798 init_ada_exception_breakpoint (struct breakpoint *b,
11799                                struct gdbarch *gdbarch,
11800                                struct symtab_and_line sal,
11801                                char *addr_string,
11802                                const struct breakpoint_ops *ops,
11803                                int tempflag,
11804                                int enabled,
11805                                int from_tty)
11806 {
11807   if (from_tty)
11808     {
11809       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11810       if (!loc_gdbarch)
11811         loc_gdbarch = gdbarch;
11812
11813       describe_other_breakpoints (loc_gdbarch,
11814                                   sal.pspace, sal.pc, sal.section, -1);
11815       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11816          version for exception catchpoints, because two catchpoints
11817          used for different exception names will use the same address.
11818          In this case, a "breakpoint ... also set at..." warning is
11819          unproductive.  Besides, the warning phrasing is also a bit
11820          inappropriate, we should use the word catchpoint, and tell
11821          the user what type of catchpoint it is.  The above is good
11822          enough for now, though.  */
11823     }
11824
11825   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11826
11827   b->enable_state = enabled ? bp_enabled : bp_disabled;
11828   b->disposition = tempflag ? disp_del : disp_donttouch;
11829   b->location = string_to_event_location (&addr_string,
11830                                           language_def (language_ada));
11831   b->language = language_ada;
11832 }
11833
11834 static void
11835 catch_command (char *arg, int from_tty)
11836 {
11837   error (_("Catch requires an event name."));
11838 }
11839 \f
11840
11841 static void
11842 tcatch_command (char *arg, int from_tty)
11843 {
11844   error (_("Catch requires an event name."));
11845 }
11846
11847 /* A qsort comparison function that sorts breakpoints in order.  */
11848
11849 static int
11850 compare_breakpoints (const void *a, const void *b)
11851 {
11852   const breakpoint_p *ba = (const breakpoint_p *) a;
11853   uintptr_t ua = (uintptr_t) *ba;
11854   const breakpoint_p *bb = (const breakpoint_p *) b;
11855   uintptr_t ub = (uintptr_t) *bb;
11856
11857   if ((*ba)->number < (*bb)->number)
11858     return -1;
11859   else if ((*ba)->number > (*bb)->number)
11860     return 1;
11861
11862   /* Now sort by address, in case we see, e..g, two breakpoints with
11863      the number 0.  */
11864   if (ua < ub)
11865     return -1;
11866   return ua > ub ? 1 : 0;
11867 }
11868
11869 /* Delete breakpoints by address or line.  */
11870
11871 static void
11872 clear_command (char *arg, int from_tty)
11873 {
11874   struct breakpoint *b, *prev;
11875   VEC(breakpoint_p) *found = 0;
11876   int ix;
11877   int default_match;
11878   struct symtabs_and_lines sals;
11879   struct symtab_and_line sal;
11880   int i;
11881   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11882
11883   if (arg)
11884     {
11885       sals = decode_line_with_current_source (arg,
11886                                               (DECODE_LINE_FUNFIRSTLINE
11887                                                | DECODE_LINE_LIST_MODE));
11888       make_cleanup (xfree, sals.sals);
11889       default_match = 0;
11890     }
11891   else
11892     {
11893       sals.sals = XNEW (struct symtab_and_line);
11894       make_cleanup (xfree, sals.sals);
11895       init_sal (&sal);          /* Initialize to zeroes.  */
11896
11897       /* Set sal's line, symtab, pc, and pspace to the values
11898          corresponding to the last call to print_frame_info.  If the
11899          codepoint is not valid, this will set all the fields to 0.  */
11900       get_last_displayed_sal (&sal);
11901       if (sal.symtab == 0)
11902         error (_("No source file specified."));
11903
11904       sals.sals[0] = sal;
11905       sals.nelts = 1;
11906
11907       default_match = 1;
11908     }
11909
11910   /* We don't call resolve_sal_pc here.  That's not as bad as it
11911      seems, because all existing breakpoints typically have both
11912      file/line and pc set.  So, if clear is given file/line, we can
11913      match this to existing breakpoint without obtaining pc at all.
11914
11915      We only support clearing given the address explicitly 
11916      present in breakpoint table.  Say, we've set breakpoint 
11917      at file:line.  There were several PC values for that file:line,
11918      due to optimization, all in one block.
11919
11920      We've picked one PC value.  If "clear" is issued with another
11921      PC corresponding to the same file:line, the breakpoint won't
11922      be cleared.  We probably can still clear the breakpoint, but 
11923      since the other PC value is never presented to user, user
11924      can only find it by guessing, and it does not seem important
11925      to support that.  */
11926
11927   /* For each line spec given, delete bps which correspond to it.  Do
11928      it in two passes, solely to preserve the current behavior that
11929      from_tty is forced true if we delete more than one
11930      breakpoint.  */
11931
11932   found = NULL;
11933   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11934   for (i = 0; i < sals.nelts; i++)
11935     {
11936       const char *sal_fullname;
11937
11938       /* If exact pc given, clear bpts at that pc.
11939          If line given (pc == 0), clear all bpts on specified line.
11940          If defaulting, clear all bpts on default line
11941          or at default pc.
11942
11943          defaulting    sal.pc != 0    tests to do
11944
11945          0              1             pc
11946          1              1             pc _and_ line
11947          0              0             line
11948          1              0             <can't happen> */
11949
11950       sal = sals.sals[i];
11951       sal_fullname = (sal.symtab == NULL
11952                       ? NULL : symtab_to_fullname (sal.symtab));
11953
11954       /* Find all matching breakpoints and add them to 'found'.  */
11955       ALL_BREAKPOINTS (b)
11956         {
11957           int match = 0;
11958           /* Are we going to delete b?  */
11959           if (b->type != bp_none && !is_watchpoint (b))
11960             {
11961               struct bp_location *loc = b->loc;
11962               for (; loc; loc = loc->next)
11963                 {
11964                   /* If the user specified file:line, don't allow a PC
11965                      match.  This matches historical gdb behavior.  */
11966                   int pc_match = (!sal.explicit_line
11967                                   && sal.pc
11968                                   && (loc->pspace == sal.pspace)
11969                                   && (loc->address == sal.pc)
11970                                   && (!section_is_overlay (loc->section)
11971                                       || loc->section == sal.section));
11972                   int line_match = 0;
11973
11974                   if ((default_match || sal.explicit_line)
11975                       && loc->symtab != NULL
11976                       && sal_fullname != NULL
11977                       && sal.pspace == loc->pspace
11978                       && loc->line_number == sal.line
11979                       && filename_cmp (symtab_to_fullname (loc->symtab),
11980                                        sal_fullname) == 0)
11981                     line_match = 1;
11982
11983                   if (pc_match || line_match)
11984                     {
11985                       match = 1;
11986                       break;
11987                     }
11988                 }
11989             }
11990
11991           if (match)
11992             VEC_safe_push(breakpoint_p, found, b);
11993         }
11994     }
11995
11996   /* Now go thru the 'found' chain and delete them.  */
11997   if (VEC_empty(breakpoint_p, found))
11998     {
11999       if (arg)
12000         error (_("No breakpoint at %s."), arg);
12001       else
12002         error (_("No breakpoint at this line."));
12003     }
12004
12005   /* Remove duplicates from the vec.  */
12006   qsort (VEC_address (breakpoint_p, found),
12007          VEC_length (breakpoint_p, found),
12008          sizeof (breakpoint_p),
12009          compare_breakpoints);
12010   prev = VEC_index (breakpoint_p, found, 0);
12011   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12012     {
12013       if (b == prev)
12014         {
12015           VEC_ordered_remove (breakpoint_p, found, ix);
12016           --ix;
12017         }
12018     }
12019
12020   if (VEC_length(breakpoint_p, found) > 1)
12021     from_tty = 1;       /* Always report if deleted more than one.  */
12022   if (from_tty)
12023     {
12024       if (VEC_length(breakpoint_p, found) == 1)
12025         printf_unfiltered (_("Deleted breakpoint "));
12026       else
12027         printf_unfiltered (_("Deleted breakpoints "));
12028     }
12029
12030   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12031     {
12032       if (from_tty)
12033         printf_unfiltered ("%d ", b->number);
12034       delete_breakpoint (b);
12035     }
12036   if (from_tty)
12037     putchar_unfiltered ('\n');
12038
12039   do_cleanups (cleanups);
12040 }
12041 \f
12042 /* Delete breakpoint in BS if they are `delete' breakpoints and
12043    all breakpoints that are marked for deletion, whether hit or not.
12044    This is called after any breakpoint is hit, or after errors.  */
12045
12046 void
12047 breakpoint_auto_delete (bpstat bs)
12048 {
12049   struct breakpoint *b, *b_tmp;
12050
12051   for (; bs; bs = bs->next)
12052     if (bs->breakpoint_at
12053         && bs->breakpoint_at->disposition == disp_del
12054         && bs->stop)
12055       delete_breakpoint (bs->breakpoint_at);
12056
12057   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12058   {
12059     if (b->disposition == disp_del_at_next_stop)
12060       delete_breakpoint (b);
12061   }
12062 }
12063
12064 /* A comparison function for bp_location AP and BP being interfaced to
12065    qsort.  Sort elements primarily by their ADDRESS (no matter what
12066    does breakpoint_address_is_meaningful say for its OWNER),
12067    secondarily by ordering first permanent elements and
12068    terciarily just ensuring the array is sorted stable way despite
12069    qsort being an unstable algorithm.  */
12070
12071 static int
12072 bp_locations_compare (const void *ap, const void *bp)
12073 {
12074   const struct bp_location *a = *(const struct bp_location **) ap;
12075   const struct bp_location *b = *(const struct bp_location **) bp;
12076
12077   if (a->address != b->address)
12078     return (a->address > b->address) - (a->address < b->address);
12079
12080   /* Sort locations at the same address by their pspace number, keeping
12081      locations of the same inferior (in a multi-inferior environment)
12082      grouped.  */
12083
12084   if (a->pspace->num != b->pspace->num)
12085     return ((a->pspace->num > b->pspace->num)
12086             - (a->pspace->num < b->pspace->num));
12087
12088   /* Sort permanent breakpoints first.  */
12089   if (a->permanent != b->permanent)
12090     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12091
12092   /* Make the internal GDB representation stable across GDB runs
12093      where A and B memory inside GDB can differ.  Breakpoint locations of
12094      the same type at the same address can be sorted in arbitrary order.  */
12095
12096   if (a->owner->number != b->owner->number)
12097     return ((a->owner->number > b->owner->number)
12098             - (a->owner->number < b->owner->number));
12099
12100   return (a > b) - (a < b);
12101 }
12102
12103 /* Set bp_locations_placed_address_before_address_max and
12104    bp_locations_shadow_len_after_address_max according to the current
12105    content of the bp_locations array.  */
12106
12107 static void
12108 bp_locations_target_extensions_update (void)
12109 {
12110   struct bp_location *bl, **blp_tmp;
12111
12112   bp_locations_placed_address_before_address_max = 0;
12113   bp_locations_shadow_len_after_address_max = 0;
12114
12115   ALL_BP_LOCATIONS (bl, blp_tmp)
12116     {
12117       CORE_ADDR start, end, addr;
12118
12119       if (!bp_location_has_shadow (bl))
12120         continue;
12121
12122       start = bl->target_info.placed_address;
12123       end = start + bl->target_info.shadow_len;
12124
12125       gdb_assert (bl->address >= start);
12126       addr = bl->address - start;
12127       if (addr > bp_locations_placed_address_before_address_max)
12128         bp_locations_placed_address_before_address_max = addr;
12129
12130       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12131
12132       gdb_assert (bl->address < end);
12133       addr = end - bl->address;
12134       if (addr > bp_locations_shadow_len_after_address_max)
12135         bp_locations_shadow_len_after_address_max = addr;
12136     }
12137 }
12138
12139 /* Download tracepoint locations if they haven't been.  */
12140
12141 static void
12142 download_tracepoint_locations (void)
12143 {
12144   struct breakpoint *b;
12145   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12146
12147   scoped_restore_current_pspace_and_thread restore_pspace_thread;
12148
12149   ALL_TRACEPOINTS (b)
12150     {
12151       struct bp_location *bl;
12152       struct tracepoint *t;
12153       int bp_location_downloaded = 0;
12154
12155       if ((b->type == bp_fast_tracepoint
12156            ? !may_insert_fast_tracepoints
12157            : !may_insert_tracepoints))
12158         continue;
12159
12160       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12161         {
12162           if (target_can_download_tracepoint ())
12163             can_download_tracepoint = TRIBOOL_TRUE;
12164           else
12165             can_download_tracepoint = TRIBOOL_FALSE;
12166         }
12167
12168       if (can_download_tracepoint == TRIBOOL_FALSE)
12169         break;
12170
12171       for (bl = b->loc; bl; bl = bl->next)
12172         {
12173           /* In tracepoint, locations are _never_ duplicated, so
12174              should_be_inserted is equivalent to
12175              unduplicated_should_be_inserted.  */
12176           if (!should_be_inserted (bl) || bl->inserted)
12177             continue;
12178
12179           switch_to_program_space_and_thread (bl->pspace);
12180
12181           target_download_tracepoint (bl);
12182
12183           bl->inserted = 1;
12184           bp_location_downloaded = 1;
12185         }
12186       t = (struct tracepoint *) b;
12187       t->number_on_target = b->number;
12188       if (bp_location_downloaded)
12189         observer_notify_breakpoint_modified (b);
12190     }
12191 }
12192
12193 /* Swap the insertion/duplication state between two locations.  */
12194
12195 static void
12196 swap_insertion (struct bp_location *left, struct bp_location *right)
12197 {
12198   const int left_inserted = left->inserted;
12199   const int left_duplicate = left->duplicate;
12200   const int left_needs_update = left->needs_update;
12201   const struct bp_target_info left_target_info = left->target_info;
12202
12203   /* Locations of tracepoints can never be duplicated.  */
12204   if (is_tracepoint (left->owner))
12205     gdb_assert (!left->duplicate);
12206   if (is_tracepoint (right->owner))
12207     gdb_assert (!right->duplicate);
12208
12209   left->inserted = right->inserted;
12210   left->duplicate = right->duplicate;
12211   left->needs_update = right->needs_update;
12212   left->target_info = right->target_info;
12213   right->inserted = left_inserted;
12214   right->duplicate = left_duplicate;
12215   right->needs_update = left_needs_update;
12216   right->target_info = left_target_info;
12217 }
12218
12219 /* Force the re-insertion of the locations at ADDRESS.  This is called
12220    once a new/deleted/modified duplicate location is found and we are evaluating
12221    conditions on the target's side.  Such conditions need to be updated on
12222    the target.  */
12223
12224 static void
12225 force_breakpoint_reinsertion (struct bp_location *bl)
12226 {
12227   struct bp_location **locp = NULL, **loc2p;
12228   struct bp_location *loc;
12229   CORE_ADDR address = 0;
12230   int pspace_num;
12231
12232   address = bl->address;
12233   pspace_num = bl->pspace->num;
12234
12235   /* This is only meaningful if the target is
12236      evaluating conditions and if the user has
12237      opted for condition evaluation on the target's
12238      side.  */
12239   if (gdb_evaluates_breakpoint_condition_p ()
12240       || !target_supports_evaluation_of_breakpoint_conditions ())
12241     return;
12242
12243   /* Flag all breakpoint locations with this address and
12244      the same program space as the location
12245      as "its condition has changed".  We need to
12246      update the conditions on the target's side.  */
12247   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12248     {
12249       loc = *loc2p;
12250
12251       if (!is_breakpoint (loc->owner)
12252           || pspace_num != loc->pspace->num)
12253         continue;
12254
12255       /* Flag the location appropriately.  We use a different state to
12256          let everyone know that we already updated the set of locations
12257          with addr bl->address and program space bl->pspace.  This is so
12258          we don't have to keep calling these functions just to mark locations
12259          that have already been marked.  */
12260       loc->condition_changed = condition_updated;
12261
12262       /* Free the agent expression bytecode as well.  We will compute
12263          it later on.  */
12264       loc->cond_bytecode.reset ();
12265     }
12266 }
12267 /* Called whether new breakpoints are created, or existing breakpoints
12268    deleted, to update the global location list and recompute which
12269    locations are duplicate of which.
12270
12271    The INSERT_MODE flag determines whether locations may not, may, or
12272    shall be inserted now.  See 'enum ugll_insert_mode' for more
12273    info.  */
12274
12275 static void
12276 update_global_location_list (enum ugll_insert_mode insert_mode)
12277 {
12278   struct breakpoint *b;
12279   struct bp_location **locp, *loc;
12280   struct cleanup *cleanups;
12281   /* Last breakpoint location address that was marked for update.  */
12282   CORE_ADDR last_addr = 0;
12283   /* Last breakpoint location program space that was marked for update.  */
12284   int last_pspace_num = -1;
12285
12286   /* Used in the duplicates detection below.  When iterating over all
12287      bp_locations, points to the first bp_location of a given address.
12288      Breakpoints and watchpoints of different types are never
12289      duplicates of each other.  Keep one pointer for each type of
12290      breakpoint/watchpoint, so we only need to loop over all locations
12291      once.  */
12292   struct bp_location *bp_loc_first;  /* breakpoint */
12293   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12294   struct bp_location *awp_loc_first; /* access watchpoint */
12295   struct bp_location *rwp_loc_first; /* read watchpoint */
12296
12297   /* Saved former bp_locations array which we compare against the newly
12298      built bp_locations from the current state of ALL_BREAKPOINTS.  */
12299   struct bp_location **old_locations, **old_locp;
12300   unsigned old_locations_count;
12301
12302   old_locations = bp_locations;
12303   old_locations_count = bp_locations_count;
12304   bp_locations = NULL;
12305   bp_locations_count = 0;
12306   cleanups = make_cleanup (xfree, old_locations);
12307
12308   ALL_BREAKPOINTS (b)
12309     for (loc = b->loc; loc; loc = loc->next)
12310       bp_locations_count++;
12311
12312   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
12313   locp = bp_locations;
12314   ALL_BREAKPOINTS (b)
12315     for (loc = b->loc; loc; loc = loc->next)
12316       *locp++ = loc;
12317   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
12318          bp_locations_compare);
12319
12320   bp_locations_target_extensions_update ();
12321
12322   /* Identify bp_location instances that are no longer present in the
12323      new list, and therefore should be freed.  Note that it's not
12324      necessary that those locations should be removed from inferior --
12325      if there's another location at the same address (previously
12326      marked as duplicate), we don't need to remove/insert the
12327      location.
12328      
12329      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12330      and former bp_location array state respectively.  */
12331
12332   locp = bp_locations;
12333   for (old_locp = old_locations;
12334        old_locp < old_locations + old_locations_count;
12335        old_locp++)
12336     {
12337       struct bp_location *old_loc = *old_locp;
12338       struct bp_location **loc2p;
12339
12340       /* Tells if 'old_loc' is found among the new locations.  If
12341          not, we have to free it.  */
12342       int found_object = 0;
12343       /* Tells if the location should remain inserted in the target.  */
12344       int keep_in_target = 0;
12345       int removed = 0;
12346
12347       /* Skip LOCP entries which will definitely never be needed.
12348          Stop either at or being the one matching OLD_LOC.  */
12349       while (locp < bp_locations + bp_locations_count
12350              && (*locp)->address < old_loc->address)
12351         locp++;
12352
12353       for (loc2p = locp;
12354            (loc2p < bp_locations + bp_locations_count
12355             && (*loc2p)->address == old_loc->address);
12356            loc2p++)
12357         {
12358           /* Check if this is a new/duplicated location or a duplicated
12359              location that had its condition modified.  If so, we want to send
12360              its condition to the target if evaluation of conditions is taking
12361              place there.  */
12362           if ((*loc2p)->condition_changed == condition_modified
12363               && (last_addr != old_loc->address
12364                   || last_pspace_num != old_loc->pspace->num))
12365             {
12366               force_breakpoint_reinsertion (*loc2p);
12367               last_pspace_num = old_loc->pspace->num;
12368             }
12369
12370           if (*loc2p == old_loc)
12371             found_object = 1;
12372         }
12373
12374       /* We have already handled this address, update it so that we don't
12375          have to go through updates again.  */
12376       last_addr = old_loc->address;
12377
12378       /* Target-side condition evaluation: Handle deleted locations.  */
12379       if (!found_object)
12380         force_breakpoint_reinsertion (old_loc);
12381
12382       /* If this location is no longer present, and inserted, look if
12383          there's maybe a new location at the same address.  If so,
12384          mark that one inserted, and don't remove this one.  This is
12385          needed so that we don't have a time window where a breakpoint
12386          at certain location is not inserted.  */
12387
12388       if (old_loc->inserted)
12389         {
12390           /* If the location is inserted now, we might have to remove
12391              it.  */
12392
12393           if (found_object && should_be_inserted (old_loc))
12394             {
12395               /* The location is still present in the location list,
12396                  and still should be inserted.  Don't do anything.  */
12397               keep_in_target = 1;
12398             }
12399           else
12400             {
12401               /* This location still exists, but it won't be kept in the
12402                  target since it may have been disabled.  We proceed to
12403                  remove its target-side condition.  */
12404
12405               /* The location is either no longer present, or got
12406                  disabled.  See if there's another location at the
12407                  same address, in which case we don't need to remove
12408                  this one from the target.  */
12409
12410               /* OLD_LOC comes from existing struct breakpoint.  */
12411               if (breakpoint_address_is_meaningful (old_loc->owner))
12412                 {
12413                   for (loc2p = locp;
12414                        (loc2p < bp_locations + bp_locations_count
12415                         && (*loc2p)->address == old_loc->address);
12416                        loc2p++)
12417                     {
12418                       struct bp_location *loc2 = *loc2p;
12419
12420                       if (breakpoint_locations_match (loc2, old_loc))
12421                         {
12422                           /* Read watchpoint locations are switched to
12423                              access watchpoints, if the former are not
12424                              supported, but the latter are.  */
12425                           if (is_hardware_watchpoint (old_loc->owner))
12426                             {
12427                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12428                               loc2->watchpoint_type = old_loc->watchpoint_type;
12429                             }
12430
12431                           /* loc2 is a duplicated location. We need to check
12432                              if it should be inserted in case it will be
12433                              unduplicated.  */
12434                           if (loc2 != old_loc
12435                               && unduplicated_should_be_inserted (loc2))
12436                             {
12437                               swap_insertion (old_loc, loc2);
12438                               keep_in_target = 1;
12439                               break;
12440                             }
12441                         }
12442                     }
12443                 }
12444             }
12445
12446           if (!keep_in_target)
12447             {
12448               if (remove_breakpoint (old_loc))
12449                 {
12450                   /* This is just about all we can do.  We could keep
12451                      this location on the global list, and try to
12452                      remove it next time, but there's no particular
12453                      reason why we will succeed next time.
12454                      
12455                      Note that at this point, old_loc->owner is still
12456                      valid, as delete_breakpoint frees the breakpoint
12457                      only after calling us.  */
12458                   printf_filtered (_("warning: Error removing "
12459                                      "breakpoint %d\n"), 
12460                                    old_loc->owner->number);
12461                 }
12462               removed = 1;
12463             }
12464         }
12465
12466       if (!found_object)
12467         {
12468           if (removed && target_is_non_stop_p ()
12469               && need_moribund_for_location_type (old_loc))
12470             {
12471               /* This location was removed from the target.  In
12472                  non-stop mode, a race condition is possible where
12473                  we've removed a breakpoint, but stop events for that
12474                  breakpoint are already queued and will arrive later.
12475                  We apply an heuristic to be able to distinguish such
12476                  SIGTRAPs from other random SIGTRAPs: we keep this
12477                  breakpoint location for a bit, and will retire it
12478                  after we see some number of events.  The theory here
12479                  is that reporting of events should, "on the average",
12480                  be fair, so after a while we'll see events from all
12481                  threads that have anything of interest, and no longer
12482                  need to keep this breakpoint location around.  We
12483                  don't hold locations forever so to reduce chances of
12484                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12485                  SIGTRAP.
12486
12487                  The heuristic failing can be disastrous on
12488                  decr_pc_after_break targets.
12489
12490                  On decr_pc_after_break targets, like e.g., x86-linux,
12491                  if we fail to recognize a late breakpoint SIGTRAP,
12492                  because events_till_retirement has reached 0 too
12493                  soon, we'll fail to do the PC adjustment, and report
12494                  a random SIGTRAP to the user.  When the user resumes
12495                  the inferior, it will most likely immediately crash
12496                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12497                  corrupted, because of being resumed e.g., in the
12498                  middle of a multi-byte instruction, or skipped a
12499                  one-byte instruction.  This was actually seen happen
12500                  on native x86-linux, and should be less rare on
12501                  targets that do not support new thread events, like
12502                  remote, due to the heuristic depending on
12503                  thread_count.
12504
12505                  Mistaking a random SIGTRAP for a breakpoint trap
12506                  causes similar symptoms (PC adjustment applied when
12507                  it shouldn't), but then again, playing with SIGTRAPs
12508                  behind the debugger's back is asking for trouble.
12509
12510                  Since hardware watchpoint traps are always
12511                  distinguishable from other traps, so we don't need to
12512                  apply keep hardware watchpoint moribund locations
12513                  around.  We simply always ignore hardware watchpoint
12514                  traps we can no longer explain.  */
12515
12516               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12517               old_loc->owner = NULL;
12518
12519               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12520             }
12521           else
12522             {
12523               old_loc->owner = NULL;
12524               decref_bp_location (&old_loc);
12525             }
12526         }
12527     }
12528
12529   /* Rescan breakpoints at the same address and section, marking the
12530      first one as "first" and any others as "duplicates".  This is so
12531      that the bpt instruction is only inserted once.  If we have a
12532      permanent breakpoint at the same place as BPT, make that one the
12533      official one, and the rest as duplicates.  Permanent breakpoints
12534      are sorted first for the same address.
12535
12536      Do the same for hardware watchpoints, but also considering the
12537      watchpoint's type (regular/access/read) and length.  */
12538
12539   bp_loc_first = NULL;
12540   wp_loc_first = NULL;
12541   awp_loc_first = NULL;
12542   rwp_loc_first = NULL;
12543   ALL_BP_LOCATIONS (loc, locp)
12544     {
12545       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12546          non-NULL.  */
12547       struct bp_location **loc_first_p;
12548       b = loc->owner;
12549
12550       if (!unduplicated_should_be_inserted (loc)
12551           || !breakpoint_address_is_meaningful (b)
12552           /* Don't detect duplicate for tracepoint locations because they are
12553            never duplicated.  See the comments in field `duplicate' of
12554            `struct bp_location'.  */
12555           || is_tracepoint (b))
12556         {
12557           /* Clear the condition modification flag.  */
12558           loc->condition_changed = condition_unchanged;
12559           continue;
12560         }
12561
12562       if (b->type == bp_hardware_watchpoint)
12563         loc_first_p = &wp_loc_first;
12564       else if (b->type == bp_read_watchpoint)
12565         loc_first_p = &rwp_loc_first;
12566       else if (b->type == bp_access_watchpoint)
12567         loc_first_p = &awp_loc_first;
12568       else
12569         loc_first_p = &bp_loc_first;
12570
12571       if (*loc_first_p == NULL
12572           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12573           || !breakpoint_locations_match (loc, *loc_first_p))
12574         {
12575           *loc_first_p = loc;
12576           loc->duplicate = 0;
12577
12578           if (is_breakpoint (loc->owner) && loc->condition_changed)
12579             {
12580               loc->needs_update = 1;
12581               /* Clear the condition modification flag.  */
12582               loc->condition_changed = condition_unchanged;
12583             }
12584           continue;
12585         }
12586
12587
12588       /* This and the above ensure the invariant that the first location
12589          is not duplicated, and is the inserted one.
12590          All following are marked as duplicated, and are not inserted.  */
12591       if (loc->inserted)
12592         swap_insertion (loc, *loc_first_p);
12593       loc->duplicate = 1;
12594
12595       /* Clear the condition modification flag.  */
12596       loc->condition_changed = condition_unchanged;
12597     }
12598
12599   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12600     {
12601       if (insert_mode != UGLL_DONT_INSERT)
12602         insert_breakpoint_locations ();
12603       else
12604         {
12605           /* Even though the caller told us to not insert new
12606              locations, we may still need to update conditions on the
12607              target's side of breakpoints that were already inserted
12608              if the target is evaluating breakpoint conditions.  We
12609              only update conditions for locations that are marked
12610              "needs_update".  */
12611           update_inserted_breakpoint_locations ();
12612         }
12613     }
12614
12615   if (insert_mode != UGLL_DONT_INSERT)
12616     download_tracepoint_locations ();
12617
12618   do_cleanups (cleanups);
12619 }
12620
12621 void
12622 breakpoint_retire_moribund (void)
12623 {
12624   struct bp_location *loc;
12625   int ix;
12626
12627   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12628     if (--(loc->events_till_retirement) == 0)
12629       {
12630         decref_bp_location (&loc);
12631         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12632         --ix;
12633       }
12634 }
12635
12636 static void
12637 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12638 {
12639
12640   TRY
12641     {
12642       update_global_location_list (insert_mode);
12643     }
12644   CATCH (e, RETURN_MASK_ERROR)
12645     {
12646     }
12647   END_CATCH
12648 }
12649
12650 /* Clear BKP from a BPS.  */
12651
12652 static void
12653 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12654 {
12655   bpstat bs;
12656
12657   for (bs = bps; bs; bs = bs->next)
12658     if (bs->breakpoint_at == bpt)
12659       {
12660         bs->breakpoint_at = NULL;
12661         bs->old_val = NULL;
12662         /* bs->commands will be freed later.  */
12663       }
12664 }
12665
12666 /* Callback for iterate_over_threads.  */
12667 static int
12668 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12669 {
12670   struct breakpoint *bpt = (struct breakpoint *) data;
12671
12672   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12673   return 0;
12674 }
12675
12676 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12677    callbacks.  */
12678
12679 static void
12680 say_where (struct breakpoint *b)
12681 {
12682   struct value_print_options opts;
12683
12684   get_user_print_options (&opts);
12685
12686   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12687      single string.  */
12688   if (b->loc == NULL)
12689     {
12690       /* For pending locations, the output differs slightly based
12691          on b->extra_string.  If this is non-NULL, it contains either
12692          a condition or dprintf arguments.  */
12693       if (b->extra_string == NULL)
12694         {
12695           printf_filtered (_(" (%s) pending."),
12696                            event_location_to_string (b->location.get ()));
12697         }
12698       else if (b->type == bp_dprintf)
12699         {
12700           printf_filtered (_(" (%s,%s) pending."),
12701                            event_location_to_string (b->location.get ()),
12702                            b->extra_string);
12703         }
12704       else
12705         {
12706           printf_filtered (_(" (%s %s) pending."),
12707                            event_location_to_string (b->location.get ()),
12708                            b->extra_string);
12709         }
12710     }
12711   else
12712     {
12713       if (opts.addressprint || b->loc->symtab == NULL)
12714         {
12715           printf_filtered (" at ");
12716           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12717                           gdb_stdout);
12718         }
12719       if (b->loc->symtab != NULL)
12720         {
12721           /* If there is a single location, we can print the location
12722              more nicely.  */
12723           if (b->loc->next == NULL)
12724             printf_filtered (": file %s, line %d.",
12725                              symtab_to_filename_for_display (b->loc->symtab),
12726                              b->loc->line_number);
12727           else
12728             /* This is not ideal, but each location may have a
12729                different file name, and this at least reflects the
12730                real situation somewhat.  */
12731             printf_filtered (": %s.",
12732                              event_location_to_string (b->location.get ()));
12733         }
12734
12735       if (b->loc->next)
12736         {
12737           struct bp_location *loc = b->loc;
12738           int n = 0;
12739           for (; loc; loc = loc->next)
12740             ++n;
12741           printf_filtered (" (%d locations)", n);
12742         }
12743     }
12744 }
12745
12746 /* Default bp_location_ops methods.  */
12747
12748 static void
12749 bp_location_dtor (struct bp_location *self)
12750 {
12751   xfree (self->function_name);
12752 }
12753
12754 static const struct bp_location_ops bp_location_ops =
12755 {
12756   bp_location_dtor
12757 };
12758
12759 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12760    inherit from.  */
12761
12762 static void
12763 base_breakpoint_dtor (struct breakpoint *self)
12764 {
12765   decref_counted_command_line (&self->commands);
12766   xfree (self->cond_string);
12767   xfree (self->extra_string);
12768   xfree (self->filter);
12769 }
12770
12771 static struct bp_location *
12772 base_breakpoint_allocate_location (struct breakpoint *self)
12773 {
12774   return new bp_location (&bp_location_ops, self);
12775 }
12776
12777 static void
12778 base_breakpoint_re_set (struct breakpoint *b)
12779 {
12780   /* Nothing to re-set. */
12781 }
12782
12783 #define internal_error_pure_virtual_called() \
12784   gdb_assert_not_reached ("pure virtual function called")
12785
12786 static int
12787 base_breakpoint_insert_location (struct bp_location *bl)
12788 {
12789   internal_error_pure_virtual_called ();
12790 }
12791
12792 static int
12793 base_breakpoint_remove_location (struct bp_location *bl,
12794                                  enum remove_bp_reason reason)
12795 {
12796   internal_error_pure_virtual_called ();
12797 }
12798
12799 static int
12800 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12801                                 struct address_space *aspace,
12802                                 CORE_ADDR bp_addr,
12803                                 const struct target_waitstatus *ws)
12804 {
12805   internal_error_pure_virtual_called ();
12806 }
12807
12808 static void
12809 base_breakpoint_check_status (bpstat bs)
12810 {
12811   /* Always stop.   */
12812 }
12813
12814 /* A "works_in_software_mode" breakpoint_ops method that just internal
12815    errors.  */
12816
12817 static int
12818 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12819 {
12820   internal_error_pure_virtual_called ();
12821 }
12822
12823 /* A "resources_needed" breakpoint_ops method that just internal
12824    errors.  */
12825
12826 static int
12827 base_breakpoint_resources_needed (const struct bp_location *bl)
12828 {
12829   internal_error_pure_virtual_called ();
12830 }
12831
12832 static enum print_stop_action
12833 base_breakpoint_print_it (bpstat bs)
12834 {
12835   internal_error_pure_virtual_called ();
12836 }
12837
12838 static void
12839 base_breakpoint_print_one_detail (const struct breakpoint *self,
12840                                   struct ui_out *uiout)
12841 {
12842   /* nothing */
12843 }
12844
12845 static void
12846 base_breakpoint_print_mention (struct breakpoint *b)
12847 {
12848   internal_error_pure_virtual_called ();
12849 }
12850
12851 static void
12852 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12853 {
12854   internal_error_pure_virtual_called ();
12855 }
12856
12857 static void
12858 base_breakpoint_create_sals_from_location
12859   (const struct event_location *location,
12860    struct linespec_result *canonical,
12861    enum bptype type_wanted)
12862 {
12863   internal_error_pure_virtual_called ();
12864 }
12865
12866 static void
12867 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12868                                         struct linespec_result *c,
12869                                         char *cond_string,
12870                                         char *extra_string,
12871                                         enum bptype type_wanted,
12872                                         enum bpdisp disposition,
12873                                         int thread,
12874                                         int task, int ignore_count,
12875                                         const struct breakpoint_ops *o,
12876                                         int from_tty, int enabled,
12877                                         int internal, unsigned flags)
12878 {
12879   internal_error_pure_virtual_called ();
12880 }
12881
12882 static void
12883 base_breakpoint_decode_location (struct breakpoint *b,
12884                                  const struct event_location *location,
12885                                  struct program_space *search_pspace,
12886                                  struct symtabs_and_lines *sals)
12887 {
12888   internal_error_pure_virtual_called ();
12889 }
12890
12891 /* The default 'explains_signal' method.  */
12892
12893 static int
12894 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12895 {
12896   return 1;
12897 }
12898
12899 /* The default "after_condition_true" method.  */
12900
12901 static void
12902 base_breakpoint_after_condition_true (struct bpstats *bs)
12903 {
12904   /* Nothing to do.   */
12905 }
12906
12907 struct breakpoint_ops base_breakpoint_ops =
12908 {
12909   base_breakpoint_dtor,
12910   base_breakpoint_allocate_location,
12911   base_breakpoint_re_set,
12912   base_breakpoint_insert_location,
12913   base_breakpoint_remove_location,
12914   base_breakpoint_breakpoint_hit,
12915   base_breakpoint_check_status,
12916   base_breakpoint_resources_needed,
12917   base_breakpoint_works_in_software_mode,
12918   base_breakpoint_print_it,
12919   NULL,
12920   base_breakpoint_print_one_detail,
12921   base_breakpoint_print_mention,
12922   base_breakpoint_print_recreate,
12923   base_breakpoint_create_sals_from_location,
12924   base_breakpoint_create_breakpoints_sal,
12925   base_breakpoint_decode_location,
12926   base_breakpoint_explains_signal,
12927   base_breakpoint_after_condition_true,
12928 };
12929
12930 /* Default breakpoint_ops methods.  */
12931
12932 static void
12933 bkpt_re_set (struct breakpoint *b)
12934 {
12935   /* FIXME: is this still reachable?  */
12936   if (breakpoint_event_location_empty_p (b))
12937     {
12938       /* Anything without a location can't be re-set.  */
12939       delete_breakpoint (b);
12940       return;
12941     }
12942
12943   breakpoint_re_set_default (b);
12944 }
12945
12946 static int
12947 bkpt_insert_location (struct bp_location *bl)
12948 {
12949   CORE_ADDR addr = bl->target_info.reqstd_address;
12950
12951   bl->target_info.kind = breakpoint_kind (bl, &addr);
12952   bl->target_info.placed_address = addr;
12953
12954   if (bl->loc_type == bp_loc_hardware_breakpoint)
12955     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12956   else
12957     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12958 }
12959
12960 static int
12961 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12962 {
12963   if (bl->loc_type == bp_loc_hardware_breakpoint)
12964     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12965   else
12966     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12967 }
12968
12969 static int
12970 bkpt_breakpoint_hit (const struct bp_location *bl,
12971                      struct address_space *aspace, CORE_ADDR bp_addr,
12972                      const struct target_waitstatus *ws)
12973 {
12974   if (ws->kind != TARGET_WAITKIND_STOPPED
12975       || ws->value.sig != GDB_SIGNAL_TRAP)
12976     return 0;
12977
12978   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12979                                  aspace, bp_addr))
12980     return 0;
12981
12982   if (overlay_debugging         /* unmapped overlay section */
12983       && section_is_overlay (bl->section)
12984       && !section_is_mapped (bl->section))
12985     return 0;
12986
12987   return 1;
12988 }
12989
12990 static int
12991 dprintf_breakpoint_hit (const struct bp_location *bl,
12992                         struct address_space *aspace, CORE_ADDR bp_addr,
12993                         const struct target_waitstatus *ws)
12994 {
12995   if (dprintf_style == dprintf_style_agent
12996       && target_can_run_breakpoint_commands ())
12997     {
12998       /* An agent-style dprintf never causes a stop.  If we see a trap
12999          for this address it must be for a breakpoint that happens to
13000          be set at the same address.  */
13001       return 0;
13002     }
13003
13004   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13005 }
13006
13007 static int
13008 bkpt_resources_needed (const struct bp_location *bl)
13009 {
13010   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13011
13012   return 1;
13013 }
13014
13015 static enum print_stop_action
13016 bkpt_print_it (bpstat bs)
13017 {
13018   struct breakpoint *b;
13019   const struct bp_location *bl;
13020   int bp_temp;
13021   struct ui_out *uiout = current_uiout;
13022
13023   gdb_assert (bs->bp_location_at != NULL);
13024
13025   bl = bs->bp_location_at;
13026   b = bs->breakpoint_at;
13027
13028   bp_temp = b->disposition == disp_del;
13029   if (bl->address != bl->requested_address)
13030     breakpoint_adjustment_warning (bl->requested_address,
13031                                    bl->address,
13032                                    b->number, 1);
13033   annotate_breakpoint (b->number);
13034   maybe_print_thread_hit_breakpoint (uiout);
13035
13036   if (bp_temp)
13037     uiout->text ("Temporary breakpoint ");
13038   else
13039     uiout->text ("Breakpoint ");
13040   if (uiout->is_mi_like_p ())
13041     {
13042       uiout->field_string ("reason",
13043                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13044       uiout->field_string ("disp", bpdisp_text (b->disposition));
13045     }
13046   uiout->field_int ("bkptno", b->number);
13047   uiout->text (", ");
13048
13049   return PRINT_SRC_AND_LOC;
13050 }
13051
13052 static void
13053 bkpt_print_mention (struct breakpoint *b)
13054 {
13055   if (current_uiout->is_mi_like_p ())
13056     return;
13057
13058   switch (b->type)
13059     {
13060     case bp_breakpoint:
13061     case bp_gnu_ifunc_resolver:
13062       if (b->disposition == disp_del)
13063         printf_filtered (_("Temporary breakpoint"));
13064       else
13065         printf_filtered (_("Breakpoint"));
13066       printf_filtered (_(" %d"), b->number);
13067       if (b->type == bp_gnu_ifunc_resolver)
13068         printf_filtered (_(" at gnu-indirect-function resolver"));
13069       break;
13070     case bp_hardware_breakpoint:
13071       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13072       break;
13073     case bp_dprintf:
13074       printf_filtered (_("Dprintf %d"), b->number);
13075       break;
13076     }
13077
13078   say_where (b);
13079 }
13080
13081 static void
13082 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13083 {
13084   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13085     fprintf_unfiltered (fp, "tbreak");
13086   else if (tp->type == bp_breakpoint)
13087     fprintf_unfiltered (fp, "break");
13088   else if (tp->type == bp_hardware_breakpoint
13089            && tp->disposition == disp_del)
13090     fprintf_unfiltered (fp, "thbreak");
13091   else if (tp->type == bp_hardware_breakpoint)
13092     fprintf_unfiltered (fp, "hbreak");
13093   else
13094     internal_error (__FILE__, __LINE__,
13095                     _("unhandled breakpoint type %d"), (int) tp->type);
13096
13097   fprintf_unfiltered (fp, " %s",
13098                       event_location_to_string (tp->location.get ()));
13099
13100   /* Print out extra_string if this breakpoint is pending.  It might
13101      contain, for example, conditions that were set by the user.  */
13102   if (tp->loc == NULL && tp->extra_string != NULL)
13103     fprintf_unfiltered (fp, " %s", tp->extra_string);
13104
13105   print_recreate_thread (tp, fp);
13106 }
13107
13108 static void
13109 bkpt_create_sals_from_location (const struct event_location *location,
13110                                 struct linespec_result *canonical,
13111                                 enum bptype type_wanted)
13112 {
13113   create_sals_from_location_default (location, canonical, type_wanted);
13114 }
13115
13116 static void
13117 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13118                              struct linespec_result *canonical,
13119                              char *cond_string,
13120                              char *extra_string,
13121                              enum bptype type_wanted,
13122                              enum bpdisp disposition,
13123                              int thread,
13124                              int task, int ignore_count,
13125                              const struct breakpoint_ops *ops,
13126                              int from_tty, int enabled,
13127                              int internal, unsigned flags)
13128 {
13129   create_breakpoints_sal_default (gdbarch, canonical,
13130                                   cond_string, extra_string,
13131                                   type_wanted,
13132                                   disposition, thread, task,
13133                                   ignore_count, ops, from_tty,
13134                                   enabled, internal, flags);
13135 }
13136
13137 static void
13138 bkpt_decode_location (struct breakpoint *b,
13139                       const struct event_location *location,
13140                       struct program_space *search_pspace,
13141                       struct symtabs_and_lines *sals)
13142 {
13143   decode_location_default (b, location, search_pspace, sals);
13144 }
13145
13146 /* Virtual table for internal breakpoints.  */
13147
13148 static void
13149 internal_bkpt_re_set (struct breakpoint *b)
13150 {
13151   switch (b->type)
13152     {
13153       /* Delete overlay event and longjmp master breakpoints; they
13154          will be reset later by breakpoint_re_set.  */
13155     case bp_overlay_event:
13156     case bp_longjmp_master:
13157     case bp_std_terminate_master:
13158     case bp_exception_master:
13159       delete_breakpoint (b);
13160       break;
13161
13162       /* This breakpoint is special, it's set up when the inferior
13163          starts and we really don't want to touch it.  */
13164     case bp_shlib_event:
13165
13166       /* Like bp_shlib_event, this breakpoint type is special.  Once
13167          it is set up, we do not want to touch it.  */
13168     case bp_thread_event:
13169       break;
13170     }
13171 }
13172
13173 static void
13174 internal_bkpt_check_status (bpstat bs)
13175 {
13176   if (bs->breakpoint_at->type == bp_shlib_event)
13177     {
13178       /* If requested, stop when the dynamic linker notifies GDB of
13179          events.  This allows the user to get control and place
13180          breakpoints in initializer routines for dynamically loaded
13181          objects (among other things).  */
13182       bs->stop = stop_on_solib_events;
13183       bs->print = stop_on_solib_events;
13184     }
13185   else
13186     bs->stop = 0;
13187 }
13188
13189 static enum print_stop_action
13190 internal_bkpt_print_it (bpstat bs)
13191 {
13192   struct breakpoint *b;
13193
13194   b = bs->breakpoint_at;
13195
13196   switch (b->type)
13197     {
13198     case bp_shlib_event:
13199       /* Did we stop because the user set the stop_on_solib_events
13200          variable?  (If so, we report this as a generic, "Stopped due
13201          to shlib event" message.) */
13202       print_solib_event (0);
13203       break;
13204
13205     case bp_thread_event:
13206       /* Not sure how we will get here.
13207          GDB should not stop for these breakpoints.  */
13208       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13209       break;
13210
13211     case bp_overlay_event:
13212       /* By analogy with the thread event, GDB should not stop for these.  */
13213       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13214       break;
13215
13216     case bp_longjmp_master:
13217       /* These should never be enabled.  */
13218       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13219       break;
13220
13221     case bp_std_terminate_master:
13222       /* These should never be enabled.  */
13223       printf_filtered (_("std::terminate Master Breakpoint: "
13224                          "gdb should not stop!\n"));
13225       break;
13226
13227     case bp_exception_master:
13228       /* These should never be enabled.  */
13229       printf_filtered (_("Exception Master Breakpoint: "
13230                          "gdb should not stop!\n"));
13231       break;
13232     }
13233
13234   return PRINT_NOTHING;
13235 }
13236
13237 static void
13238 internal_bkpt_print_mention (struct breakpoint *b)
13239 {
13240   /* Nothing to mention.  These breakpoints are internal.  */
13241 }
13242
13243 /* Virtual table for momentary breakpoints  */
13244
13245 static void
13246 momentary_bkpt_re_set (struct breakpoint *b)
13247 {
13248   /* Keep temporary breakpoints, which can be encountered when we step
13249      over a dlopen call and solib_add is resetting the breakpoints.
13250      Otherwise these should have been blown away via the cleanup chain
13251      or by breakpoint_init_inferior when we rerun the executable.  */
13252 }
13253
13254 static void
13255 momentary_bkpt_check_status (bpstat bs)
13256 {
13257   /* Nothing.  The point of these breakpoints is causing a stop.  */
13258 }
13259
13260 static enum print_stop_action
13261 momentary_bkpt_print_it (bpstat bs)
13262 {
13263   return PRINT_UNKNOWN;
13264 }
13265
13266 static void
13267 momentary_bkpt_print_mention (struct breakpoint *b)
13268 {
13269   /* Nothing to mention.  These breakpoints are internal.  */
13270 }
13271
13272 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13273
13274    It gets cleared already on the removal of the first one of such placed
13275    breakpoints.  This is OK as they get all removed altogether.  */
13276
13277 static void
13278 longjmp_bkpt_dtor (struct breakpoint *self)
13279 {
13280   struct thread_info *tp = find_thread_global_id (self->thread);
13281
13282   if (tp)
13283     tp->initiating_frame = null_frame_id;
13284
13285   momentary_breakpoint_ops.dtor (self);
13286 }
13287
13288 /* Specific methods for probe breakpoints.  */
13289
13290 static int
13291 bkpt_probe_insert_location (struct bp_location *bl)
13292 {
13293   int v = bkpt_insert_location (bl);
13294
13295   if (v == 0)
13296     {
13297       /* The insertion was successful, now let's set the probe's semaphore
13298          if needed.  */
13299       if (bl->probe.probe->pops->set_semaphore != NULL)
13300         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13301                                               bl->probe.objfile,
13302                                               bl->gdbarch);
13303     }
13304
13305   return v;
13306 }
13307
13308 static int
13309 bkpt_probe_remove_location (struct bp_location *bl,
13310                             enum remove_bp_reason reason)
13311 {
13312   /* Let's clear the semaphore before removing the location.  */
13313   if (bl->probe.probe->pops->clear_semaphore != NULL)
13314     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13315                                             bl->probe.objfile,
13316                                             bl->gdbarch);
13317
13318   return bkpt_remove_location (bl, reason);
13319 }
13320
13321 static void
13322 bkpt_probe_create_sals_from_location (const struct event_location *location,
13323                                       struct linespec_result *canonical,
13324                                       enum bptype type_wanted)
13325 {
13326   struct linespec_sals lsal;
13327
13328   lsal.sals = parse_probes (location, NULL, canonical);
13329   lsal.canonical
13330     = xstrdup (event_location_to_string (canonical->location.get ()));
13331   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13332 }
13333
13334 static void
13335 bkpt_probe_decode_location (struct breakpoint *b,
13336                             const struct event_location *location,
13337                             struct program_space *search_pspace,
13338                             struct symtabs_and_lines *sals)
13339 {
13340   *sals = parse_probes (location, search_pspace, NULL);
13341   if (!sals->sals)
13342     error (_("probe not found"));
13343 }
13344
13345 /* The breakpoint_ops structure to be used in tracepoints.  */
13346
13347 static void
13348 tracepoint_re_set (struct breakpoint *b)
13349 {
13350   breakpoint_re_set_default (b);
13351 }
13352
13353 static int
13354 tracepoint_breakpoint_hit (const struct bp_location *bl,
13355                            struct address_space *aspace, CORE_ADDR bp_addr,
13356                            const struct target_waitstatus *ws)
13357 {
13358   /* By definition, the inferior does not report stops at
13359      tracepoints.  */
13360   return 0;
13361 }
13362
13363 static void
13364 tracepoint_print_one_detail (const struct breakpoint *self,
13365                              struct ui_out *uiout)
13366 {
13367   struct tracepoint *tp = (struct tracepoint *) self;
13368   if (tp->static_trace_marker_id)
13369     {
13370       gdb_assert (self->type == bp_static_tracepoint);
13371
13372       uiout->text ("\tmarker id is ");
13373       uiout->field_string ("static-tracepoint-marker-string-id",
13374                            tp->static_trace_marker_id);
13375       uiout->text ("\n");
13376     }
13377 }
13378
13379 static void
13380 tracepoint_print_mention (struct breakpoint *b)
13381 {
13382   if (current_uiout->is_mi_like_p ())
13383     return;
13384
13385   switch (b->type)
13386     {
13387     case bp_tracepoint:
13388       printf_filtered (_("Tracepoint"));
13389       printf_filtered (_(" %d"), b->number);
13390       break;
13391     case bp_fast_tracepoint:
13392       printf_filtered (_("Fast tracepoint"));
13393       printf_filtered (_(" %d"), b->number);
13394       break;
13395     case bp_static_tracepoint:
13396       printf_filtered (_("Static tracepoint"));
13397       printf_filtered (_(" %d"), b->number);
13398       break;
13399     default:
13400       internal_error (__FILE__, __LINE__,
13401                       _("unhandled tracepoint type %d"), (int) b->type);
13402     }
13403
13404   say_where (b);
13405 }
13406
13407 static void
13408 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13409 {
13410   struct tracepoint *tp = (struct tracepoint *) self;
13411
13412   if (self->type == bp_fast_tracepoint)
13413     fprintf_unfiltered (fp, "ftrace");
13414   else if (self->type == bp_static_tracepoint)
13415     fprintf_unfiltered (fp, "strace");
13416   else if (self->type == bp_tracepoint)
13417     fprintf_unfiltered (fp, "trace");
13418   else
13419     internal_error (__FILE__, __LINE__,
13420                     _("unhandled tracepoint type %d"), (int) self->type);
13421
13422   fprintf_unfiltered (fp, " %s",
13423                       event_location_to_string (self->location.get ()));
13424   print_recreate_thread (self, fp);
13425
13426   if (tp->pass_count)
13427     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13428 }
13429
13430 static void
13431 tracepoint_create_sals_from_location (const struct event_location *location,
13432                                       struct linespec_result *canonical,
13433                                       enum bptype type_wanted)
13434 {
13435   create_sals_from_location_default (location, canonical, type_wanted);
13436 }
13437
13438 static void
13439 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13440                                    struct linespec_result *canonical,
13441                                    char *cond_string,
13442                                    char *extra_string,
13443                                    enum bptype type_wanted,
13444                                    enum bpdisp disposition,
13445                                    int thread,
13446                                    int task, int ignore_count,
13447                                    const struct breakpoint_ops *ops,
13448                                    int from_tty, int enabled,
13449                                    int internal, unsigned flags)
13450 {
13451   create_breakpoints_sal_default (gdbarch, canonical,
13452                                   cond_string, extra_string,
13453                                   type_wanted,
13454                                   disposition, thread, task,
13455                                   ignore_count, ops, from_tty,
13456                                   enabled, internal, flags);
13457 }
13458
13459 static void
13460 tracepoint_decode_location (struct breakpoint *b,
13461                             const struct event_location *location,
13462                             struct program_space *search_pspace,
13463                             struct symtabs_and_lines *sals)
13464 {
13465   decode_location_default (b, location, search_pspace, sals);
13466 }
13467
13468 struct breakpoint_ops tracepoint_breakpoint_ops;
13469
13470 /* The breakpoint_ops structure to be use on tracepoints placed in a
13471    static probe.  */
13472
13473 static void
13474 tracepoint_probe_create_sals_from_location
13475   (const struct event_location *location,
13476    struct linespec_result *canonical,
13477    enum bptype type_wanted)
13478 {
13479   /* We use the same method for breakpoint on probes.  */
13480   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13481 }
13482
13483 static void
13484 tracepoint_probe_decode_location (struct breakpoint *b,
13485                                   const struct event_location *location,
13486                                   struct program_space *search_pspace,
13487                                   struct symtabs_and_lines *sals)
13488 {
13489   /* We use the same method for breakpoint on probes.  */
13490   bkpt_probe_decode_location (b, location, search_pspace, sals);
13491 }
13492
13493 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13494
13495 /* Dprintf breakpoint_ops methods.  */
13496
13497 static void
13498 dprintf_re_set (struct breakpoint *b)
13499 {
13500   breakpoint_re_set_default (b);
13501
13502   /* extra_string should never be non-NULL for dprintf.  */
13503   gdb_assert (b->extra_string != NULL);
13504
13505   /* 1 - connect to target 1, that can run breakpoint commands.
13506      2 - create a dprintf, which resolves fine.
13507      3 - disconnect from target 1
13508      4 - connect to target 2, that can NOT run breakpoint commands.
13509
13510      After steps #3/#4, you'll want the dprintf command list to
13511      be updated, because target 1 and 2 may well return different
13512      answers for target_can_run_breakpoint_commands().
13513      Given absence of finer grained resetting, we get to do
13514      it all the time.  */
13515   if (b->extra_string != NULL)
13516     update_dprintf_command_list (b);
13517 }
13518
13519 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13520
13521 static void
13522 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13523 {
13524   fprintf_unfiltered (fp, "dprintf %s,%s",
13525                       event_location_to_string (tp->location.get ()),
13526                       tp->extra_string);
13527   print_recreate_thread (tp, fp);
13528 }
13529
13530 /* Implement the "after_condition_true" breakpoint_ops method for
13531    dprintf.
13532
13533    dprintf's are implemented with regular commands in their command
13534    list, but we run the commands here instead of before presenting the
13535    stop to the user, as dprintf's don't actually cause a stop.  This
13536    also makes it so that the commands of multiple dprintfs at the same
13537    address are all handled.  */
13538
13539 static void
13540 dprintf_after_condition_true (struct bpstats *bs)
13541 {
13542   struct cleanup *old_chain;
13543   struct bpstats tmp_bs = { NULL };
13544   struct bpstats *tmp_bs_p = &tmp_bs;
13545
13546   /* dprintf's never cause a stop.  This wasn't set in the
13547      check_status hook instead because that would make the dprintf's
13548      condition not be evaluated.  */
13549   bs->stop = 0;
13550
13551   /* Run the command list here.  Take ownership of it instead of
13552      copying.  We never want these commands to run later in
13553      bpstat_do_actions, if a breakpoint that causes a stop happens to
13554      be set at same address as this dprintf, or even if running the
13555      commands here throws.  */
13556   tmp_bs.commands = bs->commands;
13557   bs->commands = NULL;
13558   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13559
13560   bpstat_do_actions_1 (&tmp_bs_p);
13561
13562   /* 'tmp_bs.commands' will usually be NULL by now, but
13563      bpstat_do_actions_1 may return early without processing the whole
13564      list.  */
13565   do_cleanups (old_chain);
13566 }
13567
13568 /* The breakpoint_ops structure to be used on static tracepoints with
13569    markers (`-m').  */
13570
13571 static void
13572 strace_marker_create_sals_from_location (const struct event_location *location,
13573                                          struct linespec_result *canonical,
13574                                          enum bptype type_wanted)
13575 {
13576   struct linespec_sals lsal;
13577   const char *arg_start, *arg;
13578   char *str;
13579   struct cleanup *cleanup;
13580
13581   arg = arg_start = get_linespec_location (location);
13582   lsal.sals = decode_static_tracepoint_spec (&arg);
13583
13584   str = savestring (arg_start, arg - arg_start);
13585   cleanup = make_cleanup (xfree, str);
13586   canonical->location = new_linespec_location (&str);
13587   do_cleanups (cleanup);
13588
13589   lsal.canonical
13590     = xstrdup (event_location_to_string (canonical->location.get ()));
13591   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13592 }
13593
13594 static void
13595 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13596                                       struct linespec_result *canonical,
13597                                       char *cond_string,
13598                                       char *extra_string,
13599                                       enum bptype type_wanted,
13600                                       enum bpdisp disposition,
13601                                       int thread,
13602                                       int task, int ignore_count,
13603                                       const struct breakpoint_ops *ops,
13604                                       int from_tty, int enabled,
13605                                       int internal, unsigned flags)
13606 {
13607   int i;
13608   struct linespec_sals *lsal = VEC_index (linespec_sals,
13609                                           canonical->sals, 0);
13610
13611   /* If the user is creating a static tracepoint by marker id
13612      (strace -m MARKER_ID), then store the sals index, so that
13613      breakpoint_re_set can try to match up which of the newly
13614      found markers corresponds to this one, and, don't try to
13615      expand multiple locations for each sal, given than SALS
13616      already should contain all sals for MARKER_ID.  */
13617
13618   for (i = 0; i < lsal->sals.nelts; ++i)
13619     {
13620       struct symtabs_and_lines expanded;
13621       struct tracepoint *tp;
13622       event_location_up location;
13623
13624       expanded.nelts = 1;
13625       expanded.sals = &lsal->sals.sals[i];
13626
13627       location = copy_event_location (canonical->location.get ());
13628
13629       tp = new tracepoint ();
13630       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13631                            std::move (location), NULL,
13632                            cond_string, extra_string,
13633                            type_wanted, disposition,
13634                            thread, task, ignore_count, ops,
13635                            from_tty, enabled, internal, flags,
13636                            canonical->special_display);
13637       /* Given that its possible to have multiple markers with
13638          the same string id, if the user is creating a static
13639          tracepoint by marker id ("strace -m MARKER_ID"), then
13640          store the sals index, so that breakpoint_re_set can
13641          try to match up which of the newly found markers
13642          corresponds to this one  */
13643       tp->static_trace_marker_id_idx = i;
13644
13645       install_breakpoint (internal, &tp->base, 0);
13646     }
13647 }
13648
13649 static void
13650 strace_marker_decode_location (struct breakpoint *b,
13651                                const struct event_location *location,
13652                                struct program_space *search_pspace,
13653                                struct symtabs_and_lines *sals)
13654 {
13655   struct tracepoint *tp = (struct tracepoint *) b;
13656   const char *s = get_linespec_location (location);
13657
13658   *sals = decode_static_tracepoint_spec (&s);
13659   if (sals->nelts > tp->static_trace_marker_id_idx)
13660     {
13661       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13662       sals->nelts = 1;
13663     }
13664   else
13665     error (_("marker %s not found"), tp->static_trace_marker_id);
13666 }
13667
13668 static struct breakpoint_ops strace_marker_breakpoint_ops;
13669
13670 static int
13671 strace_marker_p (struct breakpoint *b)
13672 {
13673   return b->ops == &strace_marker_breakpoint_ops;
13674 }
13675
13676 /* Delete a breakpoint and clean up all traces of it in the data
13677    structures.  */
13678
13679 void
13680 delete_breakpoint (struct breakpoint *bpt)
13681 {
13682   struct breakpoint *b;
13683
13684   gdb_assert (bpt != NULL);
13685
13686   /* Has this bp already been deleted?  This can happen because
13687      multiple lists can hold pointers to bp's.  bpstat lists are
13688      especial culprits.
13689
13690      One example of this happening is a watchpoint's scope bp.  When
13691      the scope bp triggers, we notice that the watchpoint is out of
13692      scope, and delete it.  We also delete its scope bp.  But the
13693      scope bp is marked "auto-deleting", and is already on a bpstat.
13694      That bpstat is then checked for auto-deleting bp's, which are
13695      deleted.
13696
13697      A real solution to this problem might involve reference counts in
13698      bp's, and/or giving them pointers back to their referencing
13699      bpstat's, and teaching delete_breakpoint to only free a bp's
13700      storage when no more references were extent.  A cheaper bandaid
13701      was chosen.  */
13702   if (bpt->type == bp_none)
13703     return;
13704
13705   /* At least avoid this stale reference until the reference counting
13706      of breakpoints gets resolved.  */
13707   if (bpt->related_breakpoint != bpt)
13708     {
13709       struct breakpoint *related;
13710       struct watchpoint *w;
13711
13712       if (bpt->type == bp_watchpoint_scope)
13713         w = (struct watchpoint *) bpt->related_breakpoint;
13714       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13715         w = (struct watchpoint *) bpt;
13716       else
13717         w = NULL;
13718       if (w != NULL)
13719         watchpoint_del_at_next_stop (w);
13720
13721       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13722       for (related = bpt; related->related_breakpoint != bpt;
13723            related = related->related_breakpoint);
13724       related->related_breakpoint = bpt->related_breakpoint;
13725       bpt->related_breakpoint = bpt;
13726     }
13727
13728   /* watch_command_1 creates a watchpoint but only sets its number if
13729      update_watchpoint succeeds in creating its bp_locations.  If there's
13730      a problem in that process, we'll be asked to delete the half-created
13731      watchpoint.  In that case, don't announce the deletion.  */
13732   if (bpt->number)
13733     observer_notify_breakpoint_deleted (bpt);
13734
13735   if (breakpoint_chain == bpt)
13736     breakpoint_chain = bpt->next;
13737
13738   ALL_BREAKPOINTS (b)
13739     if (b->next == bpt)
13740     {
13741       b->next = bpt->next;
13742       break;
13743     }
13744
13745   /* Be sure no bpstat's are pointing at the breakpoint after it's
13746      been freed.  */
13747   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13748      in all threads for now.  Note that we cannot just remove bpstats
13749      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13750      commands are associated with the bpstat; if we remove it here,
13751      then the later call to bpstat_do_actions (&stop_bpstat); in
13752      event-top.c won't do anything, and temporary breakpoints with
13753      commands won't work.  */
13754
13755   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13756
13757   /* Now that breakpoint is removed from breakpoint list, update the
13758      global location list.  This will remove locations that used to
13759      belong to this breakpoint.  Do this before freeing the breakpoint
13760      itself, since remove_breakpoint looks at location's owner.  It
13761      might be better design to have location completely
13762      self-contained, but it's not the case now.  */
13763   update_global_location_list (UGLL_DONT_INSERT);
13764
13765   bpt->ops->dtor (bpt);
13766   /* On the chance that someone will soon try again to delete this
13767      same bp, we mark it as deleted before freeing its storage.  */
13768   bpt->type = bp_none;
13769   delete bpt;
13770 }
13771
13772 static void
13773 do_delete_breakpoint_cleanup (void *b)
13774 {
13775   delete_breakpoint ((struct breakpoint *) b);
13776 }
13777
13778 struct cleanup *
13779 make_cleanup_delete_breakpoint (struct breakpoint *b)
13780 {
13781   return make_cleanup (do_delete_breakpoint_cleanup, b);
13782 }
13783
13784 /* Iterator function to call a user-provided callback function once
13785    for each of B and its related breakpoints.  */
13786
13787 static void
13788 iterate_over_related_breakpoints (struct breakpoint *b,
13789                                   void (*function) (struct breakpoint *,
13790                                                     void *),
13791                                   void *data)
13792 {
13793   struct breakpoint *related;
13794
13795   related = b;
13796   do
13797     {
13798       struct breakpoint *next;
13799
13800       /* FUNCTION may delete RELATED.  */
13801       next = related->related_breakpoint;
13802
13803       if (next == related)
13804         {
13805           /* RELATED is the last ring entry.  */
13806           function (related, data);
13807
13808           /* FUNCTION may have deleted it, so we'd never reach back to
13809              B.  There's nothing left to do anyway, so just break
13810              out.  */
13811           break;
13812         }
13813       else
13814         function (related, data);
13815
13816       related = next;
13817     }
13818   while (related != b);
13819 }
13820
13821 static void
13822 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13823 {
13824   delete_breakpoint (b);
13825 }
13826
13827 /* A callback for map_breakpoint_numbers that calls
13828    delete_breakpoint.  */
13829
13830 static void
13831 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13832 {
13833   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13834 }
13835
13836 void
13837 delete_command (char *arg, int from_tty)
13838 {
13839   struct breakpoint *b, *b_tmp;
13840
13841   dont_repeat ();
13842
13843   if (arg == 0)
13844     {
13845       int breaks_to_delete = 0;
13846
13847       /* Delete all breakpoints if no argument.  Do not delete
13848          internal breakpoints, these have to be deleted with an
13849          explicit breakpoint number argument.  */
13850       ALL_BREAKPOINTS (b)
13851         if (user_breakpoint_p (b))
13852           {
13853             breaks_to_delete = 1;
13854             break;
13855           }
13856
13857       /* Ask user only if there are some breakpoints to delete.  */
13858       if (!from_tty
13859           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13860         {
13861           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13862             if (user_breakpoint_p (b))
13863               delete_breakpoint (b);
13864         }
13865     }
13866   else
13867     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13868 }
13869
13870 /* Return true if all locations of B bound to PSPACE are pending.  If
13871    PSPACE is NULL, all locations of all program spaces are
13872    considered.  */
13873
13874 static int
13875 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13876 {
13877   struct bp_location *loc;
13878
13879   for (loc = b->loc; loc != NULL; loc = loc->next)
13880     if ((pspace == NULL
13881          || loc->pspace == pspace)
13882         && !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           uiout->text ("Now in ");
14020           if (sym)
14021             {
14022               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
14023               uiout->text (" at ");
14024             }
14025           uiout->field_string ("file",
14026                                symtab_to_filename_for_display (sal2.symtab));
14027           uiout->text (":");
14028
14029           if (uiout->is_mi_like_p ())
14030             {
14031               const char *fullname = symtab_to_fullname (sal2.symtab);
14032
14033               uiout->field_string ("fullname", fullname);
14034             }
14035
14036           uiout->field_int ("line", sal2.line);
14037           uiout->text ("\n");
14038
14039           b->loc->line_number = sal2.line;
14040           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14041
14042           b->location.reset (NULL);
14043           initialize_explicit_location (&explicit_loc);
14044           explicit_loc.source_filename
14045             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14046           explicit_loc.line_offset.offset = b->loc->line_number;
14047           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14048           b->location = new_explicit_location (&explicit_loc);
14049
14050           /* Might be nice to check if function changed, and warn if
14051              so.  */
14052
14053           release_static_tracepoint_marker (tpmarker);
14054         }
14055     }
14056   return sal;
14057 }
14058
14059 /* Returns 1 iff locations A and B are sufficiently same that
14060    we don't need to report breakpoint as changed.  */
14061
14062 static int
14063 locations_are_equal (struct bp_location *a, struct bp_location *b)
14064 {
14065   while (a && b)
14066     {
14067       if (a->address != b->address)
14068         return 0;
14069
14070       if (a->shlib_disabled != b->shlib_disabled)
14071         return 0;
14072
14073       if (a->enabled != b->enabled)
14074         return 0;
14075
14076       a = a->next;
14077       b = b->next;
14078     }
14079
14080   if ((a == NULL) != (b == NULL))
14081     return 0;
14082
14083   return 1;
14084 }
14085
14086 /* Split all locations of B that are bound to PSPACE out of B's
14087    location list to a separate list and return that list's head.  If
14088    PSPACE is NULL, hoist out all locations of B.  */
14089
14090 static struct bp_location *
14091 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
14092 {
14093   struct bp_location head;
14094   struct bp_location *i = b->loc;
14095   struct bp_location **i_link = &b->loc;
14096   struct bp_location *hoisted = &head;
14097
14098   if (pspace == NULL)
14099     {
14100       i = b->loc;
14101       b->loc = NULL;
14102       return i;
14103     }
14104
14105   head.next = NULL;
14106
14107   while (i != NULL)
14108     {
14109       if (i->pspace == pspace)
14110         {
14111           *i_link = i->next;
14112           i->next = NULL;
14113           hoisted->next = i;
14114           hoisted = i;
14115         }
14116       else
14117         i_link = &i->next;
14118       i = *i_link;
14119     }
14120
14121   return head.next;
14122 }
14123
14124 /* Create new breakpoint locations for B (a hardware or software
14125    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
14126    zero, then B is a ranged breakpoint.  Only recreates locations for
14127    FILTER_PSPACE.  Locations of other program spaces are left
14128    untouched.  */
14129
14130 void
14131 update_breakpoint_locations (struct breakpoint *b,
14132                              struct program_space *filter_pspace,
14133                              struct symtabs_and_lines sals,
14134                              struct symtabs_and_lines sals_end)
14135 {
14136   int i;
14137   struct bp_location *existing_locations;
14138
14139   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14140     {
14141       /* Ranged breakpoints have only one start location and one end
14142          location.  */
14143       b->enable_state = bp_disabled;
14144       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14145                            "multiple locations found\n"),
14146                          b->number);
14147       return;
14148     }
14149
14150   /* If there's no new locations, and all existing locations are
14151      pending, don't do anything.  This optimizes the common case where
14152      all locations are in the same shared library, that was unloaded.
14153      We'd like to retain the location, so that when the library is
14154      loaded again, we don't loose the enabled/disabled status of the
14155      individual locations.  */
14156   if (all_locations_are_pending (b, filter_pspace) && sals.nelts == 0)
14157     return;
14158
14159   existing_locations = hoist_existing_locations (b, filter_pspace);
14160
14161   for (i = 0; i < sals.nelts; ++i)
14162     {
14163       struct bp_location *new_loc;
14164
14165       switch_to_program_space_and_thread (sals.sals[i].pspace);
14166
14167       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14168
14169       /* Reparse conditions, they might contain references to the
14170          old symtab.  */
14171       if (b->cond_string != NULL)
14172         {
14173           const char *s;
14174
14175           s = b->cond_string;
14176           TRY
14177             {
14178               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14179                                            block_for_pc (sals.sals[i].pc), 
14180                                            0);
14181             }
14182           CATCH (e, RETURN_MASK_ERROR)
14183             {
14184               warning (_("failed to reevaluate condition "
14185                          "for breakpoint %d: %s"), 
14186                        b->number, e.message);
14187               new_loc->enabled = 0;
14188             }
14189           END_CATCH
14190         }
14191
14192       if (sals_end.nelts)
14193         {
14194           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14195
14196           new_loc->length = end - sals.sals[0].pc + 1;
14197         }
14198     }
14199
14200   /* If possible, carry over 'disable' status from existing
14201      breakpoints.  */
14202   {
14203     struct bp_location *e = existing_locations;
14204     /* If there are multiple breakpoints with the same function name,
14205        e.g. for inline functions, comparing function names won't work.
14206        Instead compare pc addresses; this is just a heuristic as things
14207        may have moved, but in practice it gives the correct answer
14208        often enough until a better solution is found.  */
14209     int have_ambiguous_names = ambiguous_names_p (b->loc);
14210
14211     for (; e; e = e->next)
14212       {
14213         if (!e->enabled && e->function_name)
14214           {
14215             struct bp_location *l = b->loc;
14216             if (have_ambiguous_names)
14217               {
14218                 for (; l; l = l->next)
14219                   if (breakpoint_locations_match (e, l))
14220                     {
14221                       l->enabled = 0;
14222                       break;
14223                     }
14224               }
14225             else
14226               {
14227                 for (; l; l = l->next)
14228                   if (l->function_name
14229                       && strcmp (e->function_name, l->function_name) == 0)
14230                     {
14231                       l->enabled = 0;
14232                       break;
14233                     }
14234               }
14235           }
14236       }
14237   }
14238
14239   if (!locations_are_equal (existing_locations, b->loc))
14240     observer_notify_breakpoint_modified (b);
14241 }
14242
14243 /* Find the SaL locations corresponding to the given LOCATION.
14244    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14245
14246 static struct symtabs_and_lines
14247 location_to_sals (struct breakpoint *b, struct event_location *location,
14248                   struct program_space *search_pspace, int *found)
14249 {
14250   struct symtabs_and_lines sals = {0};
14251   struct gdb_exception exception = exception_none;
14252
14253   gdb_assert (b->ops != NULL);
14254
14255   TRY
14256     {
14257       b->ops->decode_location (b, location, search_pspace, &sals);
14258     }
14259   CATCH (e, RETURN_MASK_ERROR)
14260     {
14261       int not_found_and_ok = 0;
14262
14263       exception = e;
14264
14265       /* For pending breakpoints, it's expected that parsing will
14266          fail until the right shared library is loaded.  User has
14267          already told to create pending breakpoints and don't need
14268          extra messages.  If breakpoint is in bp_shlib_disabled
14269          state, then user already saw the message about that
14270          breakpoint being disabled, and don't want to see more
14271          errors.  */
14272       if (e.error == NOT_FOUND_ERROR
14273           && (b->condition_not_parsed
14274               || (b->loc != NULL
14275                   && search_pspace != NULL
14276                   && b->loc->pspace != search_pspace)
14277               || (b->loc && b->loc->shlib_disabled)
14278               || (b->loc && b->loc->pspace->executing_startup)
14279               || b->enable_state == bp_disabled))
14280         not_found_and_ok = 1;
14281
14282       if (!not_found_and_ok)
14283         {
14284           /* We surely don't want to warn about the same breakpoint
14285              10 times.  One solution, implemented here, is disable
14286              the breakpoint on error.  Another solution would be to
14287              have separate 'warning emitted' flag.  Since this
14288              happens only when a binary has changed, I don't know
14289              which approach is better.  */
14290           b->enable_state = bp_disabled;
14291           throw_exception (e);
14292         }
14293     }
14294   END_CATCH
14295
14296   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14297     {
14298       int i;
14299
14300       for (i = 0; i < sals.nelts; ++i)
14301         resolve_sal_pc (&sals.sals[i]);
14302       if (b->condition_not_parsed && b->extra_string != NULL)
14303         {
14304           char *cond_string, *extra_string;
14305           int thread, task;
14306
14307           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14308                                      &cond_string, &thread, &task,
14309                                      &extra_string);
14310           gdb_assert (b->cond_string == NULL);
14311           if (cond_string)
14312             b->cond_string = cond_string;
14313           b->thread = thread;
14314           b->task = task;
14315           if (extra_string)
14316             {
14317               xfree (b->extra_string);
14318               b->extra_string = extra_string;
14319             }
14320           b->condition_not_parsed = 0;
14321         }
14322
14323       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14324         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14325
14326       *found = 1;
14327     }
14328   else
14329     *found = 0;
14330
14331   return sals;
14332 }
14333
14334 /* The default re_set method, for typical hardware or software
14335    breakpoints.  Reevaluate the breakpoint and recreate its
14336    locations.  */
14337
14338 static void
14339 breakpoint_re_set_default (struct breakpoint *b)
14340 {
14341   int found;
14342   struct symtabs_and_lines sals, sals_end;
14343   struct symtabs_and_lines expanded = {0};
14344   struct symtabs_and_lines expanded_end = {0};
14345   struct program_space *filter_pspace = current_program_space;
14346
14347   sals = location_to_sals (b, b->location.get (), filter_pspace, &found);
14348   if (found)
14349     {
14350       make_cleanup (xfree, sals.sals);
14351       expanded = sals;
14352     }
14353
14354   if (b->location_range_end != NULL)
14355     {
14356       sals_end = location_to_sals (b, b->location_range_end.get (),
14357                                    filter_pspace, &found);
14358       if (found)
14359         {
14360           make_cleanup (xfree, sals_end.sals);
14361           expanded_end = sals_end;
14362         }
14363     }
14364
14365   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14366 }
14367
14368 /* Default method for creating SALs from an address string.  It basically
14369    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14370
14371 static void
14372 create_sals_from_location_default (const struct event_location *location,
14373                                    struct linespec_result *canonical,
14374                                    enum bptype type_wanted)
14375 {
14376   parse_breakpoint_sals (location, canonical);
14377 }
14378
14379 /* Call create_breakpoints_sal for the given arguments.  This is the default
14380    function for the `create_breakpoints_sal' method of
14381    breakpoint_ops.  */
14382
14383 static void
14384 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14385                                 struct linespec_result *canonical,
14386                                 char *cond_string,
14387                                 char *extra_string,
14388                                 enum bptype type_wanted,
14389                                 enum bpdisp disposition,
14390                                 int thread,
14391                                 int task, int ignore_count,
14392                                 const struct breakpoint_ops *ops,
14393                                 int from_tty, int enabled,
14394                                 int internal, unsigned flags)
14395 {
14396   create_breakpoints_sal (gdbarch, canonical, cond_string,
14397                           extra_string,
14398                           type_wanted, disposition,
14399                           thread, task, ignore_count, ops, from_tty,
14400                           enabled, internal, flags);
14401 }
14402
14403 /* Decode the line represented by S by calling decode_line_full.  This is the
14404    default function for the `decode_location' method of breakpoint_ops.  */
14405
14406 static void
14407 decode_location_default (struct breakpoint *b,
14408                          const struct event_location *location,
14409                          struct program_space *search_pspace,
14410                          struct symtabs_and_lines *sals)
14411 {
14412   struct linespec_result canonical;
14413
14414   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14415                     (struct symtab *) NULL, 0,
14416                     &canonical, multiple_symbols_all,
14417                     b->filter);
14418
14419   /* We should get 0 or 1 resulting SALs.  */
14420   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14421
14422   if (VEC_length (linespec_sals, canonical.sals) > 0)
14423     {
14424       struct linespec_sals *lsal;
14425
14426       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14427       *sals = lsal->sals;
14428       /* Arrange it so the destructor does not free the
14429          contents.  */
14430       lsal->sals.sals = NULL;
14431     }
14432 }
14433
14434 /* Prepare the global context for a re-set of breakpoint B.  */
14435
14436 static struct cleanup *
14437 prepare_re_set_context (struct breakpoint *b)
14438 {
14439   input_radix = b->input_radix;
14440   set_language (b->language);
14441
14442   return make_cleanup (null_cleanup, NULL);
14443 }
14444
14445 /* Reset a breakpoint given it's struct breakpoint * BINT.
14446    The value we return ends up being the return value from catch_errors.
14447    Unused in this case.  */
14448
14449 static int
14450 breakpoint_re_set_one (void *bint)
14451 {
14452   /* Get past catch_errs.  */
14453   struct breakpoint *b = (struct breakpoint *) bint;
14454   struct cleanup *cleanups;
14455
14456   cleanups = prepare_re_set_context (b);
14457   b->ops->re_set (b);
14458   do_cleanups (cleanups);
14459   return 0;
14460 }
14461
14462 /* Re-set breakpoint locations for the current program space.
14463    Locations bound to other program spaces are left untouched.  */
14464
14465 void
14466 breakpoint_re_set (void)
14467 {
14468   struct breakpoint *b, *b_tmp;
14469   enum language save_language;
14470   int save_input_radix;
14471
14472   save_language = current_language->la_language;
14473   save_input_radix = input_radix;
14474
14475   {
14476     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14477
14478     /* Note: we must not try to insert locations until after all
14479        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14480        breakpoint 1, we'd insert the locations of breakpoint 2, which
14481        hadn't been re-set yet, and thus may have stale locations.  */
14482
14483     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14484       {
14485         /* Format possible error msg.  */
14486         char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14487                                     b->number);
14488         struct cleanup *cleanups = make_cleanup (xfree, message);
14489         catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14490         do_cleanups (cleanups);
14491       }
14492     set_language (save_language);
14493     input_radix = save_input_radix;
14494
14495     jit_breakpoint_re_set ();
14496   }
14497
14498   create_overlay_event_breakpoint ();
14499   create_longjmp_master_breakpoint ();
14500   create_std_terminate_master_breakpoint ();
14501   create_exception_master_breakpoint ();
14502
14503   /* Now we can insert.  */
14504   update_global_location_list (UGLL_MAY_INSERT);
14505 }
14506 \f
14507 /* Reset the thread number of this breakpoint:
14508
14509    - If the breakpoint is for all threads, leave it as-is.
14510    - Else, reset it to the current thread for inferior_ptid.  */
14511 void
14512 breakpoint_re_set_thread (struct breakpoint *b)
14513 {
14514   if (b->thread != -1)
14515     {
14516       if (in_thread_list (inferior_ptid))
14517         b->thread = ptid_to_global_thread_id (inferior_ptid);
14518
14519       /* We're being called after following a fork.  The new fork is
14520          selected as current, and unless this was a vfork will have a
14521          different program space from the original thread.  Reset that
14522          as well.  */
14523       b->loc->pspace = current_program_space;
14524     }
14525 }
14526
14527 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14528    If from_tty is nonzero, it prints a message to that effect,
14529    which ends with a period (no newline).  */
14530
14531 void
14532 set_ignore_count (int bptnum, int count, int from_tty)
14533 {
14534   struct breakpoint *b;
14535
14536   if (count < 0)
14537     count = 0;
14538
14539   ALL_BREAKPOINTS (b)
14540     if (b->number == bptnum)
14541     {
14542       if (is_tracepoint (b))
14543         {
14544           if (from_tty && count != 0)
14545             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14546                              bptnum);
14547           return;
14548         }
14549       
14550       b->ignore_count = count;
14551       if (from_tty)
14552         {
14553           if (count == 0)
14554             printf_filtered (_("Will stop next time "
14555                                "breakpoint %d is reached."),
14556                              bptnum);
14557           else if (count == 1)
14558             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14559                              bptnum);
14560           else
14561             printf_filtered (_("Will ignore next %d "
14562                                "crossings of breakpoint %d."),
14563                              count, bptnum);
14564         }
14565       observer_notify_breakpoint_modified (b);
14566       return;
14567     }
14568
14569   error (_("No breakpoint number %d."), bptnum);
14570 }
14571
14572 /* Command to set ignore-count of breakpoint N to COUNT.  */
14573
14574 static void
14575 ignore_command (char *args, int from_tty)
14576 {
14577   char *p = args;
14578   int num;
14579
14580   if (p == 0)
14581     error_no_arg (_("a breakpoint number"));
14582
14583   num = get_number (&p);
14584   if (num == 0)
14585     error (_("bad breakpoint number: '%s'"), args);
14586   if (*p == 0)
14587     error (_("Second argument (specified ignore-count) is missing."));
14588
14589   set_ignore_count (num,
14590                     longest_to_int (value_as_long (parse_and_eval (p))),
14591                     from_tty);
14592   if (from_tty)
14593     printf_filtered ("\n");
14594 }
14595 \f
14596 /* Call FUNCTION on each of the breakpoints
14597    whose numbers are given in ARGS.  */
14598
14599 static void
14600 map_breakpoint_numbers (const char *args,
14601                         void (*function) (struct breakpoint *,
14602                                           void *),
14603                         void *data)
14604 {
14605   int num;
14606   struct breakpoint *b, *tmp;
14607
14608   if (args == 0 || *args == '\0')
14609     error_no_arg (_("one or more breakpoint numbers"));
14610
14611   number_or_range_parser parser (args);
14612
14613   while (!parser.finished ())
14614     {
14615       const char *p = parser.cur_tok ();
14616       bool match = false;
14617
14618       num = parser.get_number ();
14619       if (num == 0)
14620         {
14621           warning (_("bad breakpoint number at or near '%s'"), p);
14622         }
14623       else
14624         {
14625           ALL_BREAKPOINTS_SAFE (b, tmp)
14626             if (b->number == num)
14627               {
14628                 match = true;
14629                 function (b, data);
14630                 break;
14631               }
14632           if (!match)
14633             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14634         }
14635     }
14636 }
14637
14638 static struct bp_location *
14639 find_location_by_number (char *number)
14640 {
14641   char *dot = strchr (number, '.');
14642   char *p1;
14643   int bp_num;
14644   int loc_num;
14645   struct breakpoint *b;
14646   struct bp_location *loc;  
14647
14648   *dot = '\0';
14649
14650   p1 = number;
14651   bp_num = get_number (&p1);
14652   if (bp_num == 0)
14653     error (_("Bad breakpoint number '%s'"), number);
14654
14655   ALL_BREAKPOINTS (b)
14656     if (b->number == bp_num)
14657       {
14658         break;
14659       }
14660
14661   if (!b || b->number != bp_num)
14662     error (_("Bad breakpoint number '%s'"), number);
14663   
14664   p1 = dot+1;
14665   loc_num = get_number (&p1);
14666   if (loc_num == 0)
14667     error (_("Bad breakpoint location number '%s'"), number);
14668
14669   --loc_num;
14670   loc = b->loc;
14671   for (;loc_num && loc; --loc_num, loc = loc->next)
14672     ;
14673   if (!loc)
14674     error (_("Bad breakpoint location number '%s'"), dot+1);
14675     
14676   return loc;  
14677 }
14678
14679
14680 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14681    If from_tty is nonzero, it prints a message to that effect,
14682    which ends with a period (no newline).  */
14683
14684 void
14685 disable_breakpoint (struct breakpoint *bpt)
14686 {
14687   /* Never disable a watchpoint scope breakpoint; we want to
14688      hit them when we leave scope so we can delete both the
14689      watchpoint and its scope breakpoint at that time.  */
14690   if (bpt->type == bp_watchpoint_scope)
14691     return;
14692
14693   bpt->enable_state = bp_disabled;
14694
14695   /* Mark breakpoint locations modified.  */
14696   mark_breakpoint_modified (bpt);
14697
14698   if (target_supports_enable_disable_tracepoint ()
14699       && current_trace_status ()->running && is_tracepoint (bpt))
14700     {
14701       struct bp_location *location;
14702      
14703       for (location = bpt->loc; location; location = location->next)
14704         target_disable_tracepoint (location);
14705     }
14706
14707   update_global_location_list (UGLL_DONT_INSERT);
14708
14709   observer_notify_breakpoint_modified (bpt);
14710 }
14711
14712 /* A callback for iterate_over_related_breakpoints.  */
14713
14714 static void
14715 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14716 {
14717   disable_breakpoint (b);
14718 }
14719
14720 /* A callback for map_breakpoint_numbers that calls
14721    disable_breakpoint.  */
14722
14723 static void
14724 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14725 {
14726   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14727 }
14728
14729 static void
14730 disable_command (char *args, int from_tty)
14731 {
14732   if (args == 0)
14733     {
14734       struct breakpoint *bpt;
14735
14736       ALL_BREAKPOINTS (bpt)
14737         if (user_breakpoint_p (bpt))
14738           disable_breakpoint (bpt);
14739     }
14740   else
14741     {
14742       char *num = extract_arg (&args);
14743
14744       while (num)
14745         {
14746           if (strchr (num, '.'))
14747             {
14748               struct bp_location *loc = find_location_by_number (num);
14749
14750               if (loc)
14751                 {
14752                   if (loc->enabled)
14753                     {
14754                       loc->enabled = 0;
14755                       mark_breakpoint_location_modified (loc);
14756                     }
14757                   if (target_supports_enable_disable_tracepoint ()
14758                       && current_trace_status ()->running && loc->owner
14759                       && is_tracepoint (loc->owner))
14760                     target_disable_tracepoint (loc);
14761                 }
14762               update_global_location_list (UGLL_DONT_INSERT);
14763             }
14764           else
14765             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14766           num = extract_arg (&args);
14767         }
14768     }
14769 }
14770
14771 static void
14772 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14773                         int count)
14774 {
14775   int target_resources_ok;
14776
14777   if (bpt->type == bp_hardware_breakpoint)
14778     {
14779       int i;
14780       i = hw_breakpoint_used_count ();
14781       target_resources_ok = 
14782         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14783                                             i + 1, 0);
14784       if (target_resources_ok == 0)
14785         error (_("No hardware breakpoint support in the target."));
14786       else if (target_resources_ok < 0)
14787         error (_("Hardware breakpoints used exceeds limit."));
14788     }
14789
14790   if (is_watchpoint (bpt))
14791     {
14792       /* Initialize it just to avoid a GCC false warning.  */
14793       enum enable_state orig_enable_state = bp_disabled;
14794
14795       TRY
14796         {
14797           struct watchpoint *w = (struct watchpoint *) bpt;
14798
14799           orig_enable_state = bpt->enable_state;
14800           bpt->enable_state = bp_enabled;
14801           update_watchpoint (w, 1 /* reparse */);
14802         }
14803       CATCH (e, RETURN_MASK_ALL)
14804         {
14805           bpt->enable_state = orig_enable_state;
14806           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14807                              bpt->number);
14808           return;
14809         }
14810       END_CATCH
14811     }
14812
14813   bpt->enable_state = bp_enabled;
14814
14815   /* Mark breakpoint locations modified.  */
14816   mark_breakpoint_modified (bpt);
14817
14818   if (target_supports_enable_disable_tracepoint ()
14819       && current_trace_status ()->running && is_tracepoint (bpt))
14820     {
14821       struct bp_location *location;
14822
14823       for (location = bpt->loc; location; location = location->next)
14824         target_enable_tracepoint (location);
14825     }
14826
14827   bpt->disposition = disposition;
14828   bpt->enable_count = count;
14829   update_global_location_list (UGLL_MAY_INSERT);
14830
14831   observer_notify_breakpoint_modified (bpt);
14832 }
14833
14834
14835 void
14836 enable_breakpoint (struct breakpoint *bpt)
14837 {
14838   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14839 }
14840
14841 static void
14842 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14843 {
14844   enable_breakpoint (bpt);
14845 }
14846
14847 /* A callback for map_breakpoint_numbers that calls
14848    enable_breakpoint.  */
14849
14850 static void
14851 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14852 {
14853   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14854 }
14855
14856 /* The enable command enables the specified breakpoints (or all defined
14857    breakpoints) so they once again become (or continue to be) effective
14858    in stopping the inferior.  */
14859
14860 static void
14861 enable_command (char *args, int from_tty)
14862 {
14863   if (args == 0)
14864     {
14865       struct breakpoint *bpt;
14866
14867       ALL_BREAKPOINTS (bpt)
14868         if (user_breakpoint_p (bpt))
14869           enable_breakpoint (bpt);
14870     }
14871   else
14872     {
14873       char *num = extract_arg (&args);
14874
14875       while (num)
14876         {
14877           if (strchr (num, '.'))
14878             {
14879               struct bp_location *loc = find_location_by_number (num);
14880
14881               if (loc)
14882                 {
14883                   if (!loc->enabled)
14884                     {
14885                       loc->enabled = 1;
14886                       mark_breakpoint_location_modified (loc);
14887                     }
14888                   if (target_supports_enable_disable_tracepoint ()
14889                       && current_trace_status ()->running && loc->owner
14890                       && is_tracepoint (loc->owner))
14891                     target_enable_tracepoint (loc);
14892                 }
14893               update_global_location_list (UGLL_MAY_INSERT);
14894             }
14895           else
14896             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14897           num = extract_arg (&args);
14898         }
14899     }
14900 }
14901
14902 /* This struct packages up disposition data for application to multiple
14903    breakpoints.  */
14904
14905 struct disp_data
14906 {
14907   enum bpdisp disp;
14908   int count;
14909 };
14910
14911 static void
14912 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14913 {
14914   struct disp_data disp_data = *(struct disp_data *) arg;
14915
14916   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14917 }
14918
14919 static void
14920 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14921 {
14922   struct disp_data disp = { disp_disable, 1 };
14923
14924   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14925 }
14926
14927 static void
14928 enable_once_command (char *args, int from_tty)
14929 {
14930   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14931 }
14932
14933 static void
14934 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14935 {
14936   struct disp_data disp = { disp_disable, *(int *) countptr };
14937
14938   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14939 }
14940
14941 static void
14942 enable_count_command (char *args, int from_tty)
14943 {
14944   int count;
14945
14946   if (args == NULL)
14947     error_no_arg (_("hit count"));
14948
14949   count = get_number (&args);
14950
14951   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14952 }
14953
14954 static void
14955 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14956 {
14957   struct disp_data disp = { disp_del, 1 };
14958
14959   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14960 }
14961
14962 static void
14963 enable_delete_command (char *args, int from_tty)
14964 {
14965   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14966 }
14967 \f
14968 static void
14969 set_breakpoint_cmd (char *args, int from_tty)
14970 {
14971 }
14972
14973 static void
14974 show_breakpoint_cmd (char *args, int from_tty)
14975 {
14976 }
14977
14978 /* Invalidate last known value of any hardware watchpoint if
14979    the memory which that value represents has been written to by
14980    GDB itself.  */
14981
14982 static void
14983 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14984                                       CORE_ADDR addr, ssize_t len,
14985                                       const bfd_byte *data)
14986 {
14987   struct breakpoint *bp;
14988
14989   ALL_BREAKPOINTS (bp)
14990     if (bp->enable_state == bp_enabled
14991         && bp->type == bp_hardware_watchpoint)
14992       {
14993         struct watchpoint *wp = (struct watchpoint *) bp;
14994
14995         if (wp->val_valid && wp->val)
14996           {
14997             struct bp_location *loc;
14998
14999             for (loc = bp->loc; loc != NULL; loc = loc->next)
15000               if (loc->loc_type == bp_loc_hardware_watchpoint
15001                   && loc->address + loc->length > addr
15002                   && addr + len > loc->address)
15003                 {
15004                   value_free (wp->val);
15005                   wp->val = NULL;
15006                   wp->val_valid = 0;
15007                 }
15008           }
15009       }
15010 }
15011
15012 /* Create and insert a breakpoint for software single step.  */
15013
15014 void
15015 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15016                                struct address_space *aspace, 
15017                                CORE_ADDR next_pc)
15018 {
15019   struct thread_info *tp = inferior_thread ();
15020   struct symtab_and_line sal;
15021   CORE_ADDR pc = next_pc;
15022
15023   if (tp->control.single_step_breakpoints == NULL)
15024     {
15025       tp->control.single_step_breakpoints
15026         = new_single_step_breakpoint (tp->global_num, gdbarch);
15027     }
15028
15029   sal = find_pc_line (pc, 0);
15030   sal.pc = pc;
15031   sal.section = find_pc_overlay (pc);
15032   sal.explicit_pc = 1;
15033   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15034
15035   update_global_location_list (UGLL_INSERT);
15036 }
15037
15038 /* Insert single step breakpoints according to the current state.  */
15039
15040 int
15041 insert_single_step_breakpoints (struct gdbarch *gdbarch)
15042 {
15043   struct regcache *regcache = get_current_regcache ();
15044   std::vector<CORE_ADDR> next_pcs;
15045
15046   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
15047
15048   if (!next_pcs.empty ())
15049     {
15050       struct frame_info *frame = get_current_frame ();
15051       struct address_space *aspace = get_frame_address_space (frame);
15052
15053       for (CORE_ADDR pc : next_pcs)
15054         insert_single_step_breakpoint (gdbarch, aspace, pc);
15055
15056       return 1;
15057     }
15058   else
15059     return 0;
15060 }
15061
15062 /* See breakpoint.h.  */
15063
15064 int
15065 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15066                                        struct address_space *aspace,
15067                                        CORE_ADDR pc)
15068 {
15069   struct bp_location *loc;
15070
15071   for (loc = bp->loc; loc != NULL; loc = loc->next)
15072     if (loc->inserted
15073         && breakpoint_location_address_match (loc, aspace, pc))
15074       return 1;
15075
15076   return 0;
15077 }
15078
15079 /* Check whether a software single-step breakpoint is inserted at
15080    PC.  */
15081
15082 int
15083 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15084                                         CORE_ADDR pc)
15085 {
15086   struct breakpoint *bpt;
15087
15088   ALL_BREAKPOINTS (bpt)
15089     {
15090       if (bpt->type == bp_single_step
15091           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15092         return 1;
15093     }
15094   return 0;
15095 }
15096
15097 /* Tracepoint-specific operations.  */
15098
15099 /* Set tracepoint count to NUM.  */
15100 static void
15101 set_tracepoint_count (int num)
15102 {
15103   tracepoint_count = num;
15104   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15105 }
15106
15107 static void
15108 trace_command (char *arg, int from_tty)
15109 {
15110   struct breakpoint_ops *ops;
15111
15112   event_location_up location = string_to_event_location (&arg,
15113                                                          current_language);
15114   if (location != NULL
15115       && event_location_type (location.get ()) == PROBE_LOCATION)
15116     ops = &tracepoint_probe_breakpoint_ops;
15117   else
15118     ops = &tracepoint_breakpoint_ops;
15119
15120   create_breakpoint (get_current_arch (),
15121                      location.get (),
15122                      NULL, 0, arg, 1 /* parse arg */,
15123                      0 /* tempflag */,
15124                      bp_tracepoint /* type_wanted */,
15125                      0 /* Ignore count */,
15126                      pending_break_support,
15127                      ops,
15128                      from_tty,
15129                      1 /* enabled */,
15130                      0 /* internal */, 0);
15131 }
15132
15133 static void
15134 ftrace_command (char *arg, int from_tty)
15135 {
15136   event_location_up location = string_to_event_location (&arg,
15137                                                          current_language);
15138   create_breakpoint (get_current_arch (),
15139                      location.get (),
15140                      NULL, 0, arg, 1 /* parse arg */,
15141                      0 /* tempflag */,
15142                      bp_fast_tracepoint /* type_wanted */,
15143                      0 /* Ignore count */,
15144                      pending_break_support,
15145                      &tracepoint_breakpoint_ops,
15146                      from_tty,
15147                      1 /* enabled */,
15148                      0 /* internal */, 0);
15149 }
15150
15151 /* strace command implementation.  Creates a static tracepoint.  */
15152
15153 static void
15154 strace_command (char *arg, int from_tty)
15155 {
15156   struct breakpoint_ops *ops;
15157   event_location_up location;
15158   struct cleanup *back_to;
15159
15160   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15161      or with a normal static tracepoint.  */
15162   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15163     {
15164       ops = &strace_marker_breakpoint_ops;
15165       location = new_linespec_location (&arg);
15166     }
15167   else
15168     {
15169       ops = &tracepoint_breakpoint_ops;
15170       location = string_to_event_location (&arg, current_language);
15171     }
15172
15173   create_breakpoint (get_current_arch (),
15174                      location.get (),
15175                      NULL, 0, arg, 1 /* parse arg */,
15176                      0 /* tempflag */,
15177                      bp_static_tracepoint /* type_wanted */,
15178                      0 /* Ignore count */,
15179                      pending_break_support,
15180                      ops,
15181                      from_tty,
15182                      1 /* enabled */,
15183                      0 /* internal */, 0);
15184 }
15185
15186 /* Set up a fake reader function that gets command lines from a linked
15187    list that was acquired during tracepoint uploading.  */
15188
15189 static struct uploaded_tp *this_utp;
15190 static int next_cmd;
15191
15192 static char *
15193 read_uploaded_action (void)
15194 {
15195   char *rslt;
15196
15197   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15198
15199   next_cmd++;
15200
15201   return rslt;
15202 }
15203
15204 /* Given information about a tracepoint as recorded on a target (which
15205    can be either a live system or a trace file), attempt to create an
15206    equivalent GDB tracepoint.  This is not a reliable process, since
15207    the target does not necessarily have all the information used when
15208    the tracepoint was originally defined.  */
15209   
15210 struct tracepoint *
15211 create_tracepoint_from_upload (struct uploaded_tp *utp)
15212 {
15213   char *addr_str, small_buf[100];
15214   struct tracepoint *tp;
15215
15216   if (utp->at_string)
15217     addr_str = utp->at_string;
15218   else
15219     {
15220       /* In the absence of a source location, fall back to raw
15221          address.  Since there is no way to confirm that the address
15222          means the same thing as when the trace was started, warn the
15223          user.  */
15224       warning (_("Uploaded tracepoint %d has no "
15225                  "source location, using raw address"),
15226                utp->number);
15227       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15228       addr_str = small_buf;
15229     }
15230
15231   /* There's not much we can do with a sequence of bytecodes.  */
15232   if (utp->cond && !utp->cond_string)
15233     warning (_("Uploaded tracepoint %d condition "
15234                "has no source form, ignoring it"),
15235              utp->number);
15236
15237   event_location_up location = string_to_event_location (&addr_str,
15238                                                          current_language);
15239   if (!create_breakpoint (get_current_arch (),
15240                           location.get (),
15241                           utp->cond_string, -1, addr_str,
15242                           0 /* parse cond/thread */,
15243                           0 /* tempflag */,
15244                           utp->type /* type_wanted */,
15245                           0 /* Ignore count */,
15246                           pending_break_support,
15247                           &tracepoint_breakpoint_ops,
15248                           0 /* from_tty */,
15249                           utp->enabled /* enabled */,
15250                           0 /* internal */,
15251                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15252     return NULL;
15253
15254   /* Get the tracepoint we just created.  */
15255   tp = get_tracepoint (tracepoint_count);
15256   gdb_assert (tp != NULL);
15257
15258   if (utp->pass > 0)
15259     {
15260       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15261                  tp->base.number);
15262
15263       trace_pass_command (small_buf, 0);
15264     }
15265
15266   /* If we have uploaded versions of the original commands, set up a
15267      special-purpose "reader" function and call the usual command line
15268      reader, then pass the result to the breakpoint command-setting
15269      function.  */
15270   if (!VEC_empty (char_ptr, utp->cmd_strings))
15271     {
15272       command_line_up cmd_list;
15273
15274       this_utp = utp;
15275       next_cmd = 0;
15276
15277       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15278
15279       breakpoint_set_commands (&tp->base, std::move (cmd_list));
15280     }
15281   else if (!VEC_empty (char_ptr, utp->actions)
15282            || !VEC_empty (char_ptr, utp->step_actions))
15283     warning (_("Uploaded tracepoint %d actions "
15284                "have no source form, ignoring them"),
15285              utp->number);
15286
15287   /* Copy any status information that might be available.  */
15288   tp->base.hit_count = utp->hit_count;
15289   tp->traceframe_usage = utp->traceframe_usage;
15290
15291   return tp;
15292 }
15293   
15294 /* Print information on tracepoint number TPNUM_EXP, or all if
15295    omitted.  */
15296
15297 static void
15298 tracepoints_info (char *args, int from_tty)
15299 {
15300   struct ui_out *uiout = current_uiout;
15301   int num_printed;
15302
15303   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15304
15305   if (num_printed == 0)
15306     {
15307       if (args == NULL || *args == '\0')
15308         uiout->message ("No tracepoints.\n");
15309       else
15310         uiout->message ("No tracepoint matching '%s'.\n", args);
15311     }
15312
15313   default_collect_info ();
15314 }
15315
15316 /* The 'enable trace' command enables tracepoints.
15317    Not supported by all targets.  */
15318 static void
15319 enable_trace_command (char *args, int from_tty)
15320 {
15321   enable_command (args, from_tty);
15322 }
15323
15324 /* The 'disable trace' command disables tracepoints.
15325    Not supported by all targets.  */
15326 static void
15327 disable_trace_command (char *args, int from_tty)
15328 {
15329   disable_command (args, from_tty);
15330 }
15331
15332 /* Remove a tracepoint (or all if no argument).  */
15333 static void
15334 delete_trace_command (char *arg, int from_tty)
15335 {
15336   struct breakpoint *b, *b_tmp;
15337
15338   dont_repeat ();
15339
15340   if (arg == 0)
15341     {
15342       int breaks_to_delete = 0;
15343
15344       /* Delete all breakpoints if no argument.
15345          Do not delete internal or call-dummy breakpoints, these
15346          have to be deleted with an explicit breakpoint number 
15347          argument.  */
15348       ALL_TRACEPOINTS (b)
15349         if (is_tracepoint (b) && user_breakpoint_p (b))
15350           {
15351             breaks_to_delete = 1;
15352             break;
15353           }
15354
15355       /* Ask user only if there are some breakpoints to delete.  */
15356       if (!from_tty
15357           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15358         {
15359           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15360             if (is_tracepoint (b) && user_breakpoint_p (b))
15361               delete_breakpoint (b);
15362         }
15363     }
15364   else
15365     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15366 }
15367
15368 /* Helper function for trace_pass_command.  */
15369
15370 static void
15371 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15372 {
15373   tp->pass_count = count;
15374   observer_notify_breakpoint_modified (&tp->base);
15375   if (from_tty)
15376     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15377                      tp->base.number, count);
15378 }
15379
15380 /* Set passcount for tracepoint.
15381
15382    First command argument is passcount, second is tracepoint number.
15383    If tracepoint number omitted, apply to most recently defined.
15384    Also accepts special argument "all".  */
15385
15386 static void
15387 trace_pass_command (char *args, int from_tty)
15388 {
15389   struct tracepoint *t1;
15390   unsigned int count;
15391
15392   if (args == 0 || *args == 0)
15393     error (_("passcount command requires an "
15394              "argument (count + optional TP num)"));
15395
15396   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15397
15398   args = skip_spaces (args);
15399   if (*args && strncasecmp (args, "all", 3) == 0)
15400     {
15401       struct breakpoint *b;
15402
15403       args += 3;                        /* Skip special argument "all".  */
15404       if (*args)
15405         error (_("Junk at end of arguments."));
15406
15407       ALL_TRACEPOINTS (b)
15408       {
15409         t1 = (struct tracepoint *) b;
15410         trace_pass_set_count (t1, count, from_tty);
15411       }
15412     }
15413   else if (*args == '\0')
15414     {
15415       t1 = get_tracepoint_by_number (&args, NULL);
15416       if (t1)
15417         trace_pass_set_count (t1, count, from_tty);
15418     }
15419   else
15420     {
15421       number_or_range_parser parser (args);
15422       while (!parser.finished ())
15423         {
15424           t1 = get_tracepoint_by_number (&args, &parser);
15425           if (t1)
15426             trace_pass_set_count (t1, count, from_tty);
15427         }
15428     }
15429 }
15430
15431 struct tracepoint *
15432 get_tracepoint (int num)
15433 {
15434   struct breakpoint *t;
15435
15436   ALL_TRACEPOINTS (t)
15437     if (t->number == num)
15438       return (struct tracepoint *) t;
15439
15440   return NULL;
15441 }
15442
15443 /* Find the tracepoint with the given target-side number (which may be
15444    different from the tracepoint number after disconnecting and
15445    reconnecting).  */
15446
15447 struct tracepoint *
15448 get_tracepoint_by_number_on_target (int num)
15449 {
15450   struct breakpoint *b;
15451
15452   ALL_TRACEPOINTS (b)
15453     {
15454       struct tracepoint *t = (struct tracepoint *) b;
15455
15456       if (t->number_on_target == num)
15457         return t;
15458     }
15459
15460   return NULL;
15461 }
15462
15463 /* Utility: parse a tracepoint number and look it up in the list.
15464    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15465    If the argument is missing, the most recent tracepoint
15466    (tracepoint_count) is returned.  */
15467
15468 struct tracepoint *
15469 get_tracepoint_by_number (char **arg,
15470                           number_or_range_parser *parser)
15471 {
15472   struct breakpoint *t;
15473   int tpnum;
15474   char *instring = arg == NULL ? NULL : *arg;
15475
15476   if (parser != NULL)
15477     {
15478       gdb_assert (!parser->finished ());
15479       tpnum = parser->get_number ();
15480     }
15481   else if (arg == NULL || *arg == NULL || ! **arg)
15482     tpnum = tracepoint_count;
15483   else
15484     tpnum = get_number (arg);
15485
15486   if (tpnum <= 0)
15487     {
15488       if (instring && *instring)
15489         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15490                          instring);
15491       else
15492         printf_filtered (_("No previous tracepoint\n"));
15493       return NULL;
15494     }
15495
15496   ALL_TRACEPOINTS (t)
15497     if (t->number == tpnum)
15498     {
15499       return (struct tracepoint *) t;
15500     }
15501
15502   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15503   return NULL;
15504 }
15505
15506 void
15507 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15508 {
15509   if (b->thread != -1)
15510     fprintf_unfiltered (fp, " thread %d", b->thread);
15511
15512   if (b->task != 0)
15513     fprintf_unfiltered (fp, " task %d", b->task);
15514
15515   fprintf_unfiltered (fp, "\n");
15516 }
15517
15518 /* Save information on user settable breakpoints (watchpoints, etc) to
15519    a new script file named FILENAME.  If FILTER is non-NULL, call it
15520    on each breakpoint and only include the ones for which it returns
15521    non-zero.  */
15522
15523 static void
15524 save_breakpoints (char *filename, int from_tty,
15525                   int (*filter) (const struct breakpoint *))
15526 {
15527   struct breakpoint *tp;
15528   int any = 0;
15529   struct cleanup *cleanup;
15530   int extra_trace_bits = 0;
15531
15532   if (filename == 0 || *filename == 0)
15533     error (_("Argument required (file name in which to save)"));
15534
15535   /* See if we have anything to save.  */
15536   ALL_BREAKPOINTS (tp)
15537   {
15538     /* Skip internal and momentary breakpoints.  */
15539     if (!user_breakpoint_p (tp))
15540       continue;
15541
15542     /* If we have a filter, only save the breakpoints it accepts.  */
15543     if (filter && !filter (tp))
15544       continue;
15545
15546     any = 1;
15547
15548     if (is_tracepoint (tp))
15549       {
15550         extra_trace_bits = 1;
15551
15552         /* We can stop searching.  */
15553         break;
15554       }
15555   }
15556
15557   if (!any)
15558     {
15559       warning (_("Nothing to save."));
15560       return;
15561     }
15562
15563   filename = tilde_expand (filename);
15564   cleanup = make_cleanup (xfree, filename);
15565
15566   stdio_file fp;
15567
15568   if (!fp.open (filename, "w"))
15569     error (_("Unable to open file '%s' for saving (%s)"),
15570            filename, safe_strerror (errno));
15571
15572   if (extra_trace_bits)
15573     save_trace_state_variables (&fp);
15574
15575   ALL_BREAKPOINTS (tp)
15576   {
15577     /* Skip internal and momentary breakpoints.  */
15578     if (!user_breakpoint_p (tp))
15579       continue;
15580
15581     /* If we have a filter, only save the breakpoints it accepts.  */
15582     if (filter && !filter (tp))
15583       continue;
15584
15585     tp->ops->print_recreate (tp, &fp);
15586
15587     /* Note, we can't rely on tp->number for anything, as we can't
15588        assume the recreated breakpoint numbers will match.  Use $bpnum
15589        instead.  */
15590
15591     if (tp->cond_string)
15592       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15593
15594     if (tp->ignore_count)
15595       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15596
15597     if (tp->type != bp_dprintf && tp->commands)
15598       {
15599         fp.puts ("  commands\n");
15600         
15601         current_uiout->redirect (&fp);
15602         TRY
15603           {
15604             print_command_lines (current_uiout, tp->commands->commands, 2);
15605           }
15606         CATCH (ex, RETURN_MASK_ALL)
15607           {
15608           current_uiout->redirect (NULL);
15609             throw_exception (ex);
15610           }
15611         END_CATCH
15612
15613         current_uiout->redirect (NULL);
15614         fp.puts ("  end\n");
15615       }
15616
15617     if (tp->enable_state == bp_disabled)
15618       fp.puts ("disable $bpnum\n");
15619
15620     /* If this is a multi-location breakpoint, check if the locations
15621        should be individually disabled.  Watchpoint locations are
15622        special, and not user visible.  */
15623     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15624       {
15625         struct bp_location *loc;
15626         int n = 1;
15627
15628         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15629           if (!loc->enabled)
15630             fp.printf ("disable $bpnum.%d\n", n);
15631       }
15632   }
15633
15634   if (extra_trace_bits && *default_collect)
15635     fp.printf ("set default-collect %s\n", default_collect);
15636
15637   if (from_tty)
15638     printf_filtered (_("Saved to file '%s'.\n"), filename);
15639   do_cleanups (cleanup);
15640 }
15641
15642 /* The `save breakpoints' command.  */
15643
15644 static void
15645 save_breakpoints_command (char *args, int from_tty)
15646 {
15647   save_breakpoints (args, from_tty, NULL);
15648 }
15649
15650 /* The `save tracepoints' command.  */
15651
15652 static void
15653 save_tracepoints_command (char *args, int from_tty)
15654 {
15655   save_breakpoints (args, from_tty, is_tracepoint);
15656 }
15657
15658 /* Create a vector of all tracepoints.  */
15659
15660 VEC(breakpoint_p) *
15661 all_tracepoints (void)
15662 {
15663   VEC(breakpoint_p) *tp_vec = 0;
15664   struct breakpoint *tp;
15665
15666   ALL_TRACEPOINTS (tp)
15667   {
15668     VEC_safe_push (breakpoint_p, tp_vec, tp);
15669   }
15670
15671   return tp_vec;
15672 }
15673
15674 \f
15675 /* This help string is used to consolidate all the help string for specifying
15676    locations used by several commands.  */
15677
15678 #define LOCATION_HELP_STRING \
15679 "Linespecs are colon-separated lists of location parameters, such as\n\
15680 source filename, function name, label name, and line number.\n\
15681 Example: To specify the start of a label named \"the_top\" in the\n\
15682 function \"fact\" in the file \"factorial.c\", use\n\
15683 \"factorial.c:fact:the_top\".\n\
15684 \n\
15685 Address locations begin with \"*\" and specify an exact address in the\n\
15686 program.  Example: To specify the fourth byte past the start function\n\
15687 \"main\", use \"*main + 4\".\n\
15688 \n\
15689 Explicit locations are similar to linespecs but use an option/argument\n\
15690 syntax to specify location parameters.\n\
15691 Example: To specify the start of the label named \"the_top\" in the\n\
15692 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15693 -function fact -label the_top\".\n"
15694
15695 /* This help string is used for the break, hbreak, tbreak and thbreak
15696    commands.  It is defined as a macro to prevent duplication.
15697    COMMAND should be a string constant containing the name of the
15698    command.  */
15699
15700 #define BREAK_ARGS_HELP(command) \
15701 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15702 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15703 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15704 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15705 `-probe-dtrace' (for a DTrace probe).\n\
15706 LOCATION may be a linespec, address, or explicit location as described\n\
15707 below.\n\
15708 \n\
15709 With no LOCATION, uses current execution address of the selected\n\
15710 stack frame.  This is useful for breaking on return to a stack frame.\n\
15711 \n\
15712 THREADNUM is the number from \"info threads\".\n\
15713 CONDITION is a boolean expression.\n\
15714 \n" LOCATION_HELP_STRING "\n\
15715 Multiple breakpoints at one place are permitted, and useful if their\n\
15716 conditions are different.\n\
15717 \n\
15718 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15719
15720 /* List of subcommands for "catch".  */
15721 static struct cmd_list_element *catch_cmdlist;
15722
15723 /* List of subcommands for "tcatch".  */
15724 static struct cmd_list_element *tcatch_cmdlist;
15725
15726 void
15727 add_catch_command (const char *name, const char *docstring,
15728                    cmd_sfunc_ftype *sfunc,
15729                    completer_ftype *completer,
15730                    void *user_data_catch,
15731                    void *user_data_tcatch)
15732 {
15733   struct cmd_list_element *command;
15734
15735   command = add_cmd (name, class_breakpoint, NULL, docstring,
15736                      &catch_cmdlist);
15737   set_cmd_sfunc (command, sfunc);
15738   set_cmd_context (command, user_data_catch);
15739   set_cmd_completer (command, completer);
15740
15741   command = add_cmd (name, class_breakpoint, NULL, docstring,
15742                      &tcatch_cmdlist);
15743   set_cmd_sfunc (command, sfunc);
15744   set_cmd_context (command, user_data_tcatch);
15745   set_cmd_completer (command, completer);
15746 }
15747
15748 static void
15749 save_command (char *arg, int from_tty)
15750 {
15751   printf_unfiltered (_("\"save\" must be followed by "
15752                        "the name of a save subcommand.\n"));
15753   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15754 }
15755
15756 struct breakpoint *
15757 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15758                           void *data)
15759 {
15760   struct breakpoint *b, *b_tmp;
15761
15762   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15763     {
15764       if ((*callback) (b, data))
15765         return b;
15766     }
15767
15768   return NULL;
15769 }
15770
15771 /* Zero if any of the breakpoint's locations could be a location where
15772    functions have been inlined, nonzero otherwise.  */
15773
15774 static int
15775 is_non_inline_function (struct breakpoint *b)
15776 {
15777   /* The shared library event breakpoint is set on the address of a
15778      non-inline function.  */
15779   if (b->type == bp_shlib_event)
15780     return 1;
15781
15782   return 0;
15783 }
15784
15785 /* Nonzero if the specified PC cannot be a location where functions
15786    have been inlined.  */
15787
15788 int
15789 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15790                            const struct target_waitstatus *ws)
15791 {
15792   struct breakpoint *b;
15793   struct bp_location *bl;
15794
15795   ALL_BREAKPOINTS (b)
15796     {
15797       if (!is_non_inline_function (b))
15798         continue;
15799
15800       for (bl = b->loc; bl != NULL; bl = bl->next)
15801         {
15802           if (!bl->shlib_disabled
15803               && bpstat_check_location (bl, aspace, pc, ws))
15804             return 1;
15805         }
15806     }
15807
15808   return 0;
15809 }
15810
15811 /* Remove any references to OBJFILE which is going to be freed.  */
15812
15813 void
15814 breakpoint_free_objfile (struct objfile *objfile)
15815 {
15816   struct bp_location **locp, *loc;
15817
15818   ALL_BP_LOCATIONS (loc, locp)
15819     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15820       loc->symtab = NULL;
15821 }
15822
15823 void
15824 initialize_breakpoint_ops (void)
15825 {
15826   static int initialized = 0;
15827
15828   struct breakpoint_ops *ops;
15829
15830   if (initialized)
15831     return;
15832   initialized = 1;
15833
15834   /* The breakpoint_ops structure to be inherit by all kinds of
15835      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15836      internal and momentary breakpoints, etc.).  */
15837   ops = &bkpt_base_breakpoint_ops;
15838   *ops = base_breakpoint_ops;
15839   ops->re_set = bkpt_re_set;
15840   ops->insert_location = bkpt_insert_location;
15841   ops->remove_location = bkpt_remove_location;
15842   ops->breakpoint_hit = bkpt_breakpoint_hit;
15843   ops->create_sals_from_location = bkpt_create_sals_from_location;
15844   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15845   ops->decode_location = bkpt_decode_location;
15846
15847   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15848   ops = &bkpt_breakpoint_ops;
15849   *ops = bkpt_base_breakpoint_ops;
15850   ops->re_set = bkpt_re_set;
15851   ops->resources_needed = bkpt_resources_needed;
15852   ops->print_it = bkpt_print_it;
15853   ops->print_mention = bkpt_print_mention;
15854   ops->print_recreate = bkpt_print_recreate;
15855
15856   /* Ranged breakpoints.  */
15857   ops = &ranged_breakpoint_ops;
15858   *ops = bkpt_breakpoint_ops;
15859   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15860   ops->resources_needed = resources_needed_ranged_breakpoint;
15861   ops->print_it = print_it_ranged_breakpoint;
15862   ops->print_one = print_one_ranged_breakpoint;
15863   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15864   ops->print_mention = print_mention_ranged_breakpoint;
15865   ops->print_recreate = print_recreate_ranged_breakpoint;
15866
15867   /* Internal breakpoints.  */
15868   ops = &internal_breakpoint_ops;
15869   *ops = bkpt_base_breakpoint_ops;
15870   ops->re_set = internal_bkpt_re_set;
15871   ops->check_status = internal_bkpt_check_status;
15872   ops->print_it = internal_bkpt_print_it;
15873   ops->print_mention = internal_bkpt_print_mention;
15874
15875   /* Momentary breakpoints.  */
15876   ops = &momentary_breakpoint_ops;
15877   *ops = bkpt_base_breakpoint_ops;
15878   ops->re_set = momentary_bkpt_re_set;
15879   ops->check_status = momentary_bkpt_check_status;
15880   ops->print_it = momentary_bkpt_print_it;
15881   ops->print_mention = momentary_bkpt_print_mention;
15882
15883   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15884   ops = &longjmp_breakpoint_ops;
15885   *ops = momentary_breakpoint_ops;
15886   ops->dtor = longjmp_bkpt_dtor;
15887
15888   /* Probe breakpoints.  */
15889   ops = &bkpt_probe_breakpoint_ops;
15890   *ops = bkpt_breakpoint_ops;
15891   ops->insert_location = bkpt_probe_insert_location;
15892   ops->remove_location = bkpt_probe_remove_location;
15893   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15894   ops->decode_location = bkpt_probe_decode_location;
15895
15896   /* Watchpoints.  */
15897   ops = &watchpoint_breakpoint_ops;
15898   *ops = base_breakpoint_ops;
15899   ops->dtor = dtor_watchpoint;
15900   ops->re_set = re_set_watchpoint;
15901   ops->insert_location = insert_watchpoint;
15902   ops->remove_location = remove_watchpoint;
15903   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15904   ops->check_status = check_status_watchpoint;
15905   ops->resources_needed = resources_needed_watchpoint;
15906   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15907   ops->print_it = print_it_watchpoint;
15908   ops->print_mention = print_mention_watchpoint;
15909   ops->print_recreate = print_recreate_watchpoint;
15910   ops->explains_signal = explains_signal_watchpoint;
15911
15912   /* Masked watchpoints.  */
15913   ops = &masked_watchpoint_breakpoint_ops;
15914   *ops = watchpoint_breakpoint_ops;
15915   ops->insert_location = insert_masked_watchpoint;
15916   ops->remove_location = remove_masked_watchpoint;
15917   ops->resources_needed = resources_needed_masked_watchpoint;
15918   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15919   ops->print_it = print_it_masked_watchpoint;
15920   ops->print_one_detail = print_one_detail_masked_watchpoint;
15921   ops->print_mention = print_mention_masked_watchpoint;
15922   ops->print_recreate = print_recreate_masked_watchpoint;
15923
15924   /* Tracepoints.  */
15925   ops = &tracepoint_breakpoint_ops;
15926   *ops = base_breakpoint_ops;
15927   ops->re_set = tracepoint_re_set;
15928   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15929   ops->print_one_detail = tracepoint_print_one_detail;
15930   ops->print_mention = tracepoint_print_mention;
15931   ops->print_recreate = tracepoint_print_recreate;
15932   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15933   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15934   ops->decode_location = tracepoint_decode_location;
15935
15936   /* Probe tracepoints.  */
15937   ops = &tracepoint_probe_breakpoint_ops;
15938   *ops = tracepoint_breakpoint_ops;
15939   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15940   ops->decode_location = tracepoint_probe_decode_location;
15941
15942   /* Static tracepoints with marker (`-m').  */
15943   ops = &strace_marker_breakpoint_ops;
15944   *ops = tracepoint_breakpoint_ops;
15945   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15946   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15947   ops->decode_location = strace_marker_decode_location;
15948
15949   /* Fork catchpoints.  */
15950   ops = &catch_fork_breakpoint_ops;
15951   *ops = base_breakpoint_ops;
15952   ops->insert_location = insert_catch_fork;
15953   ops->remove_location = remove_catch_fork;
15954   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15955   ops->print_it = print_it_catch_fork;
15956   ops->print_one = print_one_catch_fork;
15957   ops->print_mention = print_mention_catch_fork;
15958   ops->print_recreate = print_recreate_catch_fork;
15959
15960   /* Vfork catchpoints.  */
15961   ops = &catch_vfork_breakpoint_ops;
15962   *ops = base_breakpoint_ops;
15963   ops->insert_location = insert_catch_vfork;
15964   ops->remove_location = remove_catch_vfork;
15965   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15966   ops->print_it = print_it_catch_vfork;
15967   ops->print_one = print_one_catch_vfork;
15968   ops->print_mention = print_mention_catch_vfork;
15969   ops->print_recreate = print_recreate_catch_vfork;
15970
15971   /* Exec catchpoints.  */
15972   ops = &catch_exec_breakpoint_ops;
15973   *ops = base_breakpoint_ops;
15974   ops->dtor = dtor_catch_exec;
15975   ops->insert_location = insert_catch_exec;
15976   ops->remove_location = remove_catch_exec;
15977   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15978   ops->print_it = print_it_catch_exec;
15979   ops->print_one = print_one_catch_exec;
15980   ops->print_mention = print_mention_catch_exec;
15981   ops->print_recreate = print_recreate_catch_exec;
15982
15983   /* Solib-related catchpoints.  */
15984   ops = &catch_solib_breakpoint_ops;
15985   *ops = base_breakpoint_ops;
15986   ops->dtor = dtor_catch_solib;
15987   ops->insert_location = insert_catch_solib;
15988   ops->remove_location = remove_catch_solib;
15989   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15990   ops->check_status = check_status_catch_solib;
15991   ops->print_it = print_it_catch_solib;
15992   ops->print_one = print_one_catch_solib;
15993   ops->print_mention = print_mention_catch_solib;
15994   ops->print_recreate = print_recreate_catch_solib;
15995
15996   ops = &dprintf_breakpoint_ops;
15997   *ops = bkpt_base_breakpoint_ops;
15998   ops->re_set = dprintf_re_set;
15999   ops->resources_needed = bkpt_resources_needed;
16000   ops->print_it = bkpt_print_it;
16001   ops->print_mention = bkpt_print_mention;
16002   ops->print_recreate = dprintf_print_recreate;
16003   ops->after_condition_true = dprintf_after_condition_true;
16004   ops->breakpoint_hit = dprintf_breakpoint_hit;
16005 }
16006
16007 /* Chain containing all defined "enable breakpoint" subcommands.  */
16008
16009 static struct cmd_list_element *enablebreaklist = NULL;
16010
16011 void
16012 _initialize_breakpoint (void)
16013 {
16014   struct cmd_list_element *c;
16015
16016   initialize_breakpoint_ops ();
16017
16018   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16019   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16020   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16021
16022   breakpoint_objfile_key
16023     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16024
16025   breakpoint_chain = 0;
16026   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16027      before a breakpoint is set.  */
16028   breakpoint_count = 0;
16029
16030   tracepoint_count = 0;
16031
16032   add_com ("ignore", class_breakpoint, ignore_command, _("\
16033 Set ignore-count of breakpoint number N to COUNT.\n\
16034 Usage is `ignore N COUNT'."));
16035
16036   add_com ("commands", class_breakpoint, commands_command, _("\
16037 Set commands to be executed when the given breakpoints are hit.\n\
16038 Give a space-separated breakpoint list as argument after \"commands\".\n\
16039 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
16040 (e.g. `5-7').\n\
16041 With no argument, the targeted breakpoint is the last one set.\n\
16042 The commands themselves follow starting on the next line.\n\
16043 Type a line containing \"end\" to indicate the end of them.\n\
16044 Give \"silent\" as the first line to make the breakpoint silent;\n\
16045 then no output is printed when it is hit, except what the commands print."));
16046
16047   c = add_com ("condition", class_breakpoint, condition_command, _("\
16048 Specify breakpoint number N to break only if COND is true.\n\
16049 Usage is `condition N COND', where N is an integer and COND is an\n\
16050 expression to be evaluated whenever breakpoint N is reached."));
16051   set_cmd_completer (c, condition_completer);
16052
16053   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16054 Set a temporary breakpoint.\n\
16055 Like \"break\" except the breakpoint is only temporary,\n\
16056 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16057 by using \"enable delete\" on the breakpoint number.\n\
16058 \n"
16059 BREAK_ARGS_HELP ("tbreak")));
16060   set_cmd_completer (c, location_completer);
16061
16062   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16063 Set a hardware assisted breakpoint.\n\
16064 Like \"break\" except the breakpoint requires hardware support,\n\
16065 some target hardware may not have this support.\n\
16066 \n"
16067 BREAK_ARGS_HELP ("hbreak")));
16068   set_cmd_completer (c, location_completer);
16069
16070   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16071 Set a temporary hardware assisted breakpoint.\n\
16072 Like \"hbreak\" except the breakpoint is only temporary,\n\
16073 so it will be deleted when hit.\n\
16074 \n"
16075 BREAK_ARGS_HELP ("thbreak")));
16076   set_cmd_completer (c, location_completer);
16077
16078   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16079 Enable some breakpoints.\n\
16080 Give breakpoint numbers (separated by spaces) as arguments.\n\
16081 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16082 This is used to cancel the effect of the \"disable\" command.\n\
16083 With a subcommand you can enable temporarily."),
16084                   &enablelist, "enable ", 1, &cmdlist);
16085
16086   add_com_alias ("en", "enable", class_breakpoint, 1);
16087
16088   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16089 Enable some breakpoints.\n\
16090 Give breakpoint numbers (separated by spaces) as arguments.\n\
16091 This is used to cancel the effect of the \"disable\" command.\n\
16092 May be abbreviated to simply \"enable\".\n"),
16093                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16094
16095   add_cmd ("once", no_class, enable_once_command, _("\
16096 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16097 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16098            &enablebreaklist);
16099
16100   add_cmd ("delete", no_class, enable_delete_command, _("\
16101 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16102 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16103            &enablebreaklist);
16104
16105   add_cmd ("count", no_class, enable_count_command, _("\
16106 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16107 If a breakpoint is hit while enabled in this fashion,\n\
16108 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16109            &enablebreaklist);
16110
16111   add_cmd ("delete", no_class, enable_delete_command, _("\
16112 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16113 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16114            &enablelist);
16115
16116   add_cmd ("once", no_class, enable_once_command, _("\
16117 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16118 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16119            &enablelist);
16120
16121   add_cmd ("count", no_class, enable_count_command, _("\
16122 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16123 If a breakpoint is hit while enabled in this fashion,\n\
16124 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16125            &enablelist);
16126
16127   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16128 Disable some breakpoints.\n\
16129 Arguments are breakpoint numbers with spaces in between.\n\
16130 To disable all breakpoints, give no argument.\n\
16131 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16132                   &disablelist, "disable ", 1, &cmdlist);
16133   add_com_alias ("dis", "disable", class_breakpoint, 1);
16134   add_com_alias ("disa", "disable", class_breakpoint, 1);
16135
16136   add_cmd ("breakpoints", class_alias, disable_command, _("\
16137 Disable some breakpoints.\n\
16138 Arguments are breakpoint numbers with spaces in between.\n\
16139 To disable all breakpoints, give no argument.\n\
16140 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16141 This command may be abbreviated \"disable\"."),
16142            &disablelist);
16143
16144   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16145 Delete some breakpoints or auto-display expressions.\n\
16146 Arguments are breakpoint numbers with spaces in between.\n\
16147 To delete all breakpoints, give no argument.\n\
16148 \n\
16149 Also a prefix command for deletion of other GDB objects.\n\
16150 The \"unset\" command is also an alias for \"delete\"."),
16151                   &deletelist, "delete ", 1, &cmdlist);
16152   add_com_alias ("d", "delete", class_breakpoint, 1);
16153   add_com_alias ("del", "delete", class_breakpoint, 1);
16154
16155   add_cmd ("breakpoints", class_alias, delete_command, _("\
16156 Delete some breakpoints or auto-display expressions.\n\
16157 Arguments are breakpoint numbers with spaces in between.\n\
16158 To delete all breakpoints, give no argument.\n\
16159 This command may be abbreviated \"delete\"."),
16160            &deletelist);
16161
16162   add_com ("clear", class_breakpoint, clear_command, _("\
16163 Clear breakpoint at specified location.\n\
16164 Argument may be a linespec, explicit, or address location as described below.\n\
16165 \n\
16166 With no argument, clears all breakpoints in the line that the selected frame\n\
16167 is executing in.\n"
16168 "\n" LOCATION_HELP_STRING "\n\
16169 See also the \"delete\" command which clears breakpoints by number."));
16170   add_com_alias ("cl", "clear", class_breakpoint, 1);
16171
16172   c = add_com ("break", class_breakpoint, break_command, _("\
16173 Set breakpoint at specified location.\n"
16174 BREAK_ARGS_HELP ("break")));
16175   set_cmd_completer (c, location_completer);
16176
16177   add_com_alias ("b", "break", class_run, 1);
16178   add_com_alias ("br", "break", class_run, 1);
16179   add_com_alias ("bre", "break", class_run, 1);
16180   add_com_alias ("brea", "break", class_run, 1);
16181
16182   if (dbx_commands)
16183     {
16184       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16185 Break in function/address or break at a line in the current file."),
16186                              &stoplist, "stop ", 1, &cmdlist);
16187       add_cmd ("in", class_breakpoint, stopin_command,
16188                _("Break in function or address."), &stoplist);
16189       add_cmd ("at", class_breakpoint, stopat_command,
16190                _("Break at a line in the current file."), &stoplist);
16191       add_com ("status", class_info, breakpoints_info, _("\
16192 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16193 The \"Type\" column indicates one of:\n\
16194 \tbreakpoint     - normal breakpoint\n\
16195 \twatchpoint     - watchpoint\n\
16196 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16197 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16198 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16199 address and file/line number respectively.\n\
16200 \n\
16201 Convenience variable \"$_\" and default examine address for \"x\"\n\
16202 are set to the address of the last breakpoint listed unless the command\n\
16203 is prefixed with \"server \".\n\n\
16204 Convenience variable \"$bpnum\" contains the number of the last\n\
16205 breakpoint set."));
16206     }
16207
16208   add_info ("breakpoints", breakpoints_info, _("\
16209 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16210 The \"Type\" column indicates one of:\n\
16211 \tbreakpoint     - normal breakpoint\n\
16212 \twatchpoint     - watchpoint\n\
16213 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16214 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16215 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16216 address and file/line number respectively.\n\
16217 \n\
16218 Convenience variable \"$_\" and default examine address for \"x\"\n\
16219 are set to the address of the last breakpoint listed unless the command\n\
16220 is prefixed with \"server \".\n\n\
16221 Convenience variable \"$bpnum\" contains the number of the last\n\
16222 breakpoint set."));
16223
16224   add_info_alias ("b", "breakpoints", 1);
16225
16226   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16227 Status of all breakpoints, or breakpoint number NUMBER.\n\
16228 The \"Type\" column indicates one of:\n\
16229 \tbreakpoint     - normal breakpoint\n\
16230 \twatchpoint     - watchpoint\n\
16231 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16232 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16233 \tuntil          - internal breakpoint used by the \"until\" command\n\
16234 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16235 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16236 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16237 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16238 address and file/line number respectively.\n\
16239 \n\
16240 Convenience variable \"$_\" and default examine address for \"x\"\n\
16241 are set to the address of the last breakpoint listed unless the command\n\
16242 is prefixed with \"server \".\n\n\
16243 Convenience variable \"$bpnum\" contains the number of the last\n\
16244 breakpoint set."),
16245            &maintenanceinfolist);
16246
16247   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16248 Set catchpoints to catch events."),
16249                   &catch_cmdlist, "catch ",
16250                   0/*allow-unknown*/, &cmdlist);
16251
16252   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16253 Set temporary catchpoints to catch events."),
16254                   &tcatch_cmdlist, "tcatch ",
16255                   0/*allow-unknown*/, &cmdlist);
16256
16257   add_catch_command ("fork", _("Catch calls to fork."),
16258                      catch_fork_command_1,
16259                      NULL,
16260                      (void *) (uintptr_t) catch_fork_permanent,
16261                      (void *) (uintptr_t) catch_fork_temporary);
16262   add_catch_command ("vfork", _("Catch calls to vfork."),
16263                      catch_fork_command_1,
16264                      NULL,
16265                      (void *) (uintptr_t) catch_vfork_permanent,
16266                      (void *) (uintptr_t) catch_vfork_temporary);
16267   add_catch_command ("exec", _("Catch calls to exec."),
16268                      catch_exec_command_1,
16269                      NULL,
16270                      CATCH_PERMANENT,
16271                      CATCH_TEMPORARY);
16272   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16273 Usage: catch load [REGEX]\n\
16274 If REGEX is given, only stop for libraries matching the regular expression."),
16275                      catch_load_command_1,
16276                      NULL,
16277                      CATCH_PERMANENT,
16278                      CATCH_TEMPORARY);
16279   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16280 Usage: catch unload [REGEX]\n\
16281 If REGEX is given, only stop for libraries matching the regular expression."),
16282                      catch_unload_command_1,
16283                      NULL,
16284                      CATCH_PERMANENT,
16285                      CATCH_TEMPORARY);
16286
16287   c = add_com ("watch", class_breakpoint, watch_command, _("\
16288 Set a watchpoint for an expression.\n\
16289 Usage: watch [-l|-location] EXPRESSION\n\
16290 A watchpoint stops execution of your program whenever the value of\n\
16291 an expression changes.\n\
16292 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16293 the memory to which it refers."));
16294   set_cmd_completer (c, expression_completer);
16295
16296   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16297 Set a read watchpoint for an expression.\n\
16298 Usage: rwatch [-l|-location] EXPRESSION\n\
16299 A watchpoint stops execution of your program whenever the value of\n\
16300 an expression is read.\n\
16301 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16302 the memory to which it refers."));
16303   set_cmd_completer (c, expression_completer);
16304
16305   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16306 Set a watchpoint for an expression.\n\
16307 Usage: awatch [-l|-location] EXPRESSION\n\
16308 A watchpoint stops execution of your program whenever the value of\n\
16309 an expression is either read or written.\n\
16310 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16311 the memory to which it refers."));
16312   set_cmd_completer (c, expression_completer);
16313
16314   add_info ("watchpoints", watchpoints_info, _("\
16315 Status of specified watchpoints (all watchpoints if no argument)."));
16316
16317   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16318      respond to changes - contrary to the description.  */
16319   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16320                             &can_use_hw_watchpoints, _("\
16321 Set debugger's willingness to use watchpoint hardware."), _("\
16322 Show debugger's willingness to use watchpoint hardware."), _("\
16323 If zero, gdb will not use hardware for new watchpoints, even if\n\
16324 such is available.  (However, any hardware watchpoints that were\n\
16325 created before setting this to nonzero, will continue to use watchpoint\n\
16326 hardware.)"),
16327                             NULL,
16328                             show_can_use_hw_watchpoints,
16329                             &setlist, &showlist);
16330
16331   can_use_hw_watchpoints = 1;
16332
16333   /* Tracepoint manipulation commands.  */
16334
16335   c = add_com ("trace", class_breakpoint, trace_command, _("\
16336 Set a tracepoint at specified location.\n\
16337 \n"
16338 BREAK_ARGS_HELP ("trace") "\n\
16339 Do \"help tracepoints\" for info on other tracepoint commands."));
16340   set_cmd_completer (c, location_completer);
16341
16342   add_com_alias ("tp", "trace", class_alias, 0);
16343   add_com_alias ("tr", "trace", class_alias, 1);
16344   add_com_alias ("tra", "trace", class_alias, 1);
16345   add_com_alias ("trac", "trace", class_alias, 1);
16346
16347   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16348 Set a fast tracepoint at specified location.\n\
16349 \n"
16350 BREAK_ARGS_HELP ("ftrace") "\n\
16351 Do \"help tracepoints\" for info on other tracepoint commands."));
16352   set_cmd_completer (c, location_completer);
16353
16354   c = add_com ("strace", class_breakpoint, strace_command, _("\
16355 Set a static tracepoint at location or marker.\n\
16356 \n\
16357 strace [LOCATION] [if CONDITION]\n\
16358 LOCATION may be a linespec, explicit, or address location (described below) \n\
16359 or -m MARKER_ID.\n\n\
16360 If a marker id is specified, probe the marker with that name.  With\n\
16361 no LOCATION, uses current execution address of the selected stack frame.\n\
16362 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16363 This collects arbitrary user data passed in the probe point call to the\n\
16364 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16365 by printing the $_sdata variable like any other convenience variable.\n\
16366 \n\
16367 CONDITION is a boolean expression.\n\
16368 \n" LOCATION_HELP_STRING "\n\
16369 Multiple tracepoints at one place are permitted, and useful if their\n\
16370 conditions are different.\n\
16371 \n\
16372 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16373 Do \"help tracepoints\" for info on other tracepoint commands."));
16374   set_cmd_completer (c, location_completer);
16375
16376   add_info ("tracepoints", tracepoints_info, _("\
16377 Status of specified tracepoints (all tracepoints if no argument).\n\
16378 Convenience variable \"$tpnum\" contains the number of the\n\
16379 last tracepoint set."));
16380
16381   add_info_alias ("tp", "tracepoints", 1);
16382
16383   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16384 Delete specified tracepoints.\n\
16385 Arguments are tracepoint numbers, separated by spaces.\n\
16386 No argument means delete all tracepoints."),
16387            &deletelist);
16388   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16389
16390   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16391 Disable specified tracepoints.\n\
16392 Arguments are tracepoint numbers, separated by spaces.\n\
16393 No argument means disable all tracepoints."),
16394            &disablelist);
16395   deprecate_cmd (c, "disable");
16396
16397   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16398 Enable specified tracepoints.\n\
16399 Arguments are tracepoint numbers, separated by spaces.\n\
16400 No argument means enable all tracepoints."),
16401            &enablelist);
16402   deprecate_cmd (c, "enable");
16403
16404   add_com ("passcount", class_trace, trace_pass_command, _("\
16405 Set the passcount for a tracepoint.\n\
16406 The trace will end when the tracepoint has been passed 'count' times.\n\
16407 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16408 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16409
16410   add_prefix_cmd ("save", class_breakpoint, save_command,
16411                   _("Save breakpoint definitions as a script."),
16412                   &save_cmdlist, "save ",
16413                   0/*allow-unknown*/, &cmdlist);
16414
16415   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16416 Save current breakpoint definitions as a script.\n\
16417 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16418 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16419 session to restore them."),
16420                &save_cmdlist);
16421   set_cmd_completer (c, filename_completer);
16422
16423   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16424 Save current tracepoint definitions as a script.\n\
16425 Use the 'source' command in another debug session to restore them."),
16426                &save_cmdlist);
16427   set_cmd_completer (c, filename_completer);
16428
16429   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16430   deprecate_cmd (c, "save tracepoints");
16431
16432   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16433 Breakpoint specific settings\n\
16434 Configure various breakpoint-specific variables such as\n\
16435 pending breakpoint behavior"),
16436                   &breakpoint_set_cmdlist, "set breakpoint ",
16437                   0/*allow-unknown*/, &setlist);
16438   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16439 Breakpoint specific settings\n\
16440 Configure various breakpoint-specific variables such as\n\
16441 pending breakpoint behavior"),
16442                   &breakpoint_show_cmdlist, "show breakpoint ",
16443                   0/*allow-unknown*/, &showlist);
16444
16445   add_setshow_auto_boolean_cmd ("pending", no_class,
16446                                 &pending_break_support, _("\
16447 Set debugger's behavior regarding pending breakpoints."), _("\
16448 Show debugger's behavior regarding pending breakpoints."), _("\
16449 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16450 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16451 an error.  If auto, an unrecognized breakpoint location results in a\n\
16452 user-query to see if a pending breakpoint should be created."),
16453                                 NULL,
16454                                 show_pending_break_support,
16455                                 &breakpoint_set_cmdlist,
16456                                 &breakpoint_show_cmdlist);
16457
16458   pending_break_support = AUTO_BOOLEAN_AUTO;
16459
16460   add_setshow_boolean_cmd ("auto-hw", no_class,
16461                            &automatic_hardware_breakpoints, _("\
16462 Set automatic usage of hardware breakpoints."), _("\
16463 Show automatic usage of hardware breakpoints."), _("\
16464 If set, the debugger will automatically use hardware breakpoints for\n\
16465 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16466 a warning will be emitted for such breakpoints."),
16467                            NULL,
16468                            show_automatic_hardware_breakpoints,
16469                            &breakpoint_set_cmdlist,
16470                            &breakpoint_show_cmdlist);
16471
16472   add_setshow_boolean_cmd ("always-inserted", class_support,
16473                            &always_inserted_mode, _("\
16474 Set mode for inserting breakpoints."), _("\
16475 Show mode for inserting breakpoints."), _("\
16476 When this mode is on, breakpoints are inserted immediately as soon as\n\
16477 they're created, kept inserted even when execution stops, and removed\n\
16478 only when the user deletes them.  When this mode is off (the default),\n\
16479 breakpoints are inserted only when execution continues, and removed\n\
16480 when execution stops."),
16481                                 NULL,
16482                                 &show_always_inserted_mode,
16483                                 &breakpoint_set_cmdlist,
16484                                 &breakpoint_show_cmdlist);
16485
16486   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16487                         condition_evaluation_enums,
16488                         &condition_evaluation_mode_1, _("\
16489 Set mode of breakpoint condition evaluation."), _("\
16490 Show mode of breakpoint condition evaluation."), _("\
16491 When this is set to \"host\", breakpoint conditions will be\n\
16492 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16493 breakpoint conditions will be downloaded to the target (if the target\n\
16494 supports such feature) and conditions will be evaluated on the target's side.\n\
16495 If this is set to \"auto\" (default), this will be automatically set to\n\
16496 \"target\" if it supports condition evaluation, otherwise it will\n\
16497 be set to \"gdb\""),
16498                            &set_condition_evaluation_mode,
16499                            &show_condition_evaluation_mode,
16500                            &breakpoint_set_cmdlist,
16501                            &breakpoint_show_cmdlist);
16502
16503   add_com ("break-range", class_breakpoint, break_range_command, _("\
16504 Set a breakpoint for an address range.\n\
16505 break-range START-LOCATION, END-LOCATION\n\
16506 where START-LOCATION and END-LOCATION can be one of the following:\n\
16507   LINENUM, for that line in the current file,\n\
16508   FILE:LINENUM, for that line in that file,\n\
16509   +OFFSET, for that number of lines after the current line\n\
16510            or the start of the range\n\
16511   FUNCTION, for the first line in that function,\n\
16512   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16513   *ADDRESS, for the instruction at that address.\n\
16514 \n\
16515 The breakpoint will stop execution of the inferior whenever it executes\n\
16516 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16517 range (including START-LOCATION and END-LOCATION)."));
16518
16519   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16520 Set a dynamic printf at specified location.\n\
16521 dprintf location,format string,arg1,arg2,...\n\
16522 location may be a linespec, explicit, or address location.\n"
16523 "\n" LOCATION_HELP_STRING));
16524   set_cmd_completer (c, location_completer);
16525
16526   add_setshow_enum_cmd ("dprintf-style", class_support,
16527                         dprintf_style_enums, &dprintf_style, _("\
16528 Set the style of usage for dynamic printf."), _("\
16529 Show the style of usage for dynamic printf."), _("\
16530 This setting chooses how GDB will do a dynamic printf.\n\
16531 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16532 console, as with the \"printf\" command.\n\
16533 If the value is \"call\", the print is done by calling a function in your\n\
16534 program; by default printf(), but you can choose a different function or\n\
16535 output stream by setting dprintf-function and dprintf-channel."),
16536                         update_dprintf_commands, NULL,
16537                         &setlist, &showlist);
16538
16539   dprintf_function = xstrdup ("printf");
16540   add_setshow_string_cmd ("dprintf-function", class_support,
16541                           &dprintf_function, _("\
16542 Set the function to use for dynamic printf"), _("\
16543 Show the function to use for dynamic printf"), NULL,
16544                           update_dprintf_commands, NULL,
16545                           &setlist, &showlist);
16546
16547   dprintf_channel = xstrdup ("");
16548   add_setshow_string_cmd ("dprintf-channel", class_support,
16549                           &dprintf_channel, _("\
16550 Set the channel to use for dynamic printf"), _("\
16551 Show the channel to use for dynamic printf"), NULL,
16552                           update_dprintf_commands, NULL,
16553                           &setlist, &showlist);
16554
16555   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16556                            &disconnected_dprintf, _("\
16557 Set whether dprintf continues after GDB disconnects."), _("\
16558 Show whether dprintf continues after GDB disconnects."), _("\
16559 Use this to let dprintf commands continue to hit and produce output\n\
16560 even if GDB disconnects or detaches from the target."),
16561                            NULL,
16562                            NULL,
16563                            &setlist, &showlist);
16564
16565   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16566 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16567 (target agent only) This is useful for formatted output in user-defined commands."));
16568
16569   automatic_hardware_breakpoints = 1;
16570
16571   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16572   observer_attach_thread_exit (remove_threaded_breakpoints);
16573 }