-Wwrite-strings: Don't initialize string command variables to empty string
[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 "location.h"
71 #include "thread-fsm.h"
72 #include "tid-parse.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "extension.h"
83 #include <algorithm>
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_location;                                      \
583              BP_TMP < bp_location + bp_location_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_location + bp_location_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_location_compare - primarily by the ADDRESS.  */
611
612 static struct bp_location **bp_location;
613
614 /* Number of elements of BP_LOCATION.  */
615
616 static unsigned bp_location_count;
617
618 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
619    ADDRESS for the current elements of BP_LOCATION which get a valid
620    result from bp_location_has_shadow.  You can use it for roughly
621    limiting the subrange of BP_LOCATION to scan for shadow bytes for
622    an address you need to read.  */
623
624 static CORE_ADDR bp_location_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_LOCATION which get a valid result from bp_location_has_shadow.
629    You can use it for roughly limiting the subrange of BP_LOCATION to
630    scan for shadow bytes for an address you need to read.  */
631
632 static CORE_ADDR bp_location_shadow_len_after_address_max;
633
634 /* The locations that no longer correspond to any breakpoint, unlinked
635    from bp_location array, but for which a hit may still be reported
636    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_location_compare function.  */
925
926 static int
927 bp_location_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   memset (&dummy_loc, 0, sizeof (struct bp_location));
952   dummy_loc.address = address;
953
954   /* Find a close match to the first location at ADDRESS.  */
955   locp_found = ((struct bp_location **)
956                 bsearch (&dummy_locp, bp_location, bp_location_count,
957                          sizeof (struct bp_location **),
958                          bp_location_compare_addrs));
959
960   /* Nothing was found, nothing left to do.  */
961   if (locp_found == NULL)
962     return NULL;
963
964   /* We may have found a location that is at ADDRESS but is not the first in the
965      location's list.  Go backwards (if possible) and locate the first one.  */
966   while ((locp_found - 1) >= bp_location
967          && (*(locp_found - 1))->address == address)
968     locp_found--;
969
970   return locp_found;
971 }
972
973 void
974 set_breakpoint_condition (struct breakpoint *b, const char *exp,
975                           int from_tty)
976 {
977   xfree (b->cond_string);
978   b->cond_string = NULL;
979
980   if (is_watchpoint (b))
981     {
982       struct watchpoint *w = (struct watchpoint *) b;
983
984       w->cond_exp.reset ();
985     }
986   else
987     {
988       struct bp_location *loc;
989
990       for (loc = b->loc; loc; loc = loc->next)
991         {
992           loc->cond.reset ();
993
994           /* No need to free the condition agent expression
995              bytecode (if we have one).  We will handle this
996              when we go through update_global_location_list.  */
997         }
998     }
999
1000   if (*exp == 0)
1001     {
1002       if (from_tty)
1003         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
1004     }
1005   else
1006     {
1007       const char *arg = exp;
1008
1009       /* I don't know if it matters whether this is the string the user
1010          typed in or the decompiled expression.  */
1011       b->cond_string = xstrdup (arg);
1012       b->condition_not_parsed = 0;
1013
1014       if (is_watchpoint (b))
1015         {
1016           struct watchpoint *w = (struct watchpoint *) b;
1017
1018           innermost_block = NULL;
1019           arg = exp;
1020           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1021           if (*arg)
1022             error (_("Junk at end of expression"));
1023           w->cond_exp_valid_block = innermost_block;
1024         }
1025       else
1026         {
1027           struct bp_location *loc;
1028
1029           for (loc = b->loc; loc; loc = loc->next)
1030             {
1031               arg = exp;
1032               loc->cond =
1033                 parse_exp_1 (&arg, loc->address,
1034                              block_for_pc (loc->address), 0);
1035               if (*arg)
1036                 error (_("Junk at end of expression"));
1037             }
1038         }
1039     }
1040   mark_breakpoint_modified (b);
1041
1042   observer_notify_breakpoint_modified (b);
1043 }
1044
1045 /* Completion for the "condition" command.  */
1046
1047 static VEC (char_ptr) *
1048 condition_completer (struct cmd_list_element *cmd,
1049                      const char *text, const char *word)
1050 {
1051   const char *space;
1052
1053   text = skip_spaces_const (text);
1054   space = skip_to_space_const (text);
1055   if (*space == '\0')
1056     {
1057       int len;
1058       struct breakpoint *b;
1059       VEC (char_ptr) *result = NULL;
1060
1061       if (text[0] == '$')
1062         {
1063           /* We don't support completion of history indices.  */
1064           if (isdigit (text[1]))
1065             return NULL;
1066           return complete_internalvar (&text[1]);
1067         }
1068
1069       /* We're completing the breakpoint number.  */
1070       len = strlen (text);
1071
1072       ALL_BREAKPOINTS (b)
1073         {
1074           char number[50];
1075
1076           xsnprintf (number, sizeof (number), "%d", b->number);
1077
1078           if (strncmp (number, text, len) == 0)
1079             VEC_safe_push (char_ptr, result, xstrdup (number));
1080         }
1081
1082       return result;
1083     }
1084
1085   /* We're completing the expression part.  */
1086   text = skip_spaces_const (space);
1087   return expression_completer (cmd, text, word);
1088 }
1089
1090 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1091
1092 static void
1093 condition_command (char *arg, int from_tty)
1094 {
1095   struct breakpoint *b;
1096   char *p;
1097   int bnum;
1098
1099   if (arg == 0)
1100     error_no_arg (_("breakpoint number"));
1101
1102   p = arg;
1103   bnum = get_number (&p);
1104   if (bnum == 0)
1105     error (_("Bad breakpoint argument: '%s'"), arg);
1106
1107   ALL_BREAKPOINTS (b)
1108     if (b->number == bnum)
1109       {
1110         /* Check if this breakpoint has a "stop" method implemented in an
1111            extension language.  This method and conditions entered into GDB
1112            from the CLI are mutually exclusive.  */
1113         const struct extension_language_defn *extlang
1114           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1115
1116         if (extlang != NULL)
1117           {
1118             error (_("Only one stop condition allowed.  There is currently"
1119                      " a %s stop condition defined for this breakpoint."),
1120                    ext_lang_capitalized_name (extlang));
1121           }
1122         set_breakpoint_condition (b, p, from_tty);
1123
1124         if (is_breakpoint (b))
1125           update_global_location_list (UGLL_MAY_INSERT);
1126
1127         return;
1128       }
1129
1130   error (_("No breakpoint number %d."), bnum);
1131 }
1132
1133 /* Check that COMMAND do not contain commands that are suitable
1134    only for tracepoints and not suitable for ordinary breakpoints.
1135    Throw if any such commands is found.  */
1136
1137 static void
1138 check_no_tracepoint_commands (struct command_line *commands)
1139 {
1140   struct command_line *c;
1141
1142   for (c = commands; c; c = c->next)
1143     {
1144       int i;
1145
1146       if (c->control_type == while_stepping_control)
1147         error (_("The 'while-stepping' command can "
1148                  "only be used for tracepoints"));
1149
1150       for (i = 0; i < c->body_count; ++i)
1151         check_no_tracepoint_commands ((c->body_list)[i]);
1152
1153       /* Not that command parsing removes leading whitespace and comment
1154          lines and also empty lines.  So, we only need to check for
1155          command directly.  */
1156       if (strstr (c->line, "collect ") == c->line)
1157         error (_("The 'collect' command can only be used for tracepoints"));
1158
1159       if (strstr (c->line, "teval ") == c->line)
1160         error (_("The 'teval' command can only be used for tracepoints"));
1161     }
1162 }
1163
1164 /* Encapsulate tests for different types of tracepoints.  */
1165
1166 static int
1167 is_tracepoint_type (enum bptype type)
1168 {
1169   return (type == bp_tracepoint
1170           || type == bp_fast_tracepoint
1171           || type == bp_static_tracepoint);
1172 }
1173
1174 int
1175 is_tracepoint (const struct breakpoint *b)
1176 {
1177   return is_tracepoint_type (b->type);
1178 }
1179
1180 /* A helper function that validates that COMMANDS are valid for a
1181    breakpoint.  This function will throw an exception if a problem is
1182    found.  */
1183
1184 static void
1185 validate_commands_for_breakpoint (struct breakpoint *b,
1186                                   struct command_line *commands)
1187 {
1188   if (is_tracepoint (b))
1189     {
1190       struct tracepoint *t = (struct tracepoint *) b;
1191       struct command_line *c;
1192       struct command_line *while_stepping = 0;
1193
1194       /* Reset the while-stepping step count.  The previous commands
1195          might have included a while-stepping action, while the new
1196          ones might not.  */
1197       t->step_count = 0;
1198
1199       /* We need to verify that each top-level element of commands is
1200          valid for tracepoints, that there's at most one
1201          while-stepping element, and that the while-stepping's body
1202          has valid tracing commands excluding nested while-stepping.
1203          We also need to validate the tracepoint action line in the
1204          context of the tracepoint --- validate_actionline actually
1205          has side effects, like setting the tracepoint's
1206          while-stepping STEP_COUNT, in addition to checking if the
1207          collect/teval actions parse and make sense in the
1208          tracepoint's context.  */
1209       for (c = commands; c; c = c->next)
1210         {
1211           if (c->control_type == while_stepping_control)
1212             {
1213               if (b->type == bp_fast_tracepoint)
1214                 error (_("The 'while-stepping' command "
1215                          "cannot be used for fast tracepoint"));
1216               else if (b->type == bp_static_tracepoint)
1217                 error (_("The 'while-stepping' command "
1218                          "cannot be used for static tracepoint"));
1219
1220               if (while_stepping)
1221                 error (_("The 'while-stepping' command "
1222                          "can be used only once"));
1223               else
1224                 while_stepping = c;
1225             }
1226
1227           validate_actionline (c->line, b);
1228         }
1229       if (while_stepping)
1230         {
1231           struct command_line *c2;
1232
1233           gdb_assert (while_stepping->body_count == 1);
1234           c2 = while_stepping->body_list[0];
1235           for (; c2; c2 = c2->next)
1236             {
1237               if (c2->control_type == while_stepping_control)
1238                 error (_("The 'while-stepping' command cannot be nested"));
1239             }
1240         }
1241     }
1242   else
1243     {
1244       check_no_tracepoint_commands (commands);
1245     }
1246 }
1247
1248 /* Return a vector of all the static tracepoints set at ADDR.  The
1249    caller is responsible for releasing the vector.  */
1250
1251 VEC(breakpoint_p) *
1252 static_tracepoints_here (CORE_ADDR addr)
1253 {
1254   struct breakpoint *b;
1255   VEC(breakpoint_p) *found = 0;
1256   struct bp_location *loc;
1257
1258   ALL_BREAKPOINTS (b)
1259     if (b->type == bp_static_tracepoint)
1260       {
1261         for (loc = b->loc; loc; loc = loc->next)
1262           if (loc->address == addr)
1263             VEC_safe_push(breakpoint_p, found, b);
1264       }
1265
1266   return found;
1267 }
1268
1269 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1270    validate that only allowed commands are included.  */
1271
1272 void
1273 breakpoint_set_commands (struct breakpoint *b, 
1274                          struct command_line *commands)
1275 {
1276   validate_commands_for_breakpoint (b, commands);
1277
1278   decref_counted_command_line (&b->commands);
1279   b->commands = alloc_counted_command_line (commands);
1280   observer_notify_breakpoint_modified (b);
1281 }
1282
1283 /* Set the internal `silent' flag on the breakpoint.  Note that this
1284    is not the same as the "silent" that may appear in the breakpoint's
1285    commands.  */
1286
1287 void
1288 breakpoint_set_silent (struct breakpoint *b, int silent)
1289 {
1290   int old_silent = b->silent;
1291
1292   b->silent = silent;
1293   if (old_silent != silent)
1294     observer_notify_breakpoint_modified (b);
1295 }
1296
1297 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1298    breakpoint work for any thread.  */
1299
1300 void
1301 breakpoint_set_thread (struct breakpoint *b, int thread)
1302 {
1303   int old_thread = b->thread;
1304
1305   b->thread = thread;
1306   if (old_thread != thread)
1307     observer_notify_breakpoint_modified (b);
1308 }
1309
1310 /* Set the task for this breakpoint.  If TASK is 0, make the
1311    breakpoint work for any task.  */
1312
1313 void
1314 breakpoint_set_task (struct breakpoint *b, int task)
1315 {
1316   int old_task = b->task;
1317
1318   b->task = task;
1319   if (old_task != task)
1320     observer_notify_breakpoint_modified (b);
1321 }
1322
1323 void
1324 check_tracepoint_command (char *line, void *closure)
1325 {
1326   struct breakpoint *b = (struct breakpoint *) closure;
1327
1328   validate_actionline (line, b);
1329 }
1330
1331 /* A structure used to pass information through
1332    map_breakpoint_numbers.  */
1333
1334 struct commands_info
1335 {
1336   /* True if the command was typed at a tty.  */
1337   int from_tty;
1338
1339   /* The breakpoint range spec.  */
1340   const char *arg;
1341
1342   /* Non-NULL if the body of the commands are being read from this
1343      already-parsed command.  */
1344   struct command_line *control;
1345
1346   /* The command lines read from the user, or NULL if they have not
1347      yet been read.  */
1348   struct counted_command_line *cmd;
1349 };
1350
1351 /* A callback for map_breakpoint_numbers that sets the commands for
1352    commands_command.  */
1353
1354 static void
1355 do_map_commands_command (struct breakpoint *b, void *data)
1356 {
1357   struct commands_info *info = (struct commands_info *) data;
1358
1359   if (info->cmd == NULL)
1360     {
1361       struct command_line *l;
1362
1363       if (info->control != NULL)
1364         l = copy_command_lines (info->control->body_list[0]);
1365       else
1366         {
1367           struct cleanup *old_chain;
1368           char *str;
1369
1370           str = xstrprintf (_("Type commands for breakpoint(s) "
1371                               "%s, one per line."),
1372                             info->arg);
1373
1374           old_chain = make_cleanup (xfree, str);
1375
1376           l = read_command_lines (str,
1377                                   info->from_tty, 1,
1378                                   (is_tracepoint (b)
1379                                    ? check_tracepoint_command : 0),
1380                                   b);
1381
1382           do_cleanups (old_chain);
1383         }
1384
1385       info->cmd = alloc_counted_command_line (l);
1386     }
1387
1388   /* If a breakpoint was on the list more than once, we don't need to
1389      do anything.  */
1390   if (b->commands != info->cmd)
1391     {
1392       validate_commands_for_breakpoint (b, info->cmd->commands);
1393       incref_counted_command_line (info->cmd);
1394       decref_counted_command_line (&b->commands);
1395       b->commands = info->cmd;
1396       observer_notify_breakpoint_modified (b);
1397     }
1398 }
1399
1400 static void
1401 commands_command_1 (const char *arg, int from_tty,
1402                     struct command_line *control)
1403 {
1404   struct cleanup *cleanups;
1405   struct commands_info info;
1406
1407   info.from_tty = from_tty;
1408   info.control = control;
1409   info.cmd = NULL;
1410   /* If we read command lines from the user, then `info' will hold an
1411      extra reference to the commands that we must clean up.  */
1412   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1413
1414   std::string new_arg;
1415
1416   if (arg == NULL || !*arg)
1417     {
1418       if (breakpoint_count - prev_breakpoint_count > 1)
1419         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1420                                  breakpoint_count);
1421       else if (breakpoint_count > 0)
1422         new_arg = string_printf ("%d", breakpoint_count);
1423     }
1424   else
1425     new_arg = arg;
1426
1427   info.arg = new_arg.c_str ();
1428
1429   map_breakpoint_numbers (info.arg, do_map_commands_command, &info);
1430
1431   if (info.cmd == NULL)
1432     error (_("No breakpoints specified."));
1433
1434   do_cleanups (cleanups);
1435 }
1436
1437 static void
1438 commands_command (char *arg, int from_tty)
1439 {
1440   commands_command_1 (arg, from_tty, NULL);
1441 }
1442
1443 /* Like commands_command, but instead of reading the commands from
1444    input stream, takes them from an already parsed command structure.
1445
1446    This is used by cli-script.c to DTRT with breakpoint commands
1447    that are part of if and while bodies.  */
1448 enum command_control_type
1449 commands_from_control_command (const char *arg, struct command_line *cmd)
1450 {
1451   commands_command_1 (arg, 0, cmd);
1452   return simple_control;
1453 }
1454
1455 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1456
1457 static int
1458 bp_location_has_shadow (struct bp_location *bl)
1459 {
1460   if (bl->loc_type != bp_loc_software_breakpoint)
1461     return 0;
1462   if (!bl->inserted)
1463     return 0;
1464   if (bl->target_info.shadow_len == 0)
1465     /* BL isn't valid, or doesn't shadow memory.  */
1466     return 0;
1467   return 1;
1468 }
1469
1470 /* Update BUF, which is LEN bytes read from the target address
1471    MEMADDR, by replacing a memory breakpoint with its shadowed
1472    contents.
1473
1474    If READBUF is not NULL, this buffer must not overlap with the of
1475    the breakpoint location's shadow_contents buffer.  Otherwise, a
1476    failed assertion internal error will be raised.  */
1477
1478 static void
1479 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1480                             const gdb_byte *writebuf_org,
1481                             ULONGEST memaddr, LONGEST len,
1482                             struct bp_target_info *target_info,
1483                             struct gdbarch *gdbarch)
1484 {
1485   /* Now do full processing of the found relevant range of elements.  */
1486   CORE_ADDR bp_addr = 0;
1487   int bp_size = 0;
1488   int bptoffset = 0;
1489
1490   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1491                                  current_program_space->aspace, 0))
1492     {
1493       /* The breakpoint is inserted in a different address space.  */
1494       return;
1495     }
1496
1497   /* Addresses and length of the part of the breakpoint that
1498      we need to copy.  */
1499   bp_addr = target_info->placed_address;
1500   bp_size = target_info->shadow_len;
1501
1502   if (bp_addr + bp_size <= memaddr)
1503     {
1504       /* The breakpoint is entirely before the chunk of memory we are
1505          reading.  */
1506       return;
1507     }
1508
1509   if (bp_addr >= memaddr + len)
1510     {
1511       /* The breakpoint is entirely after the chunk of memory we are
1512          reading.  */
1513       return;
1514     }
1515
1516   /* Offset within shadow_contents.  */
1517   if (bp_addr < memaddr)
1518     {
1519       /* Only copy the second part of the breakpoint.  */
1520       bp_size -= memaddr - bp_addr;
1521       bptoffset = memaddr - bp_addr;
1522       bp_addr = memaddr;
1523     }
1524
1525   if (bp_addr + bp_size > memaddr + len)
1526     {
1527       /* Only copy the first part of the breakpoint.  */
1528       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1529     }
1530
1531   if (readbuf != NULL)
1532     {
1533       /* Verify that the readbuf buffer does not overlap with the
1534          shadow_contents buffer.  */
1535       gdb_assert (target_info->shadow_contents >= readbuf + len
1536                   || readbuf >= (target_info->shadow_contents
1537                                  + target_info->shadow_len));
1538
1539       /* Update the read buffer with this inserted breakpoint's
1540          shadow.  */
1541       memcpy (readbuf + bp_addr - memaddr,
1542               target_info->shadow_contents + bptoffset, bp_size);
1543     }
1544   else
1545     {
1546       const unsigned char *bp;
1547       CORE_ADDR addr = target_info->reqstd_address;
1548       int placed_size;
1549
1550       /* Update the shadow with what we want to write to memory.  */
1551       memcpy (target_info->shadow_contents + bptoffset,
1552               writebuf_org + bp_addr - memaddr, bp_size);
1553
1554       /* Determine appropriate breakpoint contents and size for this
1555          address.  */
1556       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1557
1558       /* Update the final write buffer with this inserted
1559          breakpoint's INSN.  */
1560       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1561     }
1562 }
1563
1564 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1565    by replacing any memory breakpoints with their shadowed contents.
1566
1567    If READBUF is not NULL, this buffer must not overlap with any of
1568    the breakpoint location's shadow_contents buffers.  Otherwise,
1569    a failed assertion internal error will be raised.
1570
1571    The range of shadowed area by each bp_location is:
1572      bl->address - bp_location_placed_address_before_address_max
1573      up to bl->address + bp_location_shadow_len_after_address_max
1574    The range we were requested to resolve shadows for is:
1575      memaddr ... memaddr + len
1576    Thus the safe cutoff boundaries for performance optimization are
1577      memaddr + len <= (bl->address
1578                        - bp_location_placed_address_before_address_max)
1579    and:
1580      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1581
1582 void
1583 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1584                         const gdb_byte *writebuf_org,
1585                         ULONGEST memaddr, LONGEST len)
1586 {
1587   /* Left boundary, right boundary and median element of our binary
1588      search.  */
1589   unsigned bc_l, bc_r, bc;
1590
1591   /* Find BC_L which is a leftmost element which may affect BUF
1592      content.  It is safe to report lower value but a failure to
1593      report higher one.  */
1594
1595   bc_l = 0;
1596   bc_r = bp_location_count;
1597   while (bc_l + 1 < bc_r)
1598     {
1599       struct bp_location *bl;
1600
1601       bc = (bc_l + bc_r) / 2;
1602       bl = bp_location[bc];
1603
1604       /* Check first BL->ADDRESS will not overflow due to the added
1605          constant.  Then advance the left boundary only if we are sure
1606          the BC element can in no way affect the BUF content (MEMADDR
1607          to MEMADDR + LEN range).
1608
1609          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1610          offset so that we cannot miss a breakpoint with its shadow
1611          range tail still reaching MEMADDR.  */
1612
1613       if ((bl->address + bp_location_shadow_len_after_address_max
1614            >= bl->address)
1615           && (bl->address + bp_location_shadow_len_after_address_max
1616               <= memaddr))
1617         bc_l = bc;
1618       else
1619         bc_r = bc;
1620     }
1621
1622   /* Due to the binary search above, we need to make sure we pick the
1623      first location that's at BC_L's address.  E.g., if there are
1624      multiple locations at the same address, BC_L may end up pointing
1625      at a duplicate location, and miss the "master"/"inserted"
1626      location.  Say, given locations L1, L2 and L3 at addresses A and
1627      B:
1628
1629       L1@A, L2@A, L3@B, ...
1630
1631      BC_L could end up pointing at location L2, while the "master"
1632      location could be L1.  Since the `loc->inserted' flag is only set
1633      on "master" locations, we'd forget to restore the shadow of L1
1634      and L2.  */
1635   while (bc_l > 0
1636          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1637     bc_l--;
1638
1639   /* Now do full processing of the found relevant range of elements.  */
1640
1641   for (bc = bc_l; bc < bp_location_count; bc++)
1642   {
1643     struct bp_location *bl = bp_location[bc];
1644
1645     /* bp_location array has BL->OWNER always non-NULL.  */
1646     if (bl->owner->type == bp_none)
1647       warning (_("reading through apparently deleted breakpoint #%d?"),
1648                bl->owner->number);
1649
1650     /* Performance optimization: any further element can no longer affect BUF
1651        content.  */
1652
1653     if (bl->address >= bp_location_placed_address_before_address_max
1654         && memaddr + len <= (bl->address
1655                              - bp_location_placed_address_before_address_max))
1656       break;
1657
1658     if (!bp_location_has_shadow (bl))
1659       continue;
1660
1661     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1662                                 memaddr, len, &bl->target_info, bl->gdbarch);
1663   }
1664 }
1665
1666 \f
1667
1668 /* Return true if BPT is either a software breakpoint or a hardware
1669    breakpoint.  */
1670
1671 int
1672 is_breakpoint (const struct breakpoint *bpt)
1673 {
1674   return (bpt->type == bp_breakpoint
1675           || bpt->type == bp_hardware_breakpoint
1676           || bpt->type == bp_dprintf);
1677 }
1678
1679 /* Return true if BPT is of any hardware watchpoint kind.  */
1680
1681 static int
1682 is_hardware_watchpoint (const struct breakpoint *bpt)
1683 {
1684   return (bpt->type == bp_hardware_watchpoint
1685           || bpt->type == bp_read_watchpoint
1686           || bpt->type == bp_access_watchpoint);
1687 }
1688
1689 /* Return true if BPT is of any watchpoint kind, hardware or
1690    software.  */
1691
1692 int
1693 is_watchpoint (const struct breakpoint *bpt)
1694 {
1695   return (is_hardware_watchpoint (bpt)
1696           || bpt->type == bp_watchpoint);
1697 }
1698
1699 /* Returns true if the current thread and its running state are safe
1700    to evaluate or update watchpoint B.  Watchpoints on local
1701    expressions need to be evaluated in the context of the thread that
1702    was current when the watchpoint was created, and, that thread needs
1703    to be stopped to be able to select the correct frame context.
1704    Watchpoints on global expressions can be evaluated on any thread,
1705    and in any state.  It is presently left to the target allowing
1706    memory accesses when threads are running.  */
1707
1708 static int
1709 watchpoint_in_thread_scope (struct watchpoint *b)
1710 {
1711   return (b->base.pspace == current_program_space
1712           && (ptid_equal (b->watchpoint_thread, null_ptid)
1713               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1714                   && !is_executing (inferior_ptid))));
1715 }
1716
1717 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1718    associated bp_watchpoint_scope breakpoint.  */
1719
1720 static void
1721 watchpoint_del_at_next_stop (struct watchpoint *w)
1722 {
1723   struct breakpoint *b = &w->base;
1724
1725   if (b->related_breakpoint != b)
1726     {
1727       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1728       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1729       b->related_breakpoint->disposition = disp_del_at_next_stop;
1730       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1731       b->related_breakpoint = b;
1732     }
1733   b->disposition = disp_del_at_next_stop;
1734 }
1735
1736 /* Extract a bitfield value from value VAL using the bit parameters contained in
1737    watchpoint W.  */
1738
1739 static struct value *
1740 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1741 {
1742   struct value *bit_val;
1743
1744   if (val == NULL)
1745     return NULL;
1746
1747   bit_val = allocate_value (value_type (val));
1748
1749   unpack_value_bitfield (bit_val,
1750                          w->val_bitpos,
1751                          w->val_bitsize,
1752                          value_contents_for_printing (val),
1753                          value_offset (val),
1754                          val);
1755
1756   return bit_val;
1757 }
1758
1759 /* Allocate a dummy location and add it to B, which must be a software
1760    watchpoint.  This is required because even if a software watchpoint
1761    is not watching any memory, bpstat_stop_status requires a location
1762    to be able to report stops.  */
1763
1764 static void
1765 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1766                                             struct program_space *pspace)
1767 {
1768   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1769
1770   b->loc = allocate_bp_location (b);
1771   b->loc->pspace = pspace;
1772   b->loc->address = -1;
1773   b->loc->length = -1;
1774 }
1775
1776 /* Returns true if B is a software watchpoint that is not watching any
1777    memory (e.g., "watch $pc").  */
1778
1779 static int
1780 is_no_memory_software_watchpoint (struct breakpoint *b)
1781 {
1782   return (b->type == bp_watchpoint
1783           && b->loc != NULL
1784           && b->loc->next == NULL
1785           && b->loc->address == -1
1786           && b->loc->length == -1);
1787 }
1788
1789 /* Assuming that B is a watchpoint:
1790    - Reparse watchpoint expression, if REPARSE is non-zero
1791    - Evaluate expression and store the result in B->val
1792    - Evaluate the condition if there is one, and store the result
1793      in b->loc->cond.
1794    - Update the list of values that must be watched in B->loc.
1795
1796    If the watchpoint disposition is disp_del_at_next_stop, then do
1797    nothing.  If this is local watchpoint that is out of scope, delete
1798    it.
1799
1800    Even with `set breakpoint always-inserted on' the watchpoints are
1801    removed + inserted on each stop here.  Normal breakpoints must
1802    never be removed because they might be missed by a running thread
1803    when debugging in non-stop mode.  On the other hand, hardware
1804    watchpoints (is_hardware_watchpoint; processed here) are specific
1805    to each LWP since they are stored in each LWP's hardware debug
1806    registers.  Therefore, such LWP must be stopped first in order to
1807    be able to modify its hardware watchpoints.
1808
1809    Hardware watchpoints must be reset exactly once after being
1810    presented to the user.  It cannot be done sooner, because it would
1811    reset the data used to present the watchpoint hit to the user.  And
1812    it must not be done later because it could display the same single
1813    watchpoint hit during multiple GDB stops.  Note that the latter is
1814    relevant only to the hardware watchpoint types bp_read_watchpoint
1815    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1816    not user-visible - its hit is suppressed if the memory content has
1817    not changed.
1818
1819    The following constraints influence the location where we can reset
1820    hardware watchpoints:
1821
1822    * target_stopped_by_watchpoint and target_stopped_data_address are
1823      called several times when GDB stops.
1824
1825    [linux] 
1826    * Multiple hardware watchpoints can be hit at the same time,
1827      causing GDB to stop.  GDB only presents one hardware watchpoint
1828      hit at a time as the reason for stopping, and all the other hits
1829      are presented later, one after the other, each time the user
1830      requests the execution to be resumed.  Execution is not resumed
1831      for the threads still having pending hit event stored in
1832      LWP_INFO->STATUS.  While the watchpoint is already removed from
1833      the inferior on the first stop the thread hit event is kept being
1834      reported from its cached value by linux_nat_stopped_data_address
1835      until the real thread resume happens after the watchpoint gets
1836      presented and thus its LWP_INFO->STATUS gets reset.
1837
1838    Therefore the hardware watchpoint hit can get safely reset on the
1839    watchpoint removal from inferior.  */
1840
1841 static void
1842 update_watchpoint (struct watchpoint *b, int reparse)
1843 {
1844   int within_current_scope;
1845   struct frame_id saved_frame_id;
1846   int frame_saved;
1847
1848   /* If this is a local watchpoint, we only want to check if the
1849      watchpoint frame is in scope if the current thread is the thread
1850      that was used to create the watchpoint.  */
1851   if (!watchpoint_in_thread_scope (b))
1852     return;
1853
1854   if (b->base.disposition == disp_del_at_next_stop)
1855     return;
1856  
1857   frame_saved = 0;
1858
1859   /* Determine if the watchpoint is within scope.  */
1860   if (b->exp_valid_block == NULL)
1861     within_current_scope = 1;
1862   else
1863     {
1864       struct frame_info *fi = get_current_frame ();
1865       struct gdbarch *frame_arch = get_frame_arch (fi);
1866       CORE_ADDR frame_pc = get_frame_pc (fi);
1867
1868       /* If we're at a point where the stack has been destroyed
1869          (e.g. in a function epilogue), unwinding may not work
1870          properly. Do not attempt to recreate locations at this
1871          point.  See similar comments in watchpoint_check.  */
1872       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1873         return;
1874
1875       /* Save the current frame's ID so we can restore it after
1876          evaluating the watchpoint expression on its own frame.  */
1877       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1878          took a frame parameter, so that we didn't have to change the
1879          selected frame.  */
1880       frame_saved = 1;
1881       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1882
1883       fi = frame_find_by_id (b->watchpoint_frame);
1884       within_current_scope = (fi != NULL);
1885       if (within_current_scope)
1886         select_frame (fi);
1887     }
1888
1889   /* We don't free locations.  They are stored in the bp_location array
1890      and update_global_location_list will eventually delete them and
1891      remove breakpoints if needed.  */
1892   b->base.loc = NULL;
1893
1894   if (within_current_scope && reparse)
1895     {
1896       const char *s;
1897
1898       b->exp.reset ();
1899       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1900       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1901       /* If the meaning of expression itself changed, the old value is
1902          no longer relevant.  We don't want to report a watchpoint hit
1903          to the user when the old value and the new value may actually
1904          be completely different objects.  */
1905       value_free (b->val);
1906       b->val = NULL;
1907       b->val_valid = 0;
1908
1909       /* Note that unlike with breakpoints, the watchpoint's condition
1910          expression is stored in the breakpoint object, not in the
1911          locations (re)created below.  */
1912       if (b->base.cond_string != NULL)
1913         {
1914           b->cond_exp.reset ();
1915
1916           s = b->base.cond_string;
1917           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1918         }
1919     }
1920
1921   /* If we failed to parse the expression, for example because
1922      it refers to a global variable in a not-yet-loaded shared library,
1923      don't try to insert watchpoint.  We don't automatically delete
1924      such watchpoint, though, since failure to parse expression
1925      is different from out-of-scope watchpoint.  */
1926   if (!target_has_execution)
1927     {
1928       /* Without execution, memory can't change.  No use to try and
1929          set watchpoint locations.  The watchpoint will be reset when
1930          the target gains execution, through breakpoint_re_set.  */
1931       if (!can_use_hw_watchpoints)
1932         {
1933           if (b->base.ops->works_in_software_mode (&b->base))
1934             b->base.type = bp_watchpoint;
1935           else
1936             error (_("Can't set read/access watchpoint when "
1937                      "hardware watchpoints are disabled."));
1938         }
1939     }
1940   else if (within_current_scope && b->exp)
1941     {
1942       int pc = 0;
1943       struct value *val_chain, *v, *result, *next;
1944       struct program_space *frame_pspace;
1945
1946       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1947
1948       /* Avoid setting b->val if it's already set.  The meaning of
1949          b->val is 'the last value' user saw, and we should update
1950          it only if we reported that last value to user.  As it
1951          happens, the code that reports it updates b->val directly.
1952          We don't keep track of the memory value for masked
1953          watchpoints.  */
1954       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1955         {
1956           if (b->val_bitsize != 0)
1957             {
1958               v = extract_bitfield_from_watchpoint_value (b, v);
1959               if (v != NULL)
1960                 release_value (v);
1961             }
1962           b->val = v;
1963           b->val_valid = 1;
1964         }
1965
1966       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1967
1968       /* Look at each value on the value chain.  */
1969       for (v = val_chain; v; v = value_next (v))
1970         {
1971           /* If it's a memory location, and GDB actually needed
1972              its contents to evaluate the expression, then we
1973              must watch it.  If the first value returned is
1974              still lazy, that means an error occurred reading it;
1975              watch it anyway in case it becomes readable.  */
1976           if (VALUE_LVAL (v) == lval_memory
1977               && (v == val_chain || ! value_lazy (v)))
1978             {
1979               struct type *vtype = check_typedef (value_type (v));
1980
1981               /* We only watch structs and arrays if user asked
1982                  for it explicitly, never if they just happen to
1983                  appear in the middle of some value chain.  */
1984               if (v == result
1985                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1986                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1987                 {
1988                   CORE_ADDR addr;
1989                   enum target_hw_bp_type type;
1990                   struct bp_location *loc, **tmp;
1991                   int bitpos = 0, bitsize = 0;
1992
1993                   if (value_bitsize (v) != 0)
1994                     {
1995                       /* Extract the bit parameters out from the bitfield
1996                          sub-expression.  */
1997                       bitpos = value_bitpos (v);
1998                       bitsize = value_bitsize (v);
1999                     }
2000                   else if (v == result && b->val_bitsize != 0)
2001                     {
2002                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2003                         lvalue whose bit parameters are saved in the fields
2004                         VAL_BITPOS and VAL_BITSIZE.  */
2005                       bitpos = b->val_bitpos;
2006                       bitsize = b->val_bitsize;
2007                     }
2008
2009                   addr = value_address (v);
2010                   if (bitsize != 0)
2011                     {
2012                       /* Skip the bytes that don't contain the bitfield.  */
2013                       addr += bitpos / 8;
2014                     }
2015
2016                   type = hw_write;
2017                   if (b->base.type == bp_read_watchpoint)
2018                     type = hw_read;
2019                   else if (b->base.type == bp_access_watchpoint)
2020                     type = hw_access;
2021
2022                   loc = allocate_bp_location (&b->base);
2023                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2024                     ;
2025                   *tmp = loc;
2026                   loc->gdbarch = get_type_arch (value_type (v));
2027
2028                   loc->pspace = frame_pspace;
2029                   loc->address = addr;
2030
2031                   if (bitsize != 0)
2032                     {
2033                       /* Just cover the bytes that make up the bitfield.  */
2034                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2035                     }
2036                   else
2037                     loc->length = TYPE_LENGTH (value_type (v));
2038
2039                   loc->watchpoint_type = type;
2040                 }
2041             }
2042         }
2043
2044       /* Change the type of breakpoint between hardware assisted or
2045          an ordinary watchpoint depending on the hardware support
2046          and free hardware slots.  REPARSE is set when the inferior
2047          is started.  */
2048       if (reparse)
2049         {
2050           int reg_cnt;
2051           enum bp_loc_type loc_type;
2052           struct bp_location *bl;
2053
2054           reg_cnt = can_use_hardware_watchpoint (val_chain);
2055
2056           if (reg_cnt)
2057             {
2058               int i, target_resources_ok, other_type_used;
2059               enum bptype type;
2060
2061               /* Use an exact watchpoint when there's only one memory region to be
2062                  watched, and only one debug register is needed to watch it.  */
2063               b->exact = target_exact_watchpoints && reg_cnt == 1;
2064
2065               /* We need to determine how many resources are already
2066                  used for all other hardware watchpoints plus this one
2067                  to see if we still have enough resources to also fit
2068                  this watchpoint in as well.  */
2069
2070               /* If this is a software watchpoint, we try to turn it
2071                  to a hardware one -- count resources as if B was of
2072                  hardware watchpoint type.  */
2073               type = b->base.type;
2074               if (type == bp_watchpoint)
2075                 type = bp_hardware_watchpoint;
2076
2077               /* This watchpoint may or may not have been placed on
2078                  the list yet at this point (it won't be in the list
2079                  if we're trying to create it for the first time,
2080                  through watch_command), so always account for it
2081                  manually.  */
2082
2083               /* Count resources used by all watchpoints except B.  */
2084               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2085
2086               /* Add in the resources needed for B.  */
2087               i += hw_watchpoint_use_count (&b->base);
2088
2089               target_resources_ok
2090                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2091               if (target_resources_ok <= 0)
2092                 {
2093                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2094
2095                   if (target_resources_ok == 0 && !sw_mode)
2096                     error (_("Target does not support this type of "
2097                              "hardware watchpoint."));
2098                   else if (target_resources_ok < 0 && !sw_mode)
2099                     error (_("There are not enough available hardware "
2100                              "resources for this watchpoint."));
2101
2102                   /* Downgrade to software watchpoint.  */
2103                   b->base.type = bp_watchpoint;
2104                 }
2105               else
2106                 {
2107                   /* If this was a software watchpoint, we've just
2108                      found we have enough resources to turn it to a
2109                      hardware watchpoint.  Otherwise, this is a
2110                      nop.  */
2111                   b->base.type = type;
2112                 }
2113             }
2114           else if (!b->base.ops->works_in_software_mode (&b->base))
2115             {
2116               if (!can_use_hw_watchpoints)
2117                 error (_("Can't set read/access watchpoint when "
2118                          "hardware watchpoints are disabled."));
2119               else
2120                 error (_("Expression cannot be implemented with "
2121                          "read/access watchpoint."));
2122             }
2123           else
2124             b->base.type = bp_watchpoint;
2125
2126           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2127                       : bp_loc_hardware_watchpoint);
2128           for (bl = b->base.loc; bl; bl = bl->next)
2129             bl->loc_type = loc_type;
2130         }
2131
2132       for (v = val_chain; v; v = next)
2133         {
2134           next = value_next (v);
2135           if (v != b->val)
2136             value_free (v);
2137         }
2138
2139       /* If a software watchpoint is not watching any memory, then the
2140          above left it without any location set up.  But,
2141          bpstat_stop_status requires a location to be able to report
2142          stops, so make sure there's at least a dummy one.  */
2143       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2144         software_watchpoint_add_no_memory_location (&b->base, frame_pspace);
2145     }
2146   else if (!within_current_scope)
2147     {
2148       printf_filtered (_("\
2149 Watchpoint %d deleted because the program has left the block\n\
2150 in which its expression is valid.\n"),
2151                        b->base.number);
2152       watchpoint_del_at_next_stop (b);
2153     }
2154
2155   /* Restore the selected frame.  */
2156   if (frame_saved)
2157     select_frame (frame_find_by_id (saved_frame_id));
2158 }
2159
2160
2161 /* Returns 1 iff breakpoint location should be
2162    inserted in the inferior.  We don't differentiate the type of BL's owner
2163    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2164    breakpoint_ops is not defined, because in insert_bp_location,
2165    tracepoint's insert_location will not be called.  */
2166 static int
2167 should_be_inserted (struct bp_location *bl)
2168 {
2169   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2170     return 0;
2171
2172   if (bl->owner->disposition == disp_del_at_next_stop)
2173     return 0;
2174
2175   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2176     return 0;
2177
2178   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2179     return 0;
2180
2181   /* This is set for example, when we're attached to the parent of a
2182      vfork, and have detached from the child.  The child is running
2183      free, and we expect it to do an exec or exit, at which point the
2184      OS makes the parent schedulable again (and the target reports
2185      that the vfork is done).  Until the child is done with the shared
2186      memory region, do not insert breakpoints in the parent, otherwise
2187      the child could still trip on the parent's breakpoints.  Since
2188      the parent is blocked anyway, it won't miss any breakpoint.  */
2189   if (bl->pspace->breakpoints_not_allowed)
2190     return 0;
2191
2192   /* Don't insert a breakpoint if we're trying to step past its
2193      location, except if the breakpoint is a single-step breakpoint,
2194      and the breakpoint's thread is the thread which is stepping past
2195      a breakpoint.  */
2196   if ((bl->loc_type == bp_loc_software_breakpoint
2197        || bl->loc_type == bp_loc_hardware_breakpoint)
2198       && stepping_past_instruction_at (bl->pspace->aspace,
2199                                        bl->address)
2200       /* The single-step breakpoint may be inserted at the location
2201          we're trying to step if the instruction branches to itself.
2202          However, the instruction won't be executed at all and it may
2203          break the semantics of the instruction, for example, the
2204          instruction is a conditional branch or updates some flags.
2205          We can't fix it unless GDB is able to emulate the instruction
2206          or switch to displaced stepping.  */
2207       && !(bl->owner->type == bp_single_step
2208            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2209     {
2210       if (debug_infrun)
2211         {
2212           fprintf_unfiltered (gdb_stdlog,
2213                               "infrun: skipping breakpoint: "
2214                               "stepping past insn at: %s\n",
2215                               paddress (bl->gdbarch, bl->address));
2216         }
2217       return 0;
2218     }
2219
2220   /* Don't insert watchpoints if we're trying to step past the
2221      instruction that triggered one.  */
2222   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2223       && stepping_past_nonsteppable_watchpoint ())
2224     {
2225       if (debug_infrun)
2226         {
2227           fprintf_unfiltered (gdb_stdlog,
2228                               "infrun: stepping past non-steppable watchpoint. "
2229                               "skipping watchpoint at %s:%d\n",
2230                               paddress (bl->gdbarch, bl->address),
2231                               bl->length);
2232         }
2233       return 0;
2234     }
2235
2236   return 1;
2237 }
2238
2239 /* Same as should_be_inserted but does the check assuming
2240    that the location is not duplicated.  */
2241
2242 static int
2243 unduplicated_should_be_inserted (struct bp_location *bl)
2244 {
2245   int result;
2246   const int save_duplicate = bl->duplicate;
2247
2248   bl->duplicate = 0;
2249   result = should_be_inserted (bl);
2250   bl->duplicate = save_duplicate;
2251   return result;
2252 }
2253
2254 /* Parses a conditional described by an expression COND into an
2255    agent expression bytecode suitable for evaluation
2256    by the bytecode interpreter.  Return NULL if there was
2257    any error during parsing.  */
2258
2259 static agent_expr_up
2260 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2261 {
2262   if (cond == NULL)
2263     return NULL;
2264
2265   agent_expr_up aexpr;
2266
2267   /* We don't want to stop processing, so catch any errors
2268      that may show up.  */
2269   TRY
2270     {
2271       aexpr = gen_eval_for_expr (scope, cond);
2272     }
2273
2274   CATCH (ex, RETURN_MASK_ERROR)
2275     {
2276       /* If we got here, it means the condition could not be parsed to a valid
2277          bytecode expression and thus can't be evaluated on the target's side.
2278          It's no use iterating through the conditions.  */
2279     }
2280   END_CATCH
2281
2282   /* We have a valid agent expression.  */
2283   return aexpr;
2284 }
2285
2286 /* Based on location BL, create a list of breakpoint conditions to be
2287    passed on to the target.  If we have duplicated locations with different
2288    conditions, we will add such conditions to the list.  The idea is that the
2289    target will evaluate the list of conditions and will only notify GDB when
2290    one of them is true.  */
2291
2292 static void
2293 build_target_condition_list (struct bp_location *bl)
2294 {
2295   struct bp_location **locp = NULL, **loc2p;
2296   int null_condition_or_parse_error = 0;
2297   int modified = bl->needs_update;
2298   struct bp_location *loc;
2299
2300   /* Release conditions left over from a previous insert.  */
2301   bl->target_info.conditions.clear ();
2302
2303   /* This is only meaningful if the target is
2304      evaluating conditions and if the user has
2305      opted for condition evaluation on the target's
2306      side.  */
2307   if (gdb_evaluates_breakpoint_condition_p ()
2308       || !target_supports_evaluation_of_breakpoint_conditions ())
2309     return;
2310
2311   /* Do a first pass to check for locations with no assigned
2312      conditions or conditions that fail to parse to a valid agent expression
2313      bytecode.  If any of these happen, then it's no use to send conditions
2314      to the target since this location will always trigger and generate a
2315      response back to GDB.  */
2316   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2317     {
2318       loc = (*loc2p);
2319       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2320         {
2321           if (modified)
2322             {
2323               /* Re-parse the conditions since something changed.  In that
2324                  case we already freed the condition bytecodes (see
2325                  force_breakpoint_reinsertion).  We just
2326                  need to parse the condition to bytecodes again.  */
2327               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2328                                                         loc->cond.get ());
2329             }
2330
2331           /* If we have a NULL bytecode expression, it means something
2332              went wrong or we have a null condition expression.  */
2333           if (!loc->cond_bytecode)
2334             {
2335               null_condition_or_parse_error = 1;
2336               break;
2337             }
2338         }
2339     }
2340
2341   /* If any of these happened, it means we will have to evaluate the conditions
2342      for the location's address on gdb's side.  It is no use keeping bytecodes
2343      for all the other duplicate locations, thus we free all of them here.
2344
2345      This is so we have a finer control over which locations' conditions are
2346      being evaluated by GDB or the remote stub.  */
2347   if (null_condition_or_parse_error)
2348     {
2349       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2350         {
2351           loc = (*loc2p);
2352           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2353             {
2354               /* Only go as far as the first NULL bytecode is
2355                  located.  */
2356               if (!loc->cond_bytecode)
2357                 return;
2358
2359               loc->cond_bytecode.reset ();
2360             }
2361         }
2362     }
2363
2364   /* No NULL conditions or failed bytecode generation.  Build a condition list
2365      for this location's address.  */
2366   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2367     {
2368       loc = (*loc2p);
2369       if (loc->cond
2370           && is_breakpoint (loc->owner)
2371           && loc->pspace->num == bl->pspace->num
2372           && loc->owner->enable_state == bp_enabled
2373           && loc->enabled)
2374         {
2375           /* Add the condition to the vector.  This will be used later
2376              to send the conditions to the target.  */
2377           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2378         }
2379     }
2380
2381   return;
2382 }
2383
2384 /* Parses a command described by string CMD into an agent expression
2385    bytecode suitable for evaluation by the bytecode interpreter.
2386    Return NULL if there was any error during parsing.  */
2387
2388 static agent_expr_up
2389 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2390 {
2391   struct cleanup *old_cleanups = 0;
2392   struct expression **argvec;
2393   const char *cmdrest;
2394   const char *format_start, *format_end;
2395   struct format_piece *fpieces;
2396   int nargs;
2397   struct gdbarch *gdbarch = get_current_arch ();
2398
2399   if (cmd == NULL)
2400     return NULL;
2401
2402   cmdrest = cmd;
2403
2404   if (*cmdrest == ',')
2405     ++cmdrest;
2406   cmdrest = skip_spaces_const (cmdrest);
2407
2408   if (*cmdrest++ != '"')
2409     error (_("No format string following the location"));
2410
2411   format_start = cmdrest;
2412
2413   fpieces = parse_format_string (&cmdrest);
2414
2415   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2416
2417   format_end = cmdrest;
2418
2419   if (*cmdrest++ != '"')
2420     error (_("Bad format string, non-terminated '\"'."));
2421   
2422   cmdrest = skip_spaces_const (cmdrest);
2423
2424   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2425     error (_("Invalid argument syntax"));
2426
2427   if (*cmdrest == ',')
2428     cmdrest++;
2429   cmdrest = skip_spaces_const (cmdrest);
2430
2431   /* For each argument, make an expression.  */
2432
2433   argvec = (struct expression **) alloca (strlen (cmd)
2434                                          * sizeof (struct expression *));
2435
2436   nargs = 0;
2437   while (*cmdrest != '\0')
2438     {
2439       const char *cmd1;
2440
2441       cmd1 = cmdrest;
2442       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2443       argvec[nargs++] = expr.release ();
2444       cmdrest = cmd1;
2445       if (*cmdrest == ',')
2446         ++cmdrest;
2447     }
2448
2449   agent_expr_up aexpr;
2450
2451   /* We don't want to stop processing, so catch any errors
2452      that may show up.  */
2453   TRY
2454     {
2455       aexpr = gen_printf (scope, gdbarch, 0, 0,
2456                           format_start, format_end - format_start,
2457                           fpieces, nargs, argvec);
2458     }
2459   CATCH (ex, RETURN_MASK_ERROR)
2460     {
2461       /* If we got here, it means the command could not be parsed to a valid
2462          bytecode expression and thus can't be evaluated on the target's side.
2463          It's no use iterating through the other commands.  */
2464     }
2465   END_CATCH
2466
2467   do_cleanups (old_cleanups);
2468
2469   /* We have a valid agent expression, return it.  */
2470   return aexpr;
2471 }
2472
2473 /* Based on location BL, create a list of breakpoint commands to be
2474    passed on to the target.  If we have duplicated locations with
2475    different commands, we will add any such to the list.  */
2476
2477 static void
2478 build_target_command_list (struct bp_location *bl)
2479 {
2480   struct bp_location **locp = NULL, **loc2p;
2481   int null_command_or_parse_error = 0;
2482   int modified = bl->needs_update;
2483   struct bp_location *loc;
2484
2485   /* Clear commands left over from a previous insert.  */
2486   bl->target_info.tcommands.clear ();
2487
2488   if (!target_can_run_breakpoint_commands ())
2489     return;
2490
2491   /* For now, limit to agent-style dprintf breakpoints.  */
2492   if (dprintf_style != dprintf_style_agent)
2493     return;
2494
2495   /* For now, if we have any duplicate location that isn't a dprintf,
2496      don't install the target-side commands, as that would make the
2497      breakpoint not be reported to the core, and we'd lose
2498      control.  */
2499   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2500     {
2501       loc = (*loc2p);
2502       if (is_breakpoint (loc->owner)
2503           && loc->pspace->num == bl->pspace->num
2504           && loc->owner->type != bp_dprintf)
2505         return;
2506     }
2507
2508   /* Do a first pass to check for locations with no assigned
2509      conditions or conditions that fail to parse to a valid agent expression
2510      bytecode.  If any of these happen, then it's no use to send conditions
2511      to the target since this location will always trigger and generate a
2512      response back to GDB.  */
2513   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2514     {
2515       loc = (*loc2p);
2516       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2517         {
2518           if (modified)
2519             {
2520               /* Re-parse the commands since something changed.  In that
2521                  case we already freed the command bytecodes (see
2522                  force_breakpoint_reinsertion).  We just
2523                  need to parse the command to bytecodes again.  */
2524               loc->cmd_bytecode
2525                 = parse_cmd_to_aexpr (bl->address,
2526                                       loc->owner->extra_string);
2527             }
2528
2529           /* If we have a NULL bytecode expression, it means something
2530              went wrong or we have a null command expression.  */
2531           if (!loc->cmd_bytecode)
2532             {
2533               null_command_or_parse_error = 1;
2534               break;
2535             }
2536         }
2537     }
2538
2539   /* If anything failed, then we're not doing target-side commands,
2540      and so clean up.  */
2541   if (null_command_or_parse_error)
2542     {
2543       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2544         {
2545           loc = (*loc2p);
2546           if (is_breakpoint (loc->owner)
2547               && loc->pspace->num == bl->pspace->num)
2548             {
2549               /* Only go as far as the first NULL bytecode is
2550                  located.  */
2551               if (loc->cmd_bytecode == NULL)
2552                 return;
2553
2554               loc->cmd_bytecode.reset ();
2555             }
2556         }
2557     }
2558
2559   /* No NULL commands or failed bytecode generation.  Build a command list
2560      for this location's address.  */
2561   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2562     {
2563       loc = (*loc2p);
2564       if (loc->owner->extra_string
2565           && is_breakpoint (loc->owner)
2566           && loc->pspace->num == bl->pspace->num
2567           && loc->owner->enable_state == bp_enabled
2568           && loc->enabled)
2569         {
2570           /* Add the command to the vector.  This will be used later
2571              to send the commands to the target.  */
2572           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2573         }
2574     }
2575
2576   bl->target_info.persist = 0;
2577   /* Maybe flag this location as persistent.  */
2578   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2579     bl->target_info.persist = 1;
2580 }
2581
2582 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2583    of breakpoint according to ADDR except single-step breakpoint.
2584    Get the kind of single-step breakpoint according to the current
2585    registers state.  */
2586
2587 static int
2588 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2589 {
2590   if (bl->owner->type == bp_single_step)
2591     {
2592       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2593       struct regcache *regcache;
2594
2595       regcache = get_thread_regcache (thr->ptid);
2596
2597       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2598                                                          regcache, addr);
2599     }
2600   else
2601     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2602 }
2603
2604 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2605    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2606    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2607    Returns 0 for success, 1 if the bp_location type is not supported or
2608    -1 for failure.
2609
2610    NOTE drow/2003-09-09: This routine could be broken down to an
2611    object-style method for each breakpoint or catchpoint type.  */
2612 static int
2613 insert_bp_location (struct bp_location *bl,
2614                     struct ui_file *tmp_error_stream,
2615                     int *disabled_breaks,
2616                     int *hw_breakpoint_error,
2617                     int *hw_bp_error_explained_already)
2618 {
2619   enum errors bp_err = GDB_NO_ERROR;
2620   const char *bp_err_message = NULL;
2621
2622   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2623     return 0;
2624
2625   /* Note we don't initialize bl->target_info, as that wipes out
2626      the breakpoint location's shadow_contents if the breakpoint
2627      is still inserted at that location.  This in turn breaks
2628      target_read_memory which depends on these buffers when
2629      a memory read is requested at the breakpoint location:
2630      Once the target_info has been wiped, we fail to see that
2631      we have a breakpoint inserted at that address and thus
2632      read the breakpoint instead of returning the data saved in
2633      the breakpoint location's shadow contents.  */
2634   bl->target_info.reqstd_address = bl->address;
2635   bl->target_info.placed_address_space = bl->pspace->aspace;
2636   bl->target_info.length = bl->length;
2637
2638   /* When working with target-side conditions, we must pass all the conditions
2639      for the same breakpoint address down to the target since GDB will not
2640      insert those locations.  With a list of breakpoint conditions, the target
2641      can decide when to stop and notify GDB.  */
2642
2643   if (is_breakpoint (bl->owner))
2644     {
2645       build_target_condition_list (bl);
2646       build_target_command_list (bl);
2647       /* Reset the modification marker.  */
2648       bl->needs_update = 0;
2649     }
2650
2651   if (bl->loc_type == bp_loc_software_breakpoint
2652       || bl->loc_type == bp_loc_hardware_breakpoint)
2653     {
2654       if (bl->owner->type != bp_hardware_breakpoint)
2655         {
2656           /* If the explicitly specified breakpoint type
2657              is not hardware breakpoint, check the memory map to see
2658              if the breakpoint address is in read only memory or not.
2659
2660              Two important cases are:
2661              - location type is not hardware breakpoint, memory
2662              is readonly.  We change the type of the location to
2663              hardware breakpoint.
2664              - location type is hardware breakpoint, memory is
2665              read-write.  This means we've previously made the
2666              location hardware one, but then the memory map changed,
2667              so we undo.
2668              
2669              When breakpoints are removed, remove_breakpoints will use
2670              location types we've just set here, the only possible
2671              problem is that memory map has changed during running
2672              program, but it's not going to work anyway with current
2673              gdb.  */
2674           struct mem_region *mr 
2675             = lookup_mem_region (bl->target_info.reqstd_address);
2676           
2677           if (mr)
2678             {
2679               if (automatic_hardware_breakpoints)
2680                 {
2681                   enum bp_loc_type new_type;
2682                   
2683                   if (mr->attrib.mode != MEM_RW)
2684                     new_type = bp_loc_hardware_breakpoint;
2685                   else 
2686                     new_type = bp_loc_software_breakpoint;
2687                   
2688                   if (new_type != bl->loc_type)
2689                     {
2690                       static int said = 0;
2691
2692                       bl->loc_type = new_type;
2693                       if (!said)
2694                         {
2695                           fprintf_filtered (gdb_stdout,
2696                                             _("Note: automatically using "
2697                                               "hardware breakpoints for "
2698                                               "read-only addresses.\n"));
2699                           said = 1;
2700                         }
2701                     }
2702                 }
2703               else if (bl->loc_type == bp_loc_software_breakpoint
2704                        && mr->attrib.mode != MEM_RW)
2705                 {
2706                   fprintf_unfiltered (tmp_error_stream,
2707                                       _("Cannot insert breakpoint %d.\n"
2708                                         "Cannot set software breakpoint "
2709                                         "at read-only address %s\n"),
2710                                       bl->owner->number,
2711                                       paddress (bl->gdbarch, bl->address));
2712                   return 1;
2713                 }
2714             }
2715         }
2716         
2717       /* First check to see if we have to handle an overlay.  */
2718       if (overlay_debugging == ovly_off
2719           || bl->section == NULL
2720           || !(section_is_overlay (bl->section)))
2721         {
2722           /* No overlay handling: just set the breakpoint.  */
2723           TRY
2724             {
2725               int val;
2726
2727               val = bl->owner->ops->insert_location (bl);
2728               if (val)
2729                 bp_err = GENERIC_ERROR;
2730             }
2731           CATCH (e, RETURN_MASK_ALL)
2732             {
2733               bp_err = e.error;
2734               bp_err_message = e.message;
2735             }
2736           END_CATCH
2737         }
2738       else
2739         {
2740           /* This breakpoint is in an overlay section.
2741              Shall we set a breakpoint at the LMA?  */
2742           if (!overlay_events_enabled)
2743             {
2744               /* Yes -- overlay event support is not active, 
2745                  so we must try to set a breakpoint at the LMA.
2746                  This will not work for a hardware breakpoint.  */
2747               if (bl->loc_type == bp_loc_hardware_breakpoint)
2748                 warning (_("hardware breakpoint %d not supported in overlay!"),
2749                          bl->owner->number);
2750               else
2751                 {
2752                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2753                                                              bl->section);
2754                   /* Set a software (trap) breakpoint at the LMA.  */
2755                   bl->overlay_target_info = bl->target_info;
2756                   bl->overlay_target_info.reqstd_address = addr;
2757
2758                   /* No overlay handling: just set the breakpoint.  */
2759                   TRY
2760                     {
2761                       int val;
2762
2763                       bl->overlay_target_info.kind
2764                         = breakpoint_kind (bl, &addr);
2765                       bl->overlay_target_info.placed_address = addr;
2766                       val = target_insert_breakpoint (bl->gdbarch,
2767                                                       &bl->overlay_target_info);
2768                       if (val)
2769                         bp_err = GENERIC_ERROR;
2770                     }
2771                   CATCH (e, RETURN_MASK_ALL)
2772                     {
2773                       bp_err = e.error;
2774                       bp_err_message = e.message;
2775                     }
2776                   END_CATCH
2777
2778                   if (bp_err != GDB_NO_ERROR)
2779                     fprintf_unfiltered (tmp_error_stream,
2780                                         "Overlay breakpoint %d "
2781                                         "failed: in ROM?\n",
2782                                         bl->owner->number);
2783                 }
2784             }
2785           /* Shall we set a breakpoint at the VMA? */
2786           if (section_is_mapped (bl->section))
2787             {
2788               /* Yes.  This overlay section is mapped into memory.  */
2789               TRY
2790                 {
2791                   int val;
2792
2793                   val = bl->owner->ops->insert_location (bl);
2794                   if (val)
2795                     bp_err = GENERIC_ERROR;
2796                 }
2797               CATCH (e, RETURN_MASK_ALL)
2798                 {
2799                   bp_err = e.error;
2800                   bp_err_message = e.message;
2801                 }
2802               END_CATCH
2803             }
2804           else
2805             {
2806               /* No.  This breakpoint will not be inserted.  
2807                  No error, but do not mark the bp as 'inserted'.  */
2808               return 0;
2809             }
2810         }
2811
2812       if (bp_err != GDB_NO_ERROR)
2813         {
2814           /* Can't set the breakpoint.  */
2815
2816           /* In some cases, we might not be able to insert a
2817              breakpoint in a shared library that has already been
2818              removed, but we have not yet processed the shlib unload
2819              event.  Unfortunately, some targets that implement
2820              breakpoint insertion themselves can't tell why the
2821              breakpoint insertion failed (e.g., the remote target
2822              doesn't define error codes), so we must treat generic
2823              errors as memory errors.  */
2824           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2825               && bl->loc_type == bp_loc_software_breakpoint
2826               && (solib_name_from_address (bl->pspace, bl->address)
2827                   || shared_objfile_contains_address_p (bl->pspace,
2828                                                         bl->address)))
2829             {
2830               /* See also: disable_breakpoints_in_shlibs.  */
2831               bl->shlib_disabled = 1;
2832               observer_notify_breakpoint_modified (bl->owner);
2833               if (!*disabled_breaks)
2834                 {
2835                   fprintf_unfiltered (tmp_error_stream, 
2836                                       "Cannot insert breakpoint %d.\n", 
2837                                       bl->owner->number);
2838                   fprintf_unfiltered (tmp_error_stream, 
2839                                       "Temporarily disabling shared "
2840                                       "library breakpoints:\n");
2841                 }
2842               *disabled_breaks = 1;
2843               fprintf_unfiltered (tmp_error_stream,
2844                                   "breakpoint #%d\n", bl->owner->number);
2845               return 0;
2846             }
2847           else
2848             {
2849               if (bl->loc_type == bp_loc_hardware_breakpoint)
2850                 {
2851                   *hw_breakpoint_error = 1;
2852                   *hw_bp_error_explained_already = bp_err_message != NULL;
2853                   fprintf_unfiltered (tmp_error_stream,
2854                                       "Cannot insert hardware breakpoint %d%s",
2855                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2856                   if (bp_err_message != NULL)
2857                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2858                 }
2859               else
2860                 {
2861                   if (bp_err_message == NULL)
2862                     {
2863                       char *message
2864                         = memory_error_message (TARGET_XFER_E_IO,
2865                                                 bl->gdbarch, bl->address);
2866                       struct cleanup *old_chain = make_cleanup (xfree, message);
2867
2868                       fprintf_unfiltered (tmp_error_stream,
2869                                           "Cannot insert breakpoint %d.\n"
2870                                           "%s\n",
2871                                           bl->owner->number, message);
2872                       do_cleanups (old_chain);
2873                     }
2874                   else
2875                     {
2876                       fprintf_unfiltered (tmp_error_stream,
2877                                           "Cannot insert breakpoint %d: %s\n",
2878                                           bl->owner->number,
2879                                           bp_err_message);
2880                     }
2881                 }
2882               return 1;
2883
2884             }
2885         }
2886       else
2887         bl->inserted = 1;
2888
2889       return 0;
2890     }
2891
2892   else if (bl->loc_type == bp_loc_hardware_watchpoint
2893            /* NOTE drow/2003-09-08: This state only exists for removing
2894               watchpoints.  It's not clear that it's necessary...  */
2895            && bl->owner->disposition != disp_del_at_next_stop)
2896     {
2897       int val;
2898
2899       gdb_assert (bl->owner->ops != NULL
2900                   && bl->owner->ops->insert_location != NULL);
2901
2902       val = bl->owner->ops->insert_location (bl);
2903
2904       /* If trying to set a read-watchpoint, and it turns out it's not
2905          supported, try emulating one with an access watchpoint.  */
2906       if (val == 1 && bl->watchpoint_type == hw_read)
2907         {
2908           struct bp_location *loc, **loc_temp;
2909
2910           /* But don't try to insert it, if there's already another
2911              hw_access location that would be considered a duplicate
2912              of this one.  */
2913           ALL_BP_LOCATIONS (loc, loc_temp)
2914             if (loc != bl
2915                 && loc->watchpoint_type == hw_access
2916                 && watchpoint_locations_match (bl, loc))
2917               {
2918                 bl->duplicate = 1;
2919                 bl->inserted = 1;
2920                 bl->target_info = loc->target_info;
2921                 bl->watchpoint_type = hw_access;
2922                 val = 0;
2923                 break;
2924               }
2925
2926           if (val == 1)
2927             {
2928               bl->watchpoint_type = hw_access;
2929               val = bl->owner->ops->insert_location (bl);
2930
2931               if (val)
2932                 /* Back to the original value.  */
2933                 bl->watchpoint_type = hw_read;
2934             }
2935         }
2936
2937       bl->inserted = (val == 0);
2938     }
2939
2940   else if (bl->owner->type == bp_catchpoint)
2941     {
2942       int val;
2943
2944       gdb_assert (bl->owner->ops != NULL
2945                   && bl->owner->ops->insert_location != NULL);
2946
2947       val = bl->owner->ops->insert_location (bl);
2948       if (val)
2949         {
2950           bl->owner->enable_state = bp_disabled;
2951
2952           if (val == 1)
2953             warning (_("\
2954 Error inserting catchpoint %d: Your system does not support this type\n\
2955 of catchpoint."), bl->owner->number);
2956           else
2957             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2958         }
2959
2960       bl->inserted = (val == 0);
2961
2962       /* We've already printed an error message if there was a problem
2963          inserting this catchpoint, and we've disabled the catchpoint,
2964          so just return success.  */
2965       return 0;
2966     }
2967
2968   return 0;
2969 }
2970
2971 /* This function is called when program space PSPACE is about to be
2972    deleted.  It takes care of updating breakpoints to not reference
2973    PSPACE anymore.  */
2974
2975 void
2976 breakpoint_program_space_exit (struct program_space *pspace)
2977 {
2978   struct breakpoint *b, *b_temp;
2979   struct bp_location *loc, **loc_temp;
2980
2981   /* Remove any breakpoint that was set through this program space.  */
2982   ALL_BREAKPOINTS_SAFE (b, b_temp)
2983     {
2984       if (b->pspace == pspace)
2985         delete_breakpoint (b);
2986     }
2987
2988   /* Breakpoints set through other program spaces could have locations
2989      bound to PSPACE as well.  Remove those.  */
2990   ALL_BP_LOCATIONS (loc, loc_temp)
2991     {
2992       struct bp_location *tmp;
2993
2994       if (loc->pspace == pspace)
2995         {
2996           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2997           if (loc->owner->loc == loc)
2998             loc->owner->loc = loc->next;
2999           else
3000             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3001               if (tmp->next == loc)
3002                 {
3003                   tmp->next = loc->next;
3004                   break;
3005                 }
3006         }
3007     }
3008
3009   /* Now update the global location list to permanently delete the
3010      removed locations above.  */
3011   update_global_location_list (UGLL_DONT_INSERT);
3012 }
3013
3014 /* Make sure all breakpoints are inserted in inferior.
3015    Throws exception on any error.
3016    A breakpoint that is already inserted won't be inserted
3017    again, so calling this function twice is safe.  */
3018 void
3019 insert_breakpoints (void)
3020 {
3021   struct breakpoint *bpt;
3022
3023   ALL_BREAKPOINTS (bpt)
3024     if (is_hardware_watchpoint (bpt))
3025       {
3026         struct watchpoint *w = (struct watchpoint *) bpt;
3027
3028         update_watchpoint (w, 0 /* don't reparse.  */);
3029       }
3030
3031   /* Updating watchpoints creates new locations, so update the global
3032      location list.  Explicitly tell ugll to insert locations and
3033      ignore breakpoints_always_inserted_mode.  */
3034   update_global_location_list (UGLL_INSERT);
3035 }
3036
3037 /* Invoke CALLBACK for each of bp_location.  */
3038
3039 void
3040 iterate_over_bp_locations (walk_bp_location_callback callback)
3041 {
3042   struct bp_location *loc, **loc_tmp;
3043
3044   ALL_BP_LOCATIONS (loc, loc_tmp)
3045     {
3046       callback (loc, NULL);
3047     }
3048 }
3049
3050 /* This is used when we need to synch breakpoint conditions between GDB and the
3051    target.  It is the case with deleting and disabling of breakpoints when using
3052    always-inserted mode.  */
3053
3054 static void
3055 update_inserted_breakpoint_locations (void)
3056 {
3057   struct bp_location *bl, **blp_tmp;
3058   int error_flag = 0;
3059   int val = 0;
3060   int disabled_breaks = 0;
3061   int hw_breakpoint_error = 0;
3062   int hw_bp_details_reported = 0;
3063
3064   string_file tmp_error_stream;
3065
3066   /* Explicitly mark the warning -- this will only be printed if
3067      there was an error.  */
3068   tmp_error_stream.puts ("Warning:\n");
3069
3070   struct cleanup *cleanups = save_current_space_and_thread ();
3071
3072   ALL_BP_LOCATIONS (bl, blp_tmp)
3073     {
3074       /* We only want to update software breakpoints and hardware
3075          breakpoints.  */
3076       if (!is_breakpoint (bl->owner))
3077         continue;
3078
3079       /* We only want to update locations that are already inserted
3080          and need updating.  This is to avoid unwanted insertion during
3081          deletion of breakpoints.  */
3082       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3083         continue;
3084
3085       switch_to_program_space_and_thread (bl->pspace);
3086
3087       /* For targets that support global breakpoints, there's no need
3088          to select an inferior to insert breakpoint to.  In fact, even
3089          if we aren't attached to any process yet, we should still
3090          insert breakpoints.  */
3091       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3092           && ptid_equal (inferior_ptid, null_ptid))
3093         continue;
3094
3095       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3096                                     &hw_breakpoint_error, &hw_bp_details_reported);
3097       if (val)
3098         error_flag = val;
3099     }
3100
3101   if (error_flag)
3102     {
3103       target_terminal_ours_for_output ();
3104       error_stream (tmp_error_stream);
3105     }
3106
3107   do_cleanups (cleanups);
3108 }
3109
3110 /* Used when starting or continuing the program.  */
3111
3112 static void
3113 insert_breakpoint_locations (void)
3114 {
3115   struct breakpoint *bpt;
3116   struct bp_location *bl, **blp_tmp;
3117   int error_flag = 0;
3118   int val = 0;
3119   int disabled_breaks = 0;
3120   int hw_breakpoint_error = 0;
3121   int hw_bp_error_explained_already = 0;
3122
3123   string_file tmp_error_stream;
3124
3125   /* Explicitly mark the warning -- this will only be printed if
3126      there was an error.  */
3127   tmp_error_stream.puts ("Warning:\n");
3128
3129   struct cleanup *cleanups = save_current_space_and_thread ();
3130
3131   ALL_BP_LOCATIONS (bl, blp_tmp)
3132     {
3133       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3134         continue;
3135
3136       /* There is no point inserting thread-specific breakpoints if
3137          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3138          has BL->OWNER always non-NULL.  */
3139       if (bl->owner->thread != -1
3140           && !valid_global_thread_id (bl->owner->thread))
3141         continue;
3142
3143       switch_to_program_space_and_thread (bl->pspace);
3144
3145       /* For targets that support global breakpoints, there's no need
3146          to select an inferior to insert breakpoint to.  In fact, even
3147          if we aren't attached to any process yet, we should still
3148          insert breakpoints.  */
3149       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3150           && ptid_equal (inferior_ptid, null_ptid))
3151         continue;
3152
3153       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3154                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3155       if (val)
3156         error_flag = val;
3157     }
3158
3159   /* If we failed to insert all locations of a watchpoint, remove
3160      them, as half-inserted watchpoint is of limited use.  */
3161   ALL_BREAKPOINTS (bpt)  
3162     {
3163       int some_failed = 0;
3164       struct bp_location *loc;
3165
3166       if (!is_hardware_watchpoint (bpt))
3167         continue;
3168
3169       if (!breakpoint_enabled (bpt))
3170         continue;
3171
3172       if (bpt->disposition == disp_del_at_next_stop)
3173         continue;
3174       
3175       for (loc = bpt->loc; loc; loc = loc->next)
3176         if (!loc->inserted && should_be_inserted (loc))
3177           {
3178             some_failed = 1;
3179             break;
3180           }
3181       if (some_failed)
3182         {
3183           for (loc = bpt->loc; loc; loc = loc->next)
3184             if (loc->inserted)
3185               remove_breakpoint (loc);
3186
3187           hw_breakpoint_error = 1;
3188           tmp_error_stream.printf ("Could not insert "
3189                                    "hardware watchpoint %d.\n",
3190                                    bpt->number);
3191           error_flag = -1;
3192         }
3193     }
3194
3195   if (error_flag)
3196     {
3197       /* If a hardware breakpoint or watchpoint was inserted, add a
3198          message about possibly exhausted resources.  */
3199       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3200         {
3201           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3202 You may have requested too many hardware breakpoints/watchpoints.\n");
3203         }
3204       target_terminal_ours_for_output ();
3205       error_stream (tmp_error_stream);
3206     }
3207
3208   do_cleanups (cleanups);
3209 }
3210
3211 /* Used when the program stops.
3212    Returns zero if successful, or non-zero if there was a problem
3213    removing a breakpoint location.  */
3214
3215 int
3216 remove_breakpoints (void)
3217 {
3218   struct bp_location *bl, **blp_tmp;
3219   int val = 0;
3220
3221   ALL_BP_LOCATIONS (bl, blp_tmp)
3222   {
3223     if (bl->inserted && !is_tracepoint (bl->owner))
3224       val |= remove_breakpoint (bl);
3225   }
3226   return val;
3227 }
3228
3229 /* When a thread exits, remove breakpoints that are related to
3230    that thread.  */
3231
3232 static void
3233 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3234 {
3235   struct breakpoint *b, *b_tmp;
3236
3237   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3238     {
3239       if (b->thread == tp->global_num && user_breakpoint_p (b))
3240         {
3241           b->disposition = disp_del_at_next_stop;
3242
3243           printf_filtered (_("\
3244 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3245                            b->number, print_thread_id (tp));
3246
3247           /* Hide it from the user.  */
3248           b->number = 0;
3249        }
3250     }
3251 }
3252
3253 /* Remove breakpoints of process PID.  */
3254
3255 int
3256 remove_breakpoints_pid (int pid)
3257 {
3258   struct bp_location *bl, **blp_tmp;
3259   int val;
3260   struct inferior *inf = find_inferior_pid (pid);
3261
3262   ALL_BP_LOCATIONS (bl, blp_tmp)
3263   {
3264     if (bl->pspace != inf->pspace)
3265       continue;
3266
3267     if (bl->inserted && !bl->target_info.persist)
3268       {
3269         val = remove_breakpoint (bl);
3270         if (val != 0)
3271           return val;
3272       }
3273   }
3274   return 0;
3275 }
3276
3277 int
3278 reattach_breakpoints (int pid)
3279 {
3280   struct cleanup *old_chain;
3281   struct bp_location *bl, **blp_tmp;
3282   int val;
3283   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3284   struct inferior *inf;
3285   struct thread_info *tp;
3286
3287   tp = any_live_thread_of_process (pid);
3288   if (tp == NULL)
3289     return 1;
3290
3291   inf = find_inferior_pid (pid);
3292   old_chain = save_inferior_ptid ();
3293
3294   inferior_ptid = tp->ptid;
3295
3296   string_file tmp_error_stream;
3297
3298   ALL_BP_LOCATIONS (bl, blp_tmp)
3299   {
3300     if (bl->pspace != inf->pspace)
3301       continue;
3302
3303     if (bl->inserted)
3304       {
3305         bl->inserted = 0;
3306         val = insert_bp_location (bl, &tmp_error_stream, &dummy1, &dummy2, &dummy3);
3307         if (val != 0)
3308           {
3309             do_cleanups (old_chain);
3310             return val;
3311           }
3312       }
3313   }
3314   do_cleanups (old_chain);
3315   return 0;
3316 }
3317
3318 static int internal_breakpoint_number = -1;
3319
3320 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3321    If INTERNAL is non-zero, the breakpoint number will be populated
3322    from internal_breakpoint_number and that variable decremented.
3323    Otherwise the breakpoint number will be populated from
3324    breakpoint_count and that value incremented.  Internal breakpoints
3325    do not set the internal var bpnum.  */
3326 static void
3327 set_breakpoint_number (int internal, struct breakpoint *b)
3328 {
3329   if (internal)
3330     b->number = internal_breakpoint_number--;
3331   else
3332     {
3333       set_breakpoint_count (breakpoint_count + 1);
3334       b->number = breakpoint_count;
3335     }
3336 }
3337
3338 static struct breakpoint *
3339 create_internal_breakpoint (struct gdbarch *gdbarch,
3340                             CORE_ADDR address, enum bptype type,
3341                             const struct breakpoint_ops *ops)
3342 {
3343   struct symtab_and_line sal;
3344   struct breakpoint *b;
3345
3346   init_sal (&sal);              /* Initialize to zeroes.  */
3347
3348   sal.pc = address;
3349   sal.section = find_pc_overlay (sal.pc);
3350   sal.pspace = current_program_space;
3351
3352   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3353   b->number = internal_breakpoint_number--;
3354   b->disposition = disp_donttouch;
3355
3356   return b;
3357 }
3358
3359 static const char *const longjmp_names[] =
3360   {
3361     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3362   };
3363 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3364
3365 /* Per-objfile data private to breakpoint.c.  */
3366 struct breakpoint_objfile_data
3367 {
3368   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3369   struct bound_minimal_symbol overlay_msym;
3370
3371   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3372   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3373
3374   /* True if we have looked for longjmp probes.  */
3375   int longjmp_searched;
3376
3377   /* SystemTap probe points for longjmp (if any).  */
3378   VEC (probe_p) *longjmp_probes;
3379
3380   /* Minimal symbol for "std::terminate()" (if any).  */
3381   struct bound_minimal_symbol terminate_msym;
3382
3383   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3384   struct bound_minimal_symbol exception_msym;
3385
3386   /* True if we have looked for exception probes.  */
3387   int exception_searched;
3388
3389   /* SystemTap probe points for unwinding (if any).  */
3390   VEC (probe_p) *exception_probes;
3391 };
3392
3393 static const struct objfile_data *breakpoint_objfile_key;
3394
3395 /* Minimal symbol not found sentinel.  */
3396 static struct minimal_symbol msym_not_found;
3397
3398 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3399
3400 static int
3401 msym_not_found_p (const struct minimal_symbol *msym)
3402 {
3403   return msym == &msym_not_found;
3404 }
3405
3406 /* Return per-objfile data needed by breakpoint.c.
3407    Allocate the data if necessary.  */
3408
3409 static struct breakpoint_objfile_data *
3410 get_breakpoint_objfile_data (struct objfile *objfile)
3411 {
3412   struct breakpoint_objfile_data *bp_objfile_data;
3413
3414   bp_objfile_data = ((struct breakpoint_objfile_data *)
3415                      objfile_data (objfile, breakpoint_objfile_key));
3416   if (bp_objfile_data == NULL)
3417     {
3418       bp_objfile_data =
3419         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3420
3421       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3422       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3423     }
3424   return bp_objfile_data;
3425 }
3426
3427 static void
3428 free_breakpoint_probes (struct objfile *obj, void *data)
3429 {
3430   struct breakpoint_objfile_data *bp_objfile_data
3431     = (struct breakpoint_objfile_data *) data;
3432
3433   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3434   VEC_free (probe_p, bp_objfile_data->exception_probes);
3435 }
3436
3437 static void
3438 create_overlay_event_breakpoint (void)
3439 {
3440   struct objfile *objfile;
3441   const char *const func_name = "_ovly_debug_event";
3442
3443   ALL_OBJFILES (objfile)
3444     {
3445       struct breakpoint *b;
3446       struct breakpoint_objfile_data *bp_objfile_data;
3447       CORE_ADDR addr;
3448       struct explicit_location explicit_loc;
3449
3450       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3451
3452       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3453         continue;
3454
3455       if (bp_objfile_data->overlay_msym.minsym == NULL)
3456         {
3457           struct bound_minimal_symbol m;
3458
3459           m = lookup_minimal_symbol_text (func_name, objfile);
3460           if (m.minsym == NULL)
3461             {
3462               /* Avoid future lookups in this objfile.  */
3463               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3464               continue;
3465             }
3466           bp_objfile_data->overlay_msym = m;
3467         }
3468
3469       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3470       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3471                                       bp_overlay_event,
3472                                       &internal_breakpoint_ops);
3473       initialize_explicit_location (&explicit_loc);
3474       explicit_loc.function_name = ASTRDUP (func_name);
3475       b->location = new_explicit_location (&explicit_loc);
3476
3477       if (overlay_debugging == ovly_auto)
3478         {
3479           b->enable_state = bp_enabled;
3480           overlay_events_enabled = 1;
3481         }
3482       else
3483        {
3484          b->enable_state = bp_disabled;
3485          overlay_events_enabled = 0;
3486        }
3487     }
3488 }
3489
3490 static void
3491 create_longjmp_master_breakpoint (void)
3492 {
3493   struct program_space *pspace;
3494   struct cleanup *old_chain;
3495
3496   old_chain = save_current_program_space ();
3497
3498   ALL_PSPACES (pspace)
3499   {
3500     struct objfile *objfile;
3501
3502     set_current_program_space (pspace);
3503
3504     ALL_OBJFILES (objfile)
3505     {
3506       int i;
3507       struct gdbarch *gdbarch;
3508       struct breakpoint_objfile_data *bp_objfile_data;
3509
3510       gdbarch = get_objfile_arch (objfile);
3511
3512       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3513
3514       if (!bp_objfile_data->longjmp_searched)
3515         {
3516           VEC (probe_p) *ret;
3517
3518           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3519           if (ret != NULL)
3520             {
3521               /* We are only interested in checking one element.  */
3522               struct probe *p = VEC_index (probe_p, ret, 0);
3523
3524               if (!can_evaluate_probe_arguments (p))
3525                 {
3526                   /* We cannot use the probe interface here, because it does
3527                      not know how to evaluate arguments.  */
3528                   VEC_free (probe_p, ret);
3529                   ret = NULL;
3530                 }
3531             }
3532           bp_objfile_data->longjmp_probes = ret;
3533           bp_objfile_data->longjmp_searched = 1;
3534         }
3535
3536       if (bp_objfile_data->longjmp_probes != NULL)
3537         {
3538           int i;
3539           struct probe *probe;
3540           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3541
3542           for (i = 0;
3543                VEC_iterate (probe_p,
3544                             bp_objfile_data->longjmp_probes,
3545                             i, probe);
3546                ++i)
3547             {
3548               struct breakpoint *b;
3549
3550               b = create_internal_breakpoint (gdbarch,
3551                                               get_probe_address (probe,
3552                                                                  objfile),
3553                                               bp_longjmp_master,
3554                                               &internal_breakpoint_ops);
3555               b->location
3556                 = new_probe_location ("-probe-stap libc:longjmp");
3557               b->enable_state = bp_disabled;
3558             }
3559
3560           continue;
3561         }
3562
3563       if (!gdbarch_get_longjmp_target_p (gdbarch))
3564         continue;
3565
3566       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3567         {
3568           struct breakpoint *b;
3569           const char *func_name;
3570           CORE_ADDR addr;
3571           struct explicit_location explicit_loc;
3572
3573           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3574             continue;
3575
3576           func_name = longjmp_names[i];
3577           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3578             {
3579               struct bound_minimal_symbol m;
3580
3581               m = lookup_minimal_symbol_text (func_name, objfile);
3582               if (m.minsym == NULL)
3583                 {
3584                   /* Prevent future lookups in this objfile.  */
3585                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3586                   continue;
3587                 }
3588               bp_objfile_data->longjmp_msym[i] = m;
3589             }
3590
3591           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3592           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3593                                           &internal_breakpoint_ops);
3594           initialize_explicit_location (&explicit_loc);
3595           explicit_loc.function_name = ASTRDUP (func_name);
3596           b->location = new_explicit_location (&explicit_loc);
3597           b->enable_state = bp_disabled;
3598         }
3599     }
3600   }
3601
3602   do_cleanups (old_chain);
3603 }
3604
3605 /* Create a master std::terminate breakpoint.  */
3606 static void
3607 create_std_terminate_master_breakpoint (void)
3608 {
3609   struct program_space *pspace;
3610   struct cleanup *old_chain;
3611   const char *const func_name = "std::terminate()";
3612
3613   old_chain = save_current_program_space ();
3614
3615   ALL_PSPACES (pspace)
3616   {
3617     struct objfile *objfile;
3618     CORE_ADDR addr;
3619
3620     set_current_program_space (pspace);
3621
3622     ALL_OBJFILES (objfile)
3623     {
3624       struct breakpoint *b;
3625       struct breakpoint_objfile_data *bp_objfile_data;
3626       struct explicit_location explicit_loc;
3627
3628       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3629
3630       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3631         continue;
3632
3633       if (bp_objfile_data->terminate_msym.minsym == NULL)
3634         {
3635           struct bound_minimal_symbol m;
3636
3637           m = lookup_minimal_symbol (func_name, NULL, objfile);
3638           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3639                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3640             {
3641               /* Prevent future lookups in this objfile.  */
3642               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3643               continue;
3644             }
3645           bp_objfile_data->terminate_msym = m;
3646         }
3647
3648       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3649       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3650                                       bp_std_terminate_master,
3651                                       &internal_breakpoint_ops);
3652       initialize_explicit_location (&explicit_loc);
3653       explicit_loc.function_name = ASTRDUP (func_name);
3654       b->location = new_explicit_location (&explicit_loc);
3655       b->enable_state = bp_disabled;
3656     }
3657   }
3658
3659   do_cleanups (old_chain);
3660 }
3661
3662 /* Install a master breakpoint on the unwinder's debug hook.  */
3663
3664 static void
3665 create_exception_master_breakpoint (void)
3666 {
3667   struct objfile *objfile;
3668   const char *const func_name = "_Unwind_DebugHook";
3669
3670   ALL_OBJFILES (objfile)
3671     {
3672       struct breakpoint *b;
3673       struct gdbarch *gdbarch;
3674       struct breakpoint_objfile_data *bp_objfile_data;
3675       CORE_ADDR addr;
3676       struct explicit_location explicit_loc;
3677
3678       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3679
3680       /* We prefer the SystemTap probe point if it exists.  */
3681       if (!bp_objfile_data->exception_searched)
3682         {
3683           VEC (probe_p) *ret;
3684
3685           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3686
3687           if (ret != NULL)
3688             {
3689               /* We are only interested in checking one element.  */
3690               struct probe *p = VEC_index (probe_p, ret, 0);
3691
3692               if (!can_evaluate_probe_arguments (p))
3693                 {
3694                   /* We cannot use the probe interface here, because it does
3695                      not know how to evaluate arguments.  */
3696                   VEC_free (probe_p, ret);
3697                   ret = NULL;
3698                 }
3699             }
3700           bp_objfile_data->exception_probes = ret;
3701           bp_objfile_data->exception_searched = 1;
3702         }
3703
3704       if (bp_objfile_data->exception_probes != NULL)
3705         {
3706           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3707           int i;
3708           struct probe *probe;
3709
3710           for (i = 0;
3711                VEC_iterate (probe_p,
3712                             bp_objfile_data->exception_probes,
3713                             i, probe);
3714                ++i)
3715             {
3716               struct breakpoint *b;
3717
3718               b = create_internal_breakpoint (gdbarch,
3719                                               get_probe_address (probe,
3720                                                                  objfile),
3721                                               bp_exception_master,
3722                                               &internal_breakpoint_ops);
3723               b->location
3724                 = new_probe_location ("-probe-stap libgcc:unwind");
3725               b->enable_state = bp_disabled;
3726             }
3727
3728           continue;
3729         }
3730
3731       /* Otherwise, try the hook function.  */
3732
3733       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3734         continue;
3735
3736       gdbarch = get_objfile_arch (objfile);
3737
3738       if (bp_objfile_data->exception_msym.minsym == NULL)
3739         {
3740           struct bound_minimal_symbol debug_hook;
3741
3742           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3743           if (debug_hook.minsym == NULL)
3744             {
3745               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3746               continue;
3747             }
3748
3749           bp_objfile_data->exception_msym = debug_hook;
3750         }
3751
3752       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3753       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3754                                                  &current_target);
3755       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3756                                       &internal_breakpoint_ops);
3757       initialize_explicit_location (&explicit_loc);
3758       explicit_loc.function_name = ASTRDUP (func_name);
3759       b->location = new_explicit_location (&explicit_loc);
3760       b->enable_state = bp_disabled;
3761     }
3762 }
3763
3764 /* Does B have a location spec?  */
3765
3766 static int
3767 breakpoint_event_location_empty_p (const struct breakpoint *b)
3768 {
3769   return b->location != NULL && event_location_empty_p (b->location);
3770 }
3771
3772 void
3773 update_breakpoints_after_exec (void)
3774 {
3775   struct breakpoint *b, *b_tmp;
3776   struct bp_location *bploc, **bplocp_tmp;
3777
3778   /* We're about to delete breakpoints from GDB's lists.  If the
3779      INSERTED flag is true, GDB will try to lift the breakpoints by
3780      writing the breakpoints' "shadow contents" back into memory.  The
3781      "shadow contents" are NOT valid after an exec, so GDB should not
3782      do that.  Instead, the target is responsible from marking
3783      breakpoints out as soon as it detects an exec.  We don't do that
3784      here instead, because there may be other attempts to delete
3785      breakpoints after detecting an exec and before reaching here.  */
3786   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3787     if (bploc->pspace == current_program_space)
3788       gdb_assert (!bploc->inserted);
3789
3790   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3791   {
3792     if (b->pspace != current_program_space)
3793       continue;
3794
3795     /* Solib breakpoints must be explicitly reset after an exec().  */
3796     if (b->type == bp_shlib_event)
3797       {
3798         delete_breakpoint (b);
3799         continue;
3800       }
3801
3802     /* JIT breakpoints must be explicitly reset after an exec().  */
3803     if (b->type == bp_jit_event)
3804       {
3805         delete_breakpoint (b);
3806         continue;
3807       }
3808
3809     /* Thread event breakpoints must be set anew after an exec(),
3810        as must overlay event and longjmp master breakpoints.  */
3811     if (b->type == bp_thread_event || b->type == bp_overlay_event
3812         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3813         || b->type == bp_exception_master)
3814       {
3815         delete_breakpoint (b);
3816         continue;
3817       }
3818
3819     /* Step-resume breakpoints are meaningless after an exec().  */
3820     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3821       {
3822         delete_breakpoint (b);
3823         continue;
3824       }
3825
3826     /* Just like single-step breakpoints.  */
3827     if (b->type == bp_single_step)
3828       {
3829         delete_breakpoint (b);
3830         continue;
3831       }
3832
3833     /* Longjmp and longjmp-resume breakpoints are also meaningless
3834        after an exec.  */
3835     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3836         || b->type == bp_longjmp_call_dummy
3837         || b->type == bp_exception || b->type == bp_exception_resume)
3838       {
3839         delete_breakpoint (b);
3840         continue;
3841       }
3842
3843     if (b->type == bp_catchpoint)
3844       {
3845         /* For now, none of the bp_catchpoint breakpoints need to
3846            do anything at this point.  In the future, if some of
3847            the catchpoints need to something, we will need to add
3848            a new method, and call this method from here.  */
3849         continue;
3850       }
3851
3852     /* bp_finish is a special case.  The only way we ought to be able
3853        to see one of these when an exec() has happened, is if the user
3854        caught a vfork, and then said "finish".  Ordinarily a finish just
3855        carries them to the call-site of the current callee, by setting
3856        a temporary bp there and resuming.  But in this case, the finish
3857        will carry them entirely through the vfork & exec.
3858
3859        We don't want to allow a bp_finish to remain inserted now.  But
3860        we can't safely delete it, 'cause finish_command has a handle to
3861        the bp on a bpstat, and will later want to delete it.  There's a
3862        chance (and I've seen it happen) that if we delete the bp_finish
3863        here, that its storage will get reused by the time finish_command
3864        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3865        We really must allow finish_command to delete a bp_finish.
3866
3867        In the absence of a general solution for the "how do we know
3868        it's safe to delete something others may have handles to?"
3869        problem, what we'll do here is just uninsert the bp_finish, and
3870        let finish_command delete it.
3871
3872        (We know the bp_finish is "doomed" in the sense that it's
3873        momentary, and will be deleted as soon as finish_command sees
3874        the inferior stopped.  So it doesn't matter that the bp's
3875        address is probably bogus in the new a.out, unlike e.g., the
3876        solib breakpoints.)  */
3877
3878     if (b->type == bp_finish)
3879       {
3880         continue;
3881       }
3882
3883     /* Without a symbolic address, we have little hope of the
3884        pre-exec() address meaning the same thing in the post-exec()
3885        a.out.  */
3886     if (breakpoint_event_location_empty_p (b))
3887       {
3888         delete_breakpoint (b);
3889         continue;
3890       }
3891   }
3892 }
3893
3894 int
3895 detach_breakpoints (ptid_t ptid)
3896 {
3897   struct bp_location *bl, **blp_tmp;
3898   int val = 0;
3899   struct cleanup *old_chain = save_inferior_ptid ();
3900   struct inferior *inf = current_inferior ();
3901
3902   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3903     error (_("Cannot detach breakpoints of inferior_ptid"));
3904
3905   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3906   inferior_ptid = ptid;
3907   ALL_BP_LOCATIONS (bl, blp_tmp)
3908   {
3909     if (bl->pspace != inf->pspace)
3910       continue;
3911
3912     /* This function must physically remove breakpoints locations
3913        from the specified ptid, without modifying the breakpoint
3914        package's state.  Locations of type bp_loc_other are only
3915        maintained at GDB side.  So, there is no need to remove
3916        these bp_loc_other locations.  Moreover, removing these
3917        would modify the breakpoint package's state.  */
3918     if (bl->loc_type == bp_loc_other)
3919       continue;
3920
3921     if (bl->inserted)
3922       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3923   }
3924
3925   do_cleanups (old_chain);
3926   return val;
3927 }
3928
3929 /* Remove the breakpoint location BL from the current address space.
3930    Note that this is used to detach breakpoints from a child fork.
3931    When we get here, the child isn't in the inferior list, and neither
3932    do we have objects to represent its address space --- we should
3933    *not* look at bl->pspace->aspace here.  */
3934
3935 static int
3936 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3937 {
3938   int val;
3939
3940   /* BL is never in moribund_locations by our callers.  */
3941   gdb_assert (bl->owner != NULL);
3942
3943   /* The type of none suggests that owner is actually deleted.
3944      This should not ever happen.  */
3945   gdb_assert (bl->owner->type != bp_none);
3946
3947   if (bl->loc_type == bp_loc_software_breakpoint
3948       || bl->loc_type == bp_loc_hardware_breakpoint)
3949     {
3950       /* "Normal" instruction breakpoint: either the standard
3951          trap-instruction bp (bp_breakpoint), or a
3952          bp_hardware_breakpoint.  */
3953
3954       /* First check to see if we have to handle an overlay.  */
3955       if (overlay_debugging == ovly_off
3956           || bl->section == NULL
3957           || !(section_is_overlay (bl->section)))
3958         {
3959           /* No overlay handling: just remove the breakpoint.  */
3960
3961           /* If we're trying to uninsert a memory breakpoint that we
3962              know is set in a dynamic object that is marked
3963              shlib_disabled, then either the dynamic object was
3964              removed with "remove-symbol-file" or with
3965              "nosharedlibrary".  In the former case, we don't know
3966              whether another dynamic object might have loaded over the
3967              breakpoint's address -- the user might well let us know
3968              about it next with add-symbol-file (the whole point of
3969              add-symbol-file is letting the user manually maintain a
3970              list of dynamically loaded objects).  If we have the
3971              breakpoint's shadow memory, that is, this is a software
3972              breakpoint managed by GDB, check whether the breakpoint
3973              is still inserted in memory, to avoid overwriting wrong
3974              code with stale saved shadow contents.  Note that HW
3975              breakpoints don't have shadow memory, as they're
3976              implemented using a mechanism that is not dependent on
3977              being able to modify the target's memory, and as such
3978              they should always be removed.  */
3979           if (bl->shlib_disabled
3980               && bl->target_info.shadow_len != 0
3981               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3982             val = 0;
3983           else
3984             val = bl->owner->ops->remove_location (bl, reason);
3985         }
3986       else
3987         {
3988           /* This breakpoint is in an overlay section.
3989              Did we set a breakpoint at the LMA?  */
3990           if (!overlay_events_enabled)
3991               {
3992                 /* Yes -- overlay event support is not active, so we
3993                    should have set a breakpoint at the LMA.  Remove it.  
3994                 */
3995                 /* Ignore any failures: if the LMA is in ROM, we will
3996                    have already warned when we failed to insert it.  */
3997                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3998                   target_remove_hw_breakpoint (bl->gdbarch,
3999                                                &bl->overlay_target_info);
4000                 else
4001                   target_remove_breakpoint (bl->gdbarch,
4002                                             &bl->overlay_target_info,
4003                                             reason);
4004               }
4005           /* Did we set a breakpoint at the VMA? 
4006              If so, we will have marked the breakpoint 'inserted'.  */
4007           if (bl->inserted)
4008             {
4009               /* Yes -- remove it.  Previously we did not bother to
4010                  remove the breakpoint if the section had been
4011                  unmapped, but let's not rely on that being safe.  We
4012                  don't know what the overlay manager might do.  */
4013
4014               /* However, we should remove *software* breakpoints only
4015                  if the section is still mapped, or else we overwrite
4016                  wrong code with the saved shadow contents.  */
4017               if (bl->loc_type == bp_loc_hardware_breakpoint
4018                   || section_is_mapped (bl->section))
4019                 val = bl->owner->ops->remove_location (bl, reason);
4020               else
4021                 val = 0;
4022             }
4023           else
4024             {
4025               /* No -- not inserted, so no need to remove.  No error.  */
4026               val = 0;
4027             }
4028         }
4029
4030       /* In some cases, we might not be able to remove a breakpoint in
4031          a shared library that has already been removed, but we have
4032          not yet processed the shlib unload event.  Similarly for an
4033          unloaded add-symbol-file object - the user might not yet have
4034          had the chance to remove-symbol-file it.  shlib_disabled will
4035          be set if the library/object has already been removed, but
4036          the breakpoint hasn't been uninserted yet, e.g., after
4037          "nosharedlibrary" or "remove-symbol-file" with breakpoints
4038          always-inserted mode.  */
4039       if (val
4040           && (bl->loc_type == bp_loc_software_breakpoint
4041               && (bl->shlib_disabled
4042                   || solib_name_from_address (bl->pspace, bl->address)
4043                   || shared_objfile_contains_address_p (bl->pspace,
4044                                                         bl->address))))
4045         val = 0;
4046
4047       if (val)
4048         return val;
4049       bl->inserted = (reason == DETACH_BREAKPOINT);
4050     }
4051   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4052     {
4053       gdb_assert (bl->owner->ops != NULL
4054                   && bl->owner->ops->remove_location != NULL);
4055
4056       bl->inserted = (reason == DETACH_BREAKPOINT);
4057       bl->owner->ops->remove_location (bl, reason);
4058
4059       /* Failure to remove any of the hardware watchpoints comes here.  */
4060       if (reason == REMOVE_BREAKPOINT && bl->inserted)
4061         warning (_("Could not remove hardware watchpoint %d."),
4062                  bl->owner->number);
4063     }
4064   else if (bl->owner->type == bp_catchpoint
4065            && breakpoint_enabled (bl->owner)
4066            && !bl->duplicate)
4067     {
4068       gdb_assert (bl->owner->ops != NULL
4069                   && bl->owner->ops->remove_location != NULL);
4070
4071       val = bl->owner->ops->remove_location (bl, reason);
4072       if (val)
4073         return val;
4074
4075       bl->inserted = (reason == DETACH_BREAKPOINT);
4076     }
4077
4078   return 0;
4079 }
4080
4081 static int
4082 remove_breakpoint (struct bp_location *bl)
4083 {
4084   int ret;
4085   struct cleanup *old_chain;
4086
4087   /* BL is never in moribund_locations by our callers.  */
4088   gdb_assert (bl->owner != NULL);
4089
4090   /* The type of none suggests that owner is actually deleted.
4091      This should not ever happen.  */
4092   gdb_assert (bl->owner->type != bp_none);
4093
4094   old_chain = save_current_space_and_thread ();
4095
4096   switch_to_program_space_and_thread (bl->pspace);
4097
4098   ret = remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4099
4100   do_cleanups (old_chain);
4101   return ret;
4102 }
4103
4104 /* Clear the "inserted" flag in all breakpoints.  */
4105
4106 void
4107 mark_breakpoints_out (void)
4108 {
4109   struct bp_location *bl, **blp_tmp;
4110
4111   ALL_BP_LOCATIONS (bl, blp_tmp)
4112     if (bl->pspace == current_program_space)
4113       bl->inserted = 0;
4114 }
4115
4116 /* Clear the "inserted" flag in all breakpoints and delete any
4117    breakpoints which should go away between runs of the program.
4118
4119    Plus other such housekeeping that has to be done for breakpoints
4120    between runs.
4121
4122    Note: this function gets called at the end of a run (by
4123    generic_mourn_inferior) and when a run begins (by
4124    init_wait_for_inferior).  */
4125
4126
4127
4128 void
4129 breakpoint_init_inferior (enum inf_context context)
4130 {
4131   struct breakpoint *b, *b_tmp;
4132   struct bp_location *bl;
4133   int ix;
4134   struct program_space *pspace = current_program_space;
4135
4136   /* If breakpoint locations are shared across processes, then there's
4137      nothing to do.  */
4138   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4139     return;
4140
4141   mark_breakpoints_out ();
4142
4143   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4144   {
4145     if (b->loc && b->loc->pspace != pspace)
4146       continue;
4147
4148     switch (b->type)
4149       {
4150       case bp_call_dummy:
4151       case bp_longjmp_call_dummy:
4152
4153         /* If the call dummy breakpoint is at the entry point it will
4154            cause problems when the inferior is rerun, so we better get
4155            rid of it.  */
4156
4157       case bp_watchpoint_scope:
4158
4159         /* Also get rid of scope breakpoints.  */
4160
4161       case bp_shlib_event:
4162
4163         /* Also remove solib event breakpoints.  Their addresses may
4164            have changed since the last time we ran the program.
4165            Actually we may now be debugging against different target;
4166            and so the solib backend that installed this breakpoint may
4167            not be used in by the target.  E.g.,
4168
4169            (gdb) file prog-linux
4170            (gdb) run               # native linux target
4171            ...
4172            (gdb) kill
4173            (gdb) file prog-win.exe
4174            (gdb) tar rem :9999     # remote Windows gdbserver.
4175         */
4176
4177       case bp_step_resume:
4178
4179         /* Also remove step-resume breakpoints.  */
4180
4181       case bp_single_step:
4182
4183         /* Also remove single-step breakpoints.  */
4184
4185         delete_breakpoint (b);
4186         break;
4187
4188       case bp_watchpoint:
4189       case bp_hardware_watchpoint:
4190       case bp_read_watchpoint:
4191       case bp_access_watchpoint:
4192         {
4193           struct watchpoint *w = (struct watchpoint *) b;
4194
4195           /* Likewise for watchpoints on local expressions.  */
4196           if (w->exp_valid_block != NULL)
4197             delete_breakpoint (b);
4198           else
4199             {
4200               /* Get rid of existing locations, which are no longer
4201                  valid.  New ones will be created in
4202                  update_watchpoint, when the inferior is restarted.
4203                  The next update_global_location_list call will
4204                  garbage collect them.  */
4205               b->loc = NULL;
4206
4207               if (context == inf_starting)
4208                 {
4209                   /* Reset val field to force reread of starting value in
4210                      insert_breakpoints.  */
4211                   if (w->val)
4212                     value_free (w->val);
4213                   w->val = NULL;
4214                   w->val_valid = 0;
4215                 }
4216             }
4217         }
4218         break;
4219       default:
4220         break;
4221       }
4222   }
4223
4224   /* Get rid of the moribund locations.  */
4225   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4226     decref_bp_location (&bl);
4227   VEC_free (bp_location_p, moribund_locations);
4228 }
4229
4230 /* These functions concern about actual breakpoints inserted in the
4231    target --- to e.g. check if we need to do decr_pc adjustment or if
4232    we need to hop over the bkpt --- so we check for address space
4233    match, not program space.  */
4234
4235 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4236    exists at PC.  It returns ordinary_breakpoint_here if it's an
4237    ordinary breakpoint, or permanent_breakpoint_here if it's a
4238    permanent breakpoint.
4239    - When continuing from a location with an ordinary breakpoint, we
4240      actually single step once before calling insert_breakpoints.
4241    - When continuing from a location with a permanent breakpoint, we
4242      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4243      the target, to advance the PC past the breakpoint.  */
4244
4245 enum breakpoint_here
4246 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4247 {
4248   struct bp_location *bl, **blp_tmp;
4249   int any_breakpoint_here = 0;
4250
4251   ALL_BP_LOCATIONS (bl, blp_tmp)
4252     {
4253       if (bl->loc_type != bp_loc_software_breakpoint
4254           && bl->loc_type != bp_loc_hardware_breakpoint)
4255         continue;
4256
4257       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4258       if ((breakpoint_enabled (bl->owner)
4259            || bl->permanent)
4260           && breakpoint_location_address_match (bl, aspace, pc))
4261         {
4262           if (overlay_debugging 
4263               && section_is_overlay (bl->section)
4264               && !section_is_mapped (bl->section))
4265             continue;           /* unmapped overlay -- can't be a match */
4266           else if (bl->permanent)
4267             return permanent_breakpoint_here;
4268           else
4269             any_breakpoint_here = 1;
4270         }
4271     }
4272
4273   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4274 }
4275
4276 /* See breakpoint.h.  */
4277
4278 int
4279 breakpoint_in_range_p (struct address_space *aspace,
4280                        CORE_ADDR addr, ULONGEST len)
4281 {
4282   struct bp_location *bl, **blp_tmp;
4283
4284   ALL_BP_LOCATIONS (bl, blp_tmp)
4285     {
4286       if (bl->loc_type != bp_loc_software_breakpoint
4287           && bl->loc_type != bp_loc_hardware_breakpoint)
4288         continue;
4289
4290       if ((breakpoint_enabled (bl->owner)
4291            || bl->permanent)
4292           && breakpoint_location_address_range_overlap (bl, aspace,
4293                                                         addr, len))
4294         {
4295           if (overlay_debugging
4296               && section_is_overlay (bl->section)
4297               && !section_is_mapped (bl->section))
4298             {
4299               /* Unmapped overlay -- can't be a match.  */
4300               continue;
4301             }
4302
4303           return 1;
4304         }
4305     }
4306
4307   return 0;
4308 }
4309
4310 /* Return true if there's a moribund breakpoint at PC.  */
4311
4312 int
4313 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4314 {
4315   struct bp_location *loc;
4316   int ix;
4317
4318   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4319     if (breakpoint_location_address_match (loc, aspace, pc))
4320       return 1;
4321
4322   return 0;
4323 }
4324
4325 /* Returns non-zero iff BL is inserted at PC, in address space
4326    ASPACE.  */
4327
4328 static int
4329 bp_location_inserted_here_p (struct bp_location *bl,
4330                              struct address_space *aspace, CORE_ADDR pc)
4331 {
4332   if (bl->inserted
4333       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4334                                    aspace, pc))
4335     {
4336       if (overlay_debugging
4337           && section_is_overlay (bl->section)
4338           && !section_is_mapped (bl->section))
4339         return 0;               /* unmapped overlay -- can't be a match */
4340       else
4341         return 1;
4342     }
4343   return 0;
4344 }
4345
4346 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4347
4348 int
4349 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4350 {
4351   struct bp_location **blp, **blp_tmp = NULL;
4352
4353   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4354     {
4355       struct bp_location *bl = *blp;
4356
4357       if (bl->loc_type != bp_loc_software_breakpoint
4358           && bl->loc_type != bp_loc_hardware_breakpoint)
4359         continue;
4360
4361       if (bp_location_inserted_here_p (bl, aspace, pc))
4362         return 1;
4363     }
4364   return 0;
4365 }
4366
4367 /* This function returns non-zero iff there is a software breakpoint
4368    inserted at PC.  */
4369
4370 int
4371 software_breakpoint_inserted_here_p (struct address_space *aspace,
4372                                      CORE_ADDR pc)
4373 {
4374   struct bp_location **blp, **blp_tmp = NULL;
4375
4376   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4377     {
4378       struct bp_location *bl = *blp;
4379
4380       if (bl->loc_type != bp_loc_software_breakpoint)
4381         continue;
4382
4383       if (bp_location_inserted_here_p (bl, aspace, pc))
4384         return 1;
4385     }
4386
4387   return 0;
4388 }
4389
4390 /* See breakpoint.h.  */
4391
4392 int
4393 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4394                                      CORE_ADDR pc)
4395 {
4396   struct bp_location **blp, **blp_tmp = NULL;
4397
4398   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4399     {
4400       struct bp_location *bl = *blp;
4401
4402       if (bl->loc_type != bp_loc_hardware_breakpoint)
4403         continue;
4404
4405       if (bp_location_inserted_here_p (bl, aspace, pc))
4406         return 1;
4407     }
4408
4409   return 0;
4410 }
4411
4412 int
4413 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4414                                        CORE_ADDR addr, ULONGEST len)
4415 {
4416   struct breakpoint *bpt;
4417
4418   ALL_BREAKPOINTS (bpt)
4419     {
4420       struct bp_location *loc;
4421
4422       if (bpt->type != bp_hardware_watchpoint
4423           && bpt->type != bp_access_watchpoint)
4424         continue;
4425
4426       if (!breakpoint_enabled (bpt))
4427         continue;
4428
4429       for (loc = bpt->loc; loc; loc = loc->next)
4430         if (loc->pspace->aspace == aspace && loc->inserted)
4431           {
4432             CORE_ADDR l, h;
4433
4434             /* Check for intersection.  */
4435             l = std::max<CORE_ADDR> (loc->address, addr);
4436             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4437             if (l < h)
4438               return 1;
4439           }
4440     }
4441   return 0;
4442 }
4443 \f
4444
4445 /* bpstat stuff.  External routines' interfaces are documented
4446    in breakpoint.h.  */
4447
4448 int
4449 is_catchpoint (struct breakpoint *ep)
4450 {
4451   return (ep->type == bp_catchpoint);
4452 }
4453
4454 /* Frees any storage that is part of a bpstat.  Does not walk the
4455    'next' chain.  */
4456
4457 static void
4458 bpstat_free (bpstat bs)
4459 {
4460   if (bs->old_val != NULL)
4461     value_free (bs->old_val);
4462   decref_counted_command_line (&bs->commands);
4463   decref_bp_location (&bs->bp_location_at);
4464   xfree (bs);
4465 }
4466
4467 /* Clear a bpstat so that it says we are not at any breakpoint.
4468    Also free any storage that is part of a bpstat.  */
4469
4470 void
4471 bpstat_clear (bpstat *bsp)
4472 {
4473   bpstat p;
4474   bpstat q;
4475
4476   if (bsp == 0)
4477     return;
4478   p = *bsp;
4479   while (p != NULL)
4480     {
4481       q = p->next;
4482       bpstat_free (p);
4483       p = q;
4484     }
4485   *bsp = NULL;
4486 }
4487
4488 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4489    is part of the bpstat is copied as well.  */
4490
4491 bpstat
4492 bpstat_copy (bpstat bs)
4493 {
4494   bpstat p = NULL;
4495   bpstat tmp;
4496   bpstat retval = NULL;
4497
4498   if (bs == NULL)
4499     return bs;
4500
4501   for (; bs != NULL; bs = bs->next)
4502     {
4503       tmp = (bpstat) xmalloc (sizeof (*tmp));
4504       memcpy (tmp, bs, sizeof (*tmp));
4505       incref_counted_command_line (tmp->commands);
4506       incref_bp_location (tmp->bp_location_at);
4507       if (bs->old_val != NULL)
4508         {
4509           tmp->old_val = value_copy (bs->old_val);
4510           release_value (tmp->old_val);
4511         }
4512
4513       if (p == NULL)
4514         /* This is the first thing in the chain.  */
4515         retval = tmp;
4516       else
4517         p->next = tmp;
4518       p = tmp;
4519     }
4520   p->next = NULL;
4521   return retval;
4522 }
4523
4524 /* Find the bpstat associated with this breakpoint.  */
4525
4526 bpstat
4527 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4528 {
4529   if (bsp == NULL)
4530     return NULL;
4531
4532   for (; bsp != NULL; bsp = bsp->next)
4533     {
4534       if (bsp->breakpoint_at == breakpoint)
4535         return bsp;
4536     }
4537   return NULL;
4538 }
4539
4540 /* See breakpoint.h.  */
4541
4542 int
4543 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4544 {
4545   for (; bsp != NULL; bsp = bsp->next)
4546     {
4547       if (bsp->breakpoint_at == NULL)
4548         {
4549           /* A moribund location can never explain a signal other than
4550              GDB_SIGNAL_TRAP.  */
4551           if (sig == GDB_SIGNAL_TRAP)
4552             return 1;
4553         }
4554       else
4555         {
4556           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4557                                                         sig))
4558             return 1;
4559         }
4560     }
4561
4562   return 0;
4563 }
4564
4565 /* Put in *NUM the breakpoint number of the first breakpoint we are
4566    stopped at.  *BSP upon return is a bpstat which points to the
4567    remaining breakpoints stopped at (but which is not guaranteed to be
4568    good for anything but further calls to bpstat_num).
4569
4570    Return 0 if passed a bpstat which does not indicate any breakpoints.
4571    Return -1 if stopped at a breakpoint that has been deleted since
4572    we set it.
4573    Return 1 otherwise.  */
4574
4575 int
4576 bpstat_num (bpstat *bsp, int *num)
4577 {
4578   struct breakpoint *b;
4579
4580   if ((*bsp) == NULL)
4581     return 0;                   /* No more breakpoint values */
4582
4583   /* We assume we'll never have several bpstats that correspond to a
4584      single breakpoint -- otherwise, this function might return the
4585      same number more than once and this will look ugly.  */
4586   b = (*bsp)->breakpoint_at;
4587   *bsp = (*bsp)->next;
4588   if (b == NULL)
4589     return -1;                  /* breakpoint that's been deleted since */
4590
4591   *num = b->number;             /* We have its number */
4592   return 1;
4593 }
4594
4595 /* See breakpoint.h.  */
4596
4597 void
4598 bpstat_clear_actions (void)
4599 {
4600   struct thread_info *tp;
4601   bpstat bs;
4602
4603   if (ptid_equal (inferior_ptid, null_ptid))
4604     return;
4605
4606   tp = find_thread_ptid (inferior_ptid);
4607   if (tp == NULL)
4608     return;
4609
4610   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4611     {
4612       decref_counted_command_line (&bs->commands);
4613
4614       if (bs->old_val != NULL)
4615         {
4616           value_free (bs->old_val);
4617           bs->old_val = NULL;
4618         }
4619     }
4620 }
4621
4622 /* Called when a command is about to proceed the inferior.  */
4623
4624 static void
4625 breakpoint_about_to_proceed (void)
4626 {
4627   if (!ptid_equal (inferior_ptid, null_ptid))
4628     {
4629       struct thread_info *tp = inferior_thread ();
4630
4631       /* Allow inferior function calls in breakpoint commands to not
4632          interrupt the command list.  When the call finishes
4633          successfully, the inferior will be standing at the same
4634          breakpoint as if nothing happened.  */
4635       if (tp->control.in_infcall)
4636         return;
4637     }
4638
4639   breakpoint_proceeded = 1;
4640 }
4641
4642 /* Stub for cleaning up our state if we error-out of a breakpoint
4643    command.  */
4644 static void
4645 cleanup_executing_breakpoints (void *ignore)
4646 {
4647   executing_breakpoint_commands = 0;
4648 }
4649
4650 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4651    or its equivalent.  */
4652
4653 static int
4654 command_line_is_silent (struct command_line *cmd)
4655 {
4656   return cmd && (strcmp ("silent", cmd->line) == 0);
4657 }
4658
4659 /* Execute all the commands associated with all the breakpoints at
4660    this location.  Any of these commands could cause the process to
4661    proceed beyond this point, etc.  We look out for such changes by
4662    checking the global "breakpoint_proceeded" after each command.
4663
4664    Returns true if a breakpoint command resumed the inferior.  In that
4665    case, it is the caller's responsibility to recall it again with the
4666    bpstat of the current thread.  */
4667
4668 static int
4669 bpstat_do_actions_1 (bpstat *bsp)
4670 {
4671   bpstat bs;
4672   struct cleanup *old_chain;
4673   int again = 0;
4674
4675   /* Avoid endless recursion if a `source' command is contained
4676      in bs->commands.  */
4677   if (executing_breakpoint_commands)
4678     return 0;
4679
4680   executing_breakpoint_commands = 1;
4681   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4682
4683   scoped_restore preventer = prevent_dont_repeat ();
4684
4685   /* This pointer will iterate over the list of bpstat's.  */
4686   bs = *bsp;
4687
4688   breakpoint_proceeded = 0;
4689   for (; bs != NULL; bs = bs->next)
4690     {
4691       struct counted_command_line *ccmd;
4692       struct command_line *cmd;
4693       struct cleanup *this_cmd_tree_chain;
4694
4695       /* Take ownership of the BSP's command tree, if it has one.
4696
4697          The command tree could legitimately contain commands like
4698          'step' and 'next', which call clear_proceed_status, which
4699          frees stop_bpstat's command tree.  To make sure this doesn't
4700          free the tree we're executing out from under us, we need to
4701          take ownership of the tree ourselves.  Since a given bpstat's
4702          commands are only executed once, we don't need to copy it; we
4703          can clear the pointer in the bpstat, and make sure we free
4704          the tree when we're done.  */
4705       ccmd = bs->commands;
4706       bs->commands = NULL;
4707       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4708       cmd = ccmd ? ccmd->commands : NULL;
4709       if (command_line_is_silent (cmd))
4710         {
4711           /* The action has been already done by bpstat_stop_status.  */
4712           cmd = cmd->next;
4713         }
4714
4715       while (cmd != NULL)
4716         {
4717           execute_control_command (cmd);
4718
4719           if (breakpoint_proceeded)
4720             break;
4721           else
4722             cmd = cmd->next;
4723         }
4724
4725       /* We can free this command tree now.  */
4726       do_cleanups (this_cmd_tree_chain);
4727
4728       if (breakpoint_proceeded)
4729         {
4730           if (current_ui->async)
4731             /* If we are in async mode, then the target might be still
4732                running, not stopped at any breakpoint, so nothing for
4733                us to do here -- just return to the event loop.  */
4734             ;
4735           else
4736             /* In sync mode, when execute_control_command returns
4737                we're already standing on the next breakpoint.
4738                Breakpoint commands for that stop were not run, since
4739                execute_command does not run breakpoint commands --
4740                only command_line_handler does, but that one is not
4741                involved in execution of breakpoint commands.  So, we
4742                can now execute breakpoint commands.  It should be
4743                noted that making execute_command do bpstat actions is
4744                not an option -- in this case we'll have recursive
4745                invocation of bpstat for each breakpoint with a
4746                command, and can easily blow up GDB stack.  Instead, we
4747                return true, which will trigger the caller to recall us
4748                with the new stop_bpstat.  */
4749             again = 1;
4750           break;
4751         }
4752     }
4753   do_cleanups (old_chain);
4754   return again;
4755 }
4756
4757 void
4758 bpstat_do_actions (void)
4759 {
4760   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4761
4762   /* Do any commands attached to breakpoint we are stopped at.  */
4763   while (!ptid_equal (inferior_ptid, null_ptid)
4764          && target_has_execution
4765          && !is_exited (inferior_ptid)
4766          && !is_executing (inferior_ptid))
4767     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4768        and only return when it is stopped at the next breakpoint, we
4769        keep doing breakpoint actions until it returns false to
4770        indicate the inferior was not resumed.  */
4771     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4772       break;
4773
4774   discard_cleanups (cleanup_if_error);
4775 }
4776
4777 /* Print out the (old or new) value associated with a watchpoint.  */
4778
4779 static void
4780 watchpoint_value_print (struct value *val, struct ui_file *stream)
4781 {
4782   if (val == NULL)
4783     fprintf_unfiltered (stream, _("<unreadable>"));
4784   else
4785     {
4786       struct value_print_options opts;
4787       get_user_print_options (&opts);
4788       value_print (val, stream, &opts);
4789     }
4790 }
4791
4792 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4793    debugging multiple threads.  */
4794
4795 void
4796 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4797 {
4798   if (uiout->is_mi_like_p ())
4799     return;
4800
4801   uiout->text ("\n");
4802
4803   if (show_thread_that_caused_stop ())
4804     {
4805       const char *name;
4806       struct thread_info *thr = inferior_thread ();
4807
4808       uiout->text ("Thread ");
4809       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4810
4811       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4812       if (name != NULL)
4813         {
4814           uiout->text (" \"");
4815           uiout->field_fmt ("name", "%s", name);
4816           uiout->text ("\"");
4817         }
4818
4819       uiout->text (" hit ");
4820     }
4821 }
4822
4823 /* Generic routine for printing messages indicating why we
4824    stopped.  The behavior of this function depends on the value
4825    'print_it' in the bpstat structure.  Under some circumstances we
4826    may decide not to print anything here and delegate the task to
4827    normal_stop().  */
4828
4829 static enum print_stop_action
4830 print_bp_stop_message (bpstat bs)
4831 {
4832   switch (bs->print_it)
4833     {
4834     case print_it_noop:
4835       /* Nothing should be printed for this bpstat entry.  */
4836       return PRINT_UNKNOWN;
4837       break;
4838
4839     case print_it_done:
4840       /* We still want to print the frame, but we already printed the
4841          relevant messages.  */
4842       return PRINT_SRC_AND_LOC;
4843       break;
4844
4845     case print_it_normal:
4846       {
4847         struct breakpoint *b = bs->breakpoint_at;
4848
4849         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4850            which has since been deleted.  */
4851         if (b == NULL)
4852           return PRINT_UNKNOWN;
4853
4854         /* Normal case.  Call the breakpoint's print_it method.  */
4855         return b->ops->print_it (bs);
4856       }
4857       break;
4858
4859     default:
4860       internal_error (__FILE__, __LINE__,
4861                       _("print_bp_stop_message: unrecognized enum value"));
4862       break;
4863     }
4864 }
4865
4866 /* A helper function that prints a shared library stopped event.  */
4867
4868 static void
4869 print_solib_event (int is_catchpoint)
4870 {
4871   int any_deleted
4872     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4873   int any_added
4874     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4875
4876   if (!is_catchpoint)
4877     {
4878       if (any_added || any_deleted)
4879         current_uiout->text (_("Stopped due to shared library event:\n"));
4880       else
4881         current_uiout->text (_("Stopped due to shared library event (no "
4882                                "libraries added or removed)\n"));
4883     }
4884
4885   if (current_uiout->is_mi_like_p ())
4886     current_uiout->field_string ("reason",
4887                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4888
4889   if (any_deleted)
4890     {
4891       struct cleanup *cleanup;
4892       char *name;
4893       int ix;
4894
4895       current_uiout->text (_("  Inferior unloaded "));
4896       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4897                                                     "removed");
4898       for (ix = 0;
4899            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4900                         ix, name);
4901            ++ix)
4902         {
4903           if (ix > 0)
4904             current_uiout->text ("    ");
4905           current_uiout->field_string ("library", name);
4906           current_uiout->text ("\n");
4907         }
4908
4909       do_cleanups (cleanup);
4910     }
4911
4912   if (any_added)
4913     {
4914       struct so_list *iter;
4915       int ix;
4916       struct cleanup *cleanup;
4917
4918       current_uiout->text (_("  Inferior loaded "));
4919       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4920                                                     "added");
4921       for (ix = 0;
4922            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4923                         ix, iter);
4924            ++ix)
4925         {
4926           if (ix > 0)
4927             current_uiout->text ("    ");
4928           current_uiout->field_string ("library", iter->so_name);
4929           current_uiout->text ("\n");
4930         }
4931
4932       do_cleanups (cleanup);
4933     }
4934 }
4935
4936 /* Print a message indicating what happened.  This is called from
4937    normal_stop().  The input to this routine is the head of the bpstat
4938    list - a list of the eventpoints that caused this stop.  KIND is
4939    the target_waitkind for the stopping event.  This
4940    routine calls the generic print routine for printing a message
4941    about reasons for stopping.  This will print (for example) the
4942    "Breakpoint n," part of the output.  The return value of this
4943    routine is one of:
4944
4945    PRINT_UNKNOWN: Means we printed nothing.
4946    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4947    code to print the location.  An example is 
4948    "Breakpoint 1, " which should be followed by
4949    the location.
4950    PRINT_SRC_ONLY: Means we printed something, but there is no need
4951    to also print the location part of the message.
4952    An example is the catch/throw messages, which
4953    don't require a location appended to the end.
4954    PRINT_NOTHING: We have done some printing and we don't need any 
4955    further info to be printed.  */
4956
4957 enum print_stop_action
4958 bpstat_print (bpstat bs, int kind)
4959 {
4960   enum print_stop_action val;
4961
4962   /* Maybe another breakpoint in the chain caused us to stop.
4963      (Currently all watchpoints go on the bpstat whether hit or not.
4964      That probably could (should) be changed, provided care is taken
4965      with respect to bpstat_explains_signal).  */
4966   for (; bs; bs = bs->next)
4967     {
4968       val = print_bp_stop_message (bs);
4969       if (val == PRINT_SRC_ONLY 
4970           || val == PRINT_SRC_AND_LOC 
4971           || val == PRINT_NOTHING)
4972         return val;
4973     }
4974
4975   /* If we had hit a shared library event breakpoint,
4976      print_bp_stop_message would print out this message.  If we hit an
4977      OS-level shared library event, do the same thing.  */
4978   if (kind == TARGET_WAITKIND_LOADED)
4979     {
4980       print_solib_event (0);
4981       return PRINT_NOTHING;
4982     }
4983
4984   /* We reached the end of the chain, or we got a null BS to start
4985      with and nothing was printed.  */
4986   return PRINT_UNKNOWN;
4987 }
4988
4989 /* Evaluate the expression EXP and return 1 if value is zero.
4990    This returns the inverse of the condition because it is called
4991    from catch_errors which returns 0 if an exception happened, and if an
4992    exception happens we want execution to stop.
4993    The argument is a "struct expression *" that has been cast to a
4994    "void *" to make it pass through catch_errors.  */
4995
4996 static int
4997 breakpoint_cond_eval (void *exp)
4998 {
4999   struct value *mark = value_mark ();
5000   int i = !value_true (evaluate_expression ((struct expression *) exp));
5001
5002   value_free_to_mark (mark);
5003   return i;
5004 }
5005
5006 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
5007
5008 static bpstat
5009 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
5010 {
5011   bpstat bs;
5012
5013   bs = (bpstat) xmalloc (sizeof (*bs));
5014   bs->next = NULL;
5015   **bs_link_pointer = bs;
5016   *bs_link_pointer = &bs->next;
5017   bs->breakpoint_at = bl->owner;
5018   bs->bp_location_at = bl;
5019   incref_bp_location (bl);
5020   /* If the condition is false, etc., don't do the commands.  */
5021   bs->commands = NULL;
5022   bs->old_val = NULL;
5023   bs->print_it = print_it_normal;
5024   return bs;
5025 }
5026 \f
5027 /* The target has stopped with waitstatus WS.  Check if any hardware
5028    watchpoints have triggered, according to the target.  */
5029
5030 int
5031 watchpoints_triggered (struct target_waitstatus *ws)
5032 {
5033   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
5034   CORE_ADDR addr;
5035   struct breakpoint *b;
5036
5037   if (!stopped_by_watchpoint)
5038     {
5039       /* We were not stopped by a watchpoint.  Mark all watchpoints
5040          as not triggered.  */
5041       ALL_BREAKPOINTS (b)
5042         if (is_hardware_watchpoint (b))
5043           {
5044             struct watchpoint *w = (struct watchpoint *) b;
5045
5046             w->watchpoint_triggered = watch_triggered_no;
5047           }
5048
5049       return 0;
5050     }
5051
5052   if (!target_stopped_data_address (&current_target, &addr))
5053     {
5054       /* We were stopped by a watchpoint, but we don't know where.
5055          Mark all watchpoints as unknown.  */
5056       ALL_BREAKPOINTS (b)
5057         if (is_hardware_watchpoint (b))
5058           {
5059             struct watchpoint *w = (struct watchpoint *) b;
5060
5061             w->watchpoint_triggered = watch_triggered_unknown;
5062           }
5063
5064       return 1;
5065     }
5066
5067   /* The target could report the data address.  Mark watchpoints
5068      affected by this data address as triggered, and all others as not
5069      triggered.  */
5070
5071   ALL_BREAKPOINTS (b)
5072     if (is_hardware_watchpoint (b))
5073       {
5074         struct watchpoint *w = (struct watchpoint *) b;
5075         struct bp_location *loc;
5076
5077         w->watchpoint_triggered = watch_triggered_no;
5078         for (loc = b->loc; loc; loc = loc->next)
5079           {
5080             if (is_masked_watchpoint (b))
5081               {
5082                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5083                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5084
5085                 if (newaddr == start)
5086                   {
5087                     w->watchpoint_triggered = watch_triggered_yes;
5088                     break;
5089                   }
5090               }
5091             /* Exact match not required.  Within range is sufficient.  */
5092             else if (target_watchpoint_addr_within_range (&current_target,
5093                                                          addr, loc->address,
5094                                                          loc->length))
5095               {
5096                 w->watchpoint_triggered = watch_triggered_yes;
5097                 break;
5098               }
5099           }
5100       }
5101
5102   return 1;
5103 }
5104
5105 /* Possible return values for watchpoint_check (this can't be an enum
5106    because of check_errors).  */
5107 /* The watchpoint has been deleted.  */
5108 #define WP_DELETED 1
5109 /* The value has changed.  */
5110 #define WP_VALUE_CHANGED 2
5111 /* The value has not changed.  */
5112 #define WP_VALUE_NOT_CHANGED 3
5113 /* Ignore this watchpoint, no matter if the value changed or not.  */
5114 #define WP_IGNORE 4
5115
5116 #define BP_TEMPFLAG 1
5117 #define BP_HARDWAREFLAG 2
5118
5119 /* Evaluate watchpoint condition expression and check if its value
5120    changed.
5121
5122    P should be a pointer to struct bpstat, but is defined as a void *
5123    in order for this function to be usable with catch_errors.  */
5124
5125 static int
5126 watchpoint_check (void *p)
5127 {
5128   bpstat bs = (bpstat) p;
5129   struct watchpoint *b;
5130   struct frame_info *fr;
5131   int within_current_scope;
5132
5133   /* BS is built from an existing struct breakpoint.  */
5134   gdb_assert (bs->breakpoint_at != NULL);
5135   b = (struct watchpoint *) bs->breakpoint_at;
5136
5137   /* If this is a local watchpoint, we only want to check if the
5138      watchpoint frame is in scope if the current thread is the thread
5139      that was used to create the watchpoint.  */
5140   if (!watchpoint_in_thread_scope (b))
5141     return WP_IGNORE;
5142
5143   if (b->exp_valid_block == NULL)
5144     within_current_scope = 1;
5145   else
5146     {
5147       struct frame_info *frame = get_current_frame ();
5148       struct gdbarch *frame_arch = get_frame_arch (frame);
5149       CORE_ADDR frame_pc = get_frame_pc (frame);
5150
5151       /* stack_frame_destroyed_p() returns a non-zero value if we're
5152          still in the function but the stack frame has already been
5153          invalidated.  Since we can't rely on the values of local
5154          variables after the stack has been destroyed, we are treating
5155          the watchpoint in that state as `not changed' without further
5156          checking.  Don't mark watchpoints as changed if the current
5157          frame is in an epilogue - even if they are in some other
5158          frame, our view of the stack is likely to be wrong and
5159          frame_find_by_id could error out.  */
5160       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5161         return WP_IGNORE;
5162
5163       fr = frame_find_by_id (b->watchpoint_frame);
5164       within_current_scope = (fr != NULL);
5165
5166       /* If we've gotten confused in the unwinder, we might have
5167          returned a frame that can't describe this variable.  */
5168       if (within_current_scope)
5169         {
5170           struct symbol *function;
5171
5172           function = get_frame_function (fr);
5173           if (function == NULL
5174               || !contained_in (b->exp_valid_block,
5175                                 SYMBOL_BLOCK_VALUE (function)))
5176             within_current_scope = 0;
5177         }
5178
5179       if (within_current_scope)
5180         /* If we end up stopping, the current frame will get selected
5181            in normal_stop.  So this call to select_frame won't affect
5182            the user.  */
5183         select_frame (fr);
5184     }
5185
5186   if (within_current_scope)
5187     {
5188       /* We use value_{,free_to_}mark because it could be a *long*
5189          time before we return to the command level and call
5190          free_all_values.  We can't call free_all_values because we
5191          might be in the middle of evaluating a function call.  */
5192
5193       int pc = 0;
5194       struct value *mark;
5195       struct value *new_val;
5196
5197       if (is_masked_watchpoint (&b->base))
5198         /* Since we don't know the exact trigger address (from
5199            stopped_data_address), just tell the user we've triggered
5200            a mask watchpoint.  */
5201         return WP_VALUE_CHANGED;
5202
5203       mark = value_mark ();
5204       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
5205
5206       if (b->val_bitsize != 0)
5207         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5208
5209       /* We use value_equal_contents instead of value_equal because
5210          the latter coerces an array to a pointer, thus comparing just
5211          the address of the array instead of its contents.  This is
5212          not what we want.  */
5213       if ((b->val != NULL) != (new_val != NULL)
5214           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5215         {
5216           if (new_val != NULL)
5217             {
5218               release_value (new_val);
5219               value_free_to_mark (mark);
5220             }
5221           bs->old_val = b->val;
5222           b->val = new_val;
5223           b->val_valid = 1;
5224           return WP_VALUE_CHANGED;
5225         }
5226       else
5227         {
5228           /* Nothing changed.  */
5229           value_free_to_mark (mark);
5230           return WP_VALUE_NOT_CHANGED;
5231         }
5232     }
5233   else
5234     {
5235       /* This seems like the only logical thing to do because
5236          if we temporarily ignored the watchpoint, then when
5237          we reenter the block in which it is valid it contains
5238          garbage (in the case of a function, it may have two
5239          garbage values, one before and one after the prologue).
5240          So we can't even detect the first assignment to it and
5241          watch after that (since the garbage may or may not equal
5242          the first value assigned).  */
5243       /* We print all the stop information in
5244          breakpoint_ops->print_it, but in this case, by the time we
5245          call breakpoint_ops->print_it this bp will be deleted
5246          already.  So we have no choice but print the information
5247          here.  */
5248
5249       SWITCH_THRU_ALL_UIS ()
5250         {
5251           struct ui_out *uiout = current_uiout;
5252
5253           if (uiout->is_mi_like_p ())
5254             uiout->field_string
5255               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5256           uiout->text ("\nWatchpoint ");
5257           uiout->field_int ("wpnum", b->base.number);
5258           uiout->text (" deleted because the program has left the block in\n"
5259                        "which its expression is valid.\n");
5260         }
5261
5262       /* Make sure the watchpoint's commands aren't executed.  */
5263       decref_counted_command_line (&b->base.commands);
5264       watchpoint_del_at_next_stop (b);
5265
5266       return WP_DELETED;
5267     }
5268 }
5269
5270 /* Return true if it looks like target has stopped due to hitting
5271    breakpoint location BL.  This function does not check if we should
5272    stop, only if BL explains the stop.  */
5273
5274 static int
5275 bpstat_check_location (const struct bp_location *bl,
5276                        struct address_space *aspace, CORE_ADDR bp_addr,
5277                        const struct target_waitstatus *ws)
5278 {
5279   struct breakpoint *b = bl->owner;
5280
5281   /* BL is from an existing breakpoint.  */
5282   gdb_assert (b != NULL);
5283
5284   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5285 }
5286
5287 /* Determine if the watched values have actually changed, and we
5288    should stop.  If not, set BS->stop to 0.  */
5289
5290 static void
5291 bpstat_check_watchpoint (bpstat bs)
5292 {
5293   const struct bp_location *bl;
5294   struct watchpoint *b;
5295
5296   /* BS is built for existing struct breakpoint.  */
5297   bl = bs->bp_location_at;
5298   gdb_assert (bl != NULL);
5299   b = (struct watchpoint *) bs->breakpoint_at;
5300   gdb_assert (b != NULL);
5301
5302     {
5303       int must_check_value = 0;
5304       
5305       if (b->base.type == bp_watchpoint)
5306         /* For a software watchpoint, we must always check the
5307            watched value.  */
5308         must_check_value = 1;
5309       else if (b->watchpoint_triggered == watch_triggered_yes)
5310         /* We have a hardware watchpoint (read, write, or access)
5311            and the target earlier reported an address watched by
5312            this watchpoint.  */
5313         must_check_value = 1;
5314       else if (b->watchpoint_triggered == watch_triggered_unknown
5315                && b->base.type == bp_hardware_watchpoint)
5316         /* We were stopped by a hardware watchpoint, but the target could
5317            not report the data address.  We must check the watchpoint's
5318            value.  Access and read watchpoints are out of luck; without
5319            a data address, we can't figure it out.  */
5320         must_check_value = 1;
5321
5322       if (must_check_value)
5323         {
5324           char *message
5325             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5326                           b->base.number);
5327           struct cleanup *cleanups = make_cleanup (xfree, message);
5328           int e = catch_errors (watchpoint_check, bs, message,
5329                                 RETURN_MASK_ALL);
5330           do_cleanups (cleanups);
5331           switch (e)
5332             {
5333             case WP_DELETED:
5334               /* We've already printed what needs to be printed.  */
5335               bs->print_it = print_it_done;
5336               /* Stop.  */
5337               break;
5338             case WP_IGNORE:
5339               bs->print_it = print_it_noop;
5340               bs->stop = 0;
5341               break;
5342             case WP_VALUE_CHANGED:
5343               if (b->base.type == bp_read_watchpoint)
5344                 {
5345                   /* There are two cases to consider here:
5346
5347                      1. We're watching the triggered memory for reads.
5348                      In that case, trust the target, and always report
5349                      the watchpoint hit to the user.  Even though
5350                      reads don't cause value changes, the value may
5351                      have changed since the last time it was read, and
5352                      since we're not trapping writes, we will not see
5353                      those, and as such we should ignore our notion of
5354                      old value.
5355
5356                      2. We're watching the triggered memory for both
5357                      reads and writes.  There are two ways this may
5358                      happen:
5359
5360                      2.1. This is a target that can't break on data
5361                      reads only, but can break on accesses (reads or
5362                      writes), such as e.g., x86.  We detect this case
5363                      at the time we try to insert read watchpoints.
5364
5365                      2.2. Otherwise, the target supports read
5366                      watchpoints, but, the user set an access or write
5367                      watchpoint watching the same memory as this read
5368                      watchpoint.
5369
5370                      If we're watching memory writes as well as reads,
5371                      ignore watchpoint hits when we find that the
5372                      value hasn't changed, as reads don't cause
5373                      changes.  This still gives false positives when
5374                      the program writes the same value to memory as
5375                      what there was already in memory (we will confuse
5376                      it for a read), but it's much better than
5377                      nothing.  */
5378
5379                   int other_write_watchpoint = 0;
5380
5381                   if (bl->watchpoint_type == hw_read)
5382                     {
5383                       struct breakpoint *other_b;
5384
5385                       ALL_BREAKPOINTS (other_b)
5386                         if (other_b->type == bp_hardware_watchpoint
5387                             || other_b->type == bp_access_watchpoint)
5388                           {
5389                             struct watchpoint *other_w =
5390                               (struct watchpoint *) other_b;
5391
5392                             if (other_w->watchpoint_triggered
5393                                 == watch_triggered_yes)
5394                               {
5395                                 other_write_watchpoint = 1;
5396                                 break;
5397                               }
5398                           }
5399                     }
5400
5401                   if (other_write_watchpoint
5402                       || bl->watchpoint_type == hw_access)
5403                     {
5404                       /* We're watching the same memory for writes,
5405                          and the value changed since the last time we
5406                          updated it, so this trap must be for a write.
5407                          Ignore it.  */
5408                       bs->print_it = print_it_noop;
5409                       bs->stop = 0;
5410                     }
5411                 }
5412               break;
5413             case WP_VALUE_NOT_CHANGED:
5414               if (b->base.type == bp_hardware_watchpoint
5415                   || b->base.type == bp_watchpoint)
5416                 {
5417                   /* Don't stop: write watchpoints shouldn't fire if
5418                      the value hasn't changed.  */
5419                   bs->print_it = print_it_noop;
5420                   bs->stop = 0;
5421                 }
5422               /* Stop.  */
5423               break;
5424             default:
5425               /* Can't happen.  */
5426             case 0:
5427               /* Error from catch_errors.  */
5428               {
5429                 SWITCH_THRU_ALL_UIS ()
5430                   {
5431                     printf_filtered (_("Watchpoint %d deleted.\n"),
5432                                      b->base.number);
5433                   }
5434                 watchpoint_del_at_next_stop (b);
5435                 /* We've already printed what needs to be printed.  */
5436                 bs->print_it = print_it_done;
5437               }
5438               break;
5439             }
5440         }
5441       else      /* must_check_value == 0 */
5442         {
5443           /* This is a case where some watchpoint(s) triggered, but
5444              not at the address of this watchpoint, or else no
5445              watchpoint triggered after all.  So don't print
5446              anything for this watchpoint.  */
5447           bs->print_it = print_it_noop;
5448           bs->stop = 0;
5449         }
5450     }
5451 }
5452
5453 /* For breakpoints that are currently marked as telling gdb to stop,
5454    check conditions (condition proper, frame, thread and ignore count)
5455    of breakpoint referred to by BS.  If we should not stop for this
5456    breakpoint, set BS->stop to 0.  */
5457
5458 static void
5459 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5460 {
5461   const struct bp_location *bl;
5462   struct breakpoint *b;
5463   int value_is_zero = 0;
5464   struct expression *cond;
5465
5466   gdb_assert (bs->stop);
5467
5468   /* BS is built for existing struct breakpoint.  */
5469   bl = bs->bp_location_at;
5470   gdb_assert (bl != NULL);
5471   b = bs->breakpoint_at;
5472   gdb_assert (b != NULL);
5473
5474   /* Even if the target evaluated the condition on its end and notified GDB, we
5475      need to do so again since GDB does not know if we stopped due to a
5476      breakpoint or a single step breakpoint.  */
5477
5478   if (frame_id_p (b->frame_id)
5479       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5480     {
5481       bs->stop = 0;
5482       return;
5483     }
5484
5485   /* If this is a thread/task-specific breakpoint, don't waste cpu
5486      evaluating the condition if this isn't the specified
5487      thread/task.  */
5488   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5489       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5490
5491     {
5492       bs->stop = 0;
5493       return;
5494     }
5495
5496   /* Evaluate extension language breakpoints that have a "stop" method
5497      implemented.  */
5498   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5499
5500   if (is_watchpoint (b))
5501     {
5502       struct watchpoint *w = (struct watchpoint *) b;
5503
5504       cond = w->cond_exp.get ();
5505     }
5506   else
5507     cond = bl->cond.get ();
5508
5509   if (cond && b->disposition != disp_del_at_next_stop)
5510     {
5511       int within_current_scope = 1;
5512       struct watchpoint * w;
5513
5514       /* We use value_mark and value_free_to_mark because it could
5515          be a long time before we return to the command level and
5516          call free_all_values.  We can't call free_all_values
5517          because we might be in the middle of evaluating a
5518          function call.  */
5519       struct value *mark = value_mark ();
5520
5521       if (is_watchpoint (b))
5522         w = (struct watchpoint *) b;
5523       else
5524         w = NULL;
5525
5526       /* Need to select the frame, with all that implies so that
5527          the conditions will have the right context.  Because we
5528          use the frame, we will not see an inlined function's
5529          variables when we arrive at a breakpoint at the start
5530          of the inlined function; the current frame will be the
5531          call site.  */
5532       if (w == NULL || w->cond_exp_valid_block == NULL)
5533         select_frame (get_current_frame ());
5534       else
5535         {
5536           struct frame_info *frame;
5537
5538           /* For local watchpoint expressions, which particular
5539              instance of a local is being watched matters, so we
5540              keep track of the frame to evaluate the expression
5541              in.  To evaluate the condition however, it doesn't
5542              really matter which instantiation of the function
5543              where the condition makes sense triggers the
5544              watchpoint.  This allows an expression like "watch
5545              global if q > 10" set in `func', catch writes to
5546              global on all threads that call `func', or catch
5547              writes on all recursive calls of `func' by a single
5548              thread.  We simply always evaluate the condition in
5549              the innermost frame that's executing where it makes
5550              sense to evaluate the condition.  It seems
5551              intuitive.  */
5552           frame = block_innermost_frame (w->cond_exp_valid_block);
5553           if (frame != NULL)
5554             select_frame (frame);
5555           else
5556             within_current_scope = 0;
5557         }
5558       if (within_current_scope)
5559         value_is_zero
5560           = catch_errors (breakpoint_cond_eval, cond,
5561                           "Error in testing breakpoint condition:\n",
5562                           RETURN_MASK_ALL);
5563       else
5564         {
5565           warning (_("Watchpoint condition cannot be tested "
5566                      "in the current scope"));
5567           /* If we failed to set the right context for this
5568              watchpoint, unconditionally report it.  */
5569           value_is_zero = 0;
5570         }
5571       /* FIXME-someday, should give breakpoint #.  */
5572       value_free_to_mark (mark);
5573     }
5574
5575   if (cond && value_is_zero)
5576     {
5577       bs->stop = 0;
5578     }
5579   else if (b->ignore_count > 0)
5580     {
5581       b->ignore_count--;
5582       bs->stop = 0;
5583       /* Increase the hit count even though we don't stop.  */
5584       ++(b->hit_count);
5585       observer_notify_breakpoint_modified (b);
5586     }   
5587 }
5588
5589 /* Returns true if we need to track moribund locations of LOC's type
5590    on the current target.  */
5591
5592 static int
5593 need_moribund_for_location_type (struct bp_location *loc)
5594 {
5595   return ((loc->loc_type == bp_loc_software_breakpoint
5596            && !target_supports_stopped_by_sw_breakpoint ())
5597           || (loc->loc_type == bp_loc_hardware_breakpoint
5598               && !target_supports_stopped_by_hw_breakpoint ()));
5599 }
5600
5601
5602 /* Get a bpstat associated with having just stopped at address
5603    BP_ADDR in thread PTID.
5604
5605    Determine whether we stopped at a breakpoint, etc, or whether we
5606    don't understand this stop.  Result is a chain of bpstat's such
5607    that:
5608
5609    if we don't understand the stop, the result is a null pointer.
5610
5611    if we understand why we stopped, the result is not null.
5612
5613    Each element of the chain refers to a particular breakpoint or
5614    watchpoint at which we have stopped.  (We may have stopped for
5615    several reasons concurrently.)
5616
5617    Each element of the chain has valid next, breakpoint_at,
5618    commands, FIXME??? fields.  */
5619
5620 bpstat
5621 bpstat_stop_status (struct address_space *aspace,
5622                     CORE_ADDR bp_addr, ptid_t ptid,
5623                     const struct target_waitstatus *ws)
5624 {
5625   struct breakpoint *b = NULL;
5626   struct bp_location *bl;
5627   struct bp_location *loc;
5628   /* First item of allocated bpstat's.  */
5629   bpstat bs_head = NULL, *bs_link = &bs_head;
5630   /* Pointer to the last thing in the chain currently.  */
5631   bpstat bs;
5632   int ix;
5633   int need_remove_insert;
5634   int removed_any;
5635
5636   /* First, build the bpstat chain with locations that explain a
5637      target stop, while being careful to not set the target running,
5638      as that may invalidate locations (in particular watchpoint
5639      locations are recreated).  Resuming will happen here with
5640      breakpoint conditions or watchpoint expressions that include
5641      inferior function calls.  */
5642
5643   ALL_BREAKPOINTS (b)
5644     {
5645       if (!breakpoint_enabled (b))
5646         continue;
5647
5648       for (bl = b->loc; bl != NULL; bl = bl->next)
5649         {
5650           /* For hardware watchpoints, we look only at the first
5651              location.  The watchpoint_check function will work on the
5652              entire expression, not the individual locations.  For
5653              read watchpoints, the watchpoints_triggered function has
5654              checked all locations already.  */
5655           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5656             break;
5657
5658           if (!bl->enabled || bl->shlib_disabled)
5659             continue;
5660
5661           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5662             continue;
5663
5664           /* Come here if it's a watchpoint, or if the break address
5665              matches.  */
5666
5667           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5668                                                    explain stop.  */
5669
5670           /* Assume we stop.  Should we find a watchpoint that is not
5671              actually triggered, or if the condition of the breakpoint
5672              evaluates as false, we'll reset 'stop' to 0.  */
5673           bs->stop = 1;
5674           bs->print = 1;
5675
5676           /* If this is a scope breakpoint, mark the associated
5677              watchpoint as triggered so that we will handle the
5678              out-of-scope event.  We'll get to the watchpoint next
5679              iteration.  */
5680           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5681             {
5682               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5683
5684               w->watchpoint_triggered = watch_triggered_yes;
5685             }
5686         }
5687     }
5688
5689   /* Check if a moribund breakpoint explains the stop.  */
5690   if (!target_supports_stopped_by_sw_breakpoint ()
5691       || !target_supports_stopped_by_hw_breakpoint ())
5692     {
5693       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5694         {
5695           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5696               && need_moribund_for_location_type (loc))
5697             {
5698               bs = bpstat_alloc (loc, &bs_link);
5699               /* For hits of moribund locations, we should just proceed.  */
5700               bs->stop = 0;
5701               bs->print = 0;
5702               bs->print_it = print_it_noop;
5703             }
5704         }
5705     }
5706
5707   /* A bit of special processing for shlib breakpoints.  We need to
5708      process solib loading here, so that the lists of loaded and
5709      unloaded libraries are correct before we handle "catch load" and
5710      "catch unload".  */
5711   for (bs = bs_head; bs != NULL; bs = bs->next)
5712     {
5713       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5714         {
5715           handle_solib_event ();
5716           break;
5717         }
5718     }
5719
5720   /* Now go through the locations that caused the target to stop, and
5721      check whether we're interested in reporting this stop to higher
5722      layers, or whether we should resume the target transparently.  */
5723
5724   removed_any = 0;
5725
5726   for (bs = bs_head; bs != NULL; bs = bs->next)
5727     {
5728       if (!bs->stop)
5729         continue;
5730
5731       b = bs->breakpoint_at;
5732       b->ops->check_status (bs);
5733       if (bs->stop)
5734         {
5735           bpstat_check_breakpoint_conditions (bs, ptid);
5736
5737           if (bs->stop)
5738             {
5739               ++(b->hit_count);
5740               observer_notify_breakpoint_modified (b);
5741
5742               /* We will stop here.  */
5743               if (b->disposition == disp_disable)
5744                 {
5745                   --(b->enable_count);
5746                   if (b->enable_count <= 0)
5747                     b->enable_state = bp_disabled;
5748                   removed_any = 1;
5749                 }
5750               if (b->silent)
5751                 bs->print = 0;
5752               bs->commands = b->commands;
5753               incref_counted_command_line (bs->commands);
5754               if (command_line_is_silent (bs->commands
5755                                           ? bs->commands->commands : NULL))
5756                 bs->print = 0;
5757
5758               b->ops->after_condition_true (bs);
5759             }
5760
5761         }
5762
5763       /* Print nothing for this entry if we don't stop or don't
5764          print.  */
5765       if (!bs->stop || !bs->print)
5766         bs->print_it = print_it_noop;
5767     }
5768
5769   /* If we aren't stopping, the value of some hardware watchpoint may
5770      not have changed, but the intermediate memory locations we are
5771      watching may have.  Don't bother if we're stopping; this will get
5772      done later.  */
5773   need_remove_insert = 0;
5774   if (! bpstat_causes_stop (bs_head))
5775     for (bs = bs_head; bs != NULL; bs = bs->next)
5776       if (!bs->stop
5777           && bs->breakpoint_at
5778           && is_hardware_watchpoint (bs->breakpoint_at))
5779         {
5780           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5781
5782           update_watchpoint (w, 0 /* don't reparse.  */);
5783           need_remove_insert = 1;
5784         }
5785
5786   if (need_remove_insert)
5787     update_global_location_list (UGLL_MAY_INSERT);
5788   else if (removed_any)
5789     update_global_location_list (UGLL_DONT_INSERT);
5790
5791   return bs_head;
5792 }
5793
5794 static void
5795 handle_jit_event (void)
5796 {
5797   struct frame_info *frame;
5798   struct gdbarch *gdbarch;
5799
5800   if (debug_infrun)
5801     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5802
5803   /* Switch terminal for any messages produced by
5804      breakpoint_re_set.  */
5805   target_terminal_ours_for_output ();
5806
5807   frame = get_current_frame ();
5808   gdbarch = get_frame_arch (frame);
5809
5810   jit_event_handler (gdbarch);
5811
5812   target_terminal_inferior ();
5813 }
5814
5815 /* Prepare WHAT final decision for infrun.  */
5816
5817 /* Decide what infrun needs to do with this bpstat.  */
5818
5819 struct bpstat_what
5820 bpstat_what (bpstat bs_head)
5821 {
5822   struct bpstat_what retval;
5823   bpstat bs;
5824
5825   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5826   retval.call_dummy = STOP_NONE;
5827   retval.is_longjmp = 0;
5828
5829   for (bs = bs_head; bs != NULL; bs = bs->next)
5830     {
5831       /* Extract this BS's action.  After processing each BS, we check
5832          if its action overrides all we've seem so far.  */
5833       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5834       enum bptype bptype;
5835
5836       if (bs->breakpoint_at == NULL)
5837         {
5838           /* I suspect this can happen if it was a momentary
5839              breakpoint which has since been deleted.  */
5840           bptype = bp_none;
5841         }
5842       else
5843         bptype = bs->breakpoint_at->type;
5844
5845       switch (bptype)
5846         {
5847         case bp_none:
5848           break;
5849         case bp_breakpoint:
5850         case bp_hardware_breakpoint:
5851         case bp_single_step:
5852         case bp_until:
5853         case bp_finish:
5854         case bp_shlib_event:
5855           if (bs->stop)
5856             {
5857               if (bs->print)
5858                 this_action = BPSTAT_WHAT_STOP_NOISY;
5859               else
5860                 this_action = BPSTAT_WHAT_STOP_SILENT;
5861             }
5862           else
5863             this_action = BPSTAT_WHAT_SINGLE;
5864           break;
5865         case bp_watchpoint:
5866         case bp_hardware_watchpoint:
5867         case bp_read_watchpoint:
5868         case bp_access_watchpoint:
5869           if (bs->stop)
5870             {
5871               if (bs->print)
5872                 this_action = BPSTAT_WHAT_STOP_NOISY;
5873               else
5874                 this_action = BPSTAT_WHAT_STOP_SILENT;
5875             }
5876           else
5877             {
5878               /* There was a watchpoint, but we're not stopping.
5879                  This requires no further action.  */
5880             }
5881           break;
5882         case bp_longjmp:
5883         case bp_longjmp_call_dummy:
5884         case bp_exception:
5885           if (bs->stop)
5886             {
5887               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5888               retval.is_longjmp = bptype != bp_exception;
5889             }
5890           else
5891             this_action = BPSTAT_WHAT_SINGLE;
5892           break;
5893         case bp_longjmp_resume:
5894         case bp_exception_resume:
5895           if (bs->stop)
5896             {
5897               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5898               retval.is_longjmp = bptype == bp_longjmp_resume;
5899             }
5900           else
5901             this_action = BPSTAT_WHAT_SINGLE;
5902           break;
5903         case bp_step_resume:
5904           if (bs->stop)
5905             this_action = BPSTAT_WHAT_STEP_RESUME;
5906           else
5907             {
5908               /* It is for the wrong frame.  */
5909               this_action = BPSTAT_WHAT_SINGLE;
5910             }
5911           break;
5912         case bp_hp_step_resume:
5913           if (bs->stop)
5914             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5915           else
5916             {
5917               /* It is for the wrong frame.  */
5918               this_action = BPSTAT_WHAT_SINGLE;
5919             }
5920           break;
5921         case bp_watchpoint_scope:
5922         case bp_thread_event:
5923         case bp_overlay_event:
5924         case bp_longjmp_master:
5925         case bp_std_terminate_master:
5926         case bp_exception_master:
5927           this_action = BPSTAT_WHAT_SINGLE;
5928           break;
5929         case bp_catchpoint:
5930           if (bs->stop)
5931             {
5932               if (bs->print)
5933                 this_action = BPSTAT_WHAT_STOP_NOISY;
5934               else
5935                 this_action = BPSTAT_WHAT_STOP_SILENT;
5936             }
5937           else
5938             {
5939               /* There was a catchpoint, but we're not stopping.
5940                  This requires no further action.  */
5941             }
5942           break;
5943         case bp_jit_event:
5944           this_action = BPSTAT_WHAT_SINGLE;
5945           break;
5946         case bp_call_dummy:
5947           /* Make sure the action is stop (silent or noisy),
5948              so infrun.c pops the dummy frame.  */
5949           retval.call_dummy = STOP_STACK_DUMMY;
5950           this_action = BPSTAT_WHAT_STOP_SILENT;
5951           break;
5952         case bp_std_terminate:
5953           /* Make sure the action is stop (silent or noisy),
5954              so infrun.c pops the dummy frame.  */
5955           retval.call_dummy = STOP_STD_TERMINATE;
5956           this_action = BPSTAT_WHAT_STOP_SILENT;
5957           break;
5958         case bp_tracepoint:
5959         case bp_fast_tracepoint:
5960         case bp_static_tracepoint:
5961           /* Tracepoint hits should not be reported back to GDB, and
5962              if one got through somehow, it should have been filtered
5963              out already.  */
5964           internal_error (__FILE__, __LINE__,
5965                           _("bpstat_what: tracepoint encountered"));
5966           break;
5967         case bp_gnu_ifunc_resolver:
5968           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5969           this_action = BPSTAT_WHAT_SINGLE;
5970           break;
5971         case bp_gnu_ifunc_resolver_return:
5972           /* The breakpoint will be removed, execution will restart from the
5973              PC of the former breakpoint.  */
5974           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5975           break;
5976
5977         case bp_dprintf:
5978           if (bs->stop)
5979             this_action = BPSTAT_WHAT_STOP_SILENT;
5980           else
5981             this_action = BPSTAT_WHAT_SINGLE;
5982           break;
5983
5984         default:
5985           internal_error (__FILE__, __LINE__,
5986                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5987         }
5988
5989       retval.main_action = std::max (retval.main_action, this_action);
5990     }
5991
5992   return retval;
5993 }
5994
5995 void
5996 bpstat_run_callbacks (bpstat bs_head)
5997 {
5998   bpstat bs;
5999
6000   for (bs = bs_head; bs != NULL; bs = bs->next)
6001     {
6002       struct breakpoint *b = bs->breakpoint_at;
6003
6004       if (b == NULL)
6005         continue;
6006       switch (b->type)
6007         {
6008         case bp_jit_event:
6009           handle_jit_event ();
6010           break;
6011         case bp_gnu_ifunc_resolver:
6012           gnu_ifunc_resolver_stop (b);
6013           break;
6014         case bp_gnu_ifunc_resolver_return:
6015           gnu_ifunc_resolver_return_stop (b);
6016           break;
6017         }
6018     }
6019 }
6020
6021 /* Nonzero if we should step constantly (e.g. watchpoints on machines
6022    without hardware support).  This isn't related to a specific bpstat,
6023    just to things like whether watchpoints are set.  */
6024
6025 int
6026 bpstat_should_step (void)
6027 {
6028   struct breakpoint *b;
6029
6030   ALL_BREAKPOINTS (b)
6031     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6032       return 1;
6033   return 0;
6034 }
6035
6036 int
6037 bpstat_causes_stop (bpstat bs)
6038 {
6039   for (; bs != NULL; bs = bs->next)
6040     if (bs->stop)
6041       return 1;
6042
6043   return 0;
6044 }
6045
6046 \f
6047
6048 /* Compute a string of spaces suitable to indent the next line
6049    so it starts at the position corresponding to the table column
6050    named COL_NAME in the currently active table of UIOUT.  */
6051
6052 static char *
6053 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6054 {
6055   static char wrap_indent[80];
6056   int i, total_width, width, align;
6057   const char *text;
6058
6059   total_width = 0;
6060   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6061     {
6062       if (strcmp (text, col_name) == 0)
6063         {
6064           gdb_assert (total_width < sizeof wrap_indent);
6065           memset (wrap_indent, ' ', total_width);
6066           wrap_indent[total_width] = 0;
6067
6068           return wrap_indent;
6069         }
6070
6071       total_width += width + 1;
6072     }
6073
6074   return NULL;
6075 }
6076
6077 /* Determine if the locations of this breakpoint will have their conditions
6078    evaluated by the target, host or a mix of both.  Returns the following:
6079
6080     "host": Host evals condition.
6081     "host or target": Host or Target evals condition.
6082     "target": Target evals condition.
6083 */
6084
6085 static const char *
6086 bp_condition_evaluator (struct breakpoint *b)
6087 {
6088   struct bp_location *bl;
6089   char host_evals = 0;
6090   char target_evals = 0;
6091
6092   if (!b)
6093     return NULL;
6094
6095   if (!is_breakpoint (b))
6096     return NULL;
6097
6098   if (gdb_evaluates_breakpoint_condition_p ()
6099       || !target_supports_evaluation_of_breakpoint_conditions ())
6100     return condition_evaluation_host;
6101
6102   for (bl = b->loc; bl; bl = bl->next)
6103     {
6104       if (bl->cond_bytecode)
6105         target_evals++;
6106       else
6107         host_evals++;
6108     }
6109
6110   if (host_evals && target_evals)
6111     return condition_evaluation_both;
6112   else if (target_evals)
6113     return condition_evaluation_target;
6114   else
6115     return condition_evaluation_host;
6116 }
6117
6118 /* Determine the breakpoint location's condition evaluator.  This is
6119    similar to bp_condition_evaluator, but for locations.  */
6120
6121 static const char *
6122 bp_location_condition_evaluator (struct bp_location *bl)
6123 {
6124   if (bl && !is_breakpoint (bl->owner))
6125     return NULL;
6126
6127   if (gdb_evaluates_breakpoint_condition_p ()
6128       || !target_supports_evaluation_of_breakpoint_conditions ())
6129     return condition_evaluation_host;
6130
6131   if (bl && bl->cond_bytecode)
6132     return condition_evaluation_target;
6133   else
6134     return condition_evaluation_host;
6135 }
6136
6137 /* Print the LOC location out of the list of B->LOC locations.  */
6138
6139 static void
6140 print_breakpoint_location (struct breakpoint *b,
6141                            struct bp_location *loc)
6142 {
6143   struct ui_out *uiout = current_uiout;
6144   struct cleanup *old_chain = save_current_program_space ();
6145
6146   if (loc != NULL && loc->shlib_disabled)
6147     loc = NULL;
6148
6149   if (loc != NULL)
6150     set_current_program_space (loc->pspace);
6151
6152   if (b->display_canonical)
6153     uiout->field_string ("what", event_location_to_string (b->location));
6154   else if (loc && loc->symtab)
6155     {
6156       struct symbol *sym 
6157         = find_pc_sect_function (loc->address, loc->section);
6158       if (sym)
6159         {
6160           uiout->text ("in ");
6161           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
6162           uiout->text (" ");
6163           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6164           uiout->text ("at ");
6165         }
6166       uiout->field_string ("file",
6167                            symtab_to_filename_for_display (loc->symtab));
6168       uiout->text (":");
6169
6170       if (uiout->is_mi_like_p ())
6171         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6172       
6173       uiout->field_int ("line", loc->line_number);
6174     }
6175   else if (loc)
6176     {
6177       string_file stb;
6178
6179       print_address_symbolic (loc->gdbarch, loc->address, &stb,
6180                               demangle, "");
6181       uiout->field_stream ("at", stb);
6182     }
6183   else
6184     {
6185       uiout->field_string ("pending", event_location_to_string (b->location));
6186       /* If extra_string is available, it could be holding a condition
6187          or dprintf arguments.  In either case, make sure it is printed,
6188          too, but only for non-MI streams.  */
6189       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6190         {
6191           if (b->type == bp_dprintf)
6192             uiout->text (",");
6193           else
6194             uiout->text (" ");
6195           uiout->text (b->extra_string);
6196         }
6197     }
6198
6199   if (loc && is_breakpoint (b)
6200       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6201       && bp_condition_evaluator (b) == condition_evaluation_both)
6202     {
6203       uiout->text (" (");
6204       uiout->field_string ("evaluated-by",
6205                            bp_location_condition_evaluator (loc));
6206       uiout->text (")");
6207     }
6208
6209   do_cleanups (old_chain);
6210 }
6211
6212 static const char *
6213 bptype_string (enum bptype type)
6214 {
6215   struct ep_type_description
6216     {
6217       enum bptype type;
6218       char *description;
6219     };
6220   static struct ep_type_description bptypes[] =
6221   {
6222     {bp_none, "?deleted?"},
6223     {bp_breakpoint, "breakpoint"},
6224     {bp_hardware_breakpoint, "hw breakpoint"},
6225     {bp_single_step, "sw single-step"},
6226     {bp_until, "until"},
6227     {bp_finish, "finish"},
6228     {bp_watchpoint, "watchpoint"},
6229     {bp_hardware_watchpoint, "hw watchpoint"},
6230     {bp_read_watchpoint, "read watchpoint"},
6231     {bp_access_watchpoint, "acc watchpoint"},
6232     {bp_longjmp, "longjmp"},
6233     {bp_longjmp_resume, "longjmp resume"},
6234     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6235     {bp_exception, "exception"},
6236     {bp_exception_resume, "exception resume"},
6237     {bp_step_resume, "step resume"},
6238     {bp_hp_step_resume, "high-priority step resume"},
6239     {bp_watchpoint_scope, "watchpoint scope"},
6240     {bp_call_dummy, "call dummy"},
6241     {bp_std_terminate, "std::terminate"},
6242     {bp_shlib_event, "shlib events"},
6243     {bp_thread_event, "thread events"},
6244     {bp_overlay_event, "overlay events"},
6245     {bp_longjmp_master, "longjmp master"},
6246     {bp_std_terminate_master, "std::terminate master"},
6247     {bp_exception_master, "exception master"},
6248     {bp_catchpoint, "catchpoint"},
6249     {bp_tracepoint, "tracepoint"},
6250     {bp_fast_tracepoint, "fast tracepoint"},
6251     {bp_static_tracepoint, "static tracepoint"},
6252     {bp_dprintf, "dprintf"},
6253     {bp_jit_event, "jit events"},
6254     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6255     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6256   };
6257
6258   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6259       || ((int) type != bptypes[(int) type].type))
6260     internal_error (__FILE__, __LINE__,
6261                     _("bptypes table does not describe type #%d."),
6262                     (int) type);
6263
6264   return bptypes[(int) type].description;
6265 }
6266
6267 /* For MI, output a field named 'thread-groups' with a list as the value.
6268    For CLI, prefix the list with the string 'inf'. */
6269
6270 static void
6271 output_thread_groups (struct ui_out *uiout,
6272                       const char *field_name,
6273                       VEC(int) *inf_num,
6274                       int mi_only)
6275 {
6276   struct cleanup *back_to;
6277   int is_mi = uiout->is_mi_like_p ();
6278   int inf;
6279   int i;
6280
6281   /* For backward compatibility, don't display inferiors in CLI unless
6282      there are several.  Always display them for MI. */
6283   if (!is_mi && mi_only)
6284     return;
6285
6286   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6287
6288   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6289     {
6290       if (is_mi)
6291         {
6292           char mi_group[10];
6293
6294           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6295           uiout->field_string (NULL, mi_group);
6296         }
6297       else
6298         {
6299           if (i == 0)
6300             uiout->text (" inf ");
6301           else
6302             uiout->text (", ");
6303         
6304           uiout->text (plongest (inf));
6305         }
6306     }
6307
6308   do_cleanups (back_to);
6309 }
6310
6311 /* Print B to gdb_stdout.  */
6312
6313 static void
6314 print_one_breakpoint_location (struct breakpoint *b,
6315                                struct bp_location *loc,
6316                                int loc_number,
6317                                struct bp_location **last_loc,
6318                                int allflag)
6319 {
6320   struct command_line *l;
6321   static char bpenables[] = "nynny";
6322
6323   struct ui_out *uiout = current_uiout;
6324   int header_of_multiple = 0;
6325   int part_of_multiple = (loc != NULL);
6326   struct value_print_options opts;
6327
6328   get_user_print_options (&opts);
6329
6330   gdb_assert (!loc || loc_number != 0);
6331   /* See comment in print_one_breakpoint concerning treatment of
6332      breakpoints with single disabled location.  */
6333   if (loc == NULL 
6334       && (b->loc != NULL 
6335           && (b->loc->next != NULL || !b->loc->enabled)))
6336     header_of_multiple = 1;
6337   if (loc == NULL)
6338     loc = b->loc;
6339
6340   annotate_record ();
6341
6342   /* 1 */
6343   annotate_field (0);
6344   if (part_of_multiple)
6345     {
6346       char *formatted;
6347       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6348       uiout->field_string ("number", formatted);
6349       xfree (formatted);
6350     }
6351   else
6352     {
6353       uiout->field_int ("number", b->number);
6354     }
6355
6356   /* 2 */
6357   annotate_field (1);
6358   if (part_of_multiple)
6359     uiout->field_skip ("type");
6360   else
6361     uiout->field_string ("type", bptype_string (b->type));
6362
6363   /* 3 */
6364   annotate_field (2);
6365   if (part_of_multiple)
6366     uiout->field_skip ("disp");
6367   else
6368     uiout->field_string ("disp", bpdisp_text (b->disposition));
6369
6370
6371   /* 4 */
6372   annotate_field (3);
6373   if (part_of_multiple)
6374     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6375   else
6376     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6377   uiout->spaces (2);
6378
6379   
6380   /* 5 and 6 */
6381   if (b->ops != NULL && b->ops->print_one != NULL)
6382     {
6383       /* Although the print_one can possibly print all locations,
6384          calling it here is not likely to get any nice result.  So,
6385          make sure there's just one location.  */
6386       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6387       b->ops->print_one (b, last_loc);
6388     }
6389   else
6390     switch (b->type)
6391       {
6392       case bp_none:
6393         internal_error (__FILE__, __LINE__,
6394                         _("print_one_breakpoint: bp_none encountered\n"));
6395         break;
6396
6397       case bp_watchpoint:
6398       case bp_hardware_watchpoint:
6399       case bp_read_watchpoint:
6400       case bp_access_watchpoint:
6401         {
6402           struct watchpoint *w = (struct watchpoint *) b;
6403
6404           /* Field 4, the address, is omitted (which makes the columns
6405              not line up too nicely with the headers, but the effect
6406              is relatively readable).  */
6407           if (opts.addressprint)
6408             uiout->field_skip ("addr");
6409           annotate_field (5);
6410           uiout->field_string ("what", w->exp_string);
6411         }
6412         break;
6413
6414       case bp_breakpoint:
6415       case bp_hardware_breakpoint:
6416       case bp_single_step:
6417       case bp_until:
6418       case bp_finish:
6419       case bp_longjmp:
6420       case bp_longjmp_resume:
6421       case bp_longjmp_call_dummy:
6422       case bp_exception:
6423       case bp_exception_resume:
6424       case bp_step_resume:
6425       case bp_hp_step_resume:
6426       case bp_watchpoint_scope:
6427       case bp_call_dummy:
6428       case bp_std_terminate:
6429       case bp_shlib_event:
6430       case bp_thread_event:
6431       case bp_overlay_event:
6432       case bp_longjmp_master:
6433       case bp_std_terminate_master:
6434       case bp_exception_master:
6435       case bp_tracepoint:
6436       case bp_fast_tracepoint:
6437       case bp_static_tracepoint:
6438       case bp_dprintf:
6439       case bp_jit_event:
6440       case bp_gnu_ifunc_resolver:
6441       case bp_gnu_ifunc_resolver_return:
6442         if (opts.addressprint)
6443           {
6444             annotate_field (4);
6445             if (header_of_multiple)
6446               uiout->field_string ("addr", "<MULTIPLE>");
6447             else if (b->loc == NULL || loc->shlib_disabled)
6448               uiout->field_string ("addr", "<PENDING>");
6449             else
6450               uiout->field_core_addr ("addr",
6451                                       loc->gdbarch, loc->address);
6452           }
6453         annotate_field (5);
6454         if (!header_of_multiple)
6455           print_breakpoint_location (b, loc);
6456         if (b->loc)
6457           *last_loc = b->loc;
6458         break;
6459       }
6460
6461
6462   if (loc != NULL && !header_of_multiple)
6463     {
6464       struct inferior *inf;
6465       VEC(int) *inf_num = NULL;
6466       int mi_only = 1;
6467
6468       ALL_INFERIORS (inf)
6469         {
6470           if (inf->pspace == loc->pspace)
6471             VEC_safe_push (int, inf_num, inf->num);
6472         }
6473
6474         /* For backward compatibility, don't display inferiors in CLI unless
6475            there are several.  Always display for MI. */
6476         if (allflag
6477             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6478                 && (number_of_program_spaces () > 1
6479                     || number_of_inferiors () > 1)
6480                 /* LOC is for existing B, it cannot be in
6481                    moribund_locations and thus having NULL OWNER.  */
6482                 && loc->owner->type != bp_catchpoint))
6483         mi_only = 0;
6484       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6485       VEC_free (int, inf_num);
6486     }
6487
6488   if (!part_of_multiple)
6489     {
6490       if (b->thread != -1)
6491         {
6492           /* FIXME: This seems to be redundant and lost here; see the
6493              "stop only in" line a little further down.  */
6494           uiout->text (" thread ");
6495           uiout->field_int ("thread", b->thread);
6496         }
6497       else if (b->task != 0)
6498         {
6499           uiout->text (" task ");
6500           uiout->field_int ("task", b->task);
6501         }
6502     }
6503
6504   uiout->text ("\n");
6505
6506   if (!part_of_multiple)
6507     b->ops->print_one_detail (b, uiout);
6508
6509   if (part_of_multiple && frame_id_p (b->frame_id))
6510     {
6511       annotate_field (6);
6512       uiout->text ("\tstop only in stack frame at ");
6513       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6514          the frame ID.  */
6515       uiout->field_core_addr ("frame",
6516                               b->gdbarch, b->frame_id.stack_addr);
6517       uiout->text ("\n");
6518     }
6519   
6520   if (!part_of_multiple && b->cond_string)
6521     {
6522       annotate_field (7);
6523       if (is_tracepoint (b))
6524         uiout->text ("\ttrace only if ");
6525       else
6526         uiout->text ("\tstop only if ");
6527       uiout->field_string ("cond", b->cond_string);
6528
6529       /* Print whether the target is doing the breakpoint's condition
6530          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6531       if (is_breakpoint (b)
6532           && breakpoint_condition_evaluation_mode ()
6533           == condition_evaluation_target)
6534         {
6535           uiout->text (" (");
6536           uiout->field_string ("evaluated-by",
6537                                bp_condition_evaluator (b));
6538           uiout->text (" evals)");
6539         }
6540       uiout->text ("\n");
6541     }
6542
6543   if (!part_of_multiple && b->thread != -1)
6544     {
6545       /* FIXME should make an annotation for this.  */
6546       uiout->text ("\tstop only in thread ");
6547       if (uiout->is_mi_like_p ())
6548         uiout->field_int ("thread", b->thread);
6549       else
6550         {
6551           struct thread_info *thr = find_thread_global_id (b->thread);
6552
6553           uiout->field_string ("thread", print_thread_id (thr));
6554         }
6555       uiout->text ("\n");
6556     }
6557   
6558   if (!part_of_multiple)
6559     {
6560       if (b->hit_count)
6561         {
6562           /* FIXME should make an annotation for this.  */
6563           if (is_catchpoint (b))
6564             uiout->text ("\tcatchpoint");
6565           else if (is_tracepoint (b))
6566             uiout->text ("\ttracepoint");
6567           else
6568             uiout->text ("\tbreakpoint");
6569           uiout->text (" already hit ");
6570           uiout->field_int ("times", b->hit_count);
6571           if (b->hit_count == 1)
6572             uiout->text (" time\n");
6573           else
6574             uiout->text (" times\n");
6575         }
6576       else
6577         {
6578           /* Output the count also if it is zero, but only if this is mi.  */
6579           if (uiout->is_mi_like_p ())
6580             uiout->field_int ("times", b->hit_count);
6581         }
6582     }
6583
6584   if (!part_of_multiple && b->ignore_count)
6585     {
6586       annotate_field (8);
6587       uiout->text ("\tignore next ");
6588       uiout->field_int ("ignore", b->ignore_count);
6589       uiout->text (" hits\n");
6590     }
6591
6592   /* Note that an enable count of 1 corresponds to "enable once"
6593      behavior, which is reported by the combination of enablement and
6594      disposition, so we don't need to mention it here.  */
6595   if (!part_of_multiple && b->enable_count > 1)
6596     {
6597       annotate_field (8);
6598       uiout->text ("\tdisable after ");
6599       /* Tweak the wording to clarify that ignore and enable counts
6600          are distinct, and have additive effect.  */
6601       if (b->ignore_count)
6602         uiout->text ("additional ");
6603       else
6604         uiout->text ("next ");
6605       uiout->field_int ("enable", b->enable_count);
6606       uiout->text (" hits\n");
6607     }
6608
6609   if (!part_of_multiple && is_tracepoint (b))
6610     {
6611       struct tracepoint *tp = (struct tracepoint *) b;
6612
6613       if (tp->traceframe_usage)
6614         {
6615           uiout->text ("\ttrace buffer usage ");
6616           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6617           uiout->text (" bytes\n");
6618         }
6619     }
6620
6621   l = b->commands ? b->commands->commands : NULL;
6622   if (!part_of_multiple && l)
6623     {
6624       struct cleanup *script_chain;
6625
6626       annotate_field (9);
6627       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6628       print_command_lines (uiout, l, 4);
6629       do_cleanups (script_chain);
6630     }
6631
6632   if (is_tracepoint (b))
6633     {
6634       struct tracepoint *t = (struct tracepoint *) b;
6635
6636       if (!part_of_multiple && t->pass_count)
6637         {
6638           annotate_field (10);
6639           uiout->text ("\tpass count ");
6640           uiout->field_int ("pass", t->pass_count);
6641           uiout->text (" \n");
6642         }
6643
6644       /* Don't display it when tracepoint or tracepoint location is
6645          pending.   */
6646       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6647         {
6648           annotate_field (11);
6649
6650           if (uiout->is_mi_like_p ())
6651             uiout->field_string ("installed",
6652                                  loc->inserted ? "y" : "n");
6653           else
6654             {
6655               if (loc->inserted)
6656                 uiout->text ("\t");
6657               else
6658                 uiout->text ("\tnot ");
6659               uiout->text ("installed on target\n");
6660             }
6661         }
6662     }
6663
6664   if (uiout->is_mi_like_p () && !part_of_multiple)
6665     {
6666       if (is_watchpoint (b))
6667         {
6668           struct watchpoint *w = (struct watchpoint *) b;
6669
6670           uiout->field_string ("original-location", w->exp_string);
6671         }
6672       else if (b->location != NULL
6673                && event_location_to_string (b->location) != NULL)
6674         uiout->field_string ("original-location",
6675                              event_location_to_string (b->location));
6676     }
6677 }
6678
6679 static void
6680 print_one_breakpoint (struct breakpoint *b,
6681                       struct bp_location **last_loc, 
6682                       int allflag)
6683 {
6684   struct cleanup *bkpt_chain;
6685   struct ui_out *uiout = current_uiout;
6686
6687   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6688
6689   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6690   do_cleanups (bkpt_chain);
6691
6692   /* If this breakpoint has custom print function,
6693      it's already printed.  Otherwise, print individual
6694      locations, if any.  */
6695   if (b->ops == NULL || b->ops->print_one == NULL)
6696     {
6697       /* If breakpoint has a single location that is disabled, we
6698          print it as if it had several locations, since otherwise it's
6699          hard to represent "breakpoint enabled, location disabled"
6700          situation.
6701
6702          Note that while hardware watchpoints have several locations
6703          internally, that's not a property exposed to user.  */
6704       if (b->loc 
6705           && !is_hardware_watchpoint (b)
6706           && (b->loc->next || !b->loc->enabled))
6707         {
6708           struct bp_location *loc;
6709           int n = 1;
6710
6711           for (loc = b->loc; loc; loc = loc->next, ++n)
6712             {
6713               struct cleanup *inner2 =
6714                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6715               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6716               do_cleanups (inner2);
6717             }
6718         }
6719     }
6720 }
6721
6722 static int
6723 breakpoint_address_bits (struct breakpoint *b)
6724 {
6725   int print_address_bits = 0;
6726   struct bp_location *loc;
6727
6728   /* Software watchpoints that aren't watching memory don't have an
6729      address to print.  */
6730   if (is_no_memory_software_watchpoint (b))
6731     return 0;
6732
6733   for (loc = b->loc; loc; loc = loc->next)
6734     {
6735       int addr_bit;
6736
6737       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6738       if (addr_bit > print_address_bits)
6739         print_address_bits = addr_bit;
6740     }
6741
6742   return print_address_bits;
6743 }
6744
6745 struct captured_breakpoint_query_args
6746   {
6747     int bnum;
6748   };
6749
6750 static int
6751 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6752 {
6753   struct captured_breakpoint_query_args *args
6754     = (struct captured_breakpoint_query_args *) data;
6755   struct breakpoint *b;
6756   struct bp_location *dummy_loc = NULL;
6757
6758   ALL_BREAKPOINTS (b)
6759     {
6760       if (args->bnum == b->number)
6761         {
6762           print_one_breakpoint (b, &dummy_loc, 0);
6763           return GDB_RC_OK;
6764         }
6765     }
6766   return GDB_RC_NONE;
6767 }
6768
6769 enum gdb_rc
6770 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6771                       char **error_message)
6772 {
6773   struct captured_breakpoint_query_args args;
6774
6775   args.bnum = bnum;
6776   /* For the moment we don't trust print_one_breakpoint() to not throw
6777      an error.  */
6778   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6779                                  error_message, RETURN_MASK_ALL) < 0)
6780     return GDB_RC_FAIL;
6781   else
6782     return GDB_RC_OK;
6783 }
6784
6785 /* Return true if this breakpoint was set by the user, false if it is
6786    internal or momentary.  */
6787
6788 int
6789 user_breakpoint_p (struct breakpoint *b)
6790 {
6791   return b->number > 0;
6792 }
6793
6794 /* See breakpoint.h.  */
6795
6796 int
6797 pending_breakpoint_p (struct breakpoint *b)
6798 {
6799   return b->loc == NULL;
6800 }
6801
6802 /* Print information on user settable breakpoint (watchpoint, etc)
6803    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6804    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6805    FILTER is non-NULL, call it on each breakpoint and only include the
6806    ones for which it returns non-zero.  Return the total number of
6807    breakpoints listed.  */
6808
6809 static int
6810 breakpoint_1 (char *args, int allflag, 
6811               int (*filter) (const struct breakpoint *))
6812 {
6813   struct breakpoint *b;
6814   struct bp_location *last_loc = NULL;
6815   int nr_printable_breakpoints;
6816   struct cleanup *bkpttbl_chain;
6817   struct value_print_options opts;
6818   int print_address_bits = 0;
6819   int print_type_col_width = 14;
6820   struct ui_out *uiout = current_uiout;
6821
6822   get_user_print_options (&opts);
6823
6824   /* Compute the number of rows in the table, as well as the size
6825      required for address fields.  */
6826   nr_printable_breakpoints = 0;
6827   ALL_BREAKPOINTS (b)
6828     {
6829       /* If we have a filter, only list the breakpoints it accepts.  */
6830       if (filter && !filter (b))
6831         continue;
6832
6833       /* If we have an "args" string, it is a list of breakpoints to 
6834          accept.  Skip the others.  */
6835       if (args != NULL && *args != '\0')
6836         {
6837           if (allflag && parse_and_eval_long (args) != b->number)
6838             continue;
6839           if (!allflag && !number_is_in_list (args, b->number))
6840             continue;
6841         }
6842
6843       if (allflag || user_breakpoint_p (b))
6844         {
6845           int addr_bit, type_len;
6846
6847           addr_bit = breakpoint_address_bits (b);
6848           if (addr_bit > print_address_bits)
6849             print_address_bits = addr_bit;
6850
6851           type_len = strlen (bptype_string (b->type));
6852           if (type_len > print_type_col_width)
6853             print_type_col_width = type_len;
6854
6855           nr_printable_breakpoints++;
6856         }
6857     }
6858
6859   if (opts.addressprint)
6860     bkpttbl_chain 
6861       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6862                                              nr_printable_breakpoints,
6863                                              "BreakpointTable");
6864   else
6865     bkpttbl_chain 
6866       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6867                                              nr_printable_breakpoints,
6868                                              "BreakpointTable");
6869
6870   if (nr_printable_breakpoints > 0)
6871     annotate_breakpoints_headers ();
6872   if (nr_printable_breakpoints > 0)
6873     annotate_field (0);
6874   uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6875   if (nr_printable_breakpoints > 0)
6876     annotate_field (1);
6877   uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6878   if (nr_printable_breakpoints > 0)
6879     annotate_field (2);
6880   uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6881   if (nr_printable_breakpoints > 0)
6882     annotate_field (3);
6883   uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6884   if (opts.addressprint)
6885     {
6886       if (nr_printable_breakpoints > 0)
6887         annotate_field (4);
6888       if (print_address_bits <= 32)
6889         uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6890       else
6891         uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6892     }
6893   if (nr_printable_breakpoints > 0)
6894     annotate_field (5);
6895   uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6896   uiout->table_body ();
6897   if (nr_printable_breakpoints > 0)
6898     annotate_breakpoints_table ();
6899
6900   ALL_BREAKPOINTS (b)
6901     {
6902       QUIT;
6903       /* If we have a filter, only list the breakpoints it accepts.  */
6904       if (filter && !filter (b))
6905         continue;
6906
6907       /* If we have an "args" string, it is a list of breakpoints to 
6908          accept.  Skip the others.  */
6909
6910       if (args != NULL && *args != '\0')
6911         {
6912           if (allflag)  /* maintenance info breakpoint */
6913             {
6914               if (parse_and_eval_long (args) != b->number)
6915                 continue;
6916             }
6917           else          /* all others */
6918             {
6919               if (!number_is_in_list (args, b->number))
6920                 continue;
6921             }
6922         }
6923       /* We only print out user settable breakpoints unless the
6924          allflag is set.  */
6925       if (allflag || user_breakpoint_p (b))
6926         print_one_breakpoint (b, &last_loc, allflag);
6927     }
6928
6929   do_cleanups (bkpttbl_chain);
6930
6931   if (nr_printable_breakpoints == 0)
6932     {
6933       /* If there's a filter, let the caller decide how to report
6934          empty list.  */
6935       if (!filter)
6936         {
6937           if (args == NULL || *args == '\0')
6938             uiout->message ("No breakpoints or watchpoints.\n");
6939           else
6940             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6941                             args);
6942         }
6943     }
6944   else
6945     {
6946       if (last_loc && !server_command)
6947         set_next_address (last_loc->gdbarch, last_loc->address);
6948     }
6949
6950   /* FIXME?  Should this be moved up so that it is only called when
6951      there have been breakpoints? */
6952   annotate_breakpoints_table_end ();
6953
6954   return nr_printable_breakpoints;
6955 }
6956
6957 /* Display the value of default-collect in a way that is generally
6958    compatible with the breakpoint list.  */
6959
6960 static void
6961 default_collect_info (void)
6962 {
6963   struct ui_out *uiout = current_uiout;
6964
6965   /* If it has no value (which is frequently the case), say nothing; a
6966      message like "No default-collect." gets in user's face when it's
6967      not wanted.  */
6968   if (!*default_collect)
6969     return;
6970
6971   /* The following phrase lines up nicely with per-tracepoint collect
6972      actions.  */
6973   uiout->text ("default collect ");
6974   uiout->field_string ("default-collect", default_collect);
6975   uiout->text (" \n");
6976 }
6977   
6978 static void
6979 breakpoints_info (char *args, int from_tty)
6980 {
6981   breakpoint_1 (args, 0, NULL);
6982
6983   default_collect_info ();
6984 }
6985
6986 static void
6987 watchpoints_info (char *args, int from_tty)
6988 {
6989   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6990   struct ui_out *uiout = current_uiout;
6991
6992   if (num_printed == 0)
6993     {
6994       if (args == NULL || *args == '\0')
6995         uiout->message ("No watchpoints.\n");
6996       else
6997         uiout->message ("No watchpoint matching '%s'.\n", args);
6998     }
6999 }
7000
7001 static void
7002 maintenance_info_breakpoints (char *args, int from_tty)
7003 {
7004   breakpoint_1 (args, 1, NULL);
7005
7006   default_collect_info ();
7007 }
7008
7009 static int
7010 breakpoint_has_pc (struct breakpoint *b,
7011                    struct program_space *pspace,
7012                    CORE_ADDR pc, struct obj_section *section)
7013 {
7014   struct bp_location *bl = b->loc;
7015
7016   for (; bl; bl = bl->next)
7017     {
7018       if (bl->pspace == pspace
7019           && bl->address == pc
7020           && (!overlay_debugging || bl->section == section))
7021         return 1;         
7022     }
7023   return 0;
7024 }
7025
7026 /* Print a message describing any user-breakpoints set at PC.  This
7027    concerns with logical breakpoints, so we match program spaces, not
7028    address spaces.  */
7029
7030 static void
7031 describe_other_breakpoints (struct gdbarch *gdbarch,
7032                             struct program_space *pspace, CORE_ADDR pc,
7033                             struct obj_section *section, int thread)
7034 {
7035   int others = 0;
7036   struct breakpoint *b;
7037
7038   ALL_BREAKPOINTS (b)
7039     others += (user_breakpoint_p (b)
7040                && breakpoint_has_pc (b, pspace, pc, section));
7041   if (others > 0)
7042     {
7043       if (others == 1)
7044         printf_filtered (_("Note: breakpoint "));
7045       else /* if (others == ???) */
7046         printf_filtered (_("Note: breakpoints "));
7047       ALL_BREAKPOINTS (b)
7048         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7049           {
7050             others--;
7051             printf_filtered ("%d", b->number);
7052             if (b->thread == -1 && thread != -1)
7053               printf_filtered (" (all threads)");
7054             else if (b->thread != -1)
7055               printf_filtered (" (thread %d)", b->thread);
7056             printf_filtered ("%s%s ",
7057                              ((b->enable_state == bp_disabled
7058                                || b->enable_state == bp_call_disabled)
7059                               ? " (disabled)"
7060                               : ""),
7061                              (others > 1) ? "," 
7062                              : ((others == 1) ? " and" : ""));
7063           }
7064       printf_filtered (_("also set at pc "));
7065       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
7066       printf_filtered (".\n");
7067     }
7068 }
7069 \f
7070
7071 /* Return true iff it is meaningful to use the address member of
7072    BPT locations.  For some breakpoint types, the locations' address members
7073    are irrelevant and it makes no sense to attempt to compare them to other
7074    addresses (or use them for any other purpose either).
7075
7076    More specifically, each of the following breakpoint types will
7077    always have a zero valued location address and we don't want to mark
7078    breakpoints of any of these types to be a duplicate of an actual
7079    breakpoint location at address zero:
7080
7081       bp_watchpoint
7082       bp_catchpoint
7083
7084 */
7085
7086 static int
7087 breakpoint_address_is_meaningful (struct breakpoint *bpt)
7088 {
7089   enum bptype type = bpt->type;
7090
7091   return (type != bp_watchpoint && type != bp_catchpoint);
7092 }
7093
7094 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7095    true if LOC1 and LOC2 represent the same watchpoint location.  */
7096
7097 static int
7098 watchpoint_locations_match (struct bp_location *loc1, 
7099                             struct bp_location *loc2)
7100 {
7101   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7102   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7103
7104   /* Both of them must exist.  */
7105   gdb_assert (w1 != NULL);
7106   gdb_assert (w2 != NULL);
7107
7108   /* If the target can evaluate the condition expression in hardware,
7109      then we we need to insert both watchpoints even if they are at
7110      the same place.  Otherwise the watchpoint will only trigger when
7111      the condition of whichever watchpoint was inserted evaluates to
7112      true, not giving a chance for GDB to check the condition of the
7113      other watchpoint.  */
7114   if ((w1->cond_exp
7115        && target_can_accel_watchpoint_condition (loc1->address, 
7116                                                  loc1->length,
7117                                                  loc1->watchpoint_type,
7118                                                  w1->cond_exp.get ()))
7119       || (w2->cond_exp
7120           && target_can_accel_watchpoint_condition (loc2->address, 
7121                                                     loc2->length,
7122                                                     loc2->watchpoint_type,
7123                                                     w2->cond_exp.get ())))
7124     return 0;
7125
7126   /* Note that this checks the owner's type, not the location's.  In
7127      case the target does not support read watchpoints, but does
7128      support access watchpoints, we'll have bp_read_watchpoint
7129      watchpoints with hw_access locations.  Those should be considered
7130      duplicates of hw_read locations.  The hw_read locations will
7131      become hw_access locations later.  */
7132   return (loc1->owner->type == loc2->owner->type
7133           && loc1->pspace->aspace == loc2->pspace->aspace
7134           && loc1->address == loc2->address
7135           && loc1->length == loc2->length);
7136 }
7137
7138 /* See breakpoint.h.  */
7139
7140 int
7141 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7142                           struct address_space *aspace2, CORE_ADDR addr2)
7143 {
7144   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7145            || aspace1 == aspace2)
7146           && addr1 == addr2);
7147 }
7148
7149 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7150    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7151    matches ASPACE2.  On targets that have global breakpoints, the address
7152    space doesn't really matter.  */
7153
7154 static int
7155 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7156                                 int len1, struct address_space *aspace2,
7157                                 CORE_ADDR addr2)
7158 {
7159   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7160            || aspace1 == aspace2)
7161           && addr2 >= addr1 && addr2 < addr1 + len1);
7162 }
7163
7164 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7165    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7166    matches the breakpoint's address space.  On targets that have global
7167    breakpoints, the address space doesn't really matter.  */
7168
7169 static int
7170 breakpoint_location_address_match (struct bp_location *bl,
7171                                    struct address_space *aspace,
7172                                    CORE_ADDR addr)
7173 {
7174   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7175                                     aspace, addr)
7176           || (bl->length
7177               && breakpoint_address_match_range (bl->pspace->aspace,
7178                                                  bl->address, bl->length,
7179                                                  aspace, addr)));
7180 }
7181
7182 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7183    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7184    match happens only if ASPACE matches the breakpoint's address
7185    space.  On targets that have global breakpoints, the address space
7186    doesn't really matter.  */
7187
7188 static int
7189 breakpoint_location_address_range_overlap (struct bp_location *bl,
7190                                            struct address_space *aspace,
7191                                            CORE_ADDR addr, int len)
7192 {
7193   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7194       || bl->pspace->aspace == aspace)
7195     {
7196       int bl_len = bl->length != 0 ? bl->length : 1;
7197
7198       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7199         return 1;
7200     }
7201   return 0;
7202 }
7203
7204 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7205    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7206    true, otherwise returns false.  */
7207
7208 static int
7209 tracepoint_locations_match (struct bp_location *loc1,
7210                             struct bp_location *loc2)
7211 {
7212   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7213     /* Since tracepoint locations are never duplicated with others', tracepoint
7214        locations at the same address of different tracepoints are regarded as
7215        different locations.  */
7216     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7217   else
7218     return 0;
7219 }
7220
7221 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7222    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7223    represent the same location.  */
7224
7225 static int
7226 breakpoint_locations_match (struct bp_location *loc1, 
7227                             struct bp_location *loc2)
7228 {
7229   int hw_point1, hw_point2;
7230
7231   /* Both of them must not be in moribund_locations.  */
7232   gdb_assert (loc1->owner != NULL);
7233   gdb_assert (loc2->owner != NULL);
7234
7235   hw_point1 = is_hardware_watchpoint (loc1->owner);
7236   hw_point2 = is_hardware_watchpoint (loc2->owner);
7237
7238   if (hw_point1 != hw_point2)
7239     return 0;
7240   else if (hw_point1)
7241     return watchpoint_locations_match (loc1, loc2);
7242   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7243     return tracepoint_locations_match (loc1, loc2);
7244   else
7245     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7246     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7247                                      loc2->pspace->aspace, loc2->address)
7248             && loc1->length == loc2->length);
7249 }
7250
7251 static void
7252 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7253                                int bnum, int have_bnum)
7254 {
7255   /* The longest string possibly returned by hex_string_custom
7256      is 50 chars.  These must be at least that big for safety.  */
7257   char astr1[64];
7258   char astr2[64];
7259
7260   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7261   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7262   if (have_bnum)
7263     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7264              bnum, astr1, astr2);
7265   else
7266     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7267 }
7268
7269 /* Adjust a breakpoint's address to account for architectural
7270    constraints on breakpoint placement.  Return the adjusted address.
7271    Note: Very few targets require this kind of adjustment.  For most
7272    targets, this function is simply the identity function.  */
7273
7274 static CORE_ADDR
7275 adjust_breakpoint_address (struct gdbarch *gdbarch,
7276                            CORE_ADDR bpaddr, enum bptype bptype)
7277 {
7278   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7279     {
7280       /* Very few targets need any kind of breakpoint adjustment.  */
7281       return bpaddr;
7282     }
7283   else if (bptype == bp_watchpoint
7284            || bptype == bp_hardware_watchpoint
7285            || bptype == bp_read_watchpoint
7286            || bptype == bp_access_watchpoint
7287            || bptype == bp_catchpoint)
7288     {
7289       /* Watchpoints and the various bp_catch_* eventpoints should not
7290          have their addresses modified.  */
7291       return bpaddr;
7292     }
7293   else if (bptype == bp_single_step)
7294     {
7295       /* Single-step breakpoints should not have their addresses
7296          modified.  If there's any architectural constrain that
7297          applies to this address, then it should have already been
7298          taken into account when the breakpoint was created in the
7299          first place.  If we didn't do this, stepping through e.g.,
7300          Thumb-2 IT blocks would break.  */
7301       return bpaddr;
7302     }
7303   else
7304     {
7305       CORE_ADDR adjusted_bpaddr;
7306
7307       /* Some targets have architectural constraints on the placement
7308          of breakpoint instructions.  Obtain the adjusted address.  */
7309       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7310
7311       /* An adjusted breakpoint address can significantly alter
7312          a user's expectations.  Print a warning if an adjustment
7313          is required.  */
7314       if (adjusted_bpaddr != bpaddr)
7315         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7316
7317       return adjusted_bpaddr;
7318     }
7319 }
7320
7321 void
7322 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7323                   struct breakpoint *owner)
7324 {
7325   memset (loc, 0, sizeof (*loc));
7326
7327   gdb_assert (ops != NULL);
7328
7329   loc->ops = ops;
7330   loc->owner = owner;
7331   loc->cond_bytecode = NULL;
7332   loc->shlib_disabled = 0;
7333   loc->enabled = 1;
7334
7335   switch (owner->type)
7336     {
7337     case bp_breakpoint:
7338     case bp_single_step:
7339     case bp_until:
7340     case bp_finish:
7341     case bp_longjmp:
7342     case bp_longjmp_resume:
7343     case bp_longjmp_call_dummy:
7344     case bp_exception:
7345     case bp_exception_resume:
7346     case bp_step_resume:
7347     case bp_hp_step_resume:
7348     case bp_watchpoint_scope:
7349     case bp_call_dummy:
7350     case bp_std_terminate:
7351     case bp_shlib_event:
7352     case bp_thread_event:
7353     case bp_overlay_event:
7354     case bp_jit_event:
7355     case bp_longjmp_master:
7356     case bp_std_terminate_master:
7357     case bp_exception_master:
7358     case bp_gnu_ifunc_resolver:
7359     case bp_gnu_ifunc_resolver_return:
7360     case bp_dprintf:
7361       loc->loc_type = bp_loc_software_breakpoint;
7362       mark_breakpoint_location_modified (loc);
7363       break;
7364     case bp_hardware_breakpoint:
7365       loc->loc_type = bp_loc_hardware_breakpoint;
7366       mark_breakpoint_location_modified (loc);
7367       break;
7368     case bp_hardware_watchpoint:
7369     case bp_read_watchpoint:
7370     case bp_access_watchpoint:
7371       loc->loc_type = bp_loc_hardware_watchpoint;
7372       break;
7373     case bp_watchpoint:
7374     case bp_catchpoint:
7375     case bp_tracepoint:
7376     case bp_fast_tracepoint:
7377     case bp_static_tracepoint:
7378       loc->loc_type = bp_loc_other;
7379       break;
7380     default:
7381       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7382     }
7383
7384   loc->refc = 1;
7385 }
7386
7387 /* Allocate a struct bp_location.  */
7388
7389 static struct bp_location *
7390 allocate_bp_location (struct breakpoint *bpt)
7391 {
7392   return bpt->ops->allocate_location (bpt);
7393 }
7394
7395 static void
7396 free_bp_location (struct bp_location *loc)
7397 {
7398   loc->ops->dtor (loc);
7399   delete loc;
7400 }
7401
7402 /* Increment reference count.  */
7403
7404 static void
7405 incref_bp_location (struct bp_location *bl)
7406 {
7407   ++bl->refc;
7408 }
7409
7410 /* Decrement reference count.  If the reference count reaches 0,
7411    destroy the bp_location.  Sets *BLP to NULL.  */
7412
7413 static void
7414 decref_bp_location (struct bp_location **blp)
7415 {
7416   gdb_assert ((*blp)->refc > 0);
7417
7418   if (--(*blp)->refc == 0)
7419     free_bp_location (*blp);
7420   *blp = NULL;
7421 }
7422
7423 /* Add breakpoint B at the end of the global breakpoint chain.  */
7424
7425 static void
7426 add_to_breakpoint_chain (struct breakpoint *b)
7427 {
7428   struct breakpoint *b1;
7429
7430   /* Add this breakpoint to the end of the chain so that a list of
7431      breakpoints will come out in order of increasing numbers.  */
7432
7433   b1 = breakpoint_chain;
7434   if (b1 == 0)
7435     breakpoint_chain = b;
7436   else
7437     {
7438       while (b1->next)
7439         b1 = b1->next;
7440       b1->next = b;
7441     }
7442 }
7443
7444 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7445
7446 static void
7447 init_raw_breakpoint_without_location (struct breakpoint *b,
7448                                       struct gdbarch *gdbarch,
7449                                       enum bptype bptype,
7450                                       const struct breakpoint_ops *ops)
7451 {
7452   memset (b, 0, sizeof (*b));
7453
7454   gdb_assert (ops != NULL);
7455
7456   b->ops = ops;
7457   b->type = bptype;
7458   b->gdbarch = gdbarch;
7459   b->language = current_language->la_language;
7460   b->input_radix = input_radix;
7461   b->thread = -1;
7462   b->enable_state = bp_enabled;
7463   b->next = 0;
7464   b->silent = 0;
7465   b->ignore_count = 0;
7466   b->commands = NULL;
7467   b->frame_id = null_frame_id;
7468   b->condition_not_parsed = 0;
7469   b->py_bp_object = NULL;
7470   b->related_breakpoint = b;
7471   b->location = NULL;
7472 }
7473
7474 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7475    that has type BPTYPE and has no locations as yet.  */
7476
7477 static struct breakpoint *
7478 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7479                                      enum bptype bptype,
7480                                      const struct breakpoint_ops *ops)
7481 {
7482   struct breakpoint *b = new breakpoint ();
7483
7484   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7485   add_to_breakpoint_chain (b);
7486   return b;
7487 }
7488
7489 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7490    resolutions should be made as the user specified the location explicitly
7491    enough.  */
7492
7493 static void
7494 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7495 {
7496   gdb_assert (loc->owner != NULL);
7497
7498   if (loc->owner->type == bp_breakpoint
7499       || loc->owner->type == bp_hardware_breakpoint
7500       || is_tracepoint (loc->owner))
7501     {
7502       int is_gnu_ifunc;
7503       const char *function_name;
7504       CORE_ADDR func_addr;
7505
7506       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7507                                           &func_addr, NULL, &is_gnu_ifunc);
7508
7509       if (is_gnu_ifunc && !explicit_loc)
7510         {
7511           struct breakpoint *b = loc->owner;
7512
7513           gdb_assert (loc->pspace == current_program_space);
7514           if (gnu_ifunc_resolve_name (function_name,
7515                                       &loc->requested_address))
7516             {
7517               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7518               loc->address = adjust_breakpoint_address (loc->gdbarch,
7519                                                         loc->requested_address,
7520                                                         b->type);
7521             }
7522           else if (b->type == bp_breakpoint && b->loc == loc
7523                    && loc->next == NULL && b->related_breakpoint == b)
7524             {
7525               /* Create only the whole new breakpoint of this type but do not
7526                  mess more complicated breakpoints with multiple locations.  */
7527               b->type = bp_gnu_ifunc_resolver;
7528               /* Remember the resolver's address for use by the return
7529                  breakpoint.  */
7530               loc->related_address = func_addr;
7531             }
7532         }
7533
7534       if (function_name)
7535         loc->function_name = xstrdup (function_name);
7536     }
7537 }
7538
7539 /* Attempt to determine architecture of location identified by SAL.  */
7540 struct gdbarch *
7541 get_sal_arch (struct symtab_and_line sal)
7542 {
7543   if (sal.section)
7544     return get_objfile_arch (sal.section->objfile);
7545   if (sal.symtab)
7546     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7547
7548   return NULL;
7549 }
7550
7551 /* Low level routine for partially initializing a breakpoint of type
7552    BPTYPE.  The newly created breakpoint's address, section, source
7553    file name, and line number are provided by SAL.
7554
7555    It is expected that the caller will complete the initialization of
7556    the newly created breakpoint struct as well as output any status
7557    information regarding the creation of a new breakpoint.  */
7558
7559 static void
7560 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7561                      struct symtab_and_line sal, enum bptype bptype,
7562                      const struct breakpoint_ops *ops)
7563 {
7564   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7565
7566   add_location_to_breakpoint (b, &sal);
7567
7568   if (bptype != bp_catchpoint)
7569     gdb_assert (sal.pspace != NULL);
7570
7571   /* Store the program space that was used to set the breakpoint,
7572      except for ordinary breakpoints, which are independent of the
7573      program space.  */
7574   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7575     b->pspace = sal.pspace;
7576 }
7577
7578 /* set_raw_breakpoint is a low level routine for allocating and
7579    partially initializing a breakpoint of type BPTYPE.  The newly
7580    created breakpoint's address, section, source file name, and line
7581    number are provided by SAL.  The newly created and partially
7582    initialized breakpoint is added to the breakpoint chain and
7583    is also returned as the value of this function.
7584
7585    It is expected that the caller will complete the initialization of
7586    the newly created breakpoint struct as well as output any status
7587    information regarding the creation of a new breakpoint.  In
7588    particular, set_raw_breakpoint does NOT set the breakpoint
7589    number!  Care should be taken to not allow an error to occur
7590    prior to completing the initialization of the breakpoint.  If this
7591    should happen, a bogus breakpoint will be left on the chain.  */
7592
7593 struct breakpoint *
7594 set_raw_breakpoint (struct gdbarch *gdbarch,
7595                     struct symtab_and_line sal, enum bptype bptype,
7596                     const struct breakpoint_ops *ops)
7597 {
7598   struct breakpoint *b = new breakpoint ();
7599
7600   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7601   add_to_breakpoint_chain (b);
7602   return b;
7603 }
7604
7605 /* Call this routine when stepping and nexting to enable a breakpoint
7606    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7607    initiated the operation.  */
7608
7609 void
7610 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7611 {
7612   struct breakpoint *b, *b_tmp;
7613   int thread = tp->global_num;
7614
7615   /* To avoid having to rescan all objfile symbols at every step,
7616      we maintain a list of continually-inserted but always disabled
7617      longjmp "master" breakpoints.  Here, we simply create momentary
7618      clones of those and enable them for the requested thread.  */
7619   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7620     if (b->pspace == current_program_space
7621         && (b->type == bp_longjmp_master
7622             || b->type == bp_exception_master))
7623       {
7624         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7625         struct breakpoint *clone;
7626
7627         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7628            after their removal.  */
7629         clone = momentary_breakpoint_from_master (b, type,
7630                                                   &longjmp_breakpoint_ops, 1);
7631         clone->thread = thread;
7632       }
7633
7634   tp->initiating_frame = frame;
7635 }
7636
7637 /* Delete all longjmp breakpoints from THREAD.  */
7638 void
7639 delete_longjmp_breakpoint (int thread)
7640 {
7641   struct breakpoint *b, *b_tmp;
7642
7643   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7644     if (b->type == bp_longjmp || b->type == bp_exception)
7645       {
7646         if (b->thread == thread)
7647           delete_breakpoint (b);
7648       }
7649 }
7650
7651 void
7652 delete_longjmp_breakpoint_at_next_stop (int thread)
7653 {
7654   struct breakpoint *b, *b_tmp;
7655
7656   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7657     if (b->type == bp_longjmp || b->type == bp_exception)
7658       {
7659         if (b->thread == thread)
7660           b->disposition = disp_del_at_next_stop;
7661       }
7662 }
7663
7664 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7665    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7666    pointer to any of them.  Return NULL if this system cannot place longjmp
7667    breakpoints.  */
7668
7669 struct breakpoint *
7670 set_longjmp_breakpoint_for_call_dummy (void)
7671 {
7672   struct breakpoint *b, *retval = NULL;
7673
7674   ALL_BREAKPOINTS (b)
7675     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7676       {
7677         struct breakpoint *new_b;
7678
7679         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7680                                                   &momentary_breakpoint_ops,
7681                                                   1);
7682         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7683
7684         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7685
7686         gdb_assert (new_b->related_breakpoint == new_b);
7687         if (retval == NULL)
7688           retval = new_b;
7689         new_b->related_breakpoint = retval;
7690         while (retval->related_breakpoint != new_b->related_breakpoint)
7691           retval = retval->related_breakpoint;
7692         retval->related_breakpoint = new_b;
7693       }
7694
7695   return retval;
7696 }
7697
7698 /* Verify all existing dummy frames and their associated breakpoints for
7699    TP.  Remove those which can no longer be found in the current frame
7700    stack.
7701
7702    You should call this function only at places where it is safe to currently
7703    unwind the whole stack.  Failed stack unwind would discard live dummy
7704    frames.  */
7705
7706 void
7707 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7708 {
7709   struct breakpoint *b, *b_tmp;
7710
7711   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7712     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7713       {
7714         struct breakpoint *dummy_b = b->related_breakpoint;
7715
7716         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7717           dummy_b = dummy_b->related_breakpoint;
7718         if (dummy_b->type != bp_call_dummy
7719             || frame_find_by_id (dummy_b->frame_id) != NULL)
7720           continue;
7721         
7722         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7723
7724         while (b->related_breakpoint != b)
7725           {
7726             if (b_tmp == b->related_breakpoint)
7727               b_tmp = b->related_breakpoint->next;
7728             delete_breakpoint (b->related_breakpoint);
7729           }
7730         delete_breakpoint (b);
7731       }
7732 }
7733
7734 void
7735 enable_overlay_breakpoints (void)
7736 {
7737   struct breakpoint *b;
7738
7739   ALL_BREAKPOINTS (b)
7740     if (b->type == bp_overlay_event)
7741     {
7742       b->enable_state = bp_enabled;
7743       update_global_location_list (UGLL_MAY_INSERT);
7744       overlay_events_enabled = 1;
7745     }
7746 }
7747
7748 void
7749 disable_overlay_breakpoints (void)
7750 {
7751   struct breakpoint *b;
7752
7753   ALL_BREAKPOINTS (b)
7754     if (b->type == bp_overlay_event)
7755     {
7756       b->enable_state = bp_disabled;
7757       update_global_location_list (UGLL_DONT_INSERT);
7758       overlay_events_enabled = 0;
7759     }
7760 }
7761
7762 /* Set an active std::terminate breakpoint for each std::terminate
7763    master breakpoint.  */
7764 void
7765 set_std_terminate_breakpoint (void)
7766 {
7767   struct breakpoint *b, *b_tmp;
7768
7769   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7770     if (b->pspace == current_program_space
7771         && b->type == bp_std_terminate_master)
7772       {
7773         momentary_breakpoint_from_master (b, bp_std_terminate,
7774                                           &momentary_breakpoint_ops, 1);
7775       }
7776 }
7777
7778 /* Delete all the std::terminate breakpoints.  */
7779 void
7780 delete_std_terminate_breakpoint (void)
7781 {
7782   struct breakpoint *b, *b_tmp;
7783
7784   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7785     if (b->type == bp_std_terminate)
7786       delete_breakpoint (b);
7787 }
7788
7789 struct breakpoint *
7790 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7791 {
7792   struct breakpoint *b;
7793
7794   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7795                                   &internal_breakpoint_ops);
7796
7797   b->enable_state = bp_enabled;
7798   /* location has to be used or breakpoint_re_set will delete me.  */
7799   b->location = new_address_location (b->loc->address, NULL, 0);
7800
7801   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7802
7803   return b;
7804 }
7805
7806 struct lang_and_radix
7807   {
7808     enum language lang;
7809     int radix;
7810   };
7811
7812 /* Create a breakpoint for JIT code registration and unregistration.  */
7813
7814 struct breakpoint *
7815 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7816 {
7817   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7818                                      &internal_breakpoint_ops);
7819 }
7820
7821 /* Remove JIT code registration and unregistration breakpoint(s).  */
7822
7823 void
7824 remove_jit_event_breakpoints (void)
7825 {
7826   struct breakpoint *b, *b_tmp;
7827
7828   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7829     if (b->type == bp_jit_event
7830         && b->loc->pspace == current_program_space)
7831       delete_breakpoint (b);
7832 }
7833
7834 void
7835 remove_solib_event_breakpoints (void)
7836 {
7837   struct breakpoint *b, *b_tmp;
7838
7839   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7840     if (b->type == bp_shlib_event
7841         && b->loc->pspace == current_program_space)
7842       delete_breakpoint (b);
7843 }
7844
7845 /* See breakpoint.h.  */
7846
7847 void
7848 remove_solib_event_breakpoints_at_next_stop (void)
7849 {
7850   struct breakpoint *b, *b_tmp;
7851
7852   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7853     if (b->type == bp_shlib_event
7854         && b->loc->pspace == current_program_space)
7855       b->disposition = disp_del_at_next_stop;
7856 }
7857
7858 /* Helper for create_solib_event_breakpoint /
7859    create_and_insert_solib_event_breakpoint.  Allows specifying which
7860    INSERT_MODE to pass through to update_global_location_list.  */
7861
7862 static struct breakpoint *
7863 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7864                                  enum ugll_insert_mode insert_mode)
7865 {
7866   struct breakpoint *b;
7867
7868   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7869                                   &internal_breakpoint_ops);
7870   update_global_location_list_nothrow (insert_mode);
7871   return b;
7872 }
7873
7874 struct breakpoint *
7875 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7876 {
7877   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7878 }
7879
7880 /* See breakpoint.h.  */
7881
7882 struct breakpoint *
7883 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7884 {
7885   struct breakpoint *b;
7886
7887   /* Explicitly tell update_global_location_list to insert
7888      locations.  */
7889   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7890   if (!b->loc->inserted)
7891     {
7892       delete_breakpoint (b);
7893       return NULL;
7894     }
7895   return b;
7896 }
7897
7898 /* Disable any breakpoints that are on code in shared libraries.  Only
7899    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7900
7901 void
7902 disable_breakpoints_in_shlibs (void)
7903 {
7904   struct bp_location *loc, **locp_tmp;
7905
7906   ALL_BP_LOCATIONS (loc, locp_tmp)
7907   {
7908     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7909     struct breakpoint *b = loc->owner;
7910
7911     /* We apply the check to all breakpoints, including disabled for
7912        those with loc->duplicate set.  This is so that when breakpoint
7913        becomes enabled, or the duplicate is removed, gdb will try to
7914        insert all breakpoints.  If we don't set shlib_disabled here,
7915        we'll try to insert those breakpoints and fail.  */
7916     if (((b->type == bp_breakpoint)
7917          || (b->type == bp_jit_event)
7918          || (b->type == bp_hardware_breakpoint)
7919          || (is_tracepoint (b)))
7920         && loc->pspace == current_program_space
7921         && !loc->shlib_disabled
7922         && solib_name_from_address (loc->pspace, loc->address)
7923         )
7924       {
7925         loc->shlib_disabled = 1;
7926       }
7927   }
7928 }
7929
7930 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7931    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7932    disabled ones can just stay disabled.  */
7933
7934 static void
7935 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7936 {
7937   struct bp_location *loc, **locp_tmp;
7938   int disabled_shlib_breaks = 0;
7939
7940   ALL_BP_LOCATIONS (loc, locp_tmp)
7941   {
7942     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7943     struct breakpoint *b = loc->owner;
7944
7945     if (solib->pspace == loc->pspace
7946         && !loc->shlib_disabled
7947         && (((b->type == bp_breakpoint
7948               || b->type == bp_jit_event
7949               || b->type == bp_hardware_breakpoint)
7950              && (loc->loc_type == bp_loc_hardware_breakpoint
7951                  || loc->loc_type == bp_loc_software_breakpoint))
7952             || is_tracepoint (b))
7953         && solib_contains_address_p (solib, loc->address))
7954       {
7955         loc->shlib_disabled = 1;
7956         /* At this point, we cannot rely on remove_breakpoint
7957            succeeding so we must mark the breakpoint as not inserted
7958            to prevent future errors occurring in remove_breakpoints.  */
7959         loc->inserted = 0;
7960
7961         /* This may cause duplicate notifications for the same breakpoint.  */
7962         observer_notify_breakpoint_modified (b);
7963
7964         if (!disabled_shlib_breaks)
7965           {
7966             target_terminal_ours_for_output ();
7967             warning (_("Temporarily disabling breakpoints "
7968                        "for unloaded shared library \"%s\""),
7969                      solib->so_name);
7970           }
7971         disabled_shlib_breaks = 1;
7972       }
7973   }
7974 }
7975
7976 /* Disable any breakpoints and tracepoints in OBJFILE upon
7977    notification of free_objfile.  Only apply to enabled breakpoints,
7978    disabled ones can just stay disabled.  */
7979
7980 static void
7981 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7982 {
7983   struct breakpoint *b;
7984
7985   if (objfile == NULL)
7986     return;
7987
7988   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7989      managed by the user with add-symbol-file/remove-symbol-file.
7990      Similarly to how breakpoints in shared libraries are handled in
7991      response to "nosharedlibrary", mark breakpoints in such modules
7992      shlib_disabled so they end up uninserted on the next global
7993      location list update.  Shared libraries not loaded by the user
7994      aren't handled here -- they're already handled in
7995      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7996      solib_unloaded observer.  We skip objfiles that are not
7997      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7998      main objfile).  */
7999   if ((objfile->flags & OBJF_SHARED) == 0
8000       || (objfile->flags & OBJF_USERLOADED) == 0)
8001     return;
8002
8003   ALL_BREAKPOINTS (b)
8004     {
8005       struct bp_location *loc;
8006       int bp_modified = 0;
8007
8008       if (!is_breakpoint (b) && !is_tracepoint (b))
8009         continue;
8010
8011       for (loc = b->loc; loc != NULL; loc = loc->next)
8012         {
8013           CORE_ADDR loc_addr = loc->address;
8014
8015           if (loc->loc_type != bp_loc_hardware_breakpoint
8016               && loc->loc_type != bp_loc_software_breakpoint)
8017             continue;
8018
8019           if (loc->shlib_disabled != 0)
8020             continue;
8021
8022           if (objfile->pspace != loc->pspace)
8023             continue;
8024
8025           if (loc->loc_type != bp_loc_hardware_breakpoint
8026               && loc->loc_type != bp_loc_software_breakpoint)
8027             continue;
8028
8029           if (is_addr_in_objfile (loc_addr, objfile))
8030             {
8031               loc->shlib_disabled = 1;
8032               /* At this point, we don't know whether the object was
8033                  unmapped from the inferior or not, so leave the
8034                  inserted flag alone.  We'll handle failure to
8035                  uninsert quietly, in case the object was indeed
8036                  unmapped.  */
8037
8038               mark_breakpoint_location_modified (loc);
8039
8040               bp_modified = 1;
8041             }
8042         }
8043
8044       if (bp_modified)
8045         observer_notify_breakpoint_modified (b);
8046     }
8047 }
8048
8049 /* FORK & VFORK catchpoints.  */
8050
8051 /* An instance of this type is used to represent a fork or vfork
8052    catchpoint.  It includes a "struct breakpoint" as a kind of base
8053    class; users downcast to "struct breakpoint *" when needed.  A
8054    breakpoint is really of this type iff its ops pointer points to
8055    CATCH_FORK_BREAKPOINT_OPS.  */
8056
8057 struct fork_catchpoint
8058 {
8059   /* The base class.  */
8060   struct breakpoint base;
8061
8062   /* Process id of a child process whose forking triggered this
8063      catchpoint.  This field is only valid immediately after this
8064      catchpoint has triggered.  */
8065   ptid_t forked_inferior_pid;
8066 };
8067
8068 /* Implement the "insert" breakpoint_ops method for fork
8069    catchpoints.  */
8070
8071 static int
8072 insert_catch_fork (struct bp_location *bl)
8073 {
8074   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
8075 }
8076
8077 /* Implement the "remove" breakpoint_ops method for fork
8078    catchpoints.  */
8079
8080 static int
8081 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
8082 {
8083   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
8084 }
8085
8086 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
8087    catchpoints.  */
8088
8089 static int
8090 breakpoint_hit_catch_fork (const struct bp_location *bl,
8091                            struct address_space *aspace, CORE_ADDR bp_addr,
8092                            const struct target_waitstatus *ws)
8093 {
8094   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8095
8096   if (ws->kind != TARGET_WAITKIND_FORKED)
8097     return 0;
8098
8099   c->forked_inferior_pid = ws->value.related_pid;
8100   return 1;
8101 }
8102
8103 /* Implement the "print_it" breakpoint_ops method for fork
8104    catchpoints.  */
8105
8106 static enum print_stop_action
8107 print_it_catch_fork (bpstat bs)
8108 {
8109   struct ui_out *uiout = current_uiout;
8110   struct breakpoint *b = bs->breakpoint_at;
8111   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8112
8113   annotate_catchpoint (b->number);
8114   maybe_print_thread_hit_breakpoint (uiout);
8115   if (b->disposition == disp_del)
8116     uiout->text ("Temporary catchpoint ");
8117   else
8118     uiout->text ("Catchpoint ");
8119   if (uiout->is_mi_like_p ())
8120     {
8121       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
8122       uiout->field_string ("disp", bpdisp_text (b->disposition));
8123     }
8124   uiout->field_int ("bkptno", b->number);
8125   uiout->text (" (forked process ");
8126   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8127   uiout->text ("), ");
8128   return PRINT_SRC_AND_LOC;
8129 }
8130
8131 /* Implement the "print_one" breakpoint_ops method for fork
8132    catchpoints.  */
8133
8134 static void
8135 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8136 {
8137   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8138   struct value_print_options opts;
8139   struct ui_out *uiout = current_uiout;
8140
8141   get_user_print_options (&opts);
8142
8143   /* Field 4, the address, is omitted (which makes the columns not
8144      line up too nicely with the headers, but the effect is relatively
8145      readable).  */
8146   if (opts.addressprint)
8147     uiout->field_skip ("addr");
8148   annotate_field (5);
8149   uiout->text ("fork");
8150   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8151     {
8152       uiout->text (", process ");
8153       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8154       uiout->spaces (1);
8155     }
8156
8157   if (uiout->is_mi_like_p ())
8158     uiout->field_string ("catch-type", "fork");
8159 }
8160
8161 /* Implement the "print_mention" breakpoint_ops method for fork
8162    catchpoints.  */
8163
8164 static void
8165 print_mention_catch_fork (struct breakpoint *b)
8166 {
8167   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8168 }
8169
8170 /* Implement the "print_recreate" breakpoint_ops method for fork
8171    catchpoints.  */
8172
8173 static void
8174 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8175 {
8176   fprintf_unfiltered (fp, "catch fork");
8177   print_recreate_thread (b, fp);
8178 }
8179
8180 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8181
8182 static struct breakpoint_ops catch_fork_breakpoint_ops;
8183
8184 /* Implement the "insert" breakpoint_ops method for vfork
8185    catchpoints.  */
8186
8187 static int
8188 insert_catch_vfork (struct bp_location *bl)
8189 {
8190   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8191 }
8192
8193 /* Implement the "remove" breakpoint_ops method for vfork
8194    catchpoints.  */
8195
8196 static int
8197 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
8198 {
8199   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8200 }
8201
8202 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8203    catchpoints.  */
8204
8205 static int
8206 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8207                             struct address_space *aspace, CORE_ADDR bp_addr,
8208                             const struct target_waitstatus *ws)
8209 {
8210   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8211
8212   if (ws->kind != TARGET_WAITKIND_VFORKED)
8213     return 0;
8214
8215   c->forked_inferior_pid = ws->value.related_pid;
8216   return 1;
8217 }
8218
8219 /* Implement the "print_it" breakpoint_ops method for vfork
8220    catchpoints.  */
8221
8222 static enum print_stop_action
8223 print_it_catch_vfork (bpstat bs)
8224 {
8225   struct ui_out *uiout = current_uiout;
8226   struct breakpoint *b = bs->breakpoint_at;
8227   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8228
8229   annotate_catchpoint (b->number);
8230   maybe_print_thread_hit_breakpoint (uiout);
8231   if (b->disposition == disp_del)
8232     uiout->text ("Temporary catchpoint ");
8233   else
8234     uiout->text ("Catchpoint ");
8235   if (uiout->is_mi_like_p ())
8236     {
8237       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
8238       uiout->field_string ("disp", bpdisp_text (b->disposition));
8239     }
8240   uiout->field_int ("bkptno", b->number);
8241   uiout->text (" (vforked process ");
8242   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8243   uiout->text ("), ");
8244   return PRINT_SRC_AND_LOC;
8245 }
8246
8247 /* Implement the "print_one" breakpoint_ops method for vfork
8248    catchpoints.  */
8249
8250 static void
8251 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8252 {
8253   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8254   struct value_print_options opts;
8255   struct ui_out *uiout = current_uiout;
8256
8257   get_user_print_options (&opts);
8258   /* Field 4, the address, is omitted (which makes the columns not
8259      line up too nicely with the headers, but the effect is relatively
8260      readable).  */
8261   if (opts.addressprint)
8262     uiout->field_skip ("addr");
8263   annotate_field (5);
8264   uiout->text ("vfork");
8265   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8266     {
8267       uiout->text (", process ");
8268       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8269       uiout->spaces (1);
8270     }
8271
8272   if (uiout->is_mi_like_p ())
8273     uiout->field_string ("catch-type", "vfork");
8274 }
8275
8276 /* Implement the "print_mention" breakpoint_ops method for vfork
8277    catchpoints.  */
8278
8279 static void
8280 print_mention_catch_vfork (struct breakpoint *b)
8281 {
8282   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8283 }
8284
8285 /* Implement the "print_recreate" breakpoint_ops method for vfork
8286    catchpoints.  */
8287
8288 static void
8289 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8290 {
8291   fprintf_unfiltered (fp, "catch vfork");
8292   print_recreate_thread (b, fp);
8293 }
8294
8295 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8296
8297 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8298
8299 /* An instance of this type is used to represent an solib catchpoint.
8300    It includes a "struct breakpoint" as a kind of base class; users
8301    downcast to "struct breakpoint *" when needed.  A breakpoint is
8302    really of this type iff its ops pointer points to
8303    CATCH_SOLIB_BREAKPOINT_OPS.  */
8304
8305 struct solib_catchpoint
8306 {
8307   /* The base class.  */
8308   struct breakpoint base;
8309
8310   /* True for "catch load", false for "catch unload".  */
8311   unsigned char is_load;
8312
8313   /* Regular expression to match, if any.  COMPILED is only valid when
8314      REGEX is non-NULL.  */
8315   char *regex;
8316   regex_t compiled;
8317 };
8318
8319 static void
8320 dtor_catch_solib (struct breakpoint *b)
8321 {
8322   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8323
8324   if (self->regex)
8325     regfree (&self->compiled);
8326   xfree (self->regex);
8327
8328   base_breakpoint_ops.dtor (b);
8329 }
8330
8331 static int
8332 insert_catch_solib (struct bp_location *ignore)
8333 {
8334   return 0;
8335 }
8336
8337 static int
8338 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8339 {
8340   return 0;
8341 }
8342
8343 static int
8344 breakpoint_hit_catch_solib (const struct bp_location *bl,
8345                             struct address_space *aspace,
8346                             CORE_ADDR bp_addr,
8347                             const struct target_waitstatus *ws)
8348 {
8349   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8350   struct breakpoint *other;
8351
8352   if (ws->kind == TARGET_WAITKIND_LOADED)
8353     return 1;
8354
8355   ALL_BREAKPOINTS (other)
8356   {
8357     struct bp_location *other_bl;
8358
8359     if (other == bl->owner)
8360       continue;
8361
8362     if (other->type != bp_shlib_event)
8363       continue;
8364
8365     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8366       continue;
8367
8368     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8369       {
8370         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8371           return 1;
8372       }
8373   }
8374
8375   return 0;
8376 }
8377
8378 static void
8379 check_status_catch_solib (struct bpstats *bs)
8380 {
8381   struct solib_catchpoint *self
8382     = (struct solib_catchpoint *) bs->breakpoint_at;
8383   int ix;
8384
8385   if (self->is_load)
8386     {
8387       struct so_list *iter;
8388
8389       for (ix = 0;
8390            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8391                         ix, iter);
8392            ++ix)
8393         {
8394           if (!self->regex
8395               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8396             return;
8397         }
8398     }
8399   else
8400     {
8401       char *iter;
8402
8403       for (ix = 0;
8404            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8405                         ix, iter);
8406            ++ix)
8407         {
8408           if (!self->regex
8409               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8410             return;
8411         }
8412     }
8413
8414   bs->stop = 0;
8415   bs->print_it = print_it_noop;
8416 }
8417
8418 static enum print_stop_action
8419 print_it_catch_solib (bpstat bs)
8420 {
8421   struct breakpoint *b = bs->breakpoint_at;
8422   struct ui_out *uiout = current_uiout;
8423
8424   annotate_catchpoint (b->number);
8425   maybe_print_thread_hit_breakpoint (uiout);
8426   if (b->disposition == disp_del)
8427     uiout->text ("Temporary catchpoint ");
8428   else
8429     uiout->text ("Catchpoint ");
8430   uiout->field_int ("bkptno", b->number);
8431   uiout->text ("\n");
8432   if (uiout->is_mi_like_p ())
8433     uiout->field_string ("disp", bpdisp_text (b->disposition));
8434   print_solib_event (1);
8435   return PRINT_SRC_AND_LOC;
8436 }
8437
8438 static void
8439 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8440 {
8441   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8442   struct value_print_options opts;
8443   struct ui_out *uiout = current_uiout;
8444   char *msg;
8445
8446   get_user_print_options (&opts);
8447   /* Field 4, the address, is omitted (which makes the columns not
8448      line up too nicely with the headers, but the effect is relatively
8449      readable).  */
8450   if (opts.addressprint)
8451     {
8452       annotate_field (4);
8453       uiout->field_skip ("addr");
8454     }
8455
8456   annotate_field (5);
8457   if (self->is_load)
8458     {
8459       if (self->regex)
8460         msg = xstrprintf (_("load of library matching %s"), self->regex);
8461       else
8462         msg = xstrdup (_("load of library"));
8463     }
8464   else
8465     {
8466       if (self->regex)
8467         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8468       else
8469         msg = xstrdup (_("unload of library"));
8470     }
8471   uiout->field_string ("what", msg);
8472   xfree (msg);
8473
8474   if (uiout->is_mi_like_p ())
8475     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8476 }
8477
8478 static void
8479 print_mention_catch_solib (struct breakpoint *b)
8480 {
8481   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8482
8483   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8484                    self->is_load ? "load" : "unload");
8485 }
8486
8487 static void
8488 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8489 {
8490   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8491
8492   fprintf_unfiltered (fp, "%s %s",
8493                       b->disposition == disp_del ? "tcatch" : "catch",
8494                       self->is_load ? "load" : "unload");
8495   if (self->regex)
8496     fprintf_unfiltered (fp, " %s", self->regex);
8497   fprintf_unfiltered (fp, "\n");
8498 }
8499
8500 static struct breakpoint_ops catch_solib_breakpoint_ops;
8501
8502 /* Shared helper function (MI and CLI) for creating and installing
8503    a shared object event catchpoint.  If IS_LOAD is non-zero then
8504    the events to be caught are load events, otherwise they are
8505    unload events.  If IS_TEMP is non-zero the catchpoint is a
8506    temporary one.  If ENABLED is non-zero the catchpoint is
8507    created in an enabled state.  */
8508
8509 void
8510 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8511 {
8512   struct solib_catchpoint *c;
8513   struct gdbarch *gdbarch = get_current_arch ();
8514   struct cleanup *cleanup;
8515
8516   if (!arg)
8517     arg = "";
8518   arg = skip_spaces (arg);
8519
8520   c = new solib_catchpoint ();
8521   cleanup = make_cleanup (xfree, c);
8522
8523   if (*arg != '\0')
8524     {
8525       int errcode;
8526
8527       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8528       if (errcode != 0)
8529         {
8530           char *err = get_regcomp_error (errcode, &c->compiled);
8531
8532           make_cleanup (xfree, err);
8533           error (_("Invalid regexp (%s): %s"), err, arg);
8534         }
8535       c->regex = xstrdup (arg);
8536     }
8537
8538   c->is_load = is_load;
8539   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8540                    &catch_solib_breakpoint_ops);
8541
8542   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8543
8544   discard_cleanups (cleanup);
8545   install_breakpoint (0, &c->base, 1);
8546 }
8547
8548 /* A helper function that does all the work for "catch load" and
8549    "catch unload".  */
8550
8551 static void
8552 catch_load_or_unload (char *arg, int from_tty, int is_load,
8553                       struct cmd_list_element *command)
8554 {
8555   int tempflag;
8556   const int enabled = 1;
8557
8558   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8559
8560   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8561 }
8562
8563 static void
8564 catch_load_command_1 (char *arg, int from_tty,
8565                       struct cmd_list_element *command)
8566 {
8567   catch_load_or_unload (arg, from_tty, 1, command);
8568 }
8569
8570 static void
8571 catch_unload_command_1 (char *arg, int from_tty,
8572                         struct cmd_list_element *command)
8573 {
8574   catch_load_or_unload (arg, from_tty, 0, command);
8575 }
8576
8577 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8578    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8579    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8580    the breakpoint_ops structure associated to the catchpoint.  */
8581
8582 void
8583 init_catchpoint (struct breakpoint *b,
8584                  struct gdbarch *gdbarch, int tempflag,
8585                  char *cond_string,
8586                  const struct breakpoint_ops *ops)
8587 {
8588   struct symtab_and_line sal;
8589
8590   init_sal (&sal);
8591   sal.pspace = current_program_space;
8592
8593   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8594
8595   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8596   b->disposition = tempflag ? disp_del : disp_donttouch;
8597 }
8598
8599 void
8600 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8601 {
8602   add_to_breakpoint_chain (b);
8603   set_breakpoint_number (internal, b);
8604   if (is_tracepoint (b))
8605     set_tracepoint_count (breakpoint_count);
8606   if (!internal)
8607     mention (b);
8608   observer_notify_breakpoint_created (b);
8609
8610   if (update_gll)
8611     update_global_location_list (UGLL_MAY_INSERT);
8612 }
8613
8614 static void
8615 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8616                                     int tempflag, char *cond_string,
8617                                     const struct breakpoint_ops *ops)
8618 {
8619   struct fork_catchpoint *c = new fork_catchpoint ();
8620
8621   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8622
8623   c->forked_inferior_pid = null_ptid;
8624
8625   install_breakpoint (0, &c->base, 1);
8626 }
8627
8628 /* Exec catchpoints.  */
8629
8630 /* An instance of this type is used to represent an exec catchpoint.
8631    It includes a "struct breakpoint" as a kind of base class; users
8632    downcast to "struct breakpoint *" when needed.  A breakpoint is
8633    really of this type iff its ops pointer points to
8634    CATCH_EXEC_BREAKPOINT_OPS.  */
8635
8636 struct exec_catchpoint
8637 {
8638   /* The base class.  */
8639   struct breakpoint base;
8640
8641   /* Filename of a program whose exec triggered this catchpoint.
8642      This field is only valid immediately after this catchpoint has
8643      triggered.  */
8644   char *exec_pathname;
8645 };
8646
8647 /* Implement the "dtor" breakpoint_ops method for exec
8648    catchpoints.  */
8649
8650 static void
8651 dtor_catch_exec (struct breakpoint *b)
8652 {
8653   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8654
8655   xfree (c->exec_pathname);
8656
8657   base_breakpoint_ops.dtor (b);
8658 }
8659
8660 static int
8661 insert_catch_exec (struct bp_location *bl)
8662 {
8663   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8664 }
8665
8666 static int
8667 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8668 {
8669   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8670 }
8671
8672 static int
8673 breakpoint_hit_catch_exec (const struct bp_location *bl,
8674                            struct address_space *aspace, CORE_ADDR bp_addr,
8675                            const struct target_waitstatus *ws)
8676 {
8677   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8678
8679   if (ws->kind != TARGET_WAITKIND_EXECD)
8680     return 0;
8681
8682   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8683   return 1;
8684 }
8685
8686 static enum print_stop_action
8687 print_it_catch_exec (bpstat bs)
8688 {
8689   struct ui_out *uiout = current_uiout;
8690   struct breakpoint *b = bs->breakpoint_at;
8691   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8692
8693   annotate_catchpoint (b->number);
8694   maybe_print_thread_hit_breakpoint (uiout);
8695   if (b->disposition == disp_del)
8696     uiout->text ("Temporary catchpoint ");
8697   else
8698     uiout->text ("Catchpoint ");
8699   if (uiout->is_mi_like_p ())
8700     {
8701       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8702       uiout->field_string ("disp", bpdisp_text (b->disposition));
8703     }
8704   uiout->field_int ("bkptno", b->number);
8705   uiout->text (" (exec'd ");
8706   uiout->field_string ("new-exec", c->exec_pathname);
8707   uiout->text ("), ");
8708
8709   return PRINT_SRC_AND_LOC;
8710 }
8711
8712 static void
8713 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8714 {
8715   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8716   struct value_print_options opts;
8717   struct ui_out *uiout = current_uiout;
8718
8719   get_user_print_options (&opts);
8720
8721   /* Field 4, the address, is omitted (which makes the columns
8722      not line up too nicely with the headers, but the effect
8723      is relatively readable).  */
8724   if (opts.addressprint)
8725     uiout->field_skip ("addr");
8726   annotate_field (5);
8727   uiout->text ("exec");
8728   if (c->exec_pathname != NULL)
8729     {
8730       uiout->text (", program \"");
8731       uiout->field_string ("what", c->exec_pathname);
8732       uiout->text ("\" ");
8733     }
8734
8735   if (uiout->is_mi_like_p ())
8736     uiout->field_string ("catch-type", "exec");
8737 }
8738
8739 static void
8740 print_mention_catch_exec (struct breakpoint *b)
8741 {
8742   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8743 }
8744
8745 /* Implement the "print_recreate" breakpoint_ops method for exec
8746    catchpoints.  */
8747
8748 static void
8749 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8750 {
8751   fprintf_unfiltered (fp, "catch exec");
8752   print_recreate_thread (b, fp);
8753 }
8754
8755 static struct breakpoint_ops catch_exec_breakpoint_ops;
8756
8757 static int
8758 hw_breakpoint_used_count (void)
8759 {
8760   int i = 0;
8761   struct breakpoint *b;
8762   struct bp_location *bl;
8763
8764   ALL_BREAKPOINTS (b)
8765   {
8766     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8767       for (bl = b->loc; bl; bl = bl->next)
8768         {
8769           /* Special types of hardware breakpoints may use more than
8770              one register.  */
8771           i += b->ops->resources_needed (bl);
8772         }
8773   }
8774
8775   return i;
8776 }
8777
8778 /* Returns the resources B would use if it were a hardware
8779    watchpoint.  */
8780
8781 static int
8782 hw_watchpoint_use_count (struct breakpoint *b)
8783 {
8784   int i = 0;
8785   struct bp_location *bl;
8786
8787   if (!breakpoint_enabled (b))
8788     return 0;
8789
8790   for (bl = b->loc; bl; bl = bl->next)
8791     {
8792       /* Special types of hardware watchpoints may use more than
8793          one register.  */
8794       i += b->ops->resources_needed (bl);
8795     }
8796
8797   return i;
8798 }
8799
8800 /* Returns the sum the used resources of all hardware watchpoints of
8801    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8802    the sum of the used resources of all hardware watchpoints of other
8803    types _not_ TYPE.  */
8804
8805 static int
8806 hw_watchpoint_used_count_others (struct breakpoint *except,
8807                                  enum bptype type, int *other_type_used)
8808 {
8809   int i = 0;
8810   struct breakpoint *b;
8811
8812   *other_type_used = 0;
8813   ALL_BREAKPOINTS (b)
8814     {
8815       if (b == except)
8816         continue;
8817       if (!breakpoint_enabled (b))
8818         continue;
8819
8820       if (b->type == type)
8821         i += hw_watchpoint_use_count (b);
8822       else if (is_hardware_watchpoint (b))
8823         *other_type_used = 1;
8824     }
8825
8826   return i;
8827 }
8828
8829 void
8830 disable_watchpoints_before_interactive_call_start (void)
8831 {
8832   struct breakpoint *b;
8833
8834   ALL_BREAKPOINTS (b)
8835   {
8836     if (is_watchpoint (b) && breakpoint_enabled (b))
8837       {
8838         b->enable_state = bp_call_disabled;
8839         update_global_location_list (UGLL_DONT_INSERT);
8840       }
8841   }
8842 }
8843
8844 void
8845 enable_watchpoints_after_interactive_call_stop (void)
8846 {
8847   struct breakpoint *b;
8848
8849   ALL_BREAKPOINTS (b)
8850   {
8851     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8852       {
8853         b->enable_state = bp_enabled;
8854         update_global_location_list (UGLL_MAY_INSERT);
8855       }
8856   }
8857 }
8858
8859 void
8860 disable_breakpoints_before_startup (void)
8861 {
8862   current_program_space->executing_startup = 1;
8863   update_global_location_list (UGLL_DONT_INSERT);
8864 }
8865
8866 void
8867 enable_breakpoints_after_startup (void)
8868 {
8869   current_program_space->executing_startup = 0;
8870   breakpoint_re_set ();
8871 }
8872
8873 /* Create a new single-step breakpoint for thread THREAD, with no
8874    locations.  */
8875
8876 static struct breakpoint *
8877 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8878 {
8879   struct breakpoint *b = new breakpoint ();
8880
8881   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8882                                         &momentary_breakpoint_ops);
8883
8884   b->disposition = disp_donttouch;
8885   b->frame_id = null_frame_id;
8886
8887   b->thread = thread;
8888   gdb_assert (b->thread != 0);
8889
8890   add_to_breakpoint_chain (b);
8891
8892   return b;
8893 }
8894
8895 /* Set a momentary breakpoint of type TYPE at address specified by
8896    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8897    frame.  */
8898
8899 struct breakpoint *
8900 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8901                           struct frame_id frame_id, enum bptype type)
8902 {
8903   struct breakpoint *b;
8904
8905   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8906      tail-called one.  */
8907   gdb_assert (!frame_id_artificial_p (frame_id));
8908
8909   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8910   b->enable_state = bp_enabled;
8911   b->disposition = disp_donttouch;
8912   b->frame_id = frame_id;
8913
8914   /* If we're debugging a multi-threaded program, then we want
8915      momentary breakpoints to be active in only a single thread of
8916      control.  */
8917   if (in_thread_list (inferior_ptid))
8918     b->thread = ptid_to_global_thread_id (inferior_ptid);
8919
8920   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8921
8922   return b;
8923 }
8924
8925 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8926    The new breakpoint will have type TYPE, use OPS as its
8927    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8928
8929 static struct breakpoint *
8930 momentary_breakpoint_from_master (struct breakpoint *orig,
8931                                   enum bptype type,
8932                                   const struct breakpoint_ops *ops,
8933                                   int loc_enabled)
8934 {
8935   struct breakpoint *copy;
8936
8937   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8938   copy->loc = allocate_bp_location (copy);
8939   set_breakpoint_location_function (copy->loc, 1);
8940
8941   copy->loc->gdbarch = orig->loc->gdbarch;
8942   copy->loc->requested_address = orig->loc->requested_address;
8943   copy->loc->address = orig->loc->address;
8944   copy->loc->section = orig->loc->section;
8945   copy->loc->pspace = orig->loc->pspace;
8946   copy->loc->probe = orig->loc->probe;
8947   copy->loc->line_number = orig->loc->line_number;
8948   copy->loc->symtab = orig->loc->symtab;
8949   copy->loc->enabled = loc_enabled;
8950   copy->frame_id = orig->frame_id;
8951   copy->thread = orig->thread;
8952   copy->pspace = orig->pspace;
8953
8954   copy->enable_state = bp_enabled;
8955   copy->disposition = disp_donttouch;
8956   copy->number = internal_breakpoint_number--;
8957
8958   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8959   return copy;
8960 }
8961
8962 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8963    ORIG is NULL.  */
8964
8965 struct breakpoint *
8966 clone_momentary_breakpoint (struct breakpoint *orig)
8967 {
8968   /* If there's nothing to clone, then return nothing.  */
8969   if (orig == NULL)
8970     return NULL;
8971
8972   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8973 }
8974
8975 struct breakpoint *
8976 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8977                                 enum bptype type)
8978 {
8979   struct symtab_and_line sal;
8980
8981   sal = find_pc_line (pc, 0);
8982   sal.pc = pc;
8983   sal.section = find_pc_overlay (pc);
8984   sal.explicit_pc = 1;
8985
8986   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8987 }
8988 \f
8989
8990 /* Tell the user we have just set a breakpoint B.  */
8991
8992 static void
8993 mention (struct breakpoint *b)
8994 {
8995   b->ops->print_mention (b);
8996   if (current_uiout->is_mi_like_p ())
8997     return;
8998   printf_filtered ("\n");
8999 }
9000 \f
9001
9002 static int bp_loc_is_permanent (struct bp_location *loc);
9003
9004 static struct bp_location *
9005 add_location_to_breakpoint (struct breakpoint *b,
9006                             const struct symtab_and_line *sal)
9007 {
9008   struct bp_location *loc, **tmp;
9009   CORE_ADDR adjusted_address;
9010   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9011
9012   if (loc_gdbarch == NULL)
9013     loc_gdbarch = b->gdbarch;
9014
9015   /* Adjust the breakpoint's address prior to allocating a location.
9016      Once we call allocate_bp_location(), that mostly uninitialized
9017      location will be placed on the location chain.  Adjustment of the
9018      breakpoint may cause target_read_memory() to be called and we do
9019      not want its scan of the location chain to find a breakpoint and
9020      location that's only been partially initialized.  */
9021   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9022                                                 sal->pc, b->type);
9023
9024   /* Sort the locations by their ADDRESS.  */
9025   loc = allocate_bp_location (b);
9026   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9027        tmp = &((*tmp)->next))
9028     ;
9029   loc->next = *tmp;
9030   *tmp = loc;
9031
9032   loc->requested_address = sal->pc;
9033   loc->address = adjusted_address;
9034   loc->pspace = sal->pspace;
9035   loc->probe.probe = sal->probe;
9036   loc->probe.objfile = sal->objfile;
9037   gdb_assert (loc->pspace != NULL);
9038   loc->section = sal->section;
9039   loc->gdbarch = loc_gdbarch;
9040   loc->line_number = sal->line;
9041   loc->symtab = sal->symtab;
9042
9043   set_breakpoint_location_function (loc,
9044                                     sal->explicit_pc || sal->explicit_line);
9045
9046   /* While by definition, permanent breakpoints are already present in the
9047      code, we don't mark the location as inserted.  Normally one would expect
9048      that GDB could rely on that breakpoint instruction to stop the program,
9049      thus removing the need to insert its own breakpoint, except that executing
9050      the breakpoint instruction can kill the target instead of reporting a
9051      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
9052      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
9053      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
9054      breakpoint be inserted normally results in QEMU knowing about the GDB
9055      breakpoint, and thus trap before the breakpoint instruction is executed.
9056      (If GDB later needs to continue execution past the permanent breakpoint,
9057      it manually increments the PC, thus avoiding executing the breakpoint
9058      instruction.)  */
9059   if (bp_loc_is_permanent (loc))
9060     loc->permanent = 1;
9061
9062   return loc;
9063 }
9064 \f
9065
9066 /* See breakpoint.h.  */
9067
9068 int
9069 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
9070 {
9071   int len;
9072   CORE_ADDR addr;
9073   const gdb_byte *bpoint;
9074   gdb_byte *target_mem;
9075   struct cleanup *cleanup;
9076   int retval = 0;
9077
9078   addr = address;
9079   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
9080
9081   /* Software breakpoints unsupported?  */
9082   if (bpoint == NULL)
9083     return 0;
9084
9085   target_mem = (gdb_byte *) alloca (len);
9086
9087   /* Enable the automatic memory restoration from breakpoints while
9088      we read the memory.  Otherwise we could say about our temporary
9089      breakpoints they are permanent.  */
9090   cleanup = make_show_memory_breakpoints_cleanup (0);
9091
9092   if (target_read_memory (address, target_mem, len) == 0
9093       && memcmp (target_mem, bpoint, len) == 0)
9094     retval = 1;
9095
9096   do_cleanups (cleanup);
9097
9098   return retval;
9099 }
9100
9101 /* Return 1 if LOC is pointing to a permanent breakpoint,
9102    return 0 otherwise.  */
9103
9104 static int
9105 bp_loc_is_permanent (struct bp_location *loc)
9106 {
9107   struct cleanup *cleanup;
9108   int retval;
9109
9110   gdb_assert (loc != NULL);
9111
9112   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
9113      attempt to read from the addresses the locations of these breakpoint types
9114      point to.  program_breakpoint_here_p, below, will attempt to read
9115      memory.  */
9116   if (!breakpoint_address_is_meaningful (loc->owner))
9117     return 0;
9118
9119   cleanup = save_current_space_and_thread ();
9120   switch_to_program_space_and_thread (loc->pspace);
9121
9122   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
9123
9124   do_cleanups (cleanup);
9125
9126   return retval;
9127 }
9128
9129 /* Build a command list for the dprintf corresponding to the current
9130    settings of the dprintf style options.  */
9131
9132 static void
9133 update_dprintf_command_list (struct breakpoint *b)
9134 {
9135   char *dprintf_args = b->extra_string;
9136   char *printf_line = NULL;
9137
9138   if (!dprintf_args)
9139     return;
9140
9141   dprintf_args = skip_spaces (dprintf_args);
9142
9143   /* Allow a comma, as it may have terminated a location, but don't
9144      insist on it.  */
9145   if (*dprintf_args == ',')
9146     ++dprintf_args;
9147   dprintf_args = skip_spaces (dprintf_args);
9148
9149   if (*dprintf_args != '"')
9150     error (_("Bad format string, missing '\"'."));
9151
9152   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9153     printf_line = xstrprintf ("printf %s", dprintf_args);
9154   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9155     {
9156       if (!dprintf_function)
9157         error (_("No function supplied for dprintf call"));
9158
9159       if (dprintf_channel && strlen (dprintf_channel) > 0)
9160         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9161                                   dprintf_function,
9162                                   dprintf_channel,
9163                                   dprintf_args);
9164       else
9165         printf_line = xstrprintf ("call (void) %s (%s)",
9166                                   dprintf_function,
9167                                   dprintf_args);
9168     }
9169   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9170     {
9171       if (target_can_run_breakpoint_commands ())
9172         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9173       else
9174         {
9175           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9176           printf_line = xstrprintf ("printf %s", dprintf_args);
9177         }
9178     }
9179   else
9180     internal_error (__FILE__, __LINE__,
9181                     _("Invalid dprintf style."));
9182
9183   gdb_assert (printf_line != NULL);
9184   /* Manufacture a printf sequence.  */
9185   {
9186     struct command_line *printf_cmd_line = XNEW (struct command_line);
9187
9188     printf_cmd_line->control_type = simple_control;
9189     printf_cmd_line->body_count = 0;
9190     printf_cmd_line->body_list = NULL;
9191     printf_cmd_line->next = NULL;
9192     printf_cmd_line->line = printf_line;
9193
9194     breakpoint_set_commands (b, printf_cmd_line);
9195   }
9196 }
9197
9198 /* Update all dprintf commands, making their command lists reflect
9199    current style settings.  */
9200
9201 static void
9202 update_dprintf_commands (char *args, int from_tty,
9203                          struct cmd_list_element *c)
9204 {
9205   struct breakpoint *b;
9206
9207   ALL_BREAKPOINTS (b)
9208     {
9209       if (b->type == bp_dprintf)
9210         update_dprintf_command_list (b);
9211     }
9212 }
9213
9214 /* Create a breakpoint with SAL as location.  Use LOCATION
9215    as a description of the location, and COND_STRING
9216    as condition expression.  If LOCATION is NULL then create an
9217    "address location" from the address in the SAL.  */
9218
9219 static void
9220 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9221                      struct symtabs_and_lines sals,
9222                      struct event_location *location,
9223                      char *filter, char *cond_string,
9224                      char *extra_string,
9225                      enum bptype type, enum bpdisp disposition,
9226                      int thread, int task, int ignore_count,
9227                      const struct breakpoint_ops *ops, int from_tty,
9228                      int enabled, int internal, unsigned flags,
9229                      int display_canonical)
9230 {
9231   int i;
9232
9233   if (type == bp_hardware_breakpoint)
9234     {
9235       int target_resources_ok;
9236
9237       i = hw_breakpoint_used_count ();
9238       target_resources_ok =
9239         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9240                                             i + 1, 0);
9241       if (target_resources_ok == 0)
9242         error (_("No hardware breakpoint support in the target."));
9243       else if (target_resources_ok < 0)
9244         error (_("Hardware breakpoints used exceeds limit."));
9245     }
9246
9247   gdb_assert (sals.nelts > 0);
9248
9249   for (i = 0; i < sals.nelts; ++i)
9250     {
9251       struct symtab_and_line sal = sals.sals[i];
9252       struct bp_location *loc;
9253
9254       if (from_tty)
9255         {
9256           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9257           if (!loc_gdbarch)
9258             loc_gdbarch = gdbarch;
9259
9260           describe_other_breakpoints (loc_gdbarch,
9261                                       sal.pspace, sal.pc, sal.section, thread);
9262         }
9263
9264       if (i == 0)
9265         {
9266           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9267           b->thread = thread;
9268           b->task = task;
9269
9270           b->cond_string = cond_string;
9271           b->extra_string = extra_string;
9272           b->ignore_count = ignore_count;
9273           b->enable_state = enabled ? bp_enabled : bp_disabled;
9274           b->disposition = disposition;
9275
9276           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9277             b->loc->inserted = 1;
9278
9279           if (type == bp_static_tracepoint)
9280             {
9281               struct tracepoint *t = (struct tracepoint *) b;
9282               struct static_tracepoint_marker marker;
9283
9284               if (strace_marker_p (b))
9285                 {
9286                   /* We already know the marker exists, otherwise, we
9287                      wouldn't see a sal for it.  */
9288                   const char *p = &event_location_to_string (b->location)[3];
9289                   const char *endp;
9290                   char *marker_str;
9291
9292                   p = skip_spaces_const (p);
9293
9294                   endp = skip_to_space_const (p);
9295
9296                   marker_str = savestring (p, endp - p);
9297                   t->static_trace_marker_id = marker_str;
9298
9299                   printf_filtered (_("Probed static tracepoint "
9300                                      "marker \"%s\"\n"),
9301                                    t->static_trace_marker_id);
9302                 }
9303               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9304                 {
9305                   t->static_trace_marker_id = xstrdup (marker.str_id);
9306                   release_static_tracepoint_marker (&marker);
9307
9308                   printf_filtered (_("Probed static tracepoint "
9309                                      "marker \"%s\"\n"),
9310                                    t->static_trace_marker_id);
9311                 }
9312               else
9313                 warning (_("Couldn't determine the static "
9314                            "tracepoint marker to probe"));
9315             }
9316
9317           loc = b->loc;
9318         }
9319       else
9320         {
9321           loc = add_location_to_breakpoint (b, &sal);
9322           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9323             loc->inserted = 1;
9324         }
9325
9326       if (b->cond_string)
9327         {
9328           const char *arg = b->cond_string;
9329
9330           loc->cond = parse_exp_1 (&arg, loc->address,
9331                                    block_for_pc (loc->address), 0);
9332           if (*arg)
9333               error (_("Garbage '%s' follows condition"), arg);
9334         }
9335
9336       /* Dynamic printf requires and uses additional arguments on the
9337          command line, otherwise it's an error.  */
9338       if (type == bp_dprintf)
9339         {
9340           if (b->extra_string)
9341             update_dprintf_command_list (b);
9342           else
9343             error (_("Format string required"));
9344         }
9345       else if (b->extra_string)
9346         error (_("Garbage '%s' at end of command"), b->extra_string);
9347     }
9348
9349   b->display_canonical = display_canonical;
9350   if (location != NULL)
9351     b->location = location;
9352   else
9353     {
9354       const char *addr_string = NULL;
9355       int addr_string_len = 0;
9356
9357       if (location != NULL)
9358         addr_string = event_location_to_string (location);
9359       if (addr_string != NULL)
9360         addr_string_len = strlen (addr_string);
9361
9362       b->location = new_address_location (b->loc->address,
9363                                           addr_string, addr_string_len);
9364     }
9365   b->filter = filter;
9366 }
9367
9368 static void
9369 create_breakpoint_sal (struct gdbarch *gdbarch,
9370                        struct symtabs_and_lines sals,
9371                        struct event_location *location,
9372                        char *filter, char *cond_string,
9373                        char *extra_string,
9374                        enum bptype type, enum bpdisp disposition,
9375                        int thread, int task, int ignore_count,
9376                        const struct breakpoint_ops *ops, int from_tty,
9377                        int enabled, int internal, unsigned flags,
9378                        int display_canonical)
9379 {
9380   struct breakpoint *b;
9381   struct cleanup *old_chain;
9382
9383   if (is_tracepoint_type (type))
9384     {
9385       struct tracepoint *t;
9386
9387       t = new tracepoint ();
9388       b = &t->base;
9389     }
9390   else
9391     b = new breakpoint ();
9392
9393   old_chain = make_cleanup (xfree, b);
9394
9395   init_breakpoint_sal (b, gdbarch,
9396                        sals, location,
9397                        filter, cond_string, extra_string,
9398                        type, disposition,
9399                        thread, task, ignore_count,
9400                        ops, from_tty,
9401                        enabled, internal, flags,
9402                        display_canonical);
9403   discard_cleanups (old_chain);
9404
9405   install_breakpoint (internal, b, 0);
9406 }
9407
9408 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9409    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9410    value.  COND_STRING, if not NULL, specified the condition to be
9411    used for all breakpoints.  Essentially the only case where
9412    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9413    function.  In that case, it's still not possible to specify
9414    separate conditions for different overloaded functions, so
9415    we take just a single condition string.
9416    
9417    NOTE: If the function succeeds, the caller is expected to cleanup
9418    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9419    array contents).  If the function fails (error() is called), the
9420    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9421    COND and SALS arrays and each of those arrays contents.  */
9422
9423 static void
9424 create_breakpoints_sal (struct gdbarch *gdbarch,
9425                         struct linespec_result *canonical,
9426                         char *cond_string, char *extra_string,
9427                         enum bptype type, enum bpdisp disposition,
9428                         int thread, int task, int ignore_count,
9429                         const struct breakpoint_ops *ops, int from_tty,
9430                         int enabled, int internal, unsigned flags)
9431 {
9432   int i;
9433   struct linespec_sals *lsal;
9434
9435   if (canonical->pre_expanded)
9436     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9437
9438   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9439     {
9440       /* Note that 'location' can be NULL in the case of a plain
9441          'break', without arguments.  */
9442       struct event_location *location
9443         = (canonical->location != NULL
9444            ? copy_event_location (canonical->location) : NULL);
9445       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9446       struct cleanup *inner = make_cleanup_delete_event_location (location);
9447
9448       make_cleanup (xfree, filter_string);
9449       create_breakpoint_sal (gdbarch, lsal->sals,
9450                              location,
9451                              filter_string,
9452                              cond_string, extra_string,
9453                              type, disposition,
9454                              thread, task, ignore_count, ops,
9455                              from_tty, enabled, internal, flags,
9456                              canonical->special_display);
9457       discard_cleanups (inner);
9458     }
9459 }
9460
9461 /* Parse LOCATION which is assumed to be a SAL specification possibly
9462    followed by conditionals.  On return, SALS contains an array of SAL
9463    addresses found.  LOCATION points to the end of the SAL (for
9464    linespec locations).
9465
9466    The array and the line spec strings are allocated on the heap, it is
9467    the caller's responsibility to free them.  */
9468
9469 static void
9470 parse_breakpoint_sals (const struct event_location *location,
9471                        struct linespec_result *canonical)
9472 {
9473   struct symtab_and_line cursal;
9474
9475   if (event_location_type (location) == LINESPEC_LOCATION)
9476     {
9477       const char *address = get_linespec_location (location);
9478
9479       if (address == NULL)
9480         {
9481           /* The last displayed codepoint, if it's valid, is our default
9482              breakpoint address.  */
9483           if (last_displayed_sal_is_valid ())
9484             {
9485               struct linespec_sals lsal;
9486               struct symtab_and_line sal;
9487               CORE_ADDR pc;
9488
9489               init_sal (&sal);          /* Initialize to zeroes.  */
9490               lsal.sals.sals = XNEW (struct symtab_and_line);
9491
9492               /* Set sal's pspace, pc, symtab, and line to the values
9493                  corresponding to the last call to print_frame_info.
9494                  Be sure to reinitialize LINE with NOTCURRENT == 0
9495                  as the breakpoint line number is inappropriate otherwise.
9496                  find_pc_line would adjust PC, re-set it back.  */
9497               get_last_displayed_sal (&sal);
9498               pc = sal.pc;
9499               sal = find_pc_line (pc, 0);
9500
9501               /* "break" without arguments is equivalent to "break *PC"
9502                  where PC is the last displayed codepoint's address.  So
9503                  make sure to set sal.explicit_pc to prevent GDB from
9504                  trying to expand the list of sals to include all other
9505                  instances with the same symtab and line.  */
9506               sal.pc = pc;
9507               sal.explicit_pc = 1;
9508
9509               lsal.sals.sals[0] = sal;
9510               lsal.sals.nelts = 1;
9511               lsal.canonical = NULL;
9512
9513               VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9514               return;
9515             }
9516           else
9517             error (_("No default breakpoint address now."));
9518         }
9519     }
9520
9521   /* Force almost all breakpoints to be in terms of the
9522      current_source_symtab (which is decode_line_1's default).
9523      This should produce the results we want almost all of the
9524      time while leaving default_breakpoint_* alone.
9525
9526      ObjC: However, don't match an Objective-C method name which
9527      may have a '+' or '-' succeeded by a '['.  */
9528   cursal = get_current_source_symtab_and_line ();
9529   if (last_displayed_sal_is_valid ())
9530     {
9531       const char *address = NULL;
9532
9533       if (event_location_type (location) == LINESPEC_LOCATION)
9534         address = get_linespec_location (location);
9535
9536       if (!cursal.symtab
9537           || (address != NULL
9538               && strchr ("+-", address[0]) != NULL
9539               && address[1] != '['))
9540         {
9541           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9542                             get_last_displayed_symtab (),
9543                             get_last_displayed_line (),
9544                             canonical, NULL, NULL);
9545           return;
9546         }
9547     }
9548
9549   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9550                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9551 }
9552
9553
9554 /* Convert each SAL into a real PC.  Verify that the PC can be
9555    inserted as a breakpoint.  If it can't throw an error.  */
9556
9557 static void
9558 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9559 {    
9560   int i;
9561
9562   for (i = 0; i < sals->nelts; i++)
9563     resolve_sal_pc (&sals->sals[i]);
9564 }
9565
9566 /* Fast tracepoints may have restrictions on valid locations.  For
9567    instance, a fast tracepoint using a jump instead of a trap will
9568    likely have to overwrite more bytes than a trap would, and so can
9569    only be placed where the instruction is longer than the jump, or a
9570    multi-instruction sequence does not have a jump into the middle of
9571    it, etc.  */
9572
9573 static void
9574 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9575                             struct symtabs_and_lines *sals)
9576 {
9577   int i, rslt;
9578   struct symtab_and_line *sal;
9579   char *msg;
9580   struct cleanup *old_chain;
9581
9582   for (i = 0; i < sals->nelts; i++)
9583     {
9584       struct gdbarch *sarch;
9585
9586       sal = &sals->sals[i];
9587
9588       sarch = get_sal_arch (*sal);
9589       /* We fall back to GDBARCH if there is no architecture
9590          associated with SAL.  */
9591       if (sarch == NULL)
9592         sarch = gdbarch;
9593       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc, &msg);
9594       old_chain = make_cleanup (xfree, msg);
9595
9596       if (!rslt)
9597         error (_("May not have a fast tracepoint at %s%s"),
9598                paddress (sarch, sal->pc), (msg ? msg : ""));
9599
9600       do_cleanups (old_chain);
9601     }
9602 }
9603
9604 /* Given TOK, a string specification of condition and thread, as
9605    accepted by the 'break' command, extract the condition
9606    string and thread number and set *COND_STRING and *THREAD.
9607    PC identifies the context at which the condition should be parsed.
9608    If no condition is found, *COND_STRING is set to NULL.
9609    If no thread is found, *THREAD is set to -1.  */
9610
9611 static void
9612 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9613                            char **cond_string, int *thread, int *task,
9614                            char **rest)
9615 {
9616   *cond_string = NULL;
9617   *thread = -1;
9618   *task = 0;
9619   *rest = NULL;
9620
9621   while (tok && *tok)
9622     {
9623       const char *end_tok;
9624       int toklen;
9625       const char *cond_start = NULL;
9626       const char *cond_end = NULL;
9627
9628       tok = skip_spaces_const (tok);
9629
9630       if ((*tok == '"' || *tok == ',') && rest)
9631         {
9632           *rest = savestring (tok, strlen (tok));
9633           return;
9634         }
9635
9636       end_tok = skip_to_space_const (tok);
9637
9638       toklen = end_tok - tok;
9639
9640       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9641         {
9642           tok = cond_start = end_tok + 1;
9643           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9644           cond_end = tok;
9645           *cond_string = savestring (cond_start, cond_end - cond_start);
9646         }
9647       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9648         {
9649           const char *tmptok;
9650           struct thread_info *thr;
9651
9652           tok = end_tok + 1;
9653           thr = parse_thread_id (tok, &tmptok);
9654           if (tok == tmptok)
9655             error (_("Junk after thread keyword."));
9656           *thread = thr->global_num;
9657           tok = tmptok;
9658         }
9659       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9660         {
9661           char *tmptok;
9662
9663           tok = end_tok + 1;
9664           *task = strtol (tok, &tmptok, 0);
9665           if (tok == tmptok)
9666             error (_("Junk after task keyword."));
9667           if (!valid_task_id (*task))
9668             error (_("Unknown task %d."), *task);
9669           tok = tmptok;
9670         }
9671       else if (rest)
9672         {
9673           *rest = savestring (tok, strlen (tok));
9674           return;
9675         }
9676       else
9677         error (_("Junk at end of arguments."));
9678     }
9679 }
9680
9681 /* Decode a static tracepoint marker spec.  */
9682
9683 static struct symtabs_and_lines
9684 decode_static_tracepoint_spec (const char **arg_p)
9685 {
9686   VEC(static_tracepoint_marker_p) *markers = NULL;
9687   struct symtabs_and_lines sals;
9688   struct cleanup *old_chain;
9689   const char *p = &(*arg_p)[3];
9690   const char *endp;
9691   char *marker_str;
9692   int i;
9693
9694   p = skip_spaces_const (p);
9695
9696   endp = skip_to_space_const (p);
9697
9698   marker_str = savestring (p, endp - p);
9699   old_chain = make_cleanup (xfree, marker_str);
9700
9701   markers = target_static_tracepoint_markers_by_strid (marker_str);
9702   if (VEC_empty(static_tracepoint_marker_p, markers))
9703     error (_("No known static tracepoint marker named %s"), marker_str);
9704
9705   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9706   sals.sals = XNEWVEC (struct symtab_and_line, sals.nelts);
9707
9708   for (i = 0; i < sals.nelts; i++)
9709     {
9710       struct static_tracepoint_marker *marker;
9711
9712       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9713
9714       init_sal (&sals.sals[i]);
9715
9716       sals.sals[i] = find_pc_line (marker->address, 0);
9717       sals.sals[i].pc = marker->address;
9718
9719       release_static_tracepoint_marker (marker);
9720     }
9721
9722   do_cleanups (old_chain);
9723
9724   *arg_p = endp;
9725   return sals;
9726 }
9727
9728 /* See breakpoint.h.  */
9729
9730 int
9731 create_breakpoint (struct gdbarch *gdbarch,
9732                    const struct event_location *location, char *cond_string,
9733                    int thread, char *extra_string,
9734                    int parse_extra,
9735                    int tempflag, enum bptype type_wanted,
9736                    int ignore_count,
9737                    enum auto_boolean pending_break_support,
9738                    const struct breakpoint_ops *ops,
9739                    int from_tty, int enabled, int internal,
9740                    unsigned flags)
9741 {
9742   struct linespec_result canonical;
9743   struct cleanup *old_chain;
9744   struct cleanup *bkpt_chain = NULL;
9745   int pending = 0;
9746   int task = 0;
9747   int prev_bkpt_count = breakpoint_count;
9748
9749   gdb_assert (ops != NULL);
9750
9751   /* If extra_string isn't useful, set it to NULL.  */
9752   if (extra_string != NULL && *extra_string == '\0')
9753     extra_string = NULL;
9754
9755   init_linespec_result (&canonical);
9756
9757   TRY
9758     {
9759       ops->create_sals_from_location (location, &canonical, type_wanted);
9760     }
9761   CATCH (e, RETURN_MASK_ERROR)
9762     {
9763       /* If caller is interested in rc value from parse, set
9764          value.  */
9765       if (e.error == NOT_FOUND_ERROR)
9766         {
9767           /* If pending breakpoint support is turned off, throw
9768              error.  */
9769
9770           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9771             throw_exception (e);
9772
9773           exception_print (gdb_stderr, e);
9774
9775           /* If pending breakpoint support is auto query and the user
9776              selects no, then simply return the error code.  */
9777           if (pending_break_support == AUTO_BOOLEAN_AUTO
9778               && !nquery (_("Make %s pending on future shared library load? "),
9779                           bptype_string (type_wanted)))
9780             return 0;
9781
9782           /* At this point, either the user was queried about setting
9783              a pending breakpoint and selected yes, or pending
9784              breakpoint behavior is on and thus a pending breakpoint
9785              is defaulted on behalf of the user.  */
9786           pending = 1;
9787         }
9788       else
9789         throw_exception (e);
9790     }
9791   END_CATCH
9792
9793   if (!pending && VEC_empty (linespec_sals, canonical.sals))
9794     return 0;
9795
9796   /* Create a chain of things that always need to be cleaned up.  */
9797   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9798
9799   /* ----------------------------- SNIP -----------------------------
9800      Anything added to the cleanup chain beyond this point is assumed
9801      to be part of a breakpoint.  If the breakpoint create succeeds
9802      then the memory is not reclaimed.  */
9803   bkpt_chain = make_cleanup (null_cleanup, 0);
9804
9805   /* Resolve all line numbers to PC's and verify that the addresses
9806      are ok for the target.  */
9807   if (!pending)
9808     {
9809       int ix;
9810       struct linespec_sals *iter;
9811
9812       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9813         breakpoint_sals_to_pc (&iter->sals);
9814     }
9815
9816   /* Fast tracepoints may have additional restrictions on location.  */
9817   if (!pending && type_wanted == bp_fast_tracepoint)
9818     {
9819       int ix;
9820       struct linespec_sals *iter;
9821
9822       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9823         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9824     }
9825
9826   /* Verify that condition can be parsed, before setting any
9827      breakpoints.  Allocate a separate condition expression for each
9828      breakpoint.  */
9829   if (!pending)
9830     {
9831       if (parse_extra)
9832         {
9833           char *rest;
9834           struct linespec_sals *lsal;
9835
9836           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9837
9838           /* Here we only parse 'arg' to separate condition
9839              from thread number, so parsing in context of first
9840              sal is OK.  When setting the breakpoint we'll
9841              re-parse it in context of each sal.  */
9842
9843           find_condition_and_thread (extra_string, lsal->sals.sals[0].pc,
9844                                      &cond_string, &thread, &task, &rest);
9845           if (cond_string)
9846             make_cleanup (xfree, cond_string);
9847           if (rest)
9848             make_cleanup (xfree, rest);
9849           if (rest)
9850             extra_string = rest;
9851           else
9852             extra_string = NULL;
9853         }
9854       else
9855         {
9856           if (type_wanted != bp_dprintf
9857               && extra_string != NULL && *extra_string != '\0')
9858                 error (_("Garbage '%s' at end of location"), extra_string);
9859
9860           /* Create a private copy of condition string.  */
9861           if (cond_string)
9862             {
9863               cond_string = xstrdup (cond_string);
9864               make_cleanup (xfree, cond_string);
9865             }
9866           /* Create a private copy of any extra string.  */
9867           if (extra_string)
9868             {
9869               extra_string = xstrdup (extra_string);
9870               make_cleanup (xfree, extra_string);
9871             }
9872         }
9873
9874       ops->create_breakpoints_sal (gdbarch, &canonical,
9875                                    cond_string, extra_string, type_wanted,
9876                                    tempflag ? disp_del : disp_donttouch,
9877                                    thread, task, ignore_count, ops,
9878                                    from_tty, enabled, internal, flags);
9879     }
9880   else
9881     {
9882       struct breakpoint *b;
9883
9884       if (is_tracepoint_type (type_wanted))
9885         {
9886           struct tracepoint *t;
9887
9888           t = new tracepoint ();
9889           b = &t->base;
9890         }
9891       else
9892         b = new breakpoint ();
9893
9894       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9895       b->location = copy_event_location (location);
9896
9897       if (parse_extra)
9898         b->cond_string = NULL;
9899       else
9900         {
9901           /* Create a private copy of condition string.  */
9902           if (cond_string)
9903             {
9904               cond_string = xstrdup (cond_string);
9905               make_cleanup (xfree, cond_string);
9906             }
9907           b->cond_string = cond_string;
9908           b->thread = thread;
9909         }
9910
9911       /* Create a private copy of any extra string.  */
9912       if (extra_string != NULL)
9913         {
9914           extra_string = xstrdup (extra_string);
9915           make_cleanup (xfree, extra_string);
9916         }
9917       b->extra_string = extra_string;
9918       b->ignore_count = ignore_count;
9919       b->disposition = tempflag ? disp_del : disp_donttouch;
9920       b->condition_not_parsed = 1;
9921       b->enable_state = enabled ? bp_enabled : bp_disabled;
9922       if ((type_wanted != bp_breakpoint
9923            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9924         b->pspace = current_program_space;
9925
9926       install_breakpoint (internal, b, 0);
9927     }
9928   
9929   if (VEC_length (linespec_sals, canonical.sals) > 1)
9930     {
9931       warning (_("Multiple breakpoints were set.\nUse the "
9932                  "\"delete\" command to delete unwanted breakpoints."));
9933       prev_breakpoint_count = prev_bkpt_count;
9934     }
9935
9936   /* That's it.  Discard the cleanups for data inserted into the
9937      breakpoint.  */
9938   discard_cleanups (bkpt_chain);
9939   /* But cleanup everything else.  */
9940   do_cleanups (old_chain);
9941
9942   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9943   update_global_location_list (UGLL_MAY_INSERT);
9944
9945   return 1;
9946 }
9947
9948 /* Set a breakpoint.
9949    ARG is a string describing breakpoint address,
9950    condition, and thread.
9951    FLAG specifies if a breakpoint is hardware on,
9952    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9953    and BP_TEMPFLAG.  */
9954
9955 static void
9956 break_command_1 (char *arg, int flag, int from_tty)
9957 {
9958   int tempflag = flag & BP_TEMPFLAG;
9959   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9960                              ? bp_hardware_breakpoint
9961                              : bp_breakpoint);
9962   struct breakpoint_ops *ops;
9963   struct event_location *location;
9964   struct cleanup *cleanup;
9965
9966   location = string_to_event_location (&arg, current_language);
9967   cleanup = make_cleanup_delete_event_location (location);
9968
9969   /* Matching breakpoints on probes.  */
9970   if (location != NULL
9971       && event_location_type (location) == PROBE_LOCATION)
9972     ops = &bkpt_probe_breakpoint_ops;
9973   else
9974     ops = &bkpt_breakpoint_ops;
9975
9976   create_breakpoint (get_current_arch (),
9977                      location,
9978                      NULL, 0, arg, 1 /* parse arg */,
9979                      tempflag, type_wanted,
9980                      0 /* Ignore count */,
9981                      pending_break_support,
9982                      ops,
9983                      from_tty,
9984                      1 /* enabled */,
9985                      0 /* internal */,
9986                      0);
9987   do_cleanups (cleanup);
9988 }
9989
9990 /* Helper function for break_command_1 and disassemble_command.  */
9991
9992 void
9993 resolve_sal_pc (struct symtab_and_line *sal)
9994 {
9995   CORE_ADDR pc;
9996
9997   if (sal->pc == 0 && sal->symtab != NULL)
9998     {
9999       if (!find_line_pc (sal->symtab, sal->line, &pc))
10000         error (_("No line %d in file \"%s\"."),
10001                sal->line, symtab_to_filename_for_display (sal->symtab));
10002       sal->pc = pc;
10003
10004       /* If this SAL corresponds to a breakpoint inserted using a line
10005          number, then skip the function prologue if necessary.  */
10006       if (sal->explicit_line)
10007         skip_prologue_sal (sal);
10008     }
10009
10010   if (sal->section == 0 && sal->symtab != NULL)
10011     {
10012       const struct blockvector *bv;
10013       const struct block *b;
10014       struct symbol *sym;
10015
10016       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
10017                                     SYMTAB_COMPUNIT (sal->symtab));
10018       if (bv != NULL)
10019         {
10020           sym = block_linkage_function (b);
10021           if (sym != NULL)
10022             {
10023               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
10024               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
10025                                                  sym);
10026             }
10027           else
10028             {
10029               /* It really is worthwhile to have the section, so we'll
10030                  just have to look harder. This case can be executed
10031                  if we have line numbers but no functions (as can
10032                  happen in assembly source).  */
10033
10034               struct bound_minimal_symbol msym;
10035               struct cleanup *old_chain = save_current_space_and_thread ();
10036
10037               switch_to_program_space_and_thread (sal->pspace);
10038
10039               msym = lookup_minimal_symbol_by_pc (sal->pc);
10040               if (msym.minsym)
10041                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10042
10043               do_cleanups (old_chain);
10044             }
10045         }
10046     }
10047 }
10048
10049 void
10050 break_command (char *arg, int from_tty)
10051 {
10052   break_command_1 (arg, 0, from_tty);
10053 }
10054
10055 void
10056 tbreak_command (char *arg, int from_tty)
10057 {
10058   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10059 }
10060
10061 static void
10062 hbreak_command (char *arg, int from_tty)
10063 {
10064   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10065 }
10066
10067 static void
10068 thbreak_command (char *arg, int from_tty)
10069 {
10070   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10071 }
10072
10073 static void
10074 stop_command (char *arg, int from_tty)
10075 {
10076   printf_filtered (_("Specify the type of breakpoint to set.\n\
10077 Usage: stop in <function | address>\n\
10078        stop at <line>\n"));
10079 }
10080
10081 static void
10082 stopin_command (char *arg, int from_tty)
10083 {
10084   int badInput = 0;
10085
10086   if (arg == (char *) NULL)
10087     badInput = 1;
10088   else if (*arg != '*')
10089     {
10090       char *argptr = arg;
10091       int hasColon = 0;
10092
10093       /* Look for a ':'.  If this is a line number specification, then
10094          say it is bad, otherwise, it should be an address or
10095          function/method name.  */
10096       while (*argptr && !hasColon)
10097         {
10098           hasColon = (*argptr == ':');
10099           argptr++;
10100         }
10101
10102       if (hasColon)
10103         badInput = (*argptr != ':');    /* Not a class::method */
10104       else
10105         badInput = isdigit (*arg);      /* a simple line number */
10106     }
10107
10108   if (badInput)
10109     printf_filtered (_("Usage: stop in <function | address>\n"));
10110   else
10111     break_command_1 (arg, 0, from_tty);
10112 }
10113
10114 static void
10115 stopat_command (char *arg, int from_tty)
10116 {
10117   int badInput = 0;
10118
10119   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10120     badInput = 1;
10121   else
10122     {
10123       char *argptr = arg;
10124       int hasColon = 0;
10125
10126       /* Look for a ':'.  If there is a '::' then get out, otherwise
10127          it is probably a line number.  */
10128       while (*argptr && !hasColon)
10129         {
10130           hasColon = (*argptr == ':');
10131           argptr++;
10132         }
10133
10134       if (hasColon)
10135         badInput = (*argptr == ':');    /* we have class::method */
10136       else
10137         badInput = !isdigit (*arg);     /* not a line number */
10138     }
10139
10140   if (badInput)
10141     printf_filtered (_("Usage: stop at <line>\n"));
10142   else
10143     break_command_1 (arg, 0, from_tty);
10144 }
10145
10146 /* The dynamic printf command is mostly like a regular breakpoint, but
10147    with a prewired command list consisting of a single output command,
10148    built from extra arguments supplied on the dprintf command
10149    line.  */
10150
10151 static void
10152 dprintf_command (char *arg, int from_tty)
10153 {
10154   struct event_location *location;
10155   struct cleanup *cleanup;
10156
10157   location = string_to_event_location (&arg, current_language);
10158   cleanup = make_cleanup_delete_event_location (location);
10159
10160   /* If non-NULL, ARG should have been advanced past the location;
10161      the next character must be ','.  */
10162   if (arg != NULL)
10163     {
10164       if (arg[0] != ',' || arg[1] == '\0')
10165         error (_("Format string required"));
10166       else
10167         {
10168           /* Skip the comma.  */
10169           ++arg;
10170         }
10171     }
10172
10173   create_breakpoint (get_current_arch (),
10174                      location,
10175                      NULL, 0, arg, 1 /* parse arg */,
10176                      0, bp_dprintf,
10177                      0 /* Ignore count */,
10178                      pending_break_support,
10179                      &dprintf_breakpoint_ops,
10180                      from_tty,
10181                      1 /* enabled */,
10182                      0 /* internal */,
10183                      0);
10184   do_cleanups (cleanup);
10185 }
10186
10187 static void
10188 agent_printf_command (char *arg, int from_tty)
10189 {
10190   error (_("May only run agent-printf on the target"));
10191 }
10192
10193 /* Implement the "breakpoint_hit" breakpoint_ops method for
10194    ranged breakpoints.  */
10195
10196 static int
10197 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10198                                   struct address_space *aspace,
10199                                   CORE_ADDR bp_addr,
10200                                   const struct target_waitstatus *ws)
10201 {
10202   if (ws->kind != TARGET_WAITKIND_STOPPED
10203       || ws->value.sig != GDB_SIGNAL_TRAP)
10204     return 0;
10205
10206   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10207                                          bl->length, aspace, bp_addr);
10208 }
10209
10210 /* Implement the "resources_needed" breakpoint_ops method for
10211    ranged breakpoints.  */
10212
10213 static int
10214 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10215 {
10216   return target_ranged_break_num_registers ();
10217 }
10218
10219 /* Implement the "print_it" breakpoint_ops method for
10220    ranged breakpoints.  */
10221
10222 static enum print_stop_action
10223 print_it_ranged_breakpoint (bpstat bs)
10224 {
10225   struct breakpoint *b = bs->breakpoint_at;
10226   struct bp_location *bl = b->loc;
10227   struct ui_out *uiout = current_uiout;
10228
10229   gdb_assert (b->type == bp_hardware_breakpoint);
10230
10231   /* Ranged breakpoints have only one location.  */
10232   gdb_assert (bl && bl->next == NULL);
10233
10234   annotate_breakpoint (b->number);
10235
10236   maybe_print_thread_hit_breakpoint (uiout);
10237
10238   if (b->disposition == disp_del)
10239     uiout->text ("Temporary ranged breakpoint ");
10240   else
10241     uiout->text ("Ranged breakpoint ");
10242   if (uiout->is_mi_like_p ())
10243     {
10244       uiout->field_string ("reason",
10245                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10246       uiout->field_string ("disp", bpdisp_text (b->disposition));
10247     }
10248   uiout->field_int ("bkptno", b->number);
10249   uiout->text (", ");
10250
10251   return PRINT_SRC_AND_LOC;
10252 }
10253
10254 /* Implement the "print_one" breakpoint_ops method for
10255    ranged breakpoints.  */
10256
10257 static void
10258 print_one_ranged_breakpoint (struct breakpoint *b,
10259                              struct bp_location **last_loc)
10260 {
10261   struct bp_location *bl = b->loc;
10262   struct value_print_options opts;
10263   struct ui_out *uiout = current_uiout;
10264
10265   /* Ranged breakpoints have only one location.  */
10266   gdb_assert (bl && bl->next == NULL);
10267
10268   get_user_print_options (&opts);
10269
10270   if (opts.addressprint)
10271     /* We don't print the address range here, it will be printed later
10272        by print_one_detail_ranged_breakpoint.  */
10273     uiout->field_skip ("addr");
10274   annotate_field (5);
10275   print_breakpoint_location (b, bl);
10276   *last_loc = bl;
10277 }
10278
10279 /* Implement the "print_one_detail" breakpoint_ops method for
10280    ranged breakpoints.  */
10281
10282 static void
10283 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10284                                     struct ui_out *uiout)
10285 {
10286   CORE_ADDR address_start, address_end;
10287   struct bp_location *bl = b->loc;
10288   string_file stb;
10289
10290   gdb_assert (bl);
10291
10292   address_start = bl->address;
10293   address_end = address_start + bl->length - 1;
10294
10295   uiout->text ("\taddress range: ");
10296   stb.printf ("[%s, %s]",
10297               print_core_address (bl->gdbarch, address_start),
10298               print_core_address (bl->gdbarch, address_end));
10299   uiout->field_stream ("addr", stb);
10300   uiout->text ("\n");
10301 }
10302
10303 /* Implement the "print_mention" breakpoint_ops method for
10304    ranged breakpoints.  */
10305
10306 static void
10307 print_mention_ranged_breakpoint (struct breakpoint *b)
10308 {
10309   struct bp_location *bl = b->loc;
10310   struct ui_out *uiout = current_uiout;
10311
10312   gdb_assert (bl);
10313   gdb_assert (b->type == bp_hardware_breakpoint);
10314
10315   if (uiout->is_mi_like_p ())
10316     return;
10317
10318   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10319                    b->number, paddress (bl->gdbarch, bl->address),
10320                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10321 }
10322
10323 /* Implement the "print_recreate" breakpoint_ops method for
10324    ranged breakpoints.  */
10325
10326 static void
10327 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10328 {
10329   fprintf_unfiltered (fp, "break-range %s, %s",
10330                       event_location_to_string (b->location),
10331                       event_location_to_string (b->location_range_end));
10332   print_recreate_thread (b, fp);
10333 }
10334
10335 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10336
10337 static struct breakpoint_ops ranged_breakpoint_ops;
10338
10339 /* Find the address where the end of the breakpoint range should be
10340    placed, given the SAL of the end of the range.  This is so that if
10341    the user provides a line number, the end of the range is set to the
10342    last instruction of the given line.  */
10343
10344 static CORE_ADDR
10345 find_breakpoint_range_end (struct symtab_and_line sal)
10346 {
10347   CORE_ADDR end;
10348
10349   /* If the user provided a PC value, use it.  Otherwise,
10350      find the address of the end of the given location.  */
10351   if (sal.explicit_pc)
10352     end = sal.pc;
10353   else
10354     {
10355       int ret;
10356       CORE_ADDR start;
10357
10358       ret = find_line_pc_range (sal, &start, &end);
10359       if (!ret)
10360         error (_("Could not find location of the end of the range."));
10361
10362       /* find_line_pc_range returns the start of the next line.  */
10363       end--;
10364     }
10365
10366   return end;
10367 }
10368
10369 /* Implement the "break-range" CLI command.  */
10370
10371 static void
10372 break_range_command (char *arg, int from_tty)
10373 {
10374   char *arg_start, *addr_string_start;
10375   struct linespec_result canonical_start, canonical_end;
10376   int bp_count, can_use_bp, length;
10377   CORE_ADDR end;
10378   struct breakpoint *b;
10379   struct symtab_and_line sal_start, sal_end;
10380   struct cleanup *cleanup_bkpt;
10381   struct linespec_sals *lsal_start, *lsal_end;
10382   struct event_location *start_location, *end_location;
10383
10384   /* We don't support software ranged breakpoints.  */
10385   if (target_ranged_break_num_registers () < 0)
10386     error (_("This target does not support hardware ranged breakpoints."));
10387
10388   bp_count = hw_breakpoint_used_count ();
10389   bp_count += target_ranged_break_num_registers ();
10390   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10391                                                    bp_count, 0);
10392   if (can_use_bp < 0)
10393     error (_("Hardware breakpoints used exceeds limit."));
10394
10395   arg = skip_spaces (arg);
10396   if (arg == NULL || arg[0] == '\0')
10397     error(_("No address range specified."));
10398
10399   init_linespec_result (&canonical_start);
10400
10401   arg_start = arg;
10402   start_location = string_to_event_location (&arg, current_language);
10403   cleanup_bkpt = make_cleanup_delete_event_location (start_location);
10404   parse_breakpoint_sals (start_location, &canonical_start);
10405   make_cleanup_destroy_linespec_result (&canonical_start);
10406
10407   if (arg[0] != ',')
10408     error (_("Too few arguments."));
10409   else if (VEC_empty (linespec_sals, canonical_start.sals))
10410     error (_("Could not find location of the beginning of the range."));
10411
10412   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10413
10414   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10415       || lsal_start->sals.nelts != 1)
10416     error (_("Cannot create a ranged breakpoint with multiple locations."));
10417
10418   sal_start = lsal_start->sals.sals[0];
10419   addr_string_start = savestring (arg_start, arg - arg_start);
10420   make_cleanup (xfree, addr_string_start);
10421
10422   arg++;        /* Skip the comma.  */
10423   arg = skip_spaces (arg);
10424
10425   /* Parse the end location.  */
10426
10427   init_linespec_result (&canonical_end);
10428   arg_start = arg;
10429
10430   /* We call decode_line_full directly here instead of using
10431      parse_breakpoint_sals because we need to specify the start location's
10432      symtab and line as the default symtab and line for the end of the
10433      range.  This makes it possible to have ranges like "foo.c:27, +14",
10434      where +14 means 14 lines from the start location.  */
10435   end_location = string_to_event_location (&arg, current_language);
10436   make_cleanup_delete_event_location (end_location);
10437   decode_line_full (end_location, DECODE_LINE_FUNFIRSTLINE, NULL,
10438                     sal_start.symtab, sal_start.line,
10439                     &canonical_end, NULL, NULL);
10440
10441   make_cleanup_destroy_linespec_result (&canonical_end);
10442
10443   if (VEC_empty (linespec_sals, canonical_end.sals))
10444     error (_("Could not find location of the end of the range."));
10445
10446   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10447   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10448       || lsal_end->sals.nelts != 1)
10449     error (_("Cannot create a ranged breakpoint with multiple locations."));
10450
10451   sal_end = lsal_end->sals.sals[0];
10452
10453   end = find_breakpoint_range_end (sal_end);
10454   if (sal_start.pc > end)
10455     error (_("Invalid address range, end precedes start."));
10456
10457   length = end - sal_start.pc + 1;
10458   if (length < 0)
10459     /* Length overflowed.  */
10460     error (_("Address range too large."));
10461   else if (length == 1)
10462     {
10463       /* This range is simple enough to be handled by
10464          the `hbreak' command.  */
10465       hbreak_command (addr_string_start, 1);
10466
10467       do_cleanups (cleanup_bkpt);
10468
10469       return;
10470     }
10471
10472   /* Now set up the breakpoint.  */
10473   b = set_raw_breakpoint (get_current_arch (), sal_start,
10474                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10475   set_breakpoint_count (breakpoint_count + 1);
10476   b->number = breakpoint_count;
10477   b->disposition = disp_donttouch;
10478   b->location = copy_event_location (start_location);
10479   b->location_range_end = copy_event_location (end_location);
10480   b->loc->length = length;
10481
10482   do_cleanups (cleanup_bkpt);
10483
10484   mention (b);
10485   observer_notify_breakpoint_created (b);
10486   update_global_location_list (UGLL_MAY_INSERT);
10487 }
10488
10489 /*  Return non-zero if EXP is verified as constant.  Returned zero
10490     means EXP is variable.  Also the constant detection may fail for
10491     some constant expressions and in such case still falsely return
10492     zero.  */
10493
10494 static int
10495 watchpoint_exp_is_const (const struct expression *exp)
10496 {
10497   int i = exp->nelts;
10498
10499   while (i > 0)
10500     {
10501       int oplenp, argsp;
10502
10503       /* We are only interested in the descriptor of each element.  */
10504       operator_length (exp, i, &oplenp, &argsp);
10505       i -= oplenp;
10506
10507       switch (exp->elts[i].opcode)
10508         {
10509         case BINOP_ADD:
10510         case BINOP_SUB:
10511         case BINOP_MUL:
10512         case BINOP_DIV:
10513         case BINOP_REM:
10514         case BINOP_MOD:
10515         case BINOP_LSH:
10516         case BINOP_RSH:
10517         case BINOP_LOGICAL_AND:
10518         case BINOP_LOGICAL_OR:
10519         case BINOP_BITWISE_AND:
10520         case BINOP_BITWISE_IOR:
10521         case BINOP_BITWISE_XOR:
10522         case BINOP_EQUAL:
10523         case BINOP_NOTEQUAL:
10524         case BINOP_LESS:
10525         case BINOP_GTR:
10526         case BINOP_LEQ:
10527         case BINOP_GEQ:
10528         case BINOP_REPEAT:
10529         case BINOP_COMMA:
10530         case BINOP_EXP:
10531         case BINOP_MIN:
10532         case BINOP_MAX:
10533         case BINOP_INTDIV:
10534         case BINOP_CONCAT:
10535         case TERNOP_COND:
10536         case TERNOP_SLICE:
10537
10538         case OP_LONG:
10539         case OP_DOUBLE:
10540         case OP_DECFLOAT:
10541         case OP_LAST:
10542         case OP_COMPLEX:
10543         case OP_STRING:
10544         case OP_ARRAY:
10545         case OP_TYPE:
10546         case OP_TYPEOF:
10547         case OP_DECLTYPE:
10548         case OP_TYPEID:
10549         case OP_NAME:
10550         case OP_OBJC_NSSTRING:
10551
10552         case UNOP_NEG:
10553         case UNOP_LOGICAL_NOT:
10554         case UNOP_COMPLEMENT:
10555         case UNOP_ADDR:
10556         case UNOP_HIGH:
10557         case UNOP_CAST:
10558
10559         case UNOP_CAST_TYPE:
10560         case UNOP_REINTERPRET_CAST:
10561         case UNOP_DYNAMIC_CAST:
10562           /* Unary, binary and ternary operators: We have to check
10563              their operands.  If they are constant, then so is the
10564              result of that operation.  For instance, if A and B are
10565              determined to be constants, then so is "A + B".
10566
10567              UNOP_IND is one exception to the rule above, because the
10568              value of *ADDR is not necessarily a constant, even when
10569              ADDR is.  */
10570           break;
10571
10572         case OP_VAR_VALUE:
10573           /* Check whether the associated symbol is a constant.
10574
10575              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10576              possible that a buggy compiler could mark a variable as
10577              constant even when it is not, and TYPE_CONST would return
10578              true in this case, while SYMBOL_CLASS wouldn't.
10579
10580              We also have to check for function symbols because they
10581              are always constant.  */
10582           {
10583             struct symbol *s = exp->elts[i + 2].symbol;
10584
10585             if (SYMBOL_CLASS (s) != LOC_BLOCK
10586                 && SYMBOL_CLASS (s) != LOC_CONST
10587                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10588               return 0;
10589             break;
10590           }
10591
10592         /* The default action is to return 0 because we are using
10593            the optimistic approach here: If we don't know something,
10594            then it is not a constant.  */
10595         default:
10596           return 0;
10597         }
10598     }
10599
10600   return 1;
10601 }
10602
10603 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10604
10605 static void
10606 dtor_watchpoint (struct breakpoint *self)
10607 {
10608   struct watchpoint *w = (struct watchpoint *) self;
10609
10610   xfree (w->exp_string);
10611   xfree (w->exp_string_reparse);
10612   value_free (w->val);
10613
10614   base_breakpoint_ops.dtor (self);
10615 }
10616
10617 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10618
10619 static void
10620 re_set_watchpoint (struct breakpoint *b)
10621 {
10622   struct watchpoint *w = (struct watchpoint *) b;
10623
10624   /* Watchpoint can be either on expression using entirely global
10625      variables, or it can be on local variables.
10626
10627      Watchpoints of the first kind are never auto-deleted, and even
10628      persist across program restarts.  Since they can use variables
10629      from shared libraries, we need to reparse expression as libraries
10630      are loaded and unloaded.
10631
10632      Watchpoints on local variables can also change meaning as result
10633      of solib event.  For example, if a watchpoint uses both a local
10634      and a global variables in expression, it's a local watchpoint,
10635      but unloading of a shared library will make the expression
10636      invalid.  This is not a very common use case, but we still
10637      re-evaluate expression, to avoid surprises to the user.
10638
10639      Note that for local watchpoints, we re-evaluate it only if
10640      watchpoints frame id is still valid.  If it's not, it means the
10641      watchpoint is out of scope and will be deleted soon.  In fact,
10642      I'm not sure we'll ever be called in this case.
10643
10644      If a local watchpoint's frame id is still valid, then
10645      w->exp_valid_block is likewise valid, and we can safely use it.
10646
10647      Don't do anything about disabled watchpoints, since they will be
10648      reevaluated again when enabled.  */
10649   update_watchpoint (w, 1 /* reparse */);
10650 }
10651
10652 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10653
10654 static int
10655 insert_watchpoint (struct bp_location *bl)
10656 {
10657   struct watchpoint *w = (struct watchpoint *) bl->owner;
10658   int length = w->exact ? 1 : bl->length;
10659
10660   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10661                                    w->cond_exp.get ());
10662 }
10663
10664 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10665
10666 static int
10667 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10668 {
10669   struct watchpoint *w = (struct watchpoint *) bl->owner;
10670   int length = w->exact ? 1 : bl->length;
10671
10672   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10673                                    w->cond_exp.get ());
10674 }
10675
10676 static int
10677 breakpoint_hit_watchpoint (const struct bp_location *bl,
10678                            struct address_space *aspace, CORE_ADDR bp_addr,
10679                            const struct target_waitstatus *ws)
10680 {
10681   struct breakpoint *b = bl->owner;
10682   struct watchpoint *w = (struct watchpoint *) b;
10683
10684   /* Continuable hardware watchpoints are treated as non-existent if the
10685      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10686      some data address).  Otherwise gdb won't stop on a break instruction
10687      in the code (not from a breakpoint) when a hardware watchpoint has
10688      been defined.  Also skip watchpoints which we know did not trigger
10689      (did not match the data address).  */
10690   if (is_hardware_watchpoint (b)
10691       && w->watchpoint_triggered == watch_triggered_no)
10692     return 0;
10693
10694   return 1;
10695 }
10696
10697 static void
10698 check_status_watchpoint (bpstat bs)
10699 {
10700   gdb_assert (is_watchpoint (bs->breakpoint_at));
10701
10702   bpstat_check_watchpoint (bs);
10703 }
10704
10705 /* Implement the "resources_needed" breakpoint_ops method for
10706    hardware watchpoints.  */
10707
10708 static int
10709 resources_needed_watchpoint (const struct bp_location *bl)
10710 {
10711   struct watchpoint *w = (struct watchpoint *) bl->owner;
10712   int length = w->exact? 1 : bl->length;
10713
10714   return target_region_ok_for_hw_watchpoint (bl->address, length);
10715 }
10716
10717 /* Implement the "works_in_software_mode" breakpoint_ops method for
10718    hardware watchpoints.  */
10719
10720 static int
10721 works_in_software_mode_watchpoint (const struct breakpoint *b)
10722 {
10723   /* Read and access watchpoints only work with hardware support.  */
10724   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10725 }
10726
10727 static enum print_stop_action
10728 print_it_watchpoint (bpstat bs)
10729 {
10730   struct cleanup *old_chain;
10731   struct breakpoint *b;
10732   enum print_stop_action result;
10733   struct watchpoint *w;
10734   struct ui_out *uiout = current_uiout;
10735
10736   gdb_assert (bs->bp_location_at != NULL);
10737
10738   b = bs->breakpoint_at;
10739   w = (struct watchpoint *) b;
10740
10741   old_chain = make_cleanup (null_cleanup, NULL);
10742
10743   annotate_watchpoint (b->number);
10744   maybe_print_thread_hit_breakpoint (uiout);
10745
10746   string_file stb;
10747
10748   switch (b->type)
10749     {
10750     case bp_watchpoint:
10751     case bp_hardware_watchpoint:
10752       if (uiout->is_mi_like_p ())
10753         uiout->field_string
10754           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10755       mention (b);
10756       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10757       uiout->text ("\nOld value = ");
10758       watchpoint_value_print (bs->old_val, &stb);
10759       uiout->field_stream ("old", stb);
10760       uiout->text ("\nNew value = ");
10761       watchpoint_value_print (w->val, &stb);
10762       uiout->field_stream ("new", stb);
10763       uiout->text ("\n");
10764       /* More than one watchpoint may have been triggered.  */
10765       result = PRINT_UNKNOWN;
10766       break;
10767
10768     case bp_read_watchpoint:
10769       if (uiout->is_mi_like_p ())
10770         uiout->field_string
10771           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10772       mention (b);
10773       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10774       uiout->text ("\nValue = ");
10775       watchpoint_value_print (w->val, &stb);
10776       uiout->field_stream ("value", stb);
10777       uiout->text ("\n");
10778       result = PRINT_UNKNOWN;
10779       break;
10780
10781     case bp_access_watchpoint:
10782       if (bs->old_val != NULL)
10783         {
10784           if (uiout->is_mi_like_p ())
10785             uiout->field_string
10786               ("reason",
10787                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10788           mention (b);
10789           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10790           uiout->text ("\nOld value = ");
10791           watchpoint_value_print (bs->old_val, &stb);
10792           uiout->field_stream ("old", stb);
10793           uiout->text ("\nNew value = ");
10794         }
10795       else
10796         {
10797           mention (b);
10798           if (uiout->is_mi_like_p ())
10799             uiout->field_string
10800               ("reason",
10801                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10802           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10803           uiout->text ("\nValue = ");
10804         }
10805       watchpoint_value_print (w->val, &stb);
10806       uiout->field_stream ("new", stb);
10807       uiout->text ("\n");
10808       result = PRINT_UNKNOWN;
10809       break;
10810     default:
10811       result = PRINT_UNKNOWN;
10812     }
10813
10814   do_cleanups (old_chain);
10815   return result;
10816 }
10817
10818 /* Implement the "print_mention" breakpoint_ops method for hardware
10819    watchpoints.  */
10820
10821 static void
10822 print_mention_watchpoint (struct breakpoint *b)
10823 {
10824   struct cleanup *ui_out_chain;
10825   struct watchpoint *w = (struct watchpoint *) b;
10826   struct ui_out *uiout = current_uiout;
10827
10828   switch (b->type)
10829     {
10830     case bp_watchpoint:
10831       uiout->text ("Watchpoint ");
10832       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10833       break;
10834     case bp_hardware_watchpoint:
10835       uiout->text ("Hardware watchpoint ");
10836       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10837       break;
10838     case bp_read_watchpoint:
10839       uiout->text ("Hardware read watchpoint ");
10840       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10841       break;
10842     case bp_access_watchpoint:
10843       uiout->text ("Hardware access (read/write) watchpoint ");
10844       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10845       break;
10846     default:
10847       internal_error (__FILE__, __LINE__,
10848                       _("Invalid hardware watchpoint type."));
10849     }
10850
10851   uiout->field_int ("number", b->number);
10852   uiout->text (": ");
10853   uiout->field_string ("exp", w->exp_string);
10854   do_cleanups (ui_out_chain);
10855 }
10856
10857 /* Implement the "print_recreate" breakpoint_ops method for
10858    watchpoints.  */
10859
10860 static void
10861 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10862 {
10863   struct watchpoint *w = (struct watchpoint *) b;
10864
10865   switch (b->type)
10866     {
10867     case bp_watchpoint:
10868     case bp_hardware_watchpoint:
10869       fprintf_unfiltered (fp, "watch");
10870       break;
10871     case bp_read_watchpoint:
10872       fprintf_unfiltered (fp, "rwatch");
10873       break;
10874     case bp_access_watchpoint:
10875       fprintf_unfiltered (fp, "awatch");
10876       break;
10877     default:
10878       internal_error (__FILE__, __LINE__,
10879                       _("Invalid watchpoint type."));
10880     }
10881
10882   fprintf_unfiltered (fp, " %s", w->exp_string);
10883   print_recreate_thread (b, fp);
10884 }
10885
10886 /* Implement the "explains_signal" breakpoint_ops method for
10887    watchpoints.  */
10888
10889 static int
10890 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10891 {
10892   /* A software watchpoint cannot cause a signal other than
10893      GDB_SIGNAL_TRAP.  */
10894   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10895     return 0;
10896
10897   return 1;
10898 }
10899
10900 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10901
10902 static struct breakpoint_ops watchpoint_breakpoint_ops;
10903
10904 /* Implement the "insert" breakpoint_ops method for
10905    masked hardware watchpoints.  */
10906
10907 static int
10908 insert_masked_watchpoint (struct bp_location *bl)
10909 {
10910   struct watchpoint *w = (struct watchpoint *) bl->owner;
10911
10912   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10913                                         bl->watchpoint_type);
10914 }
10915
10916 /* Implement the "remove" breakpoint_ops method for
10917    masked hardware watchpoints.  */
10918
10919 static int
10920 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10921 {
10922   struct watchpoint *w = (struct watchpoint *) bl->owner;
10923
10924   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10925                                         bl->watchpoint_type);
10926 }
10927
10928 /* Implement the "resources_needed" breakpoint_ops method for
10929    masked hardware watchpoints.  */
10930
10931 static int
10932 resources_needed_masked_watchpoint (const struct bp_location *bl)
10933 {
10934   struct watchpoint *w = (struct watchpoint *) bl->owner;
10935
10936   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10937 }
10938
10939 /* Implement the "works_in_software_mode" breakpoint_ops method for
10940    masked hardware watchpoints.  */
10941
10942 static int
10943 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10944 {
10945   return 0;
10946 }
10947
10948 /* Implement the "print_it" breakpoint_ops method for
10949    masked hardware watchpoints.  */
10950
10951 static enum print_stop_action
10952 print_it_masked_watchpoint (bpstat bs)
10953 {
10954   struct breakpoint *b = bs->breakpoint_at;
10955   struct ui_out *uiout = current_uiout;
10956
10957   /* Masked watchpoints have only one location.  */
10958   gdb_assert (b->loc && b->loc->next == NULL);
10959
10960   annotate_watchpoint (b->number);
10961   maybe_print_thread_hit_breakpoint (uiout);
10962
10963   switch (b->type)
10964     {
10965     case bp_hardware_watchpoint:
10966       if (uiout->is_mi_like_p ())
10967         uiout->field_string
10968           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10969       break;
10970
10971     case bp_read_watchpoint:
10972       if (uiout->is_mi_like_p ())
10973         uiout->field_string
10974           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10975       break;
10976
10977     case bp_access_watchpoint:
10978       if (uiout->is_mi_like_p ())
10979         uiout->field_string
10980           ("reason",
10981            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10982       break;
10983     default:
10984       internal_error (__FILE__, __LINE__,
10985                       _("Invalid hardware watchpoint type."));
10986     }
10987
10988   mention (b);
10989   uiout->text (_("\n\
10990 Check the underlying instruction at PC for the memory\n\
10991 address and value which triggered this watchpoint.\n"));
10992   uiout->text ("\n");
10993
10994   /* More than one watchpoint may have been triggered.  */
10995   return PRINT_UNKNOWN;
10996 }
10997
10998 /* Implement the "print_one_detail" breakpoint_ops method for
10999    masked hardware watchpoints.  */
11000
11001 static void
11002 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11003                                     struct ui_out *uiout)
11004 {
11005   struct watchpoint *w = (struct watchpoint *) b;
11006
11007   /* Masked watchpoints have only one location.  */
11008   gdb_assert (b->loc && b->loc->next == NULL);
11009
11010   uiout->text ("\tmask ");
11011   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
11012   uiout->text ("\n");
11013 }
11014
11015 /* Implement the "print_mention" breakpoint_ops method for
11016    masked hardware watchpoints.  */
11017
11018 static void
11019 print_mention_masked_watchpoint (struct breakpoint *b)
11020 {
11021   struct watchpoint *w = (struct watchpoint *) b;
11022   struct ui_out *uiout = current_uiout;
11023   struct cleanup *ui_out_chain;
11024
11025   switch (b->type)
11026     {
11027     case bp_hardware_watchpoint:
11028       uiout->text ("Masked hardware watchpoint ");
11029       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11030       break;
11031     case bp_read_watchpoint:
11032       uiout->text ("Masked hardware read watchpoint ");
11033       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11034       break;
11035     case bp_access_watchpoint:
11036       uiout->text ("Masked hardware access (read/write) watchpoint ");
11037       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11038       break;
11039     default:
11040       internal_error (__FILE__, __LINE__,
11041                       _("Invalid hardware watchpoint type."));
11042     }
11043
11044   uiout->field_int ("number", b->number);
11045   uiout->text (": ");
11046   uiout->field_string ("exp", w->exp_string);
11047   do_cleanups (ui_out_chain);
11048 }
11049
11050 /* Implement the "print_recreate" breakpoint_ops method for
11051    masked hardware watchpoints.  */
11052
11053 static void
11054 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11055 {
11056   struct watchpoint *w = (struct watchpoint *) b;
11057   char tmp[40];
11058
11059   switch (b->type)
11060     {
11061     case bp_hardware_watchpoint:
11062       fprintf_unfiltered (fp, "watch");
11063       break;
11064     case bp_read_watchpoint:
11065       fprintf_unfiltered (fp, "rwatch");
11066       break;
11067     case bp_access_watchpoint:
11068       fprintf_unfiltered (fp, "awatch");
11069       break;
11070     default:
11071       internal_error (__FILE__, __LINE__,
11072                       _("Invalid hardware watchpoint type."));
11073     }
11074
11075   sprintf_vma (tmp, w->hw_wp_mask);
11076   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11077   print_recreate_thread (b, fp);
11078 }
11079
11080 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11081
11082 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11083
11084 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11085
11086 static int
11087 is_masked_watchpoint (const struct breakpoint *b)
11088 {
11089   return b->ops == &masked_watchpoint_breakpoint_ops;
11090 }
11091
11092 /* accessflag:  hw_write:  watch write, 
11093                 hw_read:   watch read, 
11094                 hw_access: watch access (read or write) */
11095 static void
11096 watch_command_1 (const char *arg, int accessflag, int from_tty,
11097                  int just_location, int internal)
11098 {
11099   struct breakpoint *b, *scope_breakpoint = NULL;
11100   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11101   struct value *val, *mark, *result;
11102   int saved_bitpos = 0, saved_bitsize = 0;
11103   struct frame_info *frame;
11104   const char *exp_start = NULL;
11105   const char *exp_end = NULL;
11106   const char *tok, *end_tok;
11107   int toklen = -1;
11108   const char *cond_start = NULL;
11109   const char *cond_end = NULL;
11110   enum bptype bp_type;
11111   int thread = -1;
11112   int pc = 0;
11113   /* Flag to indicate whether we are going to use masks for
11114      the hardware watchpoint.  */
11115   int use_mask = 0;
11116   CORE_ADDR mask = 0;
11117   struct watchpoint *w;
11118   char *expression;
11119   struct cleanup *back_to;
11120
11121   /* Make sure that we actually have parameters to parse.  */
11122   if (arg != NULL && arg[0] != '\0')
11123     {
11124       const char *value_start;
11125
11126       exp_end = arg + strlen (arg);
11127
11128       /* Look for "parameter value" pairs at the end
11129          of the arguments string.  */
11130       for (tok = exp_end - 1; tok > arg; tok--)
11131         {
11132           /* Skip whitespace at the end of the argument list.  */
11133           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11134             tok--;
11135
11136           /* Find the beginning of the last token.
11137              This is the value of the parameter.  */
11138           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11139             tok--;
11140           value_start = tok + 1;
11141
11142           /* Skip whitespace.  */
11143           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11144             tok--;
11145
11146           end_tok = tok;
11147
11148           /* Find the beginning of the second to last token.
11149              This is the parameter itself.  */
11150           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11151             tok--;
11152           tok++;
11153           toklen = end_tok - tok + 1;
11154
11155           if (toklen == 6 && startswith (tok, "thread"))
11156             {
11157               struct thread_info *thr;
11158               /* At this point we've found a "thread" token, which means
11159                  the user is trying to set a watchpoint that triggers
11160                  only in a specific thread.  */
11161               const char *endp;
11162
11163               if (thread != -1)
11164                 error(_("You can specify only one thread."));
11165
11166               /* Extract the thread ID from the next token.  */
11167               thr = parse_thread_id (value_start, &endp);
11168
11169               /* Check if the user provided a valid thread ID.  */
11170               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11171                 invalid_thread_id_error (value_start);
11172
11173               thread = thr->global_num;
11174             }
11175           else if (toklen == 4 && startswith (tok, "mask"))
11176             {
11177               /* We've found a "mask" token, which means the user wants to
11178                  create a hardware watchpoint that is going to have the mask
11179                  facility.  */
11180               struct value *mask_value, *mark;
11181
11182               if (use_mask)
11183                 error(_("You can specify only one mask."));
11184
11185               use_mask = just_location = 1;
11186
11187               mark = value_mark ();
11188               mask_value = parse_to_comma_and_eval (&value_start);
11189               mask = value_as_address (mask_value);
11190               value_free_to_mark (mark);
11191             }
11192           else
11193             /* We didn't recognize what we found.  We should stop here.  */
11194             break;
11195
11196           /* Truncate the string and get rid of the "parameter value" pair before
11197              the arguments string is parsed by the parse_exp_1 function.  */
11198           exp_end = tok;
11199         }
11200     }
11201   else
11202     exp_end = arg;
11203
11204   /* Parse the rest of the arguments.  From here on out, everything
11205      is in terms of a newly allocated string instead of the original
11206      ARG.  */
11207   innermost_block = NULL;
11208   expression = savestring (arg, exp_end - arg);
11209   back_to = make_cleanup (xfree, expression);
11210   exp_start = arg = expression;
11211   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
11212   exp_end = arg;
11213   /* Remove trailing whitespace from the expression before saving it.
11214      This makes the eventual display of the expression string a bit
11215      prettier.  */
11216   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11217     --exp_end;
11218
11219   /* Checking if the expression is not constant.  */
11220   if (watchpoint_exp_is_const (exp.get ()))
11221     {
11222       int len;
11223
11224       len = exp_end - exp_start;
11225       while (len > 0 && isspace (exp_start[len - 1]))
11226         len--;
11227       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11228     }
11229
11230   exp_valid_block = innermost_block;
11231   mark = value_mark ();
11232   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
11233
11234   if (val != NULL && just_location)
11235     {
11236       saved_bitpos = value_bitpos (val);
11237       saved_bitsize = value_bitsize (val);
11238     }
11239
11240   if (just_location)
11241     {
11242       int ret;
11243
11244       exp_valid_block = NULL;
11245       val = value_addr (result);
11246       release_value (val);
11247       value_free_to_mark (mark);
11248
11249       if (use_mask)
11250         {
11251           ret = target_masked_watch_num_registers (value_as_address (val),
11252                                                    mask);
11253           if (ret == -1)
11254             error (_("This target does not support masked watchpoints."));
11255           else if (ret == -2)
11256             error (_("Invalid mask or memory region."));
11257         }
11258     }
11259   else if (val != NULL)
11260     release_value (val);
11261
11262   tok = skip_spaces_const (arg);
11263   end_tok = skip_to_space_const (tok);
11264
11265   toklen = end_tok - tok;
11266   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11267     {
11268       innermost_block = NULL;
11269       tok = cond_start = end_tok + 1;
11270       parse_exp_1 (&tok, 0, 0, 0);
11271
11272       /* The watchpoint expression may not be local, but the condition
11273          may still be.  E.g.: `watch global if local > 0'.  */
11274       cond_exp_valid_block = innermost_block;
11275
11276       cond_end = tok;
11277     }
11278   if (*tok)
11279     error (_("Junk at end of command."));
11280
11281   frame = block_innermost_frame (exp_valid_block);
11282
11283   /* If the expression is "local", then set up a "watchpoint scope"
11284      breakpoint at the point where we've left the scope of the watchpoint
11285      expression.  Create the scope breakpoint before the watchpoint, so
11286      that we will encounter it first in bpstat_stop_status.  */
11287   if (exp_valid_block && frame)
11288     {
11289       if (frame_id_p (frame_unwind_caller_id (frame)))
11290         {
11291           scope_breakpoint
11292             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11293                                           frame_unwind_caller_pc (frame),
11294                                           bp_watchpoint_scope,
11295                                           &momentary_breakpoint_ops);
11296
11297           scope_breakpoint->enable_state = bp_enabled;
11298
11299           /* Automatically delete the breakpoint when it hits.  */
11300           scope_breakpoint->disposition = disp_del;
11301
11302           /* Only break in the proper frame (help with recursion).  */
11303           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11304
11305           /* Set the address at which we will stop.  */
11306           scope_breakpoint->loc->gdbarch
11307             = frame_unwind_caller_arch (frame);
11308           scope_breakpoint->loc->requested_address
11309             = frame_unwind_caller_pc (frame);
11310           scope_breakpoint->loc->address
11311             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11312                                          scope_breakpoint->loc->requested_address,
11313                                          scope_breakpoint->type);
11314         }
11315     }
11316
11317   /* Now set up the breakpoint.  We create all watchpoints as hardware
11318      watchpoints here even if hardware watchpoints are turned off, a call
11319      to update_watchpoint later in this function will cause the type to
11320      drop back to bp_watchpoint (software watchpoint) if required.  */
11321
11322   if (accessflag == hw_read)
11323     bp_type = bp_read_watchpoint;
11324   else if (accessflag == hw_access)
11325     bp_type = bp_access_watchpoint;
11326   else
11327     bp_type = bp_hardware_watchpoint;
11328
11329   w = new watchpoint ();
11330   b = &w->base;
11331   if (use_mask)
11332     init_raw_breakpoint_without_location (b, NULL, bp_type,
11333                                           &masked_watchpoint_breakpoint_ops);
11334   else
11335     init_raw_breakpoint_without_location (b, NULL, bp_type,
11336                                           &watchpoint_breakpoint_ops);
11337   b->thread = thread;
11338   b->disposition = disp_donttouch;
11339   b->pspace = current_program_space;
11340   w->exp = std::move (exp);
11341   w->exp_valid_block = exp_valid_block;
11342   w->cond_exp_valid_block = cond_exp_valid_block;
11343   if (just_location)
11344     {
11345       struct type *t = value_type (val);
11346       CORE_ADDR addr = value_as_address (val);
11347
11348       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11349
11350       std::string name = type_to_string (t);
11351
11352       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name.c_str (),
11353                                           core_addr_to_string (addr));
11354
11355       w->exp_string = xstrprintf ("-location %.*s",
11356                                   (int) (exp_end - exp_start), exp_start);
11357
11358       /* The above expression is in C.  */
11359       b->language = language_c;
11360     }
11361   else
11362     w->exp_string = savestring (exp_start, exp_end - exp_start);
11363
11364   if (use_mask)
11365     {
11366       w->hw_wp_mask = mask;
11367     }
11368   else
11369     {
11370       w->val = val;
11371       w->val_bitpos = saved_bitpos;
11372       w->val_bitsize = saved_bitsize;
11373       w->val_valid = 1;
11374     }
11375
11376   if (cond_start)
11377     b->cond_string = savestring (cond_start, cond_end - cond_start);
11378   else
11379     b->cond_string = 0;
11380
11381   if (frame)
11382     {
11383       w->watchpoint_frame = get_frame_id (frame);
11384       w->watchpoint_thread = inferior_ptid;
11385     }
11386   else
11387     {
11388       w->watchpoint_frame = null_frame_id;
11389       w->watchpoint_thread = null_ptid;
11390     }
11391
11392   if (scope_breakpoint != NULL)
11393     {
11394       /* The scope breakpoint is related to the watchpoint.  We will
11395          need to act on them together.  */
11396       b->related_breakpoint = scope_breakpoint;
11397       scope_breakpoint->related_breakpoint = b;
11398     }
11399
11400   if (!just_location)
11401     value_free_to_mark (mark);
11402
11403   TRY
11404     {
11405       /* Finally update the new watchpoint.  This creates the locations
11406          that should be inserted.  */
11407       update_watchpoint (w, 1);
11408     }
11409   CATCH (e, RETURN_MASK_ALL)
11410     {
11411       delete_breakpoint (b);
11412       throw_exception (e);
11413     }
11414   END_CATCH
11415
11416   install_breakpoint (internal, b, 1);
11417   do_cleanups (back_to);
11418 }
11419
11420 /* Return count of debug registers needed to watch the given expression.
11421    If the watchpoint cannot be handled in hardware return zero.  */
11422
11423 static int
11424 can_use_hardware_watchpoint (struct value *v)
11425 {
11426   int found_memory_cnt = 0;
11427   struct value *head = v;
11428
11429   /* Did the user specifically forbid us to use hardware watchpoints? */
11430   if (!can_use_hw_watchpoints)
11431     return 0;
11432
11433   /* Make sure that the value of the expression depends only upon
11434      memory contents, and values computed from them within GDB.  If we
11435      find any register references or function calls, we can't use a
11436      hardware watchpoint.
11437
11438      The idea here is that evaluating an expression generates a series
11439      of values, one holding the value of every subexpression.  (The
11440      expression a*b+c has five subexpressions: a, b, a*b, c, and
11441      a*b+c.)  GDB's values hold almost enough information to establish
11442      the criteria given above --- they identify memory lvalues,
11443      register lvalues, computed values, etcetera.  So we can evaluate
11444      the expression, and then scan the chain of values that leaves
11445      behind to decide whether we can detect any possible change to the
11446      expression's final value using only hardware watchpoints.
11447
11448      However, I don't think that the values returned by inferior
11449      function calls are special in any way.  So this function may not
11450      notice that an expression involving an inferior function call
11451      can't be watched with hardware watchpoints.  FIXME.  */
11452   for (; v; v = value_next (v))
11453     {
11454       if (VALUE_LVAL (v) == lval_memory)
11455         {
11456           if (v != head && value_lazy (v))
11457             /* A lazy memory lvalue in the chain is one that GDB never
11458                needed to fetch; we either just used its address (e.g.,
11459                `a' in `a.b') or we never needed it at all (e.g., `a'
11460                in `a,b').  This doesn't apply to HEAD; if that is
11461                lazy then it was not readable, but watch it anyway.  */
11462             ;
11463           else
11464             {
11465               /* Ahh, memory we actually used!  Check if we can cover
11466                  it with hardware watchpoints.  */
11467               struct type *vtype = check_typedef (value_type (v));
11468
11469               /* We only watch structs and arrays if user asked for it
11470                  explicitly, never if they just happen to appear in a
11471                  middle of some value chain.  */
11472               if (v == head
11473                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11474                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11475                 {
11476                   CORE_ADDR vaddr = value_address (v);
11477                   int len;
11478                   int num_regs;
11479
11480                   len = (target_exact_watchpoints
11481                          && is_scalar_type_recursive (vtype))?
11482                     1 : TYPE_LENGTH (value_type (v));
11483
11484                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11485                   if (!num_regs)
11486                     return 0;
11487                   else
11488                     found_memory_cnt += num_regs;
11489                 }
11490             }
11491         }
11492       else if (VALUE_LVAL (v) != not_lval
11493                && deprecated_value_modifiable (v) == 0)
11494         return 0;       /* These are values from the history (e.g., $1).  */
11495       else if (VALUE_LVAL (v) == lval_register)
11496         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11497     }
11498
11499   /* The expression itself looks suitable for using a hardware
11500      watchpoint, but give the target machine a chance to reject it.  */
11501   return found_memory_cnt;
11502 }
11503
11504 void
11505 watch_command_wrapper (char *arg, int from_tty, int internal)
11506 {
11507   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11508 }
11509
11510 /* A helper function that looks for the "-location" argument and then
11511    calls watch_command_1.  */
11512
11513 static void
11514 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11515 {
11516   int just_location = 0;
11517
11518   if (arg
11519       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11520           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11521     {
11522       arg = skip_spaces (arg);
11523       just_location = 1;
11524     }
11525
11526   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11527 }
11528
11529 static void
11530 watch_command (char *arg, int from_tty)
11531 {
11532   watch_maybe_just_location (arg, hw_write, from_tty);
11533 }
11534
11535 void
11536 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11537 {
11538   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11539 }
11540
11541 static void
11542 rwatch_command (char *arg, int from_tty)
11543 {
11544   watch_maybe_just_location (arg, hw_read, from_tty);
11545 }
11546
11547 void
11548 awatch_command_wrapper (char *arg, int from_tty, int internal)
11549 {
11550   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11551 }
11552
11553 static void
11554 awatch_command (char *arg, int from_tty)
11555 {
11556   watch_maybe_just_location (arg, hw_access, from_tty);
11557 }
11558 \f
11559
11560 /* Data for the FSM that manages the until(location)/advance commands
11561    in infcmd.c.  Here because it uses the mechanisms of
11562    breakpoints.  */
11563
11564 struct until_break_fsm
11565 {
11566   /* The base class.  */
11567   struct thread_fsm thread_fsm;
11568
11569   /* The thread that as current when the command was executed.  */
11570   int thread;
11571
11572   /* The breakpoint set at the destination location.  */
11573   struct breakpoint *location_breakpoint;
11574
11575   /* Breakpoint set at the return address in the caller frame.  May be
11576      NULL.  */
11577   struct breakpoint *caller_breakpoint;
11578 };
11579
11580 static void until_break_fsm_clean_up (struct thread_fsm *self,
11581                                       struct thread_info *thread);
11582 static int until_break_fsm_should_stop (struct thread_fsm *self,
11583                                         struct thread_info *thread);
11584 static enum async_reply_reason
11585   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11586
11587 /* until_break_fsm's vtable.  */
11588
11589 static struct thread_fsm_ops until_break_fsm_ops =
11590 {
11591   NULL, /* dtor */
11592   until_break_fsm_clean_up,
11593   until_break_fsm_should_stop,
11594   NULL, /* return_value */
11595   until_break_fsm_async_reply_reason,
11596 };
11597
11598 /* Allocate a new until_break_command_fsm.  */
11599
11600 static struct until_break_fsm *
11601 new_until_break_fsm (struct interp *cmd_interp, int thread,
11602                      struct breakpoint *location_breakpoint,
11603                      struct breakpoint *caller_breakpoint)
11604 {
11605   struct until_break_fsm *sm;
11606
11607   sm = XCNEW (struct until_break_fsm);
11608   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11609
11610   sm->thread = thread;
11611   sm->location_breakpoint = location_breakpoint;
11612   sm->caller_breakpoint = caller_breakpoint;
11613
11614   return sm;
11615 }
11616
11617 /* Implementation of the 'should_stop' FSM method for the
11618    until(location)/advance commands.  */
11619
11620 static int
11621 until_break_fsm_should_stop (struct thread_fsm *self,
11622                              struct thread_info *tp)
11623 {
11624   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11625
11626   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11627                               sm->location_breakpoint) != NULL
11628       || (sm->caller_breakpoint != NULL
11629           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11630                                      sm->caller_breakpoint) != NULL))
11631     thread_fsm_set_finished (self);
11632
11633   return 1;
11634 }
11635
11636 /* Implementation of the 'clean_up' FSM method for the
11637    until(location)/advance commands.  */
11638
11639 static void
11640 until_break_fsm_clean_up (struct thread_fsm *self,
11641                           struct thread_info *thread)
11642 {
11643   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11644
11645   /* Clean up our temporary breakpoints.  */
11646   if (sm->location_breakpoint != NULL)
11647     {
11648       delete_breakpoint (sm->location_breakpoint);
11649       sm->location_breakpoint = NULL;
11650     }
11651   if (sm->caller_breakpoint != NULL)
11652     {
11653       delete_breakpoint (sm->caller_breakpoint);
11654       sm->caller_breakpoint = NULL;
11655     }
11656   delete_longjmp_breakpoint (sm->thread);
11657 }
11658
11659 /* Implementation of the 'async_reply_reason' FSM method for the
11660    until(location)/advance commands.  */
11661
11662 static enum async_reply_reason
11663 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11664 {
11665   return EXEC_ASYNC_LOCATION_REACHED;
11666 }
11667
11668 void
11669 until_break_command (char *arg, int from_tty, int anywhere)
11670 {
11671   struct symtabs_and_lines sals;
11672   struct symtab_and_line sal;
11673   struct frame_info *frame;
11674   struct gdbarch *frame_gdbarch;
11675   struct frame_id stack_frame_id;
11676   struct frame_id caller_frame_id;
11677   struct breakpoint *location_breakpoint;
11678   struct breakpoint *caller_breakpoint = NULL;
11679   struct cleanup *old_chain, *cleanup;
11680   int thread;
11681   struct thread_info *tp;
11682   struct event_location *location;
11683   struct until_break_fsm *sm;
11684
11685   clear_proceed_status (0);
11686
11687   /* Set a breakpoint where the user wants it and at return from
11688      this function.  */
11689
11690   location = string_to_event_location (&arg, current_language);
11691   cleanup = make_cleanup_delete_event_location (location);
11692
11693   if (last_displayed_sal_is_valid ())
11694     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE, NULL,
11695                           get_last_displayed_symtab (),
11696                           get_last_displayed_line ());
11697   else
11698     sals = decode_line_1 (location, DECODE_LINE_FUNFIRSTLINE,
11699                           NULL, (struct symtab *) NULL, 0);
11700
11701   if (sals.nelts != 1)
11702     error (_("Couldn't get information on specified line."));
11703
11704   sal = sals.sals[0];
11705   xfree (sals.sals);    /* malloc'd, so freed.  */
11706
11707   if (*arg)
11708     error (_("Junk at end of arguments."));
11709
11710   resolve_sal_pc (&sal);
11711
11712   tp = inferior_thread ();
11713   thread = tp->global_num;
11714
11715   old_chain = make_cleanup (null_cleanup, NULL);
11716
11717   /* Note linespec handling above invalidates the frame chain.
11718      Installing a breakpoint also invalidates the frame chain (as it
11719      may need to switch threads), so do any frame handling before
11720      that.  */
11721
11722   frame = get_selected_frame (NULL);
11723   frame_gdbarch = get_frame_arch (frame);
11724   stack_frame_id = get_stack_frame_id (frame);
11725   caller_frame_id = frame_unwind_caller_id (frame);
11726
11727   /* Keep within the current frame, or in frames called by the current
11728      one.  */
11729
11730   if (frame_id_p (caller_frame_id))
11731     {
11732       struct symtab_and_line sal2;
11733       struct gdbarch *caller_gdbarch;
11734
11735       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11736       sal2.pc = frame_unwind_caller_pc (frame);
11737       caller_gdbarch = frame_unwind_caller_arch (frame);
11738       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11739                                                     sal2,
11740                                                     caller_frame_id,
11741                                                     bp_until);
11742       make_cleanup_delete_breakpoint (caller_breakpoint);
11743
11744       set_longjmp_breakpoint (tp, caller_frame_id);
11745       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11746     }
11747
11748   /* set_momentary_breakpoint could invalidate FRAME.  */
11749   frame = NULL;
11750
11751   if (anywhere)
11752     /* If the user told us to continue until a specified location,
11753        we don't specify a frame at which we need to stop.  */
11754     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11755                                                     null_frame_id, bp_until);
11756   else
11757     /* Otherwise, specify the selected frame, because we want to stop
11758        only at the very same frame.  */
11759     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11760                                                     stack_frame_id, bp_until);
11761   make_cleanup_delete_breakpoint (location_breakpoint);
11762
11763   sm = new_until_break_fsm (command_interp (), tp->global_num,
11764                             location_breakpoint, caller_breakpoint);
11765   tp->thread_fsm = &sm->thread_fsm;
11766
11767   discard_cleanups (old_chain);
11768
11769   proceed (-1, GDB_SIGNAL_DEFAULT);
11770
11771   do_cleanups (cleanup);
11772 }
11773
11774 /* This function attempts to parse an optional "if <cond>" clause
11775    from the arg string.  If one is not found, it returns NULL.
11776
11777    Else, it returns a pointer to the condition string.  (It does not
11778    attempt to evaluate the string against a particular block.)  And,
11779    it updates arg to point to the first character following the parsed
11780    if clause in the arg string.  */
11781
11782 char *
11783 ep_parse_optional_if_clause (char **arg)
11784 {
11785   char *cond_string;
11786
11787   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11788     return NULL;
11789
11790   /* Skip the "if" keyword.  */
11791   (*arg) += 2;
11792
11793   /* Skip any extra leading whitespace, and record the start of the
11794      condition string.  */
11795   *arg = skip_spaces (*arg);
11796   cond_string = *arg;
11797
11798   /* Assume that the condition occupies the remainder of the arg
11799      string.  */
11800   (*arg) += strlen (cond_string);
11801
11802   return cond_string;
11803 }
11804
11805 /* Commands to deal with catching events, such as signals, exceptions,
11806    process start/exit, etc.  */
11807
11808 typedef enum
11809 {
11810   catch_fork_temporary, catch_vfork_temporary,
11811   catch_fork_permanent, catch_vfork_permanent
11812 }
11813 catch_fork_kind;
11814
11815 static void
11816 catch_fork_command_1 (char *arg, int from_tty, 
11817                       struct cmd_list_element *command)
11818 {
11819   struct gdbarch *gdbarch = get_current_arch ();
11820   char *cond_string = NULL;
11821   catch_fork_kind fork_kind;
11822   int tempflag;
11823
11824   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11825   tempflag = (fork_kind == catch_fork_temporary
11826               || fork_kind == catch_vfork_temporary);
11827
11828   if (!arg)
11829     arg = "";
11830   arg = skip_spaces (arg);
11831
11832   /* The allowed syntax is:
11833      catch [v]fork
11834      catch [v]fork if <cond>
11835
11836      First, check if there's an if clause.  */
11837   cond_string = ep_parse_optional_if_clause (&arg);
11838
11839   if ((*arg != '\0') && !isspace (*arg))
11840     error (_("Junk at end of arguments."));
11841
11842   /* If this target supports it, create a fork or vfork catchpoint
11843      and enable reporting of such events.  */
11844   switch (fork_kind)
11845     {
11846     case catch_fork_temporary:
11847     case catch_fork_permanent:
11848       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11849                                           &catch_fork_breakpoint_ops);
11850       break;
11851     case catch_vfork_temporary:
11852     case catch_vfork_permanent:
11853       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11854                                           &catch_vfork_breakpoint_ops);
11855       break;
11856     default:
11857       error (_("unsupported or unknown fork kind; cannot catch it"));
11858       break;
11859     }
11860 }
11861
11862 static void
11863 catch_exec_command_1 (char *arg, int from_tty, 
11864                       struct cmd_list_element *command)
11865 {
11866   struct exec_catchpoint *c;
11867   struct gdbarch *gdbarch = get_current_arch ();
11868   int tempflag;
11869   char *cond_string = NULL;
11870
11871   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11872
11873   if (!arg)
11874     arg = "";
11875   arg = skip_spaces (arg);
11876
11877   /* The allowed syntax is:
11878      catch exec
11879      catch exec if <cond>
11880
11881      First, check if there's an if clause.  */
11882   cond_string = ep_parse_optional_if_clause (&arg);
11883
11884   if ((*arg != '\0') && !isspace (*arg))
11885     error (_("Junk at end of arguments."));
11886
11887   c = new exec_catchpoint ();
11888   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11889                    &catch_exec_breakpoint_ops);
11890   c->exec_pathname = NULL;
11891
11892   install_breakpoint (0, &c->base, 1);
11893 }
11894
11895 void
11896 init_ada_exception_breakpoint (struct breakpoint *b,
11897                                struct gdbarch *gdbarch,
11898                                struct symtab_and_line sal,
11899                                char *addr_string,
11900                                const struct breakpoint_ops *ops,
11901                                int tempflag,
11902                                int enabled,
11903                                int from_tty)
11904 {
11905   if (from_tty)
11906     {
11907       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11908       if (!loc_gdbarch)
11909         loc_gdbarch = gdbarch;
11910
11911       describe_other_breakpoints (loc_gdbarch,
11912                                   sal.pspace, sal.pc, sal.section, -1);
11913       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11914          version for exception catchpoints, because two catchpoints
11915          used for different exception names will use the same address.
11916          In this case, a "breakpoint ... also set at..." warning is
11917          unproductive.  Besides, the warning phrasing is also a bit
11918          inappropriate, we should use the word catchpoint, and tell
11919          the user what type of catchpoint it is.  The above is good
11920          enough for now, though.  */
11921     }
11922
11923   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11924
11925   b->enable_state = enabled ? bp_enabled : bp_disabled;
11926   b->disposition = tempflag ? disp_del : disp_donttouch;
11927   b->location = string_to_event_location (&addr_string,
11928                                           language_def (language_ada));
11929   b->language = language_ada;
11930 }
11931
11932 static void
11933 catch_command (char *arg, int from_tty)
11934 {
11935   error (_("Catch requires an event name."));
11936 }
11937 \f
11938
11939 static void
11940 tcatch_command (char *arg, int from_tty)
11941 {
11942   error (_("Catch requires an event name."));
11943 }
11944
11945 /* A qsort comparison function that sorts breakpoints in order.  */
11946
11947 static int
11948 compare_breakpoints (const void *a, const void *b)
11949 {
11950   const breakpoint_p *ba = (const breakpoint_p *) a;
11951   uintptr_t ua = (uintptr_t) *ba;
11952   const breakpoint_p *bb = (const breakpoint_p *) b;
11953   uintptr_t ub = (uintptr_t) *bb;
11954
11955   if ((*ba)->number < (*bb)->number)
11956     return -1;
11957   else if ((*ba)->number > (*bb)->number)
11958     return 1;
11959
11960   /* Now sort by address, in case we see, e..g, two breakpoints with
11961      the number 0.  */
11962   if (ua < ub)
11963     return -1;
11964   return ua > ub ? 1 : 0;
11965 }
11966
11967 /* Delete breakpoints by address or line.  */
11968
11969 static void
11970 clear_command (char *arg, int from_tty)
11971 {
11972   struct breakpoint *b, *prev;
11973   VEC(breakpoint_p) *found = 0;
11974   int ix;
11975   int default_match;
11976   struct symtabs_and_lines sals;
11977   struct symtab_and_line sal;
11978   int i;
11979   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11980
11981   if (arg)
11982     {
11983       sals = decode_line_with_current_source (arg,
11984                                               (DECODE_LINE_FUNFIRSTLINE
11985                                                | DECODE_LINE_LIST_MODE));
11986       make_cleanup (xfree, sals.sals);
11987       default_match = 0;
11988     }
11989   else
11990     {
11991       sals.sals = XNEW (struct symtab_and_line);
11992       make_cleanup (xfree, sals.sals);
11993       init_sal (&sal);          /* Initialize to zeroes.  */
11994
11995       /* Set sal's line, symtab, pc, and pspace to the values
11996          corresponding to the last call to print_frame_info.  If the
11997          codepoint is not valid, this will set all the fields to 0.  */
11998       get_last_displayed_sal (&sal);
11999       if (sal.symtab == 0)
12000         error (_("No source file specified."));
12001
12002       sals.sals[0] = sal;
12003       sals.nelts = 1;
12004
12005       default_match = 1;
12006     }
12007
12008   /* We don't call resolve_sal_pc here.  That's not as bad as it
12009      seems, because all existing breakpoints typically have both
12010      file/line and pc set.  So, if clear is given file/line, we can
12011      match this to existing breakpoint without obtaining pc at all.
12012
12013      We only support clearing given the address explicitly 
12014      present in breakpoint table.  Say, we've set breakpoint 
12015      at file:line.  There were several PC values for that file:line,
12016      due to optimization, all in one block.
12017
12018      We've picked one PC value.  If "clear" is issued with another
12019      PC corresponding to the same file:line, the breakpoint won't
12020      be cleared.  We probably can still clear the breakpoint, but 
12021      since the other PC value is never presented to user, user
12022      can only find it by guessing, and it does not seem important
12023      to support that.  */
12024
12025   /* For each line spec given, delete bps which correspond to it.  Do
12026      it in two passes, solely to preserve the current behavior that
12027      from_tty is forced true if we delete more than one
12028      breakpoint.  */
12029
12030   found = NULL;
12031   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12032   for (i = 0; i < sals.nelts; i++)
12033     {
12034       const char *sal_fullname;
12035
12036       /* If exact pc given, clear bpts at that pc.
12037          If line given (pc == 0), clear all bpts on specified line.
12038          If defaulting, clear all bpts on default line
12039          or at default pc.
12040
12041          defaulting    sal.pc != 0    tests to do
12042
12043          0              1             pc
12044          1              1             pc _and_ line
12045          0              0             line
12046          1              0             <can't happen> */
12047
12048       sal = sals.sals[i];
12049       sal_fullname = (sal.symtab == NULL
12050                       ? NULL : symtab_to_fullname (sal.symtab));
12051
12052       /* Find all matching breakpoints and add them to 'found'.  */
12053       ALL_BREAKPOINTS (b)
12054         {
12055           int match = 0;
12056           /* Are we going to delete b?  */
12057           if (b->type != bp_none && !is_watchpoint (b))
12058             {
12059               struct bp_location *loc = b->loc;
12060               for (; loc; loc = loc->next)
12061                 {
12062                   /* If the user specified file:line, don't allow a PC
12063                      match.  This matches historical gdb behavior.  */
12064                   int pc_match = (!sal.explicit_line
12065                                   && sal.pc
12066                                   && (loc->pspace == sal.pspace)
12067                                   && (loc->address == sal.pc)
12068                                   && (!section_is_overlay (loc->section)
12069                                       || loc->section == sal.section));
12070                   int line_match = 0;
12071
12072                   if ((default_match || sal.explicit_line)
12073                       && loc->symtab != NULL
12074                       && sal_fullname != NULL
12075                       && sal.pspace == loc->pspace
12076                       && loc->line_number == sal.line
12077                       && filename_cmp (symtab_to_fullname (loc->symtab),
12078                                        sal_fullname) == 0)
12079                     line_match = 1;
12080
12081                   if (pc_match || line_match)
12082                     {
12083                       match = 1;
12084                       break;
12085                     }
12086                 }
12087             }
12088
12089           if (match)
12090             VEC_safe_push(breakpoint_p, found, b);
12091         }
12092     }
12093
12094   /* Now go thru the 'found' chain and delete them.  */
12095   if (VEC_empty(breakpoint_p, found))
12096     {
12097       if (arg)
12098         error (_("No breakpoint at %s."), arg);
12099       else
12100         error (_("No breakpoint at this line."));
12101     }
12102
12103   /* Remove duplicates from the vec.  */
12104   qsort (VEC_address (breakpoint_p, found),
12105          VEC_length (breakpoint_p, found),
12106          sizeof (breakpoint_p),
12107          compare_breakpoints);
12108   prev = VEC_index (breakpoint_p, found, 0);
12109   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12110     {
12111       if (b == prev)
12112         {
12113           VEC_ordered_remove (breakpoint_p, found, ix);
12114           --ix;
12115         }
12116     }
12117
12118   if (VEC_length(breakpoint_p, found) > 1)
12119     from_tty = 1;       /* Always report if deleted more than one.  */
12120   if (from_tty)
12121     {
12122       if (VEC_length(breakpoint_p, found) == 1)
12123         printf_unfiltered (_("Deleted breakpoint "));
12124       else
12125         printf_unfiltered (_("Deleted breakpoints "));
12126     }
12127
12128   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12129     {
12130       if (from_tty)
12131         printf_unfiltered ("%d ", b->number);
12132       delete_breakpoint (b);
12133     }
12134   if (from_tty)
12135     putchar_unfiltered ('\n');
12136
12137   do_cleanups (cleanups);
12138 }
12139 \f
12140 /* Delete breakpoint in BS if they are `delete' breakpoints and
12141    all breakpoints that are marked for deletion, whether hit or not.
12142    This is called after any breakpoint is hit, or after errors.  */
12143
12144 void
12145 breakpoint_auto_delete (bpstat bs)
12146 {
12147   struct breakpoint *b, *b_tmp;
12148
12149   for (; bs; bs = bs->next)
12150     if (bs->breakpoint_at
12151         && bs->breakpoint_at->disposition == disp_del
12152         && bs->stop)
12153       delete_breakpoint (bs->breakpoint_at);
12154
12155   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12156   {
12157     if (b->disposition == disp_del_at_next_stop)
12158       delete_breakpoint (b);
12159   }
12160 }
12161
12162 /* A comparison function for bp_location AP and BP being interfaced to
12163    qsort.  Sort elements primarily by their ADDRESS (no matter what
12164    does breakpoint_address_is_meaningful say for its OWNER),
12165    secondarily by ordering first permanent elements and
12166    terciarily just ensuring the array is sorted stable way despite
12167    qsort being an unstable algorithm.  */
12168
12169 static int
12170 bp_location_compare (const void *ap, const void *bp)
12171 {
12172   const struct bp_location *a = *(const struct bp_location **) ap;
12173   const struct bp_location *b = *(const struct bp_location **) bp;
12174
12175   if (a->address != b->address)
12176     return (a->address > b->address) - (a->address < b->address);
12177
12178   /* Sort locations at the same address by their pspace number, keeping
12179      locations of the same inferior (in a multi-inferior environment)
12180      grouped.  */
12181
12182   if (a->pspace->num != b->pspace->num)
12183     return ((a->pspace->num > b->pspace->num)
12184             - (a->pspace->num < b->pspace->num));
12185
12186   /* Sort permanent breakpoints first.  */
12187   if (a->permanent != b->permanent)
12188     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12189
12190   /* Make the internal GDB representation stable across GDB runs
12191      where A and B memory inside GDB can differ.  Breakpoint locations of
12192      the same type at the same address can be sorted in arbitrary order.  */
12193
12194   if (a->owner->number != b->owner->number)
12195     return ((a->owner->number > b->owner->number)
12196             - (a->owner->number < b->owner->number));
12197
12198   return (a > b) - (a < b);
12199 }
12200
12201 /* Set bp_location_placed_address_before_address_max and
12202    bp_location_shadow_len_after_address_max according to the current
12203    content of the bp_location array.  */
12204
12205 static void
12206 bp_location_target_extensions_update (void)
12207 {
12208   struct bp_location *bl, **blp_tmp;
12209
12210   bp_location_placed_address_before_address_max = 0;
12211   bp_location_shadow_len_after_address_max = 0;
12212
12213   ALL_BP_LOCATIONS (bl, blp_tmp)
12214     {
12215       CORE_ADDR start, end, addr;
12216
12217       if (!bp_location_has_shadow (bl))
12218         continue;
12219
12220       start = bl->target_info.placed_address;
12221       end = start + bl->target_info.shadow_len;
12222
12223       gdb_assert (bl->address >= start);
12224       addr = bl->address - start;
12225       if (addr > bp_location_placed_address_before_address_max)
12226         bp_location_placed_address_before_address_max = addr;
12227
12228       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12229
12230       gdb_assert (bl->address < end);
12231       addr = end - bl->address;
12232       if (addr > bp_location_shadow_len_after_address_max)
12233         bp_location_shadow_len_after_address_max = addr;
12234     }
12235 }
12236
12237 /* Download tracepoint locations if they haven't been.  */
12238
12239 static void
12240 download_tracepoint_locations (void)
12241 {
12242   struct breakpoint *b;
12243   struct cleanup *old_chain;
12244   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
12245
12246   old_chain = save_current_space_and_thread ();
12247
12248   ALL_TRACEPOINTS (b)
12249     {
12250       struct bp_location *bl;
12251       struct tracepoint *t;
12252       int bp_location_downloaded = 0;
12253
12254       if ((b->type == bp_fast_tracepoint
12255            ? !may_insert_fast_tracepoints
12256            : !may_insert_tracepoints))
12257         continue;
12258
12259       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
12260         {
12261           if (target_can_download_tracepoint ())
12262             can_download_tracepoint = TRIBOOL_TRUE;
12263           else
12264             can_download_tracepoint = TRIBOOL_FALSE;
12265         }
12266
12267       if (can_download_tracepoint == TRIBOOL_FALSE)
12268         break;
12269
12270       for (bl = b->loc; bl; bl = bl->next)
12271         {
12272           /* In tracepoint, locations are _never_ duplicated, so
12273              should_be_inserted is equivalent to
12274              unduplicated_should_be_inserted.  */
12275           if (!should_be_inserted (bl) || bl->inserted)
12276             continue;
12277
12278           switch_to_program_space_and_thread (bl->pspace);
12279
12280           target_download_tracepoint (bl);
12281
12282           bl->inserted = 1;
12283           bp_location_downloaded = 1;
12284         }
12285       t = (struct tracepoint *) b;
12286       t->number_on_target = b->number;
12287       if (bp_location_downloaded)
12288         observer_notify_breakpoint_modified (b);
12289     }
12290
12291   do_cleanups (old_chain);
12292 }
12293
12294 /* Swap the insertion/duplication state between two locations.  */
12295
12296 static void
12297 swap_insertion (struct bp_location *left, struct bp_location *right)
12298 {
12299   const int left_inserted = left->inserted;
12300   const int left_duplicate = left->duplicate;
12301   const int left_needs_update = left->needs_update;
12302   const struct bp_target_info left_target_info = left->target_info;
12303
12304   /* Locations of tracepoints can never be duplicated.  */
12305   if (is_tracepoint (left->owner))
12306     gdb_assert (!left->duplicate);
12307   if (is_tracepoint (right->owner))
12308     gdb_assert (!right->duplicate);
12309
12310   left->inserted = right->inserted;
12311   left->duplicate = right->duplicate;
12312   left->needs_update = right->needs_update;
12313   left->target_info = right->target_info;
12314   right->inserted = left_inserted;
12315   right->duplicate = left_duplicate;
12316   right->needs_update = left_needs_update;
12317   right->target_info = left_target_info;
12318 }
12319
12320 /* Force the re-insertion of the locations at ADDRESS.  This is called
12321    once a new/deleted/modified duplicate location is found and we are evaluating
12322    conditions on the target's side.  Such conditions need to be updated on
12323    the target.  */
12324
12325 static void
12326 force_breakpoint_reinsertion (struct bp_location *bl)
12327 {
12328   struct bp_location **locp = NULL, **loc2p;
12329   struct bp_location *loc;
12330   CORE_ADDR address = 0;
12331   int pspace_num;
12332
12333   address = bl->address;
12334   pspace_num = bl->pspace->num;
12335
12336   /* This is only meaningful if the target is
12337      evaluating conditions and if the user has
12338      opted for condition evaluation on the target's
12339      side.  */
12340   if (gdb_evaluates_breakpoint_condition_p ()
12341       || !target_supports_evaluation_of_breakpoint_conditions ())
12342     return;
12343
12344   /* Flag all breakpoint locations with this address and
12345      the same program space as the location
12346      as "its condition has changed".  We need to
12347      update the conditions on the target's side.  */
12348   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12349     {
12350       loc = *loc2p;
12351
12352       if (!is_breakpoint (loc->owner)
12353           || pspace_num != loc->pspace->num)
12354         continue;
12355
12356       /* Flag the location appropriately.  We use a different state to
12357          let everyone know that we already updated the set of locations
12358          with addr bl->address and program space bl->pspace.  This is so
12359          we don't have to keep calling these functions just to mark locations
12360          that have already been marked.  */
12361       loc->condition_changed = condition_updated;
12362
12363       /* Free the agent expression bytecode as well.  We will compute
12364          it later on.  */
12365       loc->cond_bytecode.reset ();
12366     }
12367 }
12368 /* Called whether new breakpoints are created, or existing breakpoints
12369    deleted, to update the global location list and recompute which
12370    locations are duplicate of which.
12371
12372    The INSERT_MODE flag determines whether locations may not, may, or
12373    shall be inserted now.  See 'enum ugll_insert_mode' for more
12374    info.  */
12375
12376 static void
12377 update_global_location_list (enum ugll_insert_mode insert_mode)
12378 {
12379   struct breakpoint *b;
12380   struct bp_location **locp, *loc;
12381   struct cleanup *cleanups;
12382   /* Last breakpoint location address that was marked for update.  */
12383   CORE_ADDR last_addr = 0;
12384   /* Last breakpoint location program space that was marked for update.  */
12385   int last_pspace_num = -1;
12386
12387   /* Used in the duplicates detection below.  When iterating over all
12388      bp_locations, points to the first bp_location of a given address.
12389      Breakpoints and watchpoints of different types are never
12390      duplicates of each other.  Keep one pointer for each type of
12391      breakpoint/watchpoint, so we only need to loop over all locations
12392      once.  */
12393   struct bp_location *bp_loc_first;  /* breakpoint */
12394   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12395   struct bp_location *awp_loc_first; /* access watchpoint */
12396   struct bp_location *rwp_loc_first; /* read watchpoint */
12397
12398   /* Saved former bp_location array which we compare against the newly
12399      built bp_location from the current state of ALL_BREAKPOINTS.  */
12400   struct bp_location **old_location, **old_locp;
12401   unsigned old_location_count;
12402
12403   old_location = bp_location;
12404   old_location_count = bp_location_count;
12405   bp_location = NULL;
12406   bp_location_count = 0;
12407   cleanups = make_cleanup (xfree, old_location);
12408
12409   ALL_BREAKPOINTS (b)
12410     for (loc = b->loc; loc; loc = loc->next)
12411       bp_location_count++;
12412
12413   bp_location = XNEWVEC (struct bp_location *, bp_location_count);
12414   locp = bp_location;
12415   ALL_BREAKPOINTS (b)
12416     for (loc = b->loc; loc; loc = loc->next)
12417       *locp++ = loc;
12418   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12419          bp_location_compare);
12420
12421   bp_location_target_extensions_update ();
12422
12423   /* Identify bp_location instances that are no longer present in the
12424      new list, and therefore should be freed.  Note that it's not
12425      necessary that those locations should be removed from inferior --
12426      if there's another location at the same address (previously
12427      marked as duplicate), we don't need to remove/insert the
12428      location.
12429      
12430      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12431      and former bp_location array state respectively.  */
12432
12433   locp = bp_location;
12434   for (old_locp = old_location; old_locp < old_location + old_location_count;
12435        old_locp++)
12436     {
12437       struct bp_location *old_loc = *old_locp;
12438       struct bp_location **loc2p;
12439
12440       /* Tells if 'old_loc' is found among the new locations.  If
12441          not, we have to free it.  */
12442       int found_object = 0;
12443       /* Tells if the location should remain inserted in the target.  */
12444       int keep_in_target = 0;
12445       int removed = 0;
12446
12447       /* Skip LOCP entries which will definitely never be needed.
12448          Stop either at or being the one matching OLD_LOC.  */
12449       while (locp < bp_location + bp_location_count
12450              && (*locp)->address < old_loc->address)
12451         locp++;
12452
12453       for (loc2p = locp;
12454            (loc2p < bp_location + bp_location_count
12455             && (*loc2p)->address == old_loc->address);
12456            loc2p++)
12457         {
12458           /* Check if this is a new/duplicated location or a duplicated
12459              location that had its condition modified.  If so, we want to send
12460              its condition to the target if evaluation of conditions is taking
12461              place there.  */
12462           if ((*loc2p)->condition_changed == condition_modified
12463               && (last_addr != old_loc->address
12464                   || last_pspace_num != old_loc->pspace->num))
12465             {
12466               force_breakpoint_reinsertion (*loc2p);
12467               last_pspace_num = old_loc->pspace->num;
12468             }
12469
12470           if (*loc2p == old_loc)
12471             found_object = 1;
12472         }
12473
12474       /* We have already handled this address, update it so that we don't
12475          have to go through updates again.  */
12476       last_addr = old_loc->address;
12477
12478       /* Target-side condition evaluation: Handle deleted locations.  */
12479       if (!found_object)
12480         force_breakpoint_reinsertion (old_loc);
12481
12482       /* If this location is no longer present, and inserted, look if
12483          there's maybe a new location at the same address.  If so,
12484          mark that one inserted, and don't remove this one.  This is
12485          needed so that we don't have a time window where a breakpoint
12486          at certain location is not inserted.  */
12487
12488       if (old_loc->inserted)
12489         {
12490           /* If the location is inserted now, we might have to remove
12491              it.  */
12492
12493           if (found_object && should_be_inserted (old_loc))
12494             {
12495               /* The location is still present in the location list,
12496                  and still should be inserted.  Don't do anything.  */
12497               keep_in_target = 1;
12498             }
12499           else
12500             {
12501               /* This location still exists, but it won't be kept in the
12502                  target since it may have been disabled.  We proceed to
12503                  remove its target-side condition.  */
12504
12505               /* The location is either no longer present, or got
12506                  disabled.  See if there's another location at the
12507                  same address, in which case we don't need to remove
12508                  this one from the target.  */
12509
12510               /* OLD_LOC comes from existing struct breakpoint.  */
12511               if (breakpoint_address_is_meaningful (old_loc->owner))
12512                 {
12513                   for (loc2p = locp;
12514                        (loc2p < bp_location + bp_location_count
12515                         && (*loc2p)->address == old_loc->address);
12516                        loc2p++)
12517                     {
12518                       struct bp_location *loc2 = *loc2p;
12519
12520                       if (breakpoint_locations_match (loc2, old_loc))
12521                         {
12522                           /* Read watchpoint locations are switched to
12523                              access watchpoints, if the former are not
12524                              supported, but the latter are.  */
12525                           if (is_hardware_watchpoint (old_loc->owner))
12526                             {
12527                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12528                               loc2->watchpoint_type = old_loc->watchpoint_type;
12529                             }
12530
12531                           /* loc2 is a duplicated location. We need to check
12532                              if it should be inserted in case it will be
12533                              unduplicated.  */
12534                           if (loc2 != old_loc
12535                               && unduplicated_should_be_inserted (loc2))
12536                             {
12537                               swap_insertion (old_loc, loc2);
12538                               keep_in_target = 1;
12539                               break;
12540                             }
12541                         }
12542                     }
12543                 }
12544             }
12545
12546           if (!keep_in_target)
12547             {
12548               if (remove_breakpoint (old_loc))
12549                 {
12550                   /* This is just about all we can do.  We could keep
12551                      this location on the global list, and try to
12552                      remove it next time, but there's no particular
12553                      reason why we will succeed next time.
12554                      
12555                      Note that at this point, old_loc->owner is still
12556                      valid, as delete_breakpoint frees the breakpoint
12557                      only after calling us.  */
12558                   printf_filtered (_("warning: Error removing "
12559                                      "breakpoint %d\n"), 
12560                                    old_loc->owner->number);
12561                 }
12562               removed = 1;
12563             }
12564         }
12565
12566       if (!found_object)
12567         {
12568           if (removed && target_is_non_stop_p ()
12569               && need_moribund_for_location_type (old_loc))
12570             {
12571               /* This location was removed from the target.  In
12572                  non-stop mode, a race condition is possible where
12573                  we've removed a breakpoint, but stop events for that
12574                  breakpoint are already queued and will arrive later.
12575                  We apply an heuristic to be able to distinguish such
12576                  SIGTRAPs from other random SIGTRAPs: we keep this
12577                  breakpoint location for a bit, and will retire it
12578                  after we see some number of events.  The theory here
12579                  is that reporting of events should, "on the average",
12580                  be fair, so after a while we'll see events from all
12581                  threads that have anything of interest, and no longer
12582                  need to keep this breakpoint location around.  We
12583                  don't hold locations forever so to reduce chances of
12584                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12585                  SIGTRAP.
12586
12587                  The heuristic failing can be disastrous on
12588                  decr_pc_after_break targets.
12589
12590                  On decr_pc_after_break targets, like e.g., x86-linux,
12591                  if we fail to recognize a late breakpoint SIGTRAP,
12592                  because events_till_retirement has reached 0 too
12593                  soon, we'll fail to do the PC adjustment, and report
12594                  a random SIGTRAP to the user.  When the user resumes
12595                  the inferior, it will most likely immediately crash
12596                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12597                  corrupted, because of being resumed e.g., in the
12598                  middle of a multi-byte instruction, or skipped a
12599                  one-byte instruction.  This was actually seen happen
12600                  on native x86-linux, and should be less rare on
12601                  targets that do not support new thread events, like
12602                  remote, due to the heuristic depending on
12603                  thread_count.
12604
12605                  Mistaking a random SIGTRAP for a breakpoint trap
12606                  causes similar symptoms (PC adjustment applied when
12607                  it shouldn't), but then again, playing with SIGTRAPs
12608                  behind the debugger's back is asking for trouble.
12609
12610                  Since hardware watchpoint traps are always
12611                  distinguishable from other traps, so we don't need to
12612                  apply keep hardware watchpoint moribund locations
12613                  around.  We simply always ignore hardware watchpoint
12614                  traps we can no longer explain.  */
12615
12616               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12617               old_loc->owner = NULL;
12618
12619               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12620             }
12621           else
12622             {
12623               old_loc->owner = NULL;
12624               decref_bp_location (&old_loc);
12625             }
12626         }
12627     }
12628
12629   /* Rescan breakpoints at the same address and section, marking the
12630      first one as "first" and any others as "duplicates".  This is so
12631      that the bpt instruction is only inserted once.  If we have a
12632      permanent breakpoint at the same place as BPT, make that one the
12633      official one, and the rest as duplicates.  Permanent breakpoints
12634      are sorted first for the same address.
12635
12636      Do the same for hardware watchpoints, but also considering the
12637      watchpoint's type (regular/access/read) and length.  */
12638
12639   bp_loc_first = NULL;
12640   wp_loc_first = NULL;
12641   awp_loc_first = NULL;
12642   rwp_loc_first = NULL;
12643   ALL_BP_LOCATIONS (loc, locp)
12644     {
12645       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12646          non-NULL.  */
12647       struct bp_location **loc_first_p;
12648       b = loc->owner;
12649
12650       if (!unduplicated_should_be_inserted (loc)
12651           || !breakpoint_address_is_meaningful (b)
12652           /* Don't detect duplicate for tracepoint locations because they are
12653            never duplicated.  See the comments in field `duplicate' of
12654            `struct bp_location'.  */
12655           || is_tracepoint (b))
12656         {
12657           /* Clear the condition modification flag.  */
12658           loc->condition_changed = condition_unchanged;
12659           continue;
12660         }
12661
12662       if (b->type == bp_hardware_watchpoint)
12663         loc_first_p = &wp_loc_first;
12664       else if (b->type == bp_read_watchpoint)
12665         loc_first_p = &rwp_loc_first;
12666       else if (b->type == bp_access_watchpoint)
12667         loc_first_p = &awp_loc_first;
12668       else
12669         loc_first_p = &bp_loc_first;
12670
12671       if (*loc_first_p == NULL
12672           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12673           || !breakpoint_locations_match (loc, *loc_first_p))
12674         {
12675           *loc_first_p = loc;
12676           loc->duplicate = 0;
12677
12678           if (is_breakpoint (loc->owner) && loc->condition_changed)
12679             {
12680               loc->needs_update = 1;
12681               /* Clear the condition modification flag.  */
12682               loc->condition_changed = condition_unchanged;
12683             }
12684           continue;
12685         }
12686
12687
12688       /* This and the above ensure the invariant that the first location
12689          is not duplicated, and is the inserted one.
12690          All following are marked as duplicated, and are not inserted.  */
12691       if (loc->inserted)
12692         swap_insertion (loc, *loc_first_p);
12693       loc->duplicate = 1;
12694
12695       /* Clear the condition modification flag.  */
12696       loc->condition_changed = condition_unchanged;
12697     }
12698
12699   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12700     {
12701       if (insert_mode != UGLL_DONT_INSERT)
12702         insert_breakpoint_locations ();
12703       else
12704         {
12705           /* Even though the caller told us to not insert new
12706              locations, we may still need to update conditions on the
12707              target's side of breakpoints that were already inserted
12708              if the target is evaluating breakpoint conditions.  We
12709              only update conditions for locations that are marked
12710              "needs_update".  */
12711           update_inserted_breakpoint_locations ();
12712         }
12713     }
12714
12715   if (insert_mode != UGLL_DONT_INSERT)
12716     download_tracepoint_locations ();
12717
12718   do_cleanups (cleanups);
12719 }
12720
12721 void
12722 breakpoint_retire_moribund (void)
12723 {
12724   struct bp_location *loc;
12725   int ix;
12726
12727   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12728     if (--(loc->events_till_retirement) == 0)
12729       {
12730         decref_bp_location (&loc);
12731         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12732         --ix;
12733       }
12734 }
12735
12736 static void
12737 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12738 {
12739
12740   TRY
12741     {
12742       update_global_location_list (insert_mode);
12743     }
12744   CATCH (e, RETURN_MASK_ERROR)
12745     {
12746     }
12747   END_CATCH
12748 }
12749
12750 /* Clear BKP from a BPS.  */
12751
12752 static void
12753 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12754 {
12755   bpstat bs;
12756
12757   for (bs = bps; bs; bs = bs->next)
12758     if (bs->breakpoint_at == bpt)
12759       {
12760         bs->breakpoint_at = NULL;
12761         bs->old_val = NULL;
12762         /* bs->commands will be freed later.  */
12763       }
12764 }
12765
12766 /* Callback for iterate_over_threads.  */
12767 static int
12768 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12769 {
12770   struct breakpoint *bpt = (struct breakpoint *) data;
12771
12772   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12773   return 0;
12774 }
12775
12776 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12777    callbacks.  */
12778
12779 static void
12780 say_where (struct breakpoint *b)
12781 {
12782   struct value_print_options opts;
12783
12784   get_user_print_options (&opts);
12785
12786   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12787      single string.  */
12788   if (b->loc == NULL)
12789     {
12790       /* For pending locations, the output differs slightly based
12791          on b->extra_string.  If this is non-NULL, it contains either
12792          a condition or dprintf arguments.  */
12793       if (b->extra_string == NULL)
12794         {
12795           printf_filtered (_(" (%s) pending."),
12796                            event_location_to_string (b->location));
12797         }
12798       else if (b->type == bp_dprintf)
12799         {
12800           printf_filtered (_(" (%s,%s) pending."),
12801                            event_location_to_string (b->location),
12802                            b->extra_string);
12803         }
12804       else
12805         {
12806           printf_filtered (_(" (%s %s) pending."),
12807                            event_location_to_string (b->location),
12808                            b->extra_string);
12809         }
12810     }
12811   else
12812     {
12813       if (opts.addressprint || b->loc->symtab == NULL)
12814         {
12815           printf_filtered (" at ");
12816           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12817                           gdb_stdout);
12818         }
12819       if (b->loc->symtab != NULL)
12820         {
12821           /* If there is a single location, we can print the location
12822              more nicely.  */
12823           if (b->loc->next == NULL)
12824             printf_filtered (": file %s, line %d.",
12825                              symtab_to_filename_for_display (b->loc->symtab),
12826                              b->loc->line_number);
12827           else
12828             /* This is not ideal, but each location may have a
12829                different file name, and this at least reflects the
12830                real situation somewhat.  */
12831             printf_filtered (": %s.",
12832                              event_location_to_string (b->location));
12833         }
12834
12835       if (b->loc->next)
12836         {
12837           struct bp_location *loc = b->loc;
12838           int n = 0;
12839           for (; loc; loc = loc->next)
12840             ++n;
12841           printf_filtered (" (%d locations)", n);
12842         }
12843     }
12844 }
12845
12846 /* Default bp_location_ops methods.  */
12847
12848 static void
12849 bp_location_dtor (struct bp_location *self)
12850 {
12851   xfree (self->function_name);
12852 }
12853
12854 static const struct bp_location_ops bp_location_ops =
12855 {
12856   bp_location_dtor
12857 };
12858
12859 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12860    inherit from.  */
12861
12862 static void
12863 base_breakpoint_dtor (struct breakpoint *self)
12864 {
12865   decref_counted_command_line (&self->commands);
12866   xfree (self->cond_string);
12867   xfree (self->extra_string);
12868   xfree (self->filter);
12869   delete_event_location (self->location);
12870   delete_event_location (self->location_range_end);
12871 }
12872
12873 static struct bp_location *
12874 base_breakpoint_allocate_location (struct breakpoint *self)
12875 {
12876   struct bp_location *loc;
12877
12878   loc = new struct bp_location ();
12879   init_bp_location (loc, &bp_location_ops, self);
12880   return loc;
12881 }
12882
12883 static void
12884 base_breakpoint_re_set (struct breakpoint *b)
12885 {
12886   /* Nothing to re-set. */
12887 }
12888
12889 #define internal_error_pure_virtual_called() \
12890   gdb_assert_not_reached ("pure virtual function called")
12891
12892 static int
12893 base_breakpoint_insert_location (struct bp_location *bl)
12894 {
12895   internal_error_pure_virtual_called ();
12896 }
12897
12898 static int
12899 base_breakpoint_remove_location (struct bp_location *bl,
12900                                  enum remove_bp_reason reason)
12901 {
12902   internal_error_pure_virtual_called ();
12903 }
12904
12905 static int
12906 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12907                                 struct address_space *aspace,
12908                                 CORE_ADDR bp_addr,
12909                                 const struct target_waitstatus *ws)
12910 {
12911   internal_error_pure_virtual_called ();
12912 }
12913
12914 static void
12915 base_breakpoint_check_status (bpstat bs)
12916 {
12917   /* Always stop.   */
12918 }
12919
12920 /* A "works_in_software_mode" breakpoint_ops method that just internal
12921    errors.  */
12922
12923 static int
12924 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12925 {
12926   internal_error_pure_virtual_called ();
12927 }
12928
12929 /* A "resources_needed" breakpoint_ops method that just internal
12930    errors.  */
12931
12932 static int
12933 base_breakpoint_resources_needed (const struct bp_location *bl)
12934 {
12935   internal_error_pure_virtual_called ();
12936 }
12937
12938 static enum print_stop_action
12939 base_breakpoint_print_it (bpstat bs)
12940 {
12941   internal_error_pure_virtual_called ();
12942 }
12943
12944 static void
12945 base_breakpoint_print_one_detail (const struct breakpoint *self,
12946                                   struct ui_out *uiout)
12947 {
12948   /* nothing */
12949 }
12950
12951 static void
12952 base_breakpoint_print_mention (struct breakpoint *b)
12953 {
12954   internal_error_pure_virtual_called ();
12955 }
12956
12957 static void
12958 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12959 {
12960   internal_error_pure_virtual_called ();
12961 }
12962
12963 static void
12964 base_breakpoint_create_sals_from_location
12965   (const struct event_location *location,
12966    struct linespec_result *canonical,
12967    enum bptype type_wanted)
12968 {
12969   internal_error_pure_virtual_called ();
12970 }
12971
12972 static void
12973 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12974                                         struct linespec_result *c,
12975                                         char *cond_string,
12976                                         char *extra_string,
12977                                         enum bptype type_wanted,
12978                                         enum bpdisp disposition,
12979                                         int thread,
12980                                         int task, int ignore_count,
12981                                         const struct breakpoint_ops *o,
12982                                         int from_tty, int enabled,
12983                                         int internal, unsigned flags)
12984 {
12985   internal_error_pure_virtual_called ();
12986 }
12987
12988 static void
12989 base_breakpoint_decode_location (struct breakpoint *b,
12990                                  const struct event_location *location,
12991                                  struct program_space *search_pspace,
12992                                  struct symtabs_and_lines *sals)
12993 {
12994   internal_error_pure_virtual_called ();
12995 }
12996
12997 /* The default 'explains_signal' method.  */
12998
12999 static int
13000 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13001 {
13002   return 1;
13003 }
13004
13005 /* The default "after_condition_true" method.  */
13006
13007 static void
13008 base_breakpoint_after_condition_true (struct bpstats *bs)
13009 {
13010   /* Nothing to do.   */
13011 }
13012
13013 struct breakpoint_ops base_breakpoint_ops =
13014 {
13015   base_breakpoint_dtor,
13016   base_breakpoint_allocate_location,
13017   base_breakpoint_re_set,
13018   base_breakpoint_insert_location,
13019   base_breakpoint_remove_location,
13020   base_breakpoint_breakpoint_hit,
13021   base_breakpoint_check_status,
13022   base_breakpoint_resources_needed,
13023   base_breakpoint_works_in_software_mode,
13024   base_breakpoint_print_it,
13025   NULL,
13026   base_breakpoint_print_one_detail,
13027   base_breakpoint_print_mention,
13028   base_breakpoint_print_recreate,
13029   base_breakpoint_create_sals_from_location,
13030   base_breakpoint_create_breakpoints_sal,
13031   base_breakpoint_decode_location,
13032   base_breakpoint_explains_signal,
13033   base_breakpoint_after_condition_true,
13034 };
13035
13036 /* Default breakpoint_ops methods.  */
13037
13038 static void
13039 bkpt_re_set (struct breakpoint *b)
13040 {
13041   /* FIXME: is this still reachable?  */
13042   if (breakpoint_event_location_empty_p (b))
13043     {
13044       /* Anything without a location can't be re-set.  */
13045       delete_breakpoint (b);
13046       return;
13047     }
13048
13049   breakpoint_re_set_default (b);
13050 }
13051
13052 static int
13053 bkpt_insert_location (struct bp_location *bl)
13054 {
13055   CORE_ADDR addr = bl->target_info.reqstd_address;
13056
13057   bl->target_info.kind = breakpoint_kind (bl, &addr);
13058   bl->target_info.placed_address = addr;
13059
13060   if (bl->loc_type == bp_loc_hardware_breakpoint)
13061     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13062   else
13063     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13064 }
13065
13066 static int
13067 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
13068 {
13069   if (bl->loc_type == bp_loc_hardware_breakpoint)
13070     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13071   else
13072     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
13073 }
13074
13075 static int
13076 bkpt_breakpoint_hit (const struct bp_location *bl,
13077                      struct address_space *aspace, CORE_ADDR bp_addr,
13078                      const struct target_waitstatus *ws)
13079 {
13080   if (ws->kind != TARGET_WAITKIND_STOPPED
13081       || ws->value.sig != GDB_SIGNAL_TRAP)
13082     return 0;
13083
13084   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13085                                  aspace, bp_addr))
13086     return 0;
13087
13088   if (overlay_debugging         /* unmapped overlay section */
13089       && section_is_overlay (bl->section)
13090       && !section_is_mapped (bl->section))
13091     return 0;
13092
13093   return 1;
13094 }
13095
13096 static int
13097 dprintf_breakpoint_hit (const struct bp_location *bl,
13098                         struct address_space *aspace, CORE_ADDR bp_addr,
13099                         const struct target_waitstatus *ws)
13100 {
13101   if (dprintf_style == dprintf_style_agent
13102       && target_can_run_breakpoint_commands ())
13103     {
13104       /* An agent-style dprintf never causes a stop.  If we see a trap
13105          for this address it must be for a breakpoint that happens to
13106          be set at the same address.  */
13107       return 0;
13108     }
13109
13110   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13111 }
13112
13113 static int
13114 bkpt_resources_needed (const struct bp_location *bl)
13115 {
13116   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13117
13118   return 1;
13119 }
13120
13121 static enum print_stop_action
13122 bkpt_print_it (bpstat bs)
13123 {
13124   struct breakpoint *b;
13125   const struct bp_location *bl;
13126   int bp_temp;
13127   struct ui_out *uiout = current_uiout;
13128
13129   gdb_assert (bs->bp_location_at != NULL);
13130
13131   bl = bs->bp_location_at;
13132   b = bs->breakpoint_at;
13133
13134   bp_temp = b->disposition == disp_del;
13135   if (bl->address != bl->requested_address)
13136     breakpoint_adjustment_warning (bl->requested_address,
13137                                    bl->address,
13138                                    b->number, 1);
13139   annotate_breakpoint (b->number);
13140   maybe_print_thread_hit_breakpoint (uiout);
13141
13142   if (bp_temp)
13143     uiout->text ("Temporary breakpoint ");
13144   else
13145     uiout->text ("Breakpoint ");
13146   if (uiout->is_mi_like_p ())
13147     {
13148       uiout->field_string ("reason",
13149                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13150       uiout->field_string ("disp", bpdisp_text (b->disposition));
13151     }
13152   uiout->field_int ("bkptno", b->number);
13153   uiout->text (", ");
13154
13155   return PRINT_SRC_AND_LOC;
13156 }
13157
13158 static void
13159 bkpt_print_mention (struct breakpoint *b)
13160 {
13161   if (current_uiout->is_mi_like_p ())
13162     return;
13163
13164   switch (b->type)
13165     {
13166     case bp_breakpoint:
13167     case bp_gnu_ifunc_resolver:
13168       if (b->disposition == disp_del)
13169         printf_filtered (_("Temporary breakpoint"));
13170       else
13171         printf_filtered (_("Breakpoint"));
13172       printf_filtered (_(" %d"), b->number);
13173       if (b->type == bp_gnu_ifunc_resolver)
13174         printf_filtered (_(" at gnu-indirect-function resolver"));
13175       break;
13176     case bp_hardware_breakpoint:
13177       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13178       break;
13179     case bp_dprintf:
13180       printf_filtered (_("Dprintf %d"), b->number);
13181       break;
13182     }
13183
13184   say_where (b);
13185 }
13186
13187 static void
13188 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13189 {
13190   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13191     fprintf_unfiltered (fp, "tbreak");
13192   else if (tp->type == bp_breakpoint)
13193     fprintf_unfiltered (fp, "break");
13194   else if (tp->type == bp_hardware_breakpoint
13195            && tp->disposition == disp_del)
13196     fprintf_unfiltered (fp, "thbreak");
13197   else if (tp->type == bp_hardware_breakpoint)
13198     fprintf_unfiltered (fp, "hbreak");
13199   else
13200     internal_error (__FILE__, __LINE__,
13201                     _("unhandled breakpoint type %d"), (int) tp->type);
13202
13203   fprintf_unfiltered (fp, " %s",
13204                       event_location_to_string (tp->location));
13205
13206   /* Print out extra_string if this breakpoint is pending.  It might
13207      contain, for example, conditions that were set by the user.  */
13208   if (tp->loc == NULL && tp->extra_string != NULL)
13209     fprintf_unfiltered (fp, " %s", tp->extra_string);
13210
13211   print_recreate_thread (tp, fp);
13212 }
13213
13214 static void
13215 bkpt_create_sals_from_location (const struct event_location *location,
13216                                 struct linespec_result *canonical,
13217                                 enum bptype type_wanted)
13218 {
13219   create_sals_from_location_default (location, canonical, type_wanted);
13220 }
13221
13222 static void
13223 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13224                              struct linespec_result *canonical,
13225                              char *cond_string,
13226                              char *extra_string,
13227                              enum bptype type_wanted,
13228                              enum bpdisp disposition,
13229                              int thread,
13230                              int task, int ignore_count,
13231                              const struct breakpoint_ops *ops,
13232                              int from_tty, int enabled,
13233                              int internal, unsigned flags)
13234 {
13235   create_breakpoints_sal_default (gdbarch, canonical,
13236                                   cond_string, extra_string,
13237                                   type_wanted,
13238                                   disposition, thread, task,
13239                                   ignore_count, ops, from_tty,
13240                                   enabled, internal, flags);
13241 }
13242
13243 static void
13244 bkpt_decode_location (struct breakpoint *b,
13245                       const struct event_location *location,
13246                       struct program_space *search_pspace,
13247                       struct symtabs_and_lines *sals)
13248 {
13249   decode_location_default (b, location, search_pspace, sals);
13250 }
13251
13252 /* Virtual table for internal breakpoints.  */
13253
13254 static void
13255 internal_bkpt_re_set (struct breakpoint *b)
13256 {
13257   switch (b->type)
13258     {
13259       /* Delete overlay event and longjmp master breakpoints; they
13260          will be reset later by breakpoint_re_set.  */
13261     case bp_overlay_event:
13262     case bp_longjmp_master:
13263     case bp_std_terminate_master:
13264     case bp_exception_master:
13265       delete_breakpoint (b);
13266       break;
13267
13268       /* This breakpoint is special, it's set up when the inferior
13269          starts and we really don't want to touch it.  */
13270     case bp_shlib_event:
13271
13272       /* Like bp_shlib_event, this breakpoint type is special.  Once
13273          it is set up, we do not want to touch it.  */
13274     case bp_thread_event:
13275       break;
13276     }
13277 }
13278
13279 static void
13280 internal_bkpt_check_status (bpstat bs)
13281 {
13282   if (bs->breakpoint_at->type == bp_shlib_event)
13283     {
13284       /* If requested, stop when the dynamic linker notifies GDB of
13285          events.  This allows the user to get control and place
13286          breakpoints in initializer routines for dynamically loaded
13287          objects (among other things).  */
13288       bs->stop = stop_on_solib_events;
13289       bs->print = stop_on_solib_events;
13290     }
13291   else
13292     bs->stop = 0;
13293 }
13294
13295 static enum print_stop_action
13296 internal_bkpt_print_it (bpstat bs)
13297 {
13298   struct breakpoint *b;
13299
13300   b = bs->breakpoint_at;
13301
13302   switch (b->type)
13303     {
13304     case bp_shlib_event:
13305       /* Did we stop because the user set the stop_on_solib_events
13306          variable?  (If so, we report this as a generic, "Stopped due
13307          to shlib event" message.) */
13308       print_solib_event (0);
13309       break;
13310
13311     case bp_thread_event:
13312       /* Not sure how we will get here.
13313          GDB should not stop for these breakpoints.  */
13314       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13315       break;
13316
13317     case bp_overlay_event:
13318       /* By analogy with the thread event, GDB should not stop for these.  */
13319       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13320       break;
13321
13322     case bp_longjmp_master:
13323       /* These should never be enabled.  */
13324       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13325       break;
13326
13327     case bp_std_terminate_master:
13328       /* These should never be enabled.  */
13329       printf_filtered (_("std::terminate Master Breakpoint: "
13330                          "gdb should not stop!\n"));
13331       break;
13332
13333     case bp_exception_master:
13334       /* These should never be enabled.  */
13335       printf_filtered (_("Exception Master Breakpoint: "
13336                          "gdb should not stop!\n"));
13337       break;
13338     }
13339
13340   return PRINT_NOTHING;
13341 }
13342
13343 static void
13344 internal_bkpt_print_mention (struct breakpoint *b)
13345 {
13346   /* Nothing to mention.  These breakpoints are internal.  */
13347 }
13348
13349 /* Virtual table for momentary breakpoints  */
13350
13351 static void
13352 momentary_bkpt_re_set (struct breakpoint *b)
13353 {
13354   /* Keep temporary breakpoints, which can be encountered when we step
13355      over a dlopen call and solib_add is resetting the breakpoints.
13356      Otherwise these should have been blown away via the cleanup chain
13357      or by breakpoint_init_inferior when we rerun the executable.  */
13358 }
13359
13360 static void
13361 momentary_bkpt_check_status (bpstat bs)
13362 {
13363   /* Nothing.  The point of these breakpoints is causing a stop.  */
13364 }
13365
13366 static enum print_stop_action
13367 momentary_bkpt_print_it (bpstat bs)
13368 {
13369   return PRINT_UNKNOWN;
13370 }
13371
13372 static void
13373 momentary_bkpt_print_mention (struct breakpoint *b)
13374 {
13375   /* Nothing to mention.  These breakpoints are internal.  */
13376 }
13377
13378 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13379
13380    It gets cleared already on the removal of the first one of such placed
13381    breakpoints.  This is OK as they get all removed altogether.  */
13382
13383 static void
13384 longjmp_bkpt_dtor (struct breakpoint *self)
13385 {
13386   struct thread_info *tp = find_thread_global_id (self->thread);
13387
13388   if (tp)
13389     tp->initiating_frame = null_frame_id;
13390
13391   momentary_breakpoint_ops.dtor (self);
13392 }
13393
13394 /* Specific methods for probe breakpoints.  */
13395
13396 static int
13397 bkpt_probe_insert_location (struct bp_location *bl)
13398 {
13399   int v = bkpt_insert_location (bl);
13400
13401   if (v == 0)
13402     {
13403       /* The insertion was successful, now let's set the probe's semaphore
13404          if needed.  */
13405       if (bl->probe.probe->pops->set_semaphore != NULL)
13406         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13407                                               bl->probe.objfile,
13408                                               bl->gdbarch);
13409     }
13410
13411   return v;
13412 }
13413
13414 static int
13415 bkpt_probe_remove_location (struct bp_location *bl,
13416                             enum remove_bp_reason reason)
13417 {
13418   /* Let's clear the semaphore before removing the location.  */
13419   if (bl->probe.probe->pops->clear_semaphore != NULL)
13420     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13421                                             bl->probe.objfile,
13422                                             bl->gdbarch);
13423
13424   return bkpt_remove_location (bl, reason);
13425 }
13426
13427 static void
13428 bkpt_probe_create_sals_from_location (const struct event_location *location,
13429                                       struct linespec_result *canonical,
13430                                       enum bptype type_wanted)
13431 {
13432   struct linespec_sals lsal;
13433
13434   lsal.sals = parse_probes (location, NULL, canonical);
13435   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13436   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13437 }
13438
13439 static void
13440 bkpt_probe_decode_location (struct breakpoint *b,
13441                             const struct event_location *location,
13442                             struct program_space *search_pspace,
13443                             struct symtabs_and_lines *sals)
13444 {
13445   *sals = parse_probes (location, search_pspace, NULL);
13446   if (!sals->sals)
13447     error (_("probe not found"));
13448 }
13449
13450 /* The breakpoint_ops structure to be used in tracepoints.  */
13451
13452 static void
13453 tracepoint_re_set (struct breakpoint *b)
13454 {
13455   breakpoint_re_set_default (b);
13456 }
13457
13458 static int
13459 tracepoint_breakpoint_hit (const struct bp_location *bl,
13460                            struct address_space *aspace, CORE_ADDR bp_addr,
13461                            const struct target_waitstatus *ws)
13462 {
13463   /* By definition, the inferior does not report stops at
13464      tracepoints.  */
13465   return 0;
13466 }
13467
13468 static void
13469 tracepoint_print_one_detail (const struct breakpoint *self,
13470                              struct ui_out *uiout)
13471 {
13472   struct tracepoint *tp = (struct tracepoint *) self;
13473   if (tp->static_trace_marker_id)
13474     {
13475       gdb_assert (self->type == bp_static_tracepoint);
13476
13477       uiout->text ("\tmarker id is ");
13478       uiout->field_string ("static-tracepoint-marker-string-id",
13479                            tp->static_trace_marker_id);
13480       uiout->text ("\n");
13481     }
13482 }
13483
13484 static void
13485 tracepoint_print_mention (struct breakpoint *b)
13486 {
13487   if (current_uiout->is_mi_like_p ())
13488     return;
13489
13490   switch (b->type)
13491     {
13492     case bp_tracepoint:
13493       printf_filtered (_("Tracepoint"));
13494       printf_filtered (_(" %d"), b->number);
13495       break;
13496     case bp_fast_tracepoint:
13497       printf_filtered (_("Fast tracepoint"));
13498       printf_filtered (_(" %d"), b->number);
13499       break;
13500     case bp_static_tracepoint:
13501       printf_filtered (_("Static tracepoint"));
13502       printf_filtered (_(" %d"), b->number);
13503       break;
13504     default:
13505       internal_error (__FILE__, __LINE__,
13506                       _("unhandled tracepoint type %d"), (int) b->type);
13507     }
13508
13509   say_where (b);
13510 }
13511
13512 static void
13513 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13514 {
13515   struct tracepoint *tp = (struct tracepoint *) self;
13516
13517   if (self->type == bp_fast_tracepoint)
13518     fprintf_unfiltered (fp, "ftrace");
13519   else if (self->type == bp_static_tracepoint)
13520     fprintf_unfiltered (fp, "strace");
13521   else if (self->type == bp_tracepoint)
13522     fprintf_unfiltered (fp, "trace");
13523   else
13524     internal_error (__FILE__, __LINE__,
13525                     _("unhandled tracepoint type %d"), (int) self->type);
13526
13527   fprintf_unfiltered (fp, " %s",
13528                       event_location_to_string (self->location));
13529   print_recreate_thread (self, fp);
13530
13531   if (tp->pass_count)
13532     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13533 }
13534
13535 static void
13536 tracepoint_create_sals_from_location (const struct event_location *location,
13537                                       struct linespec_result *canonical,
13538                                       enum bptype type_wanted)
13539 {
13540   create_sals_from_location_default (location, canonical, type_wanted);
13541 }
13542
13543 static void
13544 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13545                                    struct linespec_result *canonical,
13546                                    char *cond_string,
13547                                    char *extra_string,
13548                                    enum bptype type_wanted,
13549                                    enum bpdisp disposition,
13550                                    int thread,
13551                                    int task, int ignore_count,
13552                                    const struct breakpoint_ops *ops,
13553                                    int from_tty, int enabled,
13554                                    int internal, unsigned flags)
13555 {
13556   create_breakpoints_sal_default (gdbarch, canonical,
13557                                   cond_string, extra_string,
13558                                   type_wanted,
13559                                   disposition, thread, task,
13560                                   ignore_count, ops, from_tty,
13561                                   enabled, internal, flags);
13562 }
13563
13564 static void
13565 tracepoint_decode_location (struct breakpoint *b,
13566                             const struct event_location *location,
13567                             struct program_space *search_pspace,
13568                             struct symtabs_and_lines *sals)
13569 {
13570   decode_location_default (b, location, search_pspace, sals);
13571 }
13572
13573 struct breakpoint_ops tracepoint_breakpoint_ops;
13574
13575 /* The breakpoint_ops structure to be use on tracepoints placed in a
13576    static probe.  */
13577
13578 static void
13579 tracepoint_probe_create_sals_from_location
13580   (const struct event_location *location,
13581    struct linespec_result *canonical,
13582    enum bptype type_wanted)
13583 {
13584   /* We use the same method for breakpoint on probes.  */
13585   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13586 }
13587
13588 static void
13589 tracepoint_probe_decode_location (struct breakpoint *b,
13590                                   const struct event_location *location,
13591                                   struct program_space *search_pspace,
13592                                   struct symtabs_and_lines *sals)
13593 {
13594   /* We use the same method for breakpoint on probes.  */
13595   bkpt_probe_decode_location (b, location, search_pspace, sals);
13596 }
13597
13598 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13599
13600 /* Dprintf breakpoint_ops methods.  */
13601
13602 static void
13603 dprintf_re_set (struct breakpoint *b)
13604 {
13605   breakpoint_re_set_default (b);
13606
13607   /* extra_string should never be non-NULL for dprintf.  */
13608   gdb_assert (b->extra_string != NULL);
13609
13610   /* 1 - connect to target 1, that can run breakpoint commands.
13611      2 - create a dprintf, which resolves fine.
13612      3 - disconnect from target 1
13613      4 - connect to target 2, that can NOT run breakpoint commands.
13614
13615      After steps #3/#4, you'll want the dprintf command list to
13616      be updated, because target 1 and 2 may well return different
13617      answers for target_can_run_breakpoint_commands().
13618      Given absence of finer grained resetting, we get to do
13619      it all the time.  */
13620   if (b->extra_string != NULL)
13621     update_dprintf_command_list (b);
13622 }
13623
13624 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13625
13626 static void
13627 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13628 {
13629   fprintf_unfiltered (fp, "dprintf %s,%s",
13630                       event_location_to_string (tp->location),
13631                       tp->extra_string);
13632   print_recreate_thread (tp, fp);
13633 }
13634
13635 /* Implement the "after_condition_true" breakpoint_ops method for
13636    dprintf.
13637
13638    dprintf's are implemented with regular commands in their command
13639    list, but we run the commands here instead of before presenting the
13640    stop to the user, as dprintf's don't actually cause a stop.  This
13641    also makes it so that the commands of multiple dprintfs at the same
13642    address are all handled.  */
13643
13644 static void
13645 dprintf_after_condition_true (struct bpstats *bs)
13646 {
13647   struct cleanup *old_chain;
13648   struct bpstats tmp_bs = { NULL };
13649   struct bpstats *tmp_bs_p = &tmp_bs;
13650
13651   /* dprintf's never cause a stop.  This wasn't set in the
13652      check_status hook instead because that would make the dprintf's
13653      condition not be evaluated.  */
13654   bs->stop = 0;
13655
13656   /* Run the command list here.  Take ownership of it instead of
13657      copying.  We never want these commands to run later in
13658      bpstat_do_actions, if a breakpoint that causes a stop happens to
13659      be set at same address as this dprintf, or even if running the
13660      commands here throws.  */
13661   tmp_bs.commands = bs->commands;
13662   bs->commands = NULL;
13663   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13664
13665   bpstat_do_actions_1 (&tmp_bs_p);
13666
13667   /* 'tmp_bs.commands' will usually be NULL by now, but
13668      bpstat_do_actions_1 may return early without processing the whole
13669      list.  */
13670   do_cleanups (old_chain);
13671 }
13672
13673 /* The breakpoint_ops structure to be used on static tracepoints with
13674    markers (`-m').  */
13675
13676 static void
13677 strace_marker_create_sals_from_location (const struct event_location *location,
13678                                          struct linespec_result *canonical,
13679                                          enum bptype type_wanted)
13680 {
13681   struct linespec_sals lsal;
13682   const char *arg_start, *arg;
13683   char *str;
13684   struct cleanup *cleanup;
13685
13686   arg = arg_start = get_linespec_location (location);
13687   lsal.sals = decode_static_tracepoint_spec (&arg);
13688
13689   str = savestring (arg_start, arg - arg_start);
13690   cleanup = make_cleanup (xfree, str);
13691   canonical->location = new_linespec_location (&str);
13692   do_cleanups (cleanup);
13693
13694   lsal.canonical = xstrdup (event_location_to_string (canonical->location));
13695   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13696 }
13697
13698 static void
13699 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13700                                       struct linespec_result *canonical,
13701                                       char *cond_string,
13702                                       char *extra_string,
13703                                       enum bptype type_wanted,
13704                                       enum bpdisp disposition,
13705                                       int thread,
13706                                       int task, int ignore_count,
13707                                       const struct breakpoint_ops *ops,
13708                                       int from_tty, int enabled,
13709                                       int internal, unsigned flags)
13710 {
13711   int i;
13712   struct linespec_sals *lsal = VEC_index (linespec_sals,
13713                                           canonical->sals, 0);
13714
13715   /* If the user is creating a static tracepoint by marker id
13716      (strace -m MARKER_ID), then store the sals index, so that
13717      breakpoint_re_set can try to match up which of the newly
13718      found markers corresponds to this one, and, don't try to
13719      expand multiple locations for each sal, given than SALS
13720      already should contain all sals for MARKER_ID.  */
13721
13722   for (i = 0; i < lsal->sals.nelts; ++i)
13723     {
13724       struct symtabs_and_lines expanded;
13725       struct tracepoint *tp;
13726       struct cleanup *old_chain;
13727       struct event_location *location;
13728
13729       expanded.nelts = 1;
13730       expanded.sals = &lsal->sals.sals[i];
13731
13732       location = copy_event_location (canonical->location);
13733       old_chain = make_cleanup_delete_event_location (location);
13734
13735       tp = new tracepoint ();
13736       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13737                            location, NULL,
13738                            cond_string, extra_string,
13739                            type_wanted, disposition,
13740                            thread, task, ignore_count, ops,
13741                            from_tty, enabled, internal, flags,
13742                            canonical->special_display);
13743       /* Given that its possible to have multiple markers with
13744          the same string id, if the user is creating a static
13745          tracepoint by marker id ("strace -m MARKER_ID"), then
13746          store the sals index, so that breakpoint_re_set can
13747          try to match up which of the newly found markers
13748          corresponds to this one  */
13749       tp->static_trace_marker_id_idx = i;
13750
13751       install_breakpoint (internal, &tp->base, 0);
13752
13753       discard_cleanups (old_chain);
13754     }
13755 }
13756
13757 static void
13758 strace_marker_decode_location (struct breakpoint *b,
13759                                const struct event_location *location,
13760                                struct program_space *search_pspace,
13761                                struct symtabs_and_lines *sals)
13762 {
13763   struct tracepoint *tp = (struct tracepoint *) b;
13764   const char *s = get_linespec_location (location);
13765
13766   *sals = decode_static_tracepoint_spec (&s);
13767   if (sals->nelts > tp->static_trace_marker_id_idx)
13768     {
13769       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13770       sals->nelts = 1;
13771     }
13772   else
13773     error (_("marker %s not found"), tp->static_trace_marker_id);
13774 }
13775
13776 static struct breakpoint_ops strace_marker_breakpoint_ops;
13777
13778 static int
13779 strace_marker_p (struct breakpoint *b)
13780 {
13781   return b->ops == &strace_marker_breakpoint_ops;
13782 }
13783
13784 /* Delete a breakpoint and clean up all traces of it in the data
13785    structures.  */
13786
13787 void
13788 delete_breakpoint (struct breakpoint *bpt)
13789 {
13790   struct breakpoint *b;
13791
13792   gdb_assert (bpt != NULL);
13793
13794   /* Has this bp already been deleted?  This can happen because
13795      multiple lists can hold pointers to bp's.  bpstat lists are
13796      especial culprits.
13797
13798      One example of this happening is a watchpoint's scope bp.  When
13799      the scope bp triggers, we notice that the watchpoint is out of
13800      scope, and delete it.  We also delete its scope bp.  But the
13801      scope bp is marked "auto-deleting", and is already on a bpstat.
13802      That bpstat is then checked for auto-deleting bp's, which are
13803      deleted.
13804
13805      A real solution to this problem might involve reference counts in
13806      bp's, and/or giving them pointers back to their referencing
13807      bpstat's, and teaching delete_breakpoint to only free a bp's
13808      storage when no more references were extent.  A cheaper bandaid
13809      was chosen.  */
13810   if (bpt->type == bp_none)
13811     return;
13812
13813   /* At least avoid this stale reference until the reference counting
13814      of breakpoints gets resolved.  */
13815   if (bpt->related_breakpoint != bpt)
13816     {
13817       struct breakpoint *related;
13818       struct watchpoint *w;
13819
13820       if (bpt->type == bp_watchpoint_scope)
13821         w = (struct watchpoint *) bpt->related_breakpoint;
13822       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13823         w = (struct watchpoint *) bpt;
13824       else
13825         w = NULL;
13826       if (w != NULL)
13827         watchpoint_del_at_next_stop (w);
13828
13829       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13830       for (related = bpt; related->related_breakpoint != bpt;
13831            related = related->related_breakpoint);
13832       related->related_breakpoint = bpt->related_breakpoint;
13833       bpt->related_breakpoint = bpt;
13834     }
13835
13836   /* watch_command_1 creates a watchpoint but only sets its number if
13837      update_watchpoint succeeds in creating its bp_locations.  If there's
13838      a problem in that process, we'll be asked to delete the half-created
13839      watchpoint.  In that case, don't announce the deletion.  */
13840   if (bpt->number)
13841     observer_notify_breakpoint_deleted (bpt);
13842
13843   if (breakpoint_chain == bpt)
13844     breakpoint_chain = bpt->next;
13845
13846   ALL_BREAKPOINTS (b)
13847     if (b->next == bpt)
13848     {
13849       b->next = bpt->next;
13850       break;
13851     }
13852
13853   /* Be sure no bpstat's are pointing at the breakpoint after it's
13854      been freed.  */
13855   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13856      in all threads for now.  Note that we cannot just remove bpstats
13857      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13858      commands are associated with the bpstat; if we remove it here,
13859      then the later call to bpstat_do_actions (&stop_bpstat); in
13860      event-top.c won't do anything, and temporary breakpoints with
13861      commands won't work.  */
13862
13863   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13864
13865   /* Now that breakpoint is removed from breakpoint list, update the
13866      global location list.  This will remove locations that used to
13867      belong to this breakpoint.  Do this before freeing the breakpoint
13868      itself, since remove_breakpoint looks at location's owner.  It
13869      might be better design to have location completely
13870      self-contained, but it's not the case now.  */
13871   update_global_location_list (UGLL_DONT_INSERT);
13872
13873   bpt->ops->dtor (bpt);
13874   /* On the chance that someone will soon try again to delete this
13875      same bp, we mark it as deleted before freeing its storage.  */
13876   bpt->type = bp_none;
13877   delete bpt;
13878 }
13879
13880 static void
13881 do_delete_breakpoint_cleanup (void *b)
13882 {
13883   delete_breakpoint ((struct breakpoint *) b);
13884 }
13885
13886 struct cleanup *
13887 make_cleanup_delete_breakpoint (struct breakpoint *b)
13888 {
13889   return make_cleanup (do_delete_breakpoint_cleanup, b);
13890 }
13891
13892 /* Iterator function to call a user-provided callback function once
13893    for each of B and its related breakpoints.  */
13894
13895 static void
13896 iterate_over_related_breakpoints (struct breakpoint *b,
13897                                   void (*function) (struct breakpoint *,
13898                                                     void *),
13899                                   void *data)
13900 {
13901   struct breakpoint *related;
13902
13903   related = b;
13904   do
13905     {
13906       struct breakpoint *next;
13907
13908       /* FUNCTION may delete RELATED.  */
13909       next = related->related_breakpoint;
13910
13911       if (next == related)
13912         {
13913           /* RELATED is the last ring entry.  */
13914           function (related, data);
13915
13916           /* FUNCTION may have deleted it, so we'd never reach back to
13917              B.  There's nothing left to do anyway, so just break
13918              out.  */
13919           break;
13920         }
13921       else
13922         function (related, data);
13923
13924       related = next;
13925     }
13926   while (related != b);
13927 }
13928
13929 static void
13930 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13931 {
13932   delete_breakpoint (b);
13933 }
13934
13935 /* A callback for map_breakpoint_numbers that calls
13936    delete_breakpoint.  */
13937
13938 static void
13939 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13940 {
13941   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13942 }
13943
13944 void
13945 delete_command (char *arg, int from_tty)
13946 {
13947   struct breakpoint *b, *b_tmp;
13948
13949   dont_repeat ();
13950
13951   if (arg == 0)
13952     {
13953       int breaks_to_delete = 0;
13954
13955       /* Delete all breakpoints if no argument.  Do not delete
13956          internal breakpoints, these have to be deleted with an
13957          explicit breakpoint number argument.  */
13958       ALL_BREAKPOINTS (b)
13959         if (user_breakpoint_p (b))
13960           {
13961             breaks_to_delete = 1;
13962             break;
13963           }
13964
13965       /* Ask user only if there are some breakpoints to delete.  */
13966       if (!from_tty
13967           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13968         {
13969           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13970             if (user_breakpoint_p (b))
13971               delete_breakpoint (b);
13972         }
13973     }
13974   else
13975     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13976 }
13977
13978 /* Return true if all locations of B bound to PSPACE are pending.  If
13979    PSPACE is NULL, all locations of all program spaces are
13980    considered.  */
13981
13982 static int
13983 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13984 {
13985   struct bp_location *loc;
13986
13987   for (loc = b->loc; loc != NULL; loc = loc->next)
13988     if ((pspace == NULL
13989          || loc->pspace == pspace)
13990         && !loc->shlib_disabled
13991         && !loc->pspace->executing_startup)
13992       return 0;
13993   return 1;
13994 }
13995
13996 /* Subroutine of update_breakpoint_locations to simplify it.
13997    Return non-zero if multiple fns in list LOC have the same name.
13998    Null names are ignored.  */
13999
14000 static int
14001 ambiguous_names_p (struct bp_location *loc)
14002 {
14003   struct bp_location *l;
14004   htab_t htab = htab_create_alloc (13, htab_hash_string,
14005                                    (int (*) (const void *, 
14006                                              const void *)) streq,
14007                                    NULL, xcalloc, xfree);
14008
14009   for (l = loc; l != NULL; l = l->next)
14010     {
14011       const char **slot;
14012       const char *name = l->function_name;
14013
14014       /* Allow for some names to be NULL, ignore them.  */
14015       if (name == NULL)
14016         continue;
14017
14018       slot = (const char **) htab_find_slot (htab, (const void *) name,
14019                                              INSERT);
14020       /* NOTE: We can assume slot != NULL here because xcalloc never
14021          returns NULL.  */
14022       if (*slot != NULL)
14023         {
14024           htab_delete (htab);
14025           return 1;
14026         }
14027       *slot = name;
14028     }
14029
14030   htab_delete (htab);
14031   return 0;
14032 }
14033
14034 /* When symbols change, it probably means the sources changed as well,
14035    and it might mean the static tracepoint markers are no longer at
14036    the same address or line numbers they used to be at last we
14037    checked.  Losing your static tracepoints whenever you rebuild is
14038    undesirable.  This function tries to resync/rematch gdb static
14039    tracepoints with the markers on the target, for static tracepoints
14040    that have not been set by marker id.  Static tracepoint that have
14041    been set by marker id are reset by marker id in breakpoint_re_set.
14042    The heuristic is:
14043
14044    1) For a tracepoint set at a specific address, look for a marker at
14045    the old PC.  If one is found there, assume to be the same marker.
14046    If the name / string id of the marker found is different from the
14047    previous known name, assume that means the user renamed the marker
14048    in the sources, and output a warning.
14049
14050    2) For a tracepoint set at a given line number, look for a marker
14051    at the new address of the old line number.  If one is found there,
14052    assume to be the same marker.  If the name / string id of the
14053    marker found is different from the previous known name, assume that
14054    means the user renamed the marker in the sources, and output a
14055    warning.
14056
14057    3) If a marker is no longer found at the same address or line, it
14058    may mean the marker no longer exists.  But it may also just mean
14059    the code changed a bit.  Maybe the user added a few lines of code
14060    that made the marker move up or down (in line number terms).  Ask
14061    the target for info about the marker with the string id as we knew
14062    it.  If found, update line number and address in the matching
14063    static tracepoint.  This will get confused if there's more than one
14064    marker with the same ID (possible in UST, although unadvised
14065    precisely because it confuses tools).  */
14066
14067 static struct symtab_and_line
14068 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14069 {
14070   struct tracepoint *tp = (struct tracepoint *) b;
14071   struct static_tracepoint_marker marker;
14072   CORE_ADDR pc;
14073
14074   pc = sal.pc;
14075   if (sal.line)
14076     find_line_pc (sal.symtab, sal.line, &pc);
14077
14078   if (target_static_tracepoint_marker_at (pc, &marker))
14079     {
14080       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14081         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14082                  b->number,
14083                  tp->static_trace_marker_id, marker.str_id);
14084
14085       xfree (tp->static_trace_marker_id);
14086       tp->static_trace_marker_id = xstrdup (marker.str_id);
14087       release_static_tracepoint_marker (&marker);
14088
14089       return sal;
14090     }
14091
14092   /* Old marker wasn't found on target at lineno.  Try looking it up
14093      by string ID.  */
14094   if (!sal.explicit_pc
14095       && sal.line != 0
14096       && sal.symtab != NULL
14097       && tp->static_trace_marker_id != NULL)
14098     {
14099       VEC(static_tracepoint_marker_p) *markers;
14100
14101       markers
14102         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14103
14104       if (!VEC_empty(static_tracepoint_marker_p, markers))
14105         {
14106           struct symtab_and_line sal2;
14107           struct symbol *sym;
14108           struct static_tracepoint_marker *tpmarker;
14109           struct ui_out *uiout = current_uiout;
14110           struct explicit_location explicit_loc;
14111
14112           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14113
14114           xfree (tp->static_trace_marker_id);
14115           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14116
14117           warning (_("marker for static tracepoint %d (%s) not "
14118                      "found at previous line number"),
14119                    b->number, tp->static_trace_marker_id);
14120
14121           init_sal (&sal2);
14122
14123           sal2.pc = tpmarker->address;
14124
14125           sal2 = find_pc_line (tpmarker->address, 0);
14126           sym = find_pc_sect_function (tpmarker->address, NULL);
14127           uiout->text ("Now in ");
14128           if (sym)
14129             {
14130               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
14131               uiout->text (" at ");
14132             }
14133           uiout->field_string ("file",
14134                                symtab_to_filename_for_display (sal2.symtab));
14135           uiout->text (":");
14136
14137           if (uiout->is_mi_like_p ())
14138             {
14139               const char *fullname = symtab_to_fullname (sal2.symtab);
14140
14141               uiout->field_string ("fullname", fullname);
14142             }
14143
14144           uiout->field_int ("line", sal2.line);
14145           uiout->text ("\n");
14146
14147           b->loc->line_number = sal2.line;
14148           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14149
14150           delete_event_location (b->location);
14151           initialize_explicit_location (&explicit_loc);
14152           explicit_loc.source_filename
14153             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
14154           explicit_loc.line_offset.offset = b->loc->line_number;
14155           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
14156           b->location = new_explicit_location (&explicit_loc);
14157
14158           /* Might be nice to check if function changed, and warn if
14159              so.  */
14160
14161           release_static_tracepoint_marker (tpmarker);
14162         }
14163     }
14164   return sal;
14165 }
14166
14167 /* Returns 1 iff locations A and B are sufficiently same that
14168    we don't need to report breakpoint as changed.  */
14169
14170 static int
14171 locations_are_equal (struct bp_location *a, struct bp_location *b)
14172 {
14173   while (a && b)
14174     {
14175       if (a->address != b->address)
14176         return 0;
14177
14178       if (a->shlib_disabled != b->shlib_disabled)
14179         return 0;
14180
14181       if (a->enabled != b->enabled)
14182         return 0;
14183
14184       a = a->next;
14185       b = b->next;
14186     }
14187
14188   if ((a == NULL) != (b == NULL))
14189     return 0;
14190
14191   return 1;
14192 }
14193
14194 /* Split all locations of B that are bound to PSPACE out of B's
14195    location list to a separate list and return that list's head.  If
14196    PSPACE is NULL, hoist out all locations of B.  */
14197
14198 static struct bp_location *
14199 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
14200 {
14201   struct bp_location head;
14202   struct bp_location *i = b->loc;
14203   struct bp_location **i_link = &b->loc;
14204   struct bp_location *hoisted = &head;
14205
14206   if (pspace == NULL)
14207     {
14208       i = b->loc;
14209       b->loc = NULL;
14210       return i;
14211     }
14212
14213   head.next = NULL;
14214
14215   while (i != NULL)
14216     {
14217       if (i->pspace == pspace)
14218         {
14219           *i_link = i->next;
14220           i->next = NULL;
14221           hoisted->next = i;
14222           hoisted = i;
14223         }
14224       else
14225         i_link = &i->next;
14226       i = *i_link;
14227     }
14228
14229   return head.next;
14230 }
14231
14232 /* Create new breakpoint locations for B (a hardware or software
14233    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
14234    zero, then B is a ranged breakpoint.  Only recreates locations for
14235    FILTER_PSPACE.  Locations of other program spaces are left
14236    untouched.  */
14237
14238 void
14239 update_breakpoint_locations (struct breakpoint *b,
14240                              struct program_space *filter_pspace,
14241                              struct symtabs_and_lines sals,
14242                              struct symtabs_and_lines sals_end)
14243 {
14244   int i;
14245   struct bp_location *existing_locations;
14246
14247   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14248     {
14249       /* Ranged breakpoints have only one start location and one end
14250          location.  */
14251       b->enable_state = bp_disabled;
14252       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14253                            "multiple locations found\n"),
14254                          b->number);
14255       return;
14256     }
14257
14258   /* If there's no new locations, and all existing locations are
14259      pending, don't do anything.  This optimizes the common case where
14260      all locations are in the same shared library, that was unloaded.
14261      We'd like to retain the location, so that when the library is
14262      loaded again, we don't loose the enabled/disabled status of the
14263      individual locations.  */
14264   if (all_locations_are_pending (b, filter_pspace) && sals.nelts == 0)
14265     return;
14266
14267   existing_locations = hoist_existing_locations (b, filter_pspace);
14268
14269   for (i = 0; i < sals.nelts; ++i)
14270     {
14271       struct bp_location *new_loc;
14272
14273       switch_to_program_space_and_thread (sals.sals[i].pspace);
14274
14275       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14276
14277       /* Reparse conditions, they might contain references to the
14278          old symtab.  */
14279       if (b->cond_string != NULL)
14280         {
14281           const char *s;
14282
14283           s = b->cond_string;
14284           TRY
14285             {
14286               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14287                                            block_for_pc (sals.sals[i].pc), 
14288                                            0);
14289             }
14290           CATCH (e, RETURN_MASK_ERROR)
14291             {
14292               warning (_("failed to reevaluate condition "
14293                          "for breakpoint %d: %s"), 
14294                        b->number, e.message);
14295               new_loc->enabled = 0;
14296             }
14297           END_CATCH
14298         }
14299
14300       if (sals_end.nelts)
14301         {
14302           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14303
14304           new_loc->length = end - sals.sals[0].pc + 1;
14305         }
14306     }
14307
14308   /* If possible, carry over 'disable' status from existing
14309      breakpoints.  */
14310   {
14311     struct bp_location *e = existing_locations;
14312     /* If there are multiple breakpoints with the same function name,
14313        e.g. for inline functions, comparing function names won't work.
14314        Instead compare pc addresses; this is just a heuristic as things
14315        may have moved, but in practice it gives the correct answer
14316        often enough until a better solution is found.  */
14317     int have_ambiguous_names = ambiguous_names_p (b->loc);
14318
14319     for (; e; e = e->next)
14320       {
14321         if (!e->enabled && e->function_name)
14322           {
14323             struct bp_location *l = b->loc;
14324             if (have_ambiguous_names)
14325               {
14326                 for (; l; l = l->next)
14327                   if (breakpoint_locations_match (e, l))
14328                     {
14329                       l->enabled = 0;
14330                       break;
14331                     }
14332               }
14333             else
14334               {
14335                 for (; l; l = l->next)
14336                   if (l->function_name
14337                       && strcmp (e->function_name, l->function_name) == 0)
14338                     {
14339                       l->enabled = 0;
14340                       break;
14341                     }
14342               }
14343           }
14344       }
14345   }
14346
14347   if (!locations_are_equal (existing_locations, b->loc))
14348     observer_notify_breakpoint_modified (b);
14349 }
14350
14351 /* Find the SaL locations corresponding to the given LOCATION.
14352    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14353
14354 static struct symtabs_and_lines
14355 location_to_sals (struct breakpoint *b, struct event_location *location,
14356                   struct program_space *search_pspace, int *found)
14357 {
14358   struct symtabs_and_lines sals = {0};
14359   struct gdb_exception exception = exception_none;
14360
14361   gdb_assert (b->ops != NULL);
14362
14363   TRY
14364     {
14365       b->ops->decode_location (b, location, search_pspace, &sals);
14366     }
14367   CATCH (e, RETURN_MASK_ERROR)
14368     {
14369       int not_found_and_ok = 0;
14370
14371       exception = e;
14372
14373       /* For pending breakpoints, it's expected that parsing will
14374          fail until the right shared library is loaded.  User has
14375          already told to create pending breakpoints and don't need
14376          extra messages.  If breakpoint is in bp_shlib_disabled
14377          state, then user already saw the message about that
14378          breakpoint being disabled, and don't want to see more
14379          errors.  */
14380       if (e.error == NOT_FOUND_ERROR
14381           && (b->condition_not_parsed
14382               || (b->loc != NULL
14383                   && search_pspace != NULL
14384                   && b->loc->pspace != search_pspace)
14385               || (b->loc && b->loc->shlib_disabled)
14386               || (b->loc && b->loc->pspace->executing_startup)
14387               || b->enable_state == bp_disabled))
14388         not_found_and_ok = 1;
14389
14390       if (!not_found_and_ok)
14391         {
14392           /* We surely don't want to warn about the same breakpoint
14393              10 times.  One solution, implemented here, is disable
14394              the breakpoint on error.  Another solution would be to
14395              have separate 'warning emitted' flag.  Since this
14396              happens only when a binary has changed, I don't know
14397              which approach is better.  */
14398           b->enable_state = bp_disabled;
14399           throw_exception (e);
14400         }
14401     }
14402   END_CATCH
14403
14404   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14405     {
14406       int i;
14407
14408       for (i = 0; i < sals.nelts; ++i)
14409         resolve_sal_pc (&sals.sals[i]);
14410       if (b->condition_not_parsed && b->extra_string != NULL)
14411         {
14412           char *cond_string, *extra_string;
14413           int thread, task;
14414
14415           find_condition_and_thread (b->extra_string, sals.sals[0].pc,
14416                                      &cond_string, &thread, &task,
14417                                      &extra_string);
14418           gdb_assert (b->cond_string == NULL);
14419           if (cond_string)
14420             b->cond_string = cond_string;
14421           b->thread = thread;
14422           b->task = task;
14423           if (extra_string)
14424             {
14425               xfree (b->extra_string);
14426               b->extra_string = extra_string;
14427             }
14428           b->condition_not_parsed = 0;
14429         }
14430
14431       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14432         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14433
14434       *found = 1;
14435     }
14436   else
14437     *found = 0;
14438
14439   return sals;
14440 }
14441
14442 /* The default re_set method, for typical hardware or software
14443    breakpoints.  Reevaluate the breakpoint and recreate its
14444    locations.  */
14445
14446 static void
14447 breakpoint_re_set_default (struct breakpoint *b)
14448 {
14449   int found;
14450   struct symtabs_and_lines sals, sals_end;
14451   struct symtabs_and_lines expanded = {0};
14452   struct symtabs_and_lines expanded_end = {0};
14453   struct program_space *filter_pspace = current_program_space;
14454
14455   sals = location_to_sals (b, b->location, filter_pspace, &found);
14456   if (found)
14457     {
14458       make_cleanup (xfree, sals.sals);
14459       expanded = sals;
14460     }
14461
14462   if (b->location_range_end != NULL)
14463     {
14464       sals_end = location_to_sals (b, b->location_range_end,
14465                                    filter_pspace, &found);
14466       if (found)
14467         {
14468           make_cleanup (xfree, sals_end.sals);
14469           expanded_end = sals_end;
14470         }
14471     }
14472
14473   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14474 }
14475
14476 /* Default method for creating SALs from an address string.  It basically
14477    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14478
14479 static void
14480 create_sals_from_location_default (const struct event_location *location,
14481                                    struct linespec_result *canonical,
14482                                    enum bptype type_wanted)
14483 {
14484   parse_breakpoint_sals (location, canonical);
14485 }
14486
14487 /* Call create_breakpoints_sal for the given arguments.  This is the default
14488    function for the `create_breakpoints_sal' method of
14489    breakpoint_ops.  */
14490
14491 static void
14492 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14493                                 struct linespec_result *canonical,
14494                                 char *cond_string,
14495                                 char *extra_string,
14496                                 enum bptype type_wanted,
14497                                 enum bpdisp disposition,
14498                                 int thread,
14499                                 int task, int ignore_count,
14500                                 const struct breakpoint_ops *ops,
14501                                 int from_tty, int enabled,
14502                                 int internal, unsigned flags)
14503 {
14504   create_breakpoints_sal (gdbarch, canonical, cond_string,
14505                           extra_string,
14506                           type_wanted, disposition,
14507                           thread, task, ignore_count, ops, from_tty,
14508                           enabled, internal, flags);
14509 }
14510
14511 /* Decode the line represented by S by calling decode_line_full.  This is the
14512    default function for the `decode_location' method of breakpoint_ops.  */
14513
14514 static void
14515 decode_location_default (struct breakpoint *b,
14516                          const struct event_location *location,
14517                          struct program_space *search_pspace,
14518                          struct symtabs_and_lines *sals)
14519 {
14520   struct linespec_result canonical;
14521
14522   init_linespec_result (&canonical);
14523   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14524                     (struct symtab *) NULL, 0,
14525                     &canonical, multiple_symbols_all,
14526                     b->filter);
14527
14528   /* We should get 0 or 1 resulting SALs.  */
14529   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14530
14531   if (VEC_length (linespec_sals, canonical.sals) > 0)
14532     {
14533       struct linespec_sals *lsal;
14534
14535       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14536       *sals = lsal->sals;
14537       /* Arrange it so the destructor does not free the
14538          contents.  */
14539       lsal->sals.sals = NULL;
14540     }
14541
14542   destroy_linespec_result (&canonical);
14543 }
14544
14545 /* Prepare the global context for a re-set of breakpoint B.  */
14546
14547 static struct cleanup *
14548 prepare_re_set_context (struct breakpoint *b)
14549 {
14550   input_radix = b->input_radix;
14551   set_language (b->language);
14552
14553   return make_cleanup (null_cleanup, NULL);
14554 }
14555
14556 /* Reset a breakpoint given it's struct breakpoint * BINT.
14557    The value we return ends up being the return value from catch_errors.
14558    Unused in this case.  */
14559
14560 static int
14561 breakpoint_re_set_one (void *bint)
14562 {
14563   /* Get past catch_errs.  */
14564   struct breakpoint *b = (struct breakpoint *) bint;
14565   struct cleanup *cleanups;
14566
14567   cleanups = prepare_re_set_context (b);
14568   b->ops->re_set (b);
14569   do_cleanups (cleanups);
14570   return 0;
14571 }
14572
14573 /* Re-set breakpoint locations for the current program space.
14574    Locations bound to other program spaces are left untouched.  */
14575
14576 void
14577 breakpoint_re_set (void)
14578 {
14579   struct breakpoint *b, *b_tmp;
14580   enum language save_language;
14581   int save_input_radix;
14582   struct cleanup *old_chain;
14583
14584   save_language = current_language->la_language;
14585   save_input_radix = input_radix;
14586   old_chain = save_current_space_and_thread ();
14587
14588   /* Note: we must not try to insert locations until after all
14589      breakpoints have been re-set.  Otherwise, e.g., when re-setting
14590      breakpoint 1, we'd insert the locations of breakpoint 2, which
14591      hadn't been re-set yet, and thus may have stale locations.  */
14592
14593   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14594   {
14595     /* Format possible error msg.  */
14596     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14597                                 b->number);
14598     struct cleanup *cleanups = make_cleanup (xfree, message);
14599     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14600     do_cleanups (cleanups);
14601   }
14602   set_language (save_language);
14603   input_radix = save_input_radix;
14604
14605   jit_breakpoint_re_set ();
14606
14607   do_cleanups (old_chain);
14608
14609   create_overlay_event_breakpoint ();
14610   create_longjmp_master_breakpoint ();
14611   create_std_terminate_master_breakpoint ();
14612   create_exception_master_breakpoint ();
14613
14614   /* Now we can insert.  */
14615   update_global_location_list (UGLL_MAY_INSERT);
14616 }
14617 \f
14618 /* Reset the thread number of this breakpoint:
14619
14620    - If the breakpoint is for all threads, leave it as-is.
14621    - Else, reset it to the current thread for inferior_ptid.  */
14622 void
14623 breakpoint_re_set_thread (struct breakpoint *b)
14624 {
14625   if (b->thread != -1)
14626     {
14627       if (in_thread_list (inferior_ptid))
14628         b->thread = ptid_to_global_thread_id (inferior_ptid);
14629
14630       /* We're being called after following a fork.  The new fork is
14631          selected as current, and unless this was a vfork will have a
14632          different program space from the original thread.  Reset that
14633          as well.  */
14634       b->loc->pspace = current_program_space;
14635     }
14636 }
14637
14638 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14639    If from_tty is nonzero, it prints a message to that effect,
14640    which ends with a period (no newline).  */
14641
14642 void
14643 set_ignore_count (int bptnum, int count, int from_tty)
14644 {
14645   struct breakpoint *b;
14646
14647   if (count < 0)
14648     count = 0;
14649
14650   ALL_BREAKPOINTS (b)
14651     if (b->number == bptnum)
14652     {
14653       if (is_tracepoint (b))
14654         {
14655           if (from_tty && count != 0)
14656             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14657                              bptnum);
14658           return;
14659         }
14660       
14661       b->ignore_count = count;
14662       if (from_tty)
14663         {
14664           if (count == 0)
14665             printf_filtered (_("Will stop next time "
14666                                "breakpoint %d is reached."),
14667                              bptnum);
14668           else if (count == 1)
14669             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14670                              bptnum);
14671           else
14672             printf_filtered (_("Will ignore next %d "
14673                                "crossings of breakpoint %d."),
14674                              count, bptnum);
14675         }
14676       observer_notify_breakpoint_modified (b);
14677       return;
14678     }
14679
14680   error (_("No breakpoint number %d."), bptnum);
14681 }
14682
14683 /* Command to set ignore-count of breakpoint N to COUNT.  */
14684
14685 static void
14686 ignore_command (char *args, int from_tty)
14687 {
14688   char *p = args;
14689   int num;
14690
14691   if (p == 0)
14692     error_no_arg (_("a breakpoint number"));
14693
14694   num = get_number (&p);
14695   if (num == 0)
14696     error (_("bad breakpoint number: '%s'"), args);
14697   if (*p == 0)
14698     error (_("Second argument (specified ignore-count) is missing."));
14699
14700   set_ignore_count (num,
14701                     longest_to_int (value_as_long (parse_and_eval (p))),
14702                     from_tty);
14703   if (from_tty)
14704     printf_filtered ("\n");
14705 }
14706 \f
14707 /* Call FUNCTION on each of the breakpoints
14708    whose numbers are given in ARGS.  */
14709
14710 static void
14711 map_breakpoint_numbers (const char *args,
14712                         void (*function) (struct breakpoint *,
14713                                           void *),
14714                         void *data)
14715 {
14716   int num;
14717   struct breakpoint *b, *tmp;
14718
14719   if (args == 0 || *args == '\0')
14720     error_no_arg (_("one or more breakpoint numbers"));
14721
14722   number_or_range_parser parser (args);
14723
14724   while (!parser.finished ())
14725     {
14726       const char *p = parser.cur_tok ();
14727       bool match = false;
14728
14729       num = parser.get_number ();
14730       if (num == 0)
14731         {
14732           warning (_("bad breakpoint number at or near '%s'"), p);
14733         }
14734       else
14735         {
14736           ALL_BREAKPOINTS_SAFE (b, tmp)
14737             if (b->number == num)
14738               {
14739                 match = true;
14740                 function (b, data);
14741                 break;
14742               }
14743           if (!match)
14744             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14745         }
14746     }
14747 }
14748
14749 static struct bp_location *
14750 find_location_by_number (char *number)
14751 {
14752   char *dot = strchr (number, '.');
14753   char *p1;
14754   int bp_num;
14755   int loc_num;
14756   struct breakpoint *b;
14757   struct bp_location *loc;  
14758
14759   *dot = '\0';
14760
14761   p1 = number;
14762   bp_num = get_number (&p1);
14763   if (bp_num == 0)
14764     error (_("Bad breakpoint number '%s'"), number);
14765
14766   ALL_BREAKPOINTS (b)
14767     if (b->number == bp_num)
14768       {
14769         break;
14770       }
14771
14772   if (!b || b->number != bp_num)
14773     error (_("Bad breakpoint number '%s'"), number);
14774   
14775   p1 = dot+1;
14776   loc_num = get_number (&p1);
14777   if (loc_num == 0)
14778     error (_("Bad breakpoint location number '%s'"), number);
14779
14780   --loc_num;
14781   loc = b->loc;
14782   for (;loc_num && loc; --loc_num, loc = loc->next)
14783     ;
14784   if (!loc)
14785     error (_("Bad breakpoint location number '%s'"), dot+1);
14786     
14787   return loc;  
14788 }
14789
14790
14791 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14792    If from_tty is nonzero, it prints a message to that effect,
14793    which ends with a period (no newline).  */
14794
14795 void
14796 disable_breakpoint (struct breakpoint *bpt)
14797 {
14798   /* Never disable a watchpoint scope breakpoint; we want to
14799      hit them when we leave scope so we can delete both the
14800      watchpoint and its scope breakpoint at that time.  */
14801   if (bpt->type == bp_watchpoint_scope)
14802     return;
14803
14804   bpt->enable_state = bp_disabled;
14805
14806   /* Mark breakpoint locations modified.  */
14807   mark_breakpoint_modified (bpt);
14808
14809   if (target_supports_enable_disable_tracepoint ()
14810       && current_trace_status ()->running && is_tracepoint (bpt))
14811     {
14812       struct bp_location *location;
14813      
14814       for (location = bpt->loc; location; location = location->next)
14815         target_disable_tracepoint (location);
14816     }
14817
14818   update_global_location_list (UGLL_DONT_INSERT);
14819
14820   observer_notify_breakpoint_modified (bpt);
14821 }
14822
14823 /* A callback for iterate_over_related_breakpoints.  */
14824
14825 static void
14826 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14827 {
14828   disable_breakpoint (b);
14829 }
14830
14831 /* A callback for map_breakpoint_numbers that calls
14832    disable_breakpoint.  */
14833
14834 static void
14835 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14836 {
14837   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14838 }
14839
14840 static void
14841 disable_command (char *args, int from_tty)
14842 {
14843   if (args == 0)
14844     {
14845       struct breakpoint *bpt;
14846
14847       ALL_BREAKPOINTS (bpt)
14848         if (user_breakpoint_p (bpt))
14849           disable_breakpoint (bpt);
14850     }
14851   else
14852     {
14853       char *num = extract_arg (&args);
14854
14855       while (num)
14856         {
14857           if (strchr (num, '.'))
14858             {
14859               struct bp_location *loc = find_location_by_number (num);
14860
14861               if (loc)
14862                 {
14863                   if (loc->enabled)
14864                     {
14865                       loc->enabled = 0;
14866                       mark_breakpoint_location_modified (loc);
14867                     }
14868                   if (target_supports_enable_disable_tracepoint ()
14869                       && current_trace_status ()->running && loc->owner
14870                       && is_tracepoint (loc->owner))
14871                     target_disable_tracepoint (loc);
14872                 }
14873               update_global_location_list (UGLL_DONT_INSERT);
14874             }
14875           else
14876             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14877           num = extract_arg (&args);
14878         }
14879     }
14880 }
14881
14882 static void
14883 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14884                         int count)
14885 {
14886   int target_resources_ok;
14887
14888   if (bpt->type == bp_hardware_breakpoint)
14889     {
14890       int i;
14891       i = hw_breakpoint_used_count ();
14892       target_resources_ok = 
14893         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14894                                             i + 1, 0);
14895       if (target_resources_ok == 0)
14896         error (_("No hardware breakpoint support in the target."));
14897       else if (target_resources_ok < 0)
14898         error (_("Hardware breakpoints used exceeds limit."));
14899     }
14900
14901   if (is_watchpoint (bpt))
14902     {
14903       /* Initialize it just to avoid a GCC false warning.  */
14904       enum enable_state orig_enable_state = bp_disabled;
14905
14906       TRY
14907         {
14908           struct watchpoint *w = (struct watchpoint *) bpt;
14909
14910           orig_enable_state = bpt->enable_state;
14911           bpt->enable_state = bp_enabled;
14912           update_watchpoint (w, 1 /* reparse */);
14913         }
14914       CATCH (e, RETURN_MASK_ALL)
14915         {
14916           bpt->enable_state = orig_enable_state;
14917           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14918                              bpt->number);
14919           return;
14920         }
14921       END_CATCH
14922     }
14923
14924   bpt->enable_state = bp_enabled;
14925
14926   /* Mark breakpoint locations modified.  */
14927   mark_breakpoint_modified (bpt);
14928
14929   if (target_supports_enable_disable_tracepoint ()
14930       && current_trace_status ()->running && is_tracepoint (bpt))
14931     {
14932       struct bp_location *location;
14933
14934       for (location = bpt->loc; location; location = location->next)
14935         target_enable_tracepoint (location);
14936     }
14937
14938   bpt->disposition = disposition;
14939   bpt->enable_count = count;
14940   update_global_location_list (UGLL_MAY_INSERT);
14941
14942   observer_notify_breakpoint_modified (bpt);
14943 }
14944
14945
14946 void
14947 enable_breakpoint (struct breakpoint *bpt)
14948 {
14949   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14950 }
14951
14952 static void
14953 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14954 {
14955   enable_breakpoint (bpt);
14956 }
14957
14958 /* A callback for map_breakpoint_numbers that calls
14959    enable_breakpoint.  */
14960
14961 static void
14962 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14963 {
14964   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14965 }
14966
14967 /* The enable command enables the specified breakpoints (or all defined
14968    breakpoints) so they once again become (or continue to be) effective
14969    in stopping the inferior.  */
14970
14971 static void
14972 enable_command (char *args, int from_tty)
14973 {
14974   if (args == 0)
14975     {
14976       struct breakpoint *bpt;
14977
14978       ALL_BREAKPOINTS (bpt)
14979         if (user_breakpoint_p (bpt))
14980           enable_breakpoint (bpt);
14981     }
14982   else
14983     {
14984       char *num = extract_arg (&args);
14985
14986       while (num)
14987         {
14988           if (strchr (num, '.'))
14989             {
14990               struct bp_location *loc = find_location_by_number (num);
14991
14992               if (loc)
14993                 {
14994                   if (!loc->enabled)
14995                     {
14996                       loc->enabled = 1;
14997                       mark_breakpoint_location_modified (loc);
14998                     }
14999                   if (target_supports_enable_disable_tracepoint ()
15000                       && current_trace_status ()->running && loc->owner
15001                       && is_tracepoint (loc->owner))
15002                     target_enable_tracepoint (loc);
15003                 }
15004               update_global_location_list (UGLL_MAY_INSERT);
15005             }
15006           else
15007             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15008           num = extract_arg (&args);
15009         }
15010     }
15011 }
15012
15013 /* This struct packages up disposition data for application to multiple
15014    breakpoints.  */
15015
15016 struct disp_data
15017 {
15018   enum bpdisp disp;
15019   int count;
15020 };
15021
15022 static void
15023 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15024 {
15025   struct disp_data disp_data = *(struct disp_data *) arg;
15026
15027   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15028 }
15029
15030 static void
15031 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15032 {
15033   struct disp_data disp = { disp_disable, 1 };
15034
15035   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15036 }
15037
15038 static void
15039 enable_once_command (char *args, int from_tty)
15040 {
15041   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15042 }
15043
15044 static void
15045 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15046 {
15047   struct disp_data disp = { disp_disable, *(int *) countptr };
15048
15049   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15050 }
15051
15052 static void
15053 enable_count_command (char *args, int from_tty)
15054 {
15055   int count;
15056
15057   if (args == NULL)
15058     error_no_arg (_("hit count"));
15059
15060   count = get_number (&args);
15061
15062   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15063 }
15064
15065 static void
15066 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15067 {
15068   struct disp_data disp = { disp_del, 1 };
15069
15070   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15071 }
15072
15073 static void
15074 enable_delete_command (char *args, int from_tty)
15075 {
15076   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15077 }
15078 \f
15079 static void
15080 set_breakpoint_cmd (char *args, int from_tty)
15081 {
15082 }
15083
15084 static void
15085 show_breakpoint_cmd (char *args, int from_tty)
15086 {
15087 }
15088
15089 /* Invalidate last known value of any hardware watchpoint if
15090    the memory which that value represents has been written to by
15091    GDB itself.  */
15092
15093 static void
15094 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15095                                       CORE_ADDR addr, ssize_t len,
15096                                       const bfd_byte *data)
15097 {
15098   struct breakpoint *bp;
15099
15100   ALL_BREAKPOINTS (bp)
15101     if (bp->enable_state == bp_enabled
15102         && bp->type == bp_hardware_watchpoint)
15103       {
15104         struct watchpoint *wp = (struct watchpoint *) bp;
15105
15106         if (wp->val_valid && wp->val)
15107           {
15108             struct bp_location *loc;
15109
15110             for (loc = bp->loc; loc != NULL; loc = loc->next)
15111               if (loc->loc_type == bp_loc_hardware_watchpoint
15112                   && loc->address + loc->length > addr
15113                   && addr + len > loc->address)
15114                 {
15115                   value_free (wp->val);
15116                   wp->val = NULL;
15117                   wp->val_valid = 0;
15118                 }
15119           }
15120       }
15121 }
15122
15123 /* Create and insert a breakpoint for software single step.  */
15124
15125 void
15126 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15127                                struct address_space *aspace, 
15128                                CORE_ADDR next_pc)
15129 {
15130   struct thread_info *tp = inferior_thread ();
15131   struct symtab_and_line sal;
15132   CORE_ADDR pc = next_pc;
15133
15134   if (tp->control.single_step_breakpoints == NULL)
15135     {
15136       tp->control.single_step_breakpoints
15137         = new_single_step_breakpoint (tp->global_num, gdbarch);
15138     }
15139
15140   sal = find_pc_line (pc, 0);
15141   sal.pc = pc;
15142   sal.section = find_pc_overlay (pc);
15143   sal.explicit_pc = 1;
15144   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15145
15146   update_global_location_list (UGLL_INSERT);
15147 }
15148
15149 /* Insert single step breakpoints according to the current state.  */
15150
15151 int
15152 insert_single_step_breakpoints (struct gdbarch *gdbarch)
15153 {
15154   struct regcache *regcache = get_current_regcache ();
15155   VEC (CORE_ADDR) * next_pcs;
15156
15157   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
15158
15159   if (next_pcs != NULL)
15160     {
15161       int i;
15162       CORE_ADDR pc;
15163       struct frame_info *frame = get_current_frame ();
15164       struct address_space *aspace = get_frame_address_space (frame);
15165
15166       for (i = 0; VEC_iterate (CORE_ADDR, next_pcs, i, pc); i++)
15167         insert_single_step_breakpoint (gdbarch, aspace, pc);
15168
15169       VEC_free (CORE_ADDR, next_pcs);
15170
15171       return 1;
15172     }
15173   else
15174     return 0;
15175 }
15176
15177 /* See breakpoint.h.  */
15178
15179 int
15180 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15181                                        struct address_space *aspace,
15182                                        CORE_ADDR pc)
15183 {
15184   struct bp_location *loc;
15185
15186   for (loc = bp->loc; loc != NULL; loc = loc->next)
15187     if (loc->inserted
15188         && breakpoint_location_address_match (loc, aspace, pc))
15189       return 1;
15190
15191   return 0;
15192 }
15193
15194 /* Check whether a software single-step breakpoint is inserted at
15195    PC.  */
15196
15197 int
15198 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15199                                         CORE_ADDR pc)
15200 {
15201   struct breakpoint *bpt;
15202
15203   ALL_BREAKPOINTS (bpt)
15204     {
15205       if (bpt->type == bp_single_step
15206           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15207         return 1;
15208     }
15209   return 0;
15210 }
15211
15212 /* Tracepoint-specific operations.  */
15213
15214 /* Set tracepoint count to NUM.  */
15215 static void
15216 set_tracepoint_count (int num)
15217 {
15218   tracepoint_count = num;
15219   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15220 }
15221
15222 static void
15223 trace_command (char *arg, int from_tty)
15224 {
15225   struct breakpoint_ops *ops;
15226   struct event_location *location;
15227   struct cleanup *back_to;
15228
15229   location = string_to_event_location (&arg, current_language);
15230   back_to = make_cleanup_delete_event_location (location);
15231   if (location != NULL
15232       && event_location_type (location) == PROBE_LOCATION)
15233     ops = &tracepoint_probe_breakpoint_ops;
15234   else
15235     ops = &tracepoint_breakpoint_ops;
15236
15237   create_breakpoint (get_current_arch (),
15238                      location,
15239                      NULL, 0, arg, 1 /* parse arg */,
15240                      0 /* tempflag */,
15241                      bp_tracepoint /* type_wanted */,
15242                      0 /* Ignore count */,
15243                      pending_break_support,
15244                      ops,
15245                      from_tty,
15246                      1 /* enabled */,
15247                      0 /* internal */, 0);
15248   do_cleanups (back_to);
15249 }
15250
15251 static void
15252 ftrace_command (char *arg, int from_tty)
15253 {
15254   struct event_location *location;
15255   struct cleanup *back_to;
15256
15257   location = string_to_event_location (&arg, current_language);
15258   back_to = make_cleanup_delete_event_location (location);
15259   create_breakpoint (get_current_arch (),
15260                      location,
15261                      NULL, 0, arg, 1 /* parse arg */,
15262                      0 /* tempflag */,
15263                      bp_fast_tracepoint /* type_wanted */,
15264                      0 /* Ignore count */,
15265                      pending_break_support,
15266                      &tracepoint_breakpoint_ops,
15267                      from_tty,
15268                      1 /* enabled */,
15269                      0 /* internal */, 0);
15270   do_cleanups (back_to);
15271 }
15272
15273 /* strace command implementation.  Creates a static tracepoint.  */
15274
15275 static void
15276 strace_command (char *arg, int from_tty)
15277 {
15278   struct breakpoint_ops *ops;
15279   struct event_location *location;
15280   struct cleanup *back_to;
15281
15282   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15283      or with a normal static tracepoint.  */
15284   if (arg && startswith (arg, "-m") && isspace (arg[2]))
15285     {
15286       ops = &strace_marker_breakpoint_ops;
15287       location = new_linespec_location (&arg);
15288     }
15289   else
15290     {
15291       ops = &tracepoint_breakpoint_ops;
15292       location = string_to_event_location (&arg, current_language);
15293     }
15294
15295   back_to = make_cleanup_delete_event_location (location);
15296   create_breakpoint (get_current_arch (),
15297                      location,
15298                      NULL, 0, arg, 1 /* parse arg */,
15299                      0 /* tempflag */,
15300                      bp_static_tracepoint /* type_wanted */,
15301                      0 /* Ignore count */,
15302                      pending_break_support,
15303                      ops,
15304                      from_tty,
15305                      1 /* enabled */,
15306                      0 /* internal */, 0);
15307   do_cleanups (back_to);
15308 }
15309
15310 /* Set up a fake reader function that gets command lines from a linked
15311    list that was acquired during tracepoint uploading.  */
15312
15313 static struct uploaded_tp *this_utp;
15314 static int next_cmd;
15315
15316 static char *
15317 read_uploaded_action (void)
15318 {
15319   char *rslt;
15320
15321   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15322
15323   next_cmd++;
15324
15325   return rslt;
15326 }
15327
15328 /* Given information about a tracepoint as recorded on a target (which
15329    can be either a live system or a trace file), attempt to create an
15330    equivalent GDB tracepoint.  This is not a reliable process, since
15331    the target does not necessarily have all the information used when
15332    the tracepoint was originally defined.  */
15333   
15334 struct tracepoint *
15335 create_tracepoint_from_upload (struct uploaded_tp *utp)
15336 {
15337   char *addr_str, small_buf[100];
15338   struct tracepoint *tp;
15339   struct event_location *location;
15340   struct cleanup *cleanup;
15341
15342   if (utp->at_string)
15343     addr_str = utp->at_string;
15344   else
15345     {
15346       /* In the absence of a source location, fall back to raw
15347          address.  Since there is no way to confirm that the address
15348          means the same thing as when the trace was started, warn the
15349          user.  */
15350       warning (_("Uploaded tracepoint %d has no "
15351                  "source location, using raw address"),
15352                utp->number);
15353       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15354       addr_str = small_buf;
15355     }
15356
15357   /* There's not much we can do with a sequence of bytecodes.  */
15358   if (utp->cond && !utp->cond_string)
15359     warning (_("Uploaded tracepoint %d condition "
15360                "has no source form, ignoring it"),
15361              utp->number);
15362
15363   location = string_to_event_location (&addr_str, current_language);
15364   cleanup = make_cleanup_delete_event_location (location);
15365   if (!create_breakpoint (get_current_arch (),
15366                           location,
15367                           utp->cond_string, -1, addr_str,
15368                           0 /* parse cond/thread */,
15369                           0 /* tempflag */,
15370                           utp->type /* type_wanted */,
15371                           0 /* Ignore count */,
15372                           pending_break_support,
15373                           &tracepoint_breakpoint_ops,
15374                           0 /* from_tty */,
15375                           utp->enabled /* enabled */,
15376                           0 /* internal */,
15377                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15378     {
15379       do_cleanups (cleanup);
15380       return NULL;
15381     }
15382
15383   do_cleanups (cleanup);
15384
15385   /* Get the tracepoint we just created.  */
15386   tp = get_tracepoint (tracepoint_count);
15387   gdb_assert (tp != NULL);
15388
15389   if (utp->pass > 0)
15390     {
15391       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15392                  tp->base.number);
15393
15394       trace_pass_command (small_buf, 0);
15395     }
15396
15397   /* If we have uploaded versions of the original commands, set up a
15398      special-purpose "reader" function and call the usual command line
15399      reader, then pass the result to the breakpoint command-setting
15400      function.  */
15401   if (!VEC_empty (char_ptr, utp->cmd_strings))
15402     {
15403       struct command_line *cmd_list;
15404
15405       this_utp = utp;
15406       next_cmd = 0;
15407
15408       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15409
15410       breakpoint_set_commands (&tp->base, cmd_list);
15411     }
15412   else if (!VEC_empty (char_ptr, utp->actions)
15413            || !VEC_empty (char_ptr, utp->step_actions))
15414     warning (_("Uploaded tracepoint %d actions "
15415                "have no source form, ignoring them"),
15416              utp->number);
15417
15418   /* Copy any status information that might be available.  */
15419   tp->base.hit_count = utp->hit_count;
15420   tp->traceframe_usage = utp->traceframe_usage;
15421
15422   return tp;
15423 }
15424   
15425 /* Print information on tracepoint number TPNUM_EXP, or all if
15426    omitted.  */
15427
15428 static void
15429 tracepoints_info (char *args, int from_tty)
15430 {
15431   struct ui_out *uiout = current_uiout;
15432   int num_printed;
15433
15434   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15435
15436   if (num_printed == 0)
15437     {
15438       if (args == NULL || *args == '\0')
15439         uiout->message ("No tracepoints.\n");
15440       else
15441         uiout->message ("No tracepoint matching '%s'.\n", args);
15442     }
15443
15444   default_collect_info ();
15445 }
15446
15447 /* The 'enable trace' command enables tracepoints.
15448    Not supported by all targets.  */
15449 static void
15450 enable_trace_command (char *args, int from_tty)
15451 {
15452   enable_command (args, from_tty);
15453 }
15454
15455 /* The 'disable trace' command disables tracepoints.
15456    Not supported by all targets.  */
15457 static void
15458 disable_trace_command (char *args, int from_tty)
15459 {
15460   disable_command (args, from_tty);
15461 }
15462
15463 /* Remove a tracepoint (or all if no argument).  */
15464 static void
15465 delete_trace_command (char *arg, int from_tty)
15466 {
15467   struct breakpoint *b, *b_tmp;
15468
15469   dont_repeat ();
15470
15471   if (arg == 0)
15472     {
15473       int breaks_to_delete = 0;
15474
15475       /* Delete all breakpoints if no argument.
15476          Do not delete internal or call-dummy breakpoints, these
15477          have to be deleted with an explicit breakpoint number 
15478          argument.  */
15479       ALL_TRACEPOINTS (b)
15480         if (is_tracepoint (b) && user_breakpoint_p (b))
15481           {
15482             breaks_to_delete = 1;
15483             break;
15484           }
15485
15486       /* Ask user only if there are some breakpoints to delete.  */
15487       if (!from_tty
15488           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15489         {
15490           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15491             if (is_tracepoint (b) && user_breakpoint_p (b))
15492               delete_breakpoint (b);
15493         }
15494     }
15495   else
15496     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15497 }
15498
15499 /* Helper function for trace_pass_command.  */
15500
15501 static void
15502 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15503 {
15504   tp->pass_count = count;
15505   observer_notify_breakpoint_modified (&tp->base);
15506   if (from_tty)
15507     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15508                      tp->base.number, count);
15509 }
15510
15511 /* Set passcount for tracepoint.
15512
15513    First command argument is passcount, second is tracepoint number.
15514    If tracepoint number omitted, apply to most recently defined.
15515    Also accepts special argument "all".  */
15516
15517 static void
15518 trace_pass_command (char *args, int from_tty)
15519 {
15520   struct tracepoint *t1;
15521   unsigned int count;
15522
15523   if (args == 0 || *args == 0)
15524     error (_("passcount command requires an "
15525              "argument (count + optional TP num)"));
15526
15527   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15528
15529   args = skip_spaces (args);
15530   if (*args && strncasecmp (args, "all", 3) == 0)
15531     {
15532       struct breakpoint *b;
15533
15534       args += 3;                        /* Skip special argument "all".  */
15535       if (*args)
15536         error (_("Junk at end of arguments."));
15537
15538       ALL_TRACEPOINTS (b)
15539       {
15540         t1 = (struct tracepoint *) b;
15541         trace_pass_set_count (t1, count, from_tty);
15542       }
15543     }
15544   else if (*args == '\0')
15545     {
15546       t1 = get_tracepoint_by_number (&args, NULL);
15547       if (t1)
15548         trace_pass_set_count (t1, count, from_tty);
15549     }
15550   else
15551     {
15552       number_or_range_parser parser (args);
15553       while (!parser.finished ())
15554         {
15555           t1 = get_tracepoint_by_number (&args, &parser);
15556           if (t1)
15557             trace_pass_set_count (t1, count, from_tty);
15558         }
15559     }
15560 }
15561
15562 struct tracepoint *
15563 get_tracepoint (int num)
15564 {
15565   struct breakpoint *t;
15566
15567   ALL_TRACEPOINTS (t)
15568     if (t->number == num)
15569       return (struct tracepoint *) t;
15570
15571   return NULL;
15572 }
15573
15574 /* Find the tracepoint with the given target-side number (which may be
15575    different from the tracepoint number after disconnecting and
15576    reconnecting).  */
15577
15578 struct tracepoint *
15579 get_tracepoint_by_number_on_target (int num)
15580 {
15581   struct breakpoint *b;
15582
15583   ALL_TRACEPOINTS (b)
15584     {
15585       struct tracepoint *t = (struct tracepoint *) b;
15586
15587       if (t->number_on_target == num)
15588         return t;
15589     }
15590
15591   return NULL;
15592 }
15593
15594 /* Utility: parse a tracepoint number and look it up in the list.
15595    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15596    If the argument is missing, the most recent tracepoint
15597    (tracepoint_count) is returned.  */
15598
15599 struct tracepoint *
15600 get_tracepoint_by_number (char **arg,
15601                           number_or_range_parser *parser)
15602 {
15603   struct breakpoint *t;
15604   int tpnum;
15605   char *instring = arg == NULL ? NULL : *arg;
15606
15607   if (parser != NULL)
15608     {
15609       gdb_assert (!parser->finished ());
15610       tpnum = parser->get_number ();
15611     }
15612   else if (arg == NULL || *arg == NULL || ! **arg)
15613     tpnum = tracepoint_count;
15614   else
15615     tpnum = get_number (arg);
15616
15617   if (tpnum <= 0)
15618     {
15619       if (instring && *instring)
15620         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15621                          instring);
15622       else
15623         printf_filtered (_("No previous tracepoint\n"));
15624       return NULL;
15625     }
15626
15627   ALL_TRACEPOINTS (t)
15628     if (t->number == tpnum)
15629     {
15630       return (struct tracepoint *) t;
15631     }
15632
15633   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15634   return NULL;
15635 }
15636
15637 void
15638 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15639 {
15640   if (b->thread != -1)
15641     fprintf_unfiltered (fp, " thread %d", b->thread);
15642
15643   if (b->task != 0)
15644     fprintf_unfiltered (fp, " task %d", b->task);
15645
15646   fprintf_unfiltered (fp, "\n");
15647 }
15648
15649 /* Save information on user settable breakpoints (watchpoints, etc) to
15650    a new script file named FILENAME.  If FILTER is non-NULL, call it
15651    on each breakpoint and only include the ones for which it returns
15652    non-zero.  */
15653
15654 static void
15655 save_breakpoints (char *filename, int from_tty,
15656                   int (*filter) (const struct breakpoint *))
15657 {
15658   struct breakpoint *tp;
15659   int any = 0;
15660   struct cleanup *cleanup;
15661   int extra_trace_bits = 0;
15662
15663   if (filename == 0 || *filename == 0)
15664     error (_("Argument required (file name in which to save)"));
15665
15666   /* See if we have anything to save.  */
15667   ALL_BREAKPOINTS (tp)
15668   {
15669     /* Skip internal and momentary breakpoints.  */
15670     if (!user_breakpoint_p (tp))
15671       continue;
15672
15673     /* If we have a filter, only save the breakpoints it accepts.  */
15674     if (filter && !filter (tp))
15675       continue;
15676
15677     any = 1;
15678
15679     if (is_tracepoint (tp))
15680       {
15681         extra_trace_bits = 1;
15682
15683         /* We can stop searching.  */
15684         break;
15685       }
15686   }
15687
15688   if (!any)
15689     {
15690       warning (_("Nothing to save."));
15691       return;
15692     }
15693
15694   filename = tilde_expand (filename);
15695   cleanup = make_cleanup (xfree, filename);
15696
15697   stdio_file fp;
15698
15699   if (!fp.open (filename, "w"))
15700     error (_("Unable to open file '%s' for saving (%s)"),
15701            filename, safe_strerror (errno));
15702
15703   if (extra_trace_bits)
15704     save_trace_state_variables (&fp);
15705
15706   ALL_BREAKPOINTS (tp)
15707   {
15708     /* Skip internal and momentary breakpoints.  */
15709     if (!user_breakpoint_p (tp))
15710       continue;
15711
15712     /* If we have a filter, only save the breakpoints it accepts.  */
15713     if (filter && !filter (tp))
15714       continue;
15715
15716     tp->ops->print_recreate (tp, &fp);
15717
15718     /* Note, we can't rely on tp->number for anything, as we can't
15719        assume the recreated breakpoint numbers will match.  Use $bpnum
15720        instead.  */
15721
15722     if (tp->cond_string)
15723       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15724
15725     if (tp->ignore_count)
15726       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15727
15728     if (tp->type != bp_dprintf && tp->commands)
15729       {
15730         fp.puts ("  commands\n");
15731         
15732         current_uiout->redirect (&fp);
15733         TRY
15734           {
15735             print_command_lines (current_uiout, tp->commands->commands, 2);
15736           }
15737         CATCH (ex, RETURN_MASK_ALL)
15738           {
15739           current_uiout->redirect (NULL);
15740             throw_exception (ex);
15741           }
15742         END_CATCH
15743
15744         current_uiout->redirect (NULL);
15745         fp.puts ("  end\n");
15746       }
15747
15748     if (tp->enable_state == bp_disabled)
15749       fp.puts ("disable $bpnum\n");
15750
15751     /* If this is a multi-location breakpoint, check if the locations
15752        should be individually disabled.  Watchpoint locations are
15753        special, and not user visible.  */
15754     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15755       {
15756         struct bp_location *loc;
15757         int n = 1;
15758
15759         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15760           if (!loc->enabled)
15761             fp.printf ("disable $bpnum.%d\n", n);
15762       }
15763   }
15764
15765   if (extra_trace_bits && *default_collect)
15766     fp.printf ("set default-collect %s\n", default_collect);
15767
15768   if (from_tty)
15769     printf_filtered (_("Saved to file '%s'.\n"), filename);
15770   do_cleanups (cleanup);
15771 }
15772
15773 /* The `save breakpoints' command.  */
15774
15775 static void
15776 save_breakpoints_command (char *args, int from_tty)
15777 {
15778   save_breakpoints (args, from_tty, NULL);
15779 }
15780
15781 /* The `save tracepoints' command.  */
15782
15783 static void
15784 save_tracepoints_command (char *args, int from_tty)
15785 {
15786   save_breakpoints (args, from_tty, is_tracepoint);
15787 }
15788
15789 /* Create a vector of all tracepoints.  */
15790
15791 VEC(breakpoint_p) *
15792 all_tracepoints (void)
15793 {
15794   VEC(breakpoint_p) *tp_vec = 0;
15795   struct breakpoint *tp;
15796
15797   ALL_TRACEPOINTS (tp)
15798   {
15799     VEC_safe_push (breakpoint_p, tp_vec, tp);
15800   }
15801
15802   return tp_vec;
15803 }
15804
15805 \f
15806 /* This help string is used to consolidate all the help string for specifying
15807    locations used by several commands.  */
15808
15809 #define LOCATION_HELP_STRING \
15810 "Linespecs are colon-separated lists of location parameters, such as\n\
15811 source filename, function name, label name, and line number.\n\
15812 Example: To specify the start of a label named \"the_top\" in the\n\
15813 function \"fact\" in the file \"factorial.c\", use\n\
15814 \"factorial.c:fact:the_top\".\n\
15815 \n\
15816 Address locations begin with \"*\" and specify an exact address in the\n\
15817 program.  Example: To specify the fourth byte past the start function\n\
15818 \"main\", use \"*main + 4\".\n\
15819 \n\
15820 Explicit locations are similar to linespecs but use an option/argument\n\
15821 syntax to specify location parameters.\n\
15822 Example: To specify the start of the label named \"the_top\" in the\n\
15823 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15824 -function fact -label the_top\".\n"
15825
15826 /* This help string is used for the break, hbreak, tbreak and thbreak
15827    commands.  It is defined as a macro to prevent duplication.
15828    COMMAND should be a string constant containing the name of the
15829    command.  */
15830
15831 #define BREAK_ARGS_HELP(command) \
15832 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15833 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15834 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15835 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15836 `-probe-dtrace' (for a DTrace probe).\n\
15837 LOCATION may be a linespec, address, or explicit location as described\n\
15838 below.\n\
15839 \n\
15840 With no LOCATION, uses current execution address of the selected\n\
15841 stack frame.  This is useful for breaking on return to a stack frame.\n\
15842 \n\
15843 THREADNUM is the number from \"info threads\".\n\
15844 CONDITION is a boolean expression.\n\
15845 \n" LOCATION_HELP_STRING "\n\
15846 Multiple breakpoints at one place are permitted, and useful if their\n\
15847 conditions are different.\n\
15848 \n\
15849 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15850
15851 /* List of subcommands for "catch".  */
15852 static struct cmd_list_element *catch_cmdlist;
15853
15854 /* List of subcommands for "tcatch".  */
15855 static struct cmd_list_element *tcatch_cmdlist;
15856
15857 void
15858 add_catch_command (char *name, char *docstring,
15859                    cmd_sfunc_ftype *sfunc,
15860                    completer_ftype *completer,
15861                    void *user_data_catch,
15862                    void *user_data_tcatch)
15863 {
15864   struct cmd_list_element *command;
15865
15866   command = add_cmd (name, class_breakpoint, NULL, docstring,
15867                      &catch_cmdlist);
15868   set_cmd_sfunc (command, sfunc);
15869   set_cmd_context (command, user_data_catch);
15870   set_cmd_completer (command, completer);
15871
15872   command = add_cmd (name, class_breakpoint, NULL, docstring,
15873                      &tcatch_cmdlist);
15874   set_cmd_sfunc (command, sfunc);
15875   set_cmd_context (command, user_data_tcatch);
15876   set_cmd_completer (command, completer);
15877 }
15878
15879 static void
15880 save_command (char *arg, int from_tty)
15881 {
15882   printf_unfiltered (_("\"save\" must be followed by "
15883                        "the name of a save subcommand.\n"));
15884   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15885 }
15886
15887 struct breakpoint *
15888 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15889                           void *data)
15890 {
15891   struct breakpoint *b, *b_tmp;
15892
15893   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15894     {
15895       if ((*callback) (b, data))
15896         return b;
15897     }
15898
15899   return NULL;
15900 }
15901
15902 /* Zero if any of the breakpoint's locations could be a location where
15903    functions have been inlined, nonzero otherwise.  */
15904
15905 static int
15906 is_non_inline_function (struct breakpoint *b)
15907 {
15908   /* The shared library event breakpoint is set on the address of a
15909      non-inline function.  */
15910   if (b->type == bp_shlib_event)
15911     return 1;
15912
15913   return 0;
15914 }
15915
15916 /* Nonzero if the specified PC cannot be a location where functions
15917    have been inlined.  */
15918
15919 int
15920 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15921                            const struct target_waitstatus *ws)
15922 {
15923   struct breakpoint *b;
15924   struct bp_location *bl;
15925
15926   ALL_BREAKPOINTS (b)
15927     {
15928       if (!is_non_inline_function (b))
15929         continue;
15930
15931       for (bl = b->loc; bl != NULL; bl = bl->next)
15932         {
15933           if (!bl->shlib_disabled
15934               && bpstat_check_location (bl, aspace, pc, ws))
15935             return 1;
15936         }
15937     }
15938
15939   return 0;
15940 }
15941
15942 /* Remove any references to OBJFILE which is going to be freed.  */
15943
15944 void
15945 breakpoint_free_objfile (struct objfile *objfile)
15946 {
15947   struct bp_location **locp, *loc;
15948
15949   ALL_BP_LOCATIONS (loc, locp)
15950     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15951       loc->symtab = NULL;
15952 }
15953
15954 void
15955 initialize_breakpoint_ops (void)
15956 {
15957   static int initialized = 0;
15958
15959   struct breakpoint_ops *ops;
15960
15961   if (initialized)
15962     return;
15963   initialized = 1;
15964
15965   /* The breakpoint_ops structure to be inherit by all kinds of
15966      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15967      internal and momentary breakpoints, etc.).  */
15968   ops = &bkpt_base_breakpoint_ops;
15969   *ops = base_breakpoint_ops;
15970   ops->re_set = bkpt_re_set;
15971   ops->insert_location = bkpt_insert_location;
15972   ops->remove_location = bkpt_remove_location;
15973   ops->breakpoint_hit = bkpt_breakpoint_hit;
15974   ops->create_sals_from_location = bkpt_create_sals_from_location;
15975   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15976   ops->decode_location = bkpt_decode_location;
15977
15978   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15979   ops = &bkpt_breakpoint_ops;
15980   *ops = bkpt_base_breakpoint_ops;
15981   ops->re_set = bkpt_re_set;
15982   ops->resources_needed = bkpt_resources_needed;
15983   ops->print_it = bkpt_print_it;
15984   ops->print_mention = bkpt_print_mention;
15985   ops->print_recreate = bkpt_print_recreate;
15986
15987   /* Ranged breakpoints.  */
15988   ops = &ranged_breakpoint_ops;
15989   *ops = bkpt_breakpoint_ops;
15990   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15991   ops->resources_needed = resources_needed_ranged_breakpoint;
15992   ops->print_it = print_it_ranged_breakpoint;
15993   ops->print_one = print_one_ranged_breakpoint;
15994   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15995   ops->print_mention = print_mention_ranged_breakpoint;
15996   ops->print_recreate = print_recreate_ranged_breakpoint;
15997
15998   /* Internal breakpoints.  */
15999   ops = &internal_breakpoint_ops;
16000   *ops = bkpt_base_breakpoint_ops;
16001   ops->re_set = internal_bkpt_re_set;
16002   ops->check_status = internal_bkpt_check_status;
16003   ops->print_it = internal_bkpt_print_it;
16004   ops->print_mention = internal_bkpt_print_mention;
16005
16006   /* Momentary breakpoints.  */
16007   ops = &momentary_breakpoint_ops;
16008   *ops = bkpt_base_breakpoint_ops;
16009   ops->re_set = momentary_bkpt_re_set;
16010   ops->check_status = momentary_bkpt_check_status;
16011   ops->print_it = momentary_bkpt_print_it;
16012   ops->print_mention = momentary_bkpt_print_mention;
16013
16014   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16015   ops = &longjmp_breakpoint_ops;
16016   *ops = momentary_breakpoint_ops;
16017   ops->dtor = longjmp_bkpt_dtor;
16018
16019   /* Probe breakpoints.  */
16020   ops = &bkpt_probe_breakpoint_ops;
16021   *ops = bkpt_breakpoint_ops;
16022   ops->insert_location = bkpt_probe_insert_location;
16023   ops->remove_location = bkpt_probe_remove_location;
16024   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
16025   ops->decode_location = bkpt_probe_decode_location;
16026
16027   /* Watchpoints.  */
16028   ops = &watchpoint_breakpoint_ops;
16029   *ops = base_breakpoint_ops;
16030   ops->dtor = dtor_watchpoint;
16031   ops->re_set = re_set_watchpoint;
16032   ops->insert_location = insert_watchpoint;
16033   ops->remove_location = remove_watchpoint;
16034   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16035   ops->check_status = check_status_watchpoint;
16036   ops->resources_needed = resources_needed_watchpoint;
16037   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16038   ops->print_it = print_it_watchpoint;
16039   ops->print_mention = print_mention_watchpoint;
16040   ops->print_recreate = print_recreate_watchpoint;
16041   ops->explains_signal = explains_signal_watchpoint;
16042
16043   /* Masked watchpoints.  */
16044   ops = &masked_watchpoint_breakpoint_ops;
16045   *ops = watchpoint_breakpoint_ops;
16046   ops->insert_location = insert_masked_watchpoint;
16047   ops->remove_location = remove_masked_watchpoint;
16048   ops->resources_needed = resources_needed_masked_watchpoint;
16049   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16050   ops->print_it = print_it_masked_watchpoint;
16051   ops->print_one_detail = print_one_detail_masked_watchpoint;
16052   ops->print_mention = print_mention_masked_watchpoint;
16053   ops->print_recreate = print_recreate_masked_watchpoint;
16054
16055   /* Tracepoints.  */
16056   ops = &tracepoint_breakpoint_ops;
16057   *ops = base_breakpoint_ops;
16058   ops->re_set = tracepoint_re_set;
16059   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16060   ops->print_one_detail = tracepoint_print_one_detail;
16061   ops->print_mention = tracepoint_print_mention;
16062   ops->print_recreate = tracepoint_print_recreate;
16063   ops->create_sals_from_location = tracepoint_create_sals_from_location;
16064   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16065   ops->decode_location = tracepoint_decode_location;
16066
16067   /* Probe tracepoints.  */
16068   ops = &tracepoint_probe_breakpoint_ops;
16069   *ops = tracepoint_breakpoint_ops;
16070   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
16071   ops->decode_location = tracepoint_probe_decode_location;
16072
16073   /* Static tracepoints with marker (`-m').  */
16074   ops = &strace_marker_breakpoint_ops;
16075   *ops = tracepoint_breakpoint_ops;
16076   ops->create_sals_from_location = strace_marker_create_sals_from_location;
16077   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16078   ops->decode_location = strace_marker_decode_location;
16079
16080   /* Fork catchpoints.  */
16081   ops = &catch_fork_breakpoint_ops;
16082   *ops = base_breakpoint_ops;
16083   ops->insert_location = insert_catch_fork;
16084   ops->remove_location = remove_catch_fork;
16085   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16086   ops->print_it = print_it_catch_fork;
16087   ops->print_one = print_one_catch_fork;
16088   ops->print_mention = print_mention_catch_fork;
16089   ops->print_recreate = print_recreate_catch_fork;
16090
16091   /* Vfork catchpoints.  */
16092   ops = &catch_vfork_breakpoint_ops;
16093   *ops = base_breakpoint_ops;
16094   ops->insert_location = insert_catch_vfork;
16095   ops->remove_location = remove_catch_vfork;
16096   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16097   ops->print_it = print_it_catch_vfork;
16098   ops->print_one = print_one_catch_vfork;
16099   ops->print_mention = print_mention_catch_vfork;
16100   ops->print_recreate = print_recreate_catch_vfork;
16101
16102   /* Exec catchpoints.  */
16103   ops = &catch_exec_breakpoint_ops;
16104   *ops = base_breakpoint_ops;
16105   ops->dtor = dtor_catch_exec;
16106   ops->insert_location = insert_catch_exec;
16107   ops->remove_location = remove_catch_exec;
16108   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16109   ops->print_it = print_it_catch_exec;
16110   ops->print_one = print_one_catch_exec;
16111   ops->print_mention = print_mention_catch_exec;
16112   ops->print_recreate = print_recreate_catch_exec;
16113
16114   /* Solib-related catchpoints.  */
16115   ops = &catch_solib_breakpoint_ops;
16116   *ops = base_breakpoint_ops;
16117   ops->dtor = dtor_catch_solib;
16118   ops->insert_location = insert_catch_solib;
16119   ops->remove_location = remove_catch_solib;
16120   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16121   ops->check_status = check_status_catch_solib;
16122   ops->print_it = print_it_catch_solib;
16123   ops->print_one = print_one_catch_solib;
16124   ops->print_mention = print_mention_catch_solib;
16125   ops->print_recreate = print_recreate_catch_solib;
16126
16127   ops = &dprintf_breakpoint_ops;
16128   *ops = bkpt_base_breakpoint_ops;
16129   ops->re_set = dprintf_re_set;
16130   ops->resources_needed = bkpt_resources_needed;
16131   ops->print_it = bkpt_print_it;
16132   ops->print_mention = bkpt_print_mention;
16133   ops->print_recreate = dprintf_print_recreate;
16134   ops->after_condition_true = dprintf_after_condition_true;
16135   ops->breakpoint_hit = dprintf_breakpoint_hit;
16136 }
16137
16138 /* Chain containing all defined "enable breakpoint" subcommands.  */
16139
16140 static struct cmd_list_element *enablebreaklist = NULL;
16141
16142 void
16143 _initialize_breakpoint (void)
16144 {
16145   struct cmd_list_element *c;
16146
16147   initialize_breakpoint_ops ();
16148
16149   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16150   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16151   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16152
16153   breakpoint_objfile_key
16154     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16155
16156   breakpoint_chain = 0;
16157   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16158      before a breakpoint is set.  */
16159   breakpoint_count = 0;
16160
16161   tracepoint_count = 0;
16162
16163   add_com ("ignore", class_breakpoint, ignore_command, _("\
16164 Set ignore-count of breakpoint number N to COUNT.\n\
16165 Usage is `ignore N COUNT'."));
16166
16167   add_com ("commands", class_breakpoint, commands_command, _("\
16168 Set commands to be executed when the given breakpoints are hit.\n\
16169 Give a space-separated breakpoint list as argument after \"commands\".\n\
16170 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
16171 (e.g. `5-7').\n\
16172 With no argument, the targeted breakpoint is the last one set.\n\
16173 The commands themselves follow starting on the next line.\n\
16174 Type a line containing \"end\" to indicate the end of them.\n\
16175 Give \"silent\" as the first line to make the breakpoint silent;\n\
16176 then no output is printed when it is hit, except what the commands print."));
16177
16178   c = add_com ("condition", class_breakpoint, condition_command, _("\
16179 Specify breakpoint number N to break only if COND is true.\n\
16180 Usage is `condition N COND', where N is an integer and COND is an\n\
16181 expression to be evaluated whenever breakpoint N is reached."));
16182   set_cmd_completer (c, condition_completer);
16183
16184   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16185 Set a temporary breakpoint.\n\
16186 Like \"break\" except the breakpoint is only temporary,\n\
16187 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16188 by using \"enable delete\" on the breakpoint number.\n\
16189 \n"
16190 BREAK_ARGS_HELP ("tbreak")));
16191   set_cmd_completer (c, location_completer);
16192
16193   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16194 Set a hardware assisted breakpoint.\n\
16195 Like \"break\" except the breakpoint requires hardware support,\n\
16196 some target hardware may not have this support.\n\
16197 \n"
16198 BREAK_ARGS_HELP ("hbreak")));
16199   set_cmd_completer (c, location_completer);
16200
16201   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16202 Set a temporary hardware assisted breakpoint.\n\
16203 Like \"hbreak\" except the breakpoint is only temporary,\n\
16204 so it will be deleted when hit.\n\
16205 \n"
16206 BREAK_ARGS_HELP ("thbreak")));
16207   set_cmd_completer (c, location_completer);
16208
16209   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16210 Enable some breakpoints.\n\
16211 Give breakpoint numbers (separated by spaces) as arguments.\n\
16212 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16213 This is used to cancel the effect of the \"disable\" command.\n\
16214 With a subcommand you can enable temporarily."),
16215                   &enablelist, "enable ", 1, &cmdlist);
16216
16217   add_com_alias ("en", "enable", class_breakpoint, 1);
16218
16219   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16220 Enable some breakpoints.\n\
16221 Give breakpoint numbers (separated by spaces) as arguments.\n\
16222 This is used to cancel the effect of the \"disable\" command.\n\
16223 May be abbreviated to simply \"enable\".\n"),
16224                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16225
16226   add_cmd ("once", no_class, enable_once_command, _("\
16227 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16228 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16229            &enablebreaklist);
16230
16231   add_cmd ("delete", no_class, enable_delete_command, _("\
16232 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16233 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16234            &enablebreaklist);
16235
16236   add_cmd ("count", no_class, enable_count_command, _("\
16237 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16238 If a breakpoint is hit while enabled in this fashion,\n\
16239 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16240            &enablebreaklist);
16241
16242   add_cmd ("delete", no_class, enable_delete_command, _("\
16243 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16244 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16245            &enablelist);
16246
16247   add_cmd ("once", no_class, enable_once_command, _("\
16248 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16249 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16250            &enablelist);
16251
16252   add_cmd ("count", no_class, enable_count_command, _("\
16253 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16254 If a breakpoint is hit while enabled in this fashion,\n\
16255 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16256            &enablelist);
16257
16258   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16259 Disable some breakpoints.\n\
16260 Arguments are breakpoint numbers with spaces in between.\n\
16261 To disable all breakpoints, give no argument.\n\
16262 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16263                   &disablelist, "disable ", 1, &cmdlist);
16264   add_com_alias ("dis", "disable", class_breakpoint, 1);
16265   add_com_alias ("disa", "disable", class_breakpoint, 1);
16266
16267   add_cmd ("breakpoints", class_alias, disable_command, _("\
16268 Disable some breakpoints.\n\
16269 Arguments are breakpoint numbers with spaces in between.\n\
16270 To disable all breakpoints, give no argument.\n\
16271 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16272 This command may be abbreviated \"disable\"."),
16273            &disablelist);
16274
16275   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16276 Delete some breakpoints or auto-display expressions.\n\
16277 Arguments are breakpoint numbers with spaces in between.\n\
16278 To delete all breakpoints, give no argument.\n\
16279 \n\
16280 Also a prefix command for deletion of other GDB objects.\n\
16281 The \"unset\" command is also an alias for \"delete\"."),
16282                   &deletelist, "delete ", 1, &cmdlist);
16283   add_com_alias ("d", "delete", class_breakpoint, 1);
16284   add_com_alias ("del", "delete", class_breakpoint, 1);
16285
16286   add_cmd ("breakpoints", class_alias, delete_command, _("\
16287 Delete some breakpoints or auto-display expressions.\n\
16288 Arguments are breakpoint numbers with spaces in between.\n\
16289 To delete all breakpoints, give no argument.\n\
16290 This command may be abbreviated \"delete\"."),
16291            &deletelist);
16292
16293   add_com ("clear", class_breakpoint, clear_command, _("\
16294 Clear breakpoint at specified location.\n\
16295 Argument may be a linespec, explicit, or address location as described below.\n\
16296 \n\
16297 With no argument, clears all breakpoints in the line that the selected frame\n\
16298 is executing in.\n"
16299 "\n" LOCATION_HELP_STRING "\n\
16300 See also the \"delete\" command which clears breakpoints by number."));
16301   add_com_alias ("cl", "clear", class_breakpoint, 1);
16302
16303   c = add_com ("break", class_breakpoint, break_command, _("\
16304 Set breakpoint at specified location.\n"
16305 BREAK_ARGS_HELP ("break")));
16306   set_cmd_completer (c, location_completer);
16307
16308   add_com_alias ("b", "break", class_run, 1);
16309   add_com_alias ("br", "break", class_run, 1);
16310   add_com_alias ("bre", "break", class_run, 1);
16311   add_com_alias ("brea", "break", class_run, 1);
16312
16313   if (dbx_commands)
16314     {
16315       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16316 Break in function/address or break at a line in the current file."),
16317                              &stoplist, "stop ", 1, &cmdlist);
16318       add_cmd ("in", class_breakpoint, stopin_command,
16319                _("Break in function or address."), &stoplist);
16320       add_cmd ("at", class_breakpoint, stopat_command,
16321                _("Break at a line in the current file."), &stoplist);
16322       add_com ("status", class_info, breakpoints_info, _("\
16323 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16324 The \"Type\" column indicates one of:\n\
16325 \tbreakpoint     - normal breakpoint\n\
16326 \twatchpoint     - watchpoint\n\
16327 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16328 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16329 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16330 address and file/line number respectively.\n\
16331 \n\
16332 Convenience variable \"$_\" and default examine address for \"x\"\n\
16333 are set to the address of the last breakpoint listed unless the command\n\
16334 is prefixed with \"server \".\n\n\
16335 Convenience variable \"$bpnum\" contains the number of the last\n\
16336 breakpoint set."));
16337     }
16338
16339   add_info ("breakpoints", breakpoints_info, _("\
16340 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16341 The \"Type\" column indicates one of:\n\
16342 \tbreakpoint     - normal breakpoint\n\
16343 \twatchpoint     - watchpoint\n\
16344 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16345 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16346 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16347 address and file/line number respectively.\n\
16348 \n\
16349 Convenience variable \"$_\" and default examine address for \"x\"\n\
16350 are set to the address of the last breakpoint listed unless the command\n\
16351 is prefixed with \"server \".\n\n\
16352 Convenience variable \"$bpnum\" contains the number of the last\n\
16353 breakpoint set."));
16354
16355   add_info_alias ("b", "breakpoints", 1);
16356
16357   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16358 Status of all breakpoints, or breakpoint number NUMBER.\n\
16359 The \"Type\" column indicates one of:\n\
16360 \tbreakpoint     - normal breakpoint\n\
16361 \twatchpoint     - watchpoint\n\
16362 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16363 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16364 \tuntil          - internal breakpoint used by the \"until\" command\n\
16365 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16366 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16367 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16368 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16369 address and file/line number respectively.\n\
16370 \n\
16371 Convenience variable \"$_\" and default examine address for \"x\"\n\
16372 are set to the address of the last breakpoint listed unless the command\n\
16373 is prefixed with \"server \".\n\n\
16374 Convenience variable \"$bpnum\" contains the number of the last\n\
16375 breakpoint set."),
16376            &maintenanceinfolist);
16377
16378   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16379 Set catchpoints to catch events."),
16380                   &catch_cmdlist, "catch ",
16381                   0/*allow-unknown*/, &cmdlist);
16382
16383   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16384 Set temporary catchpoints to catch events."),
16385                   &tcatch_cmdlist, "tcatch ",
16386                   0/*allow-unknown*/, &cmdlist);
16387
16388   add_catch_command ("fork", _("Catch calls to fork."),
16389                      catch_fork_command_1,
16390                      NULL,
16391                      (void *) (uintptr_t) catch_fork_permanent,
16392                      (void *) (uintptr_t) catch_fork_temporary);
16393   add_catch_command ("vfork", _("Catch calls to vfork."),
16394                      catch_fork_command_1,
16395                      NULL,
16396                      (void *) (uintptr_t) catch_vfork_permanent,
16397                      (void *) (uintptr_t) catch_vfork_temporary);
16398   add_catch_command ("exec", _("Catch calls to exec."),
16399                      catch_exec_command_1,
16400                      NULL,
16401                      CATCH_PERMANENT,
16402                      CATCH_TEMPORARY);
16403   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16404 Usage: catch load [REGEX]\n\
16405 If REGEX is given, only stop for libraries matching the regular expression."),
16406                      catch_load_command_1,
16407                      NULL,
16408                      CATCH_PERMANENT,
16409                      CATCH_TEMPORARY);
16410   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16411 Usage: catch unload [REGEX]\n\
16412 If REGEX is given, only stop for libraries matching the regular expression."),
16413                      catch_unload_command_1,
16414                      NULL,
16415                      CATCH_PERMANENT,
16416                      CATCH_TEMPORARY);
16417
16418   c = add_com ("watch", class_breakpoint, watch_command, _("\
16419 Set a watchpoint for an expression.\n\
16420 Usage: watch [-l|-location] EXPRESSION\n\
16421 A watchpoint stops execution of your program whenever the value of\n\
16422 an expression changes.\n\
16423 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16424 the memory to which it refers."));
16425   set_cmd_completer (c, expression_completer);
16426
16427   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16428 Set a read watchpoint for an expression.\n\
16429 Usage: rwatch [-l|-location] EXPRESSION\n\
16430 A watchpoint stops execution of your program whenever the value of\n\
16431 an expression is read.\n\
16432 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16433 the memory to which it refers."));
16434   set_cmd_completer (c, expression_completer);
16435
16436   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16437 Set a watchpoint for an expression.\n\
16438 Usage: awatch [-l|-location] EXPRESSION\n\
16439 A watchpoint stops execution of your program whenever the value of\n\
16440 an expression is either read or written.\n\
16441 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16442 the memory to which it refers."));
16443   set_cmd_completer (c, expression_completer);
16444
16445   add_info ("watchpoints", watchpoints_info, _("\
16446 Status of specified watchpoints (all watchpoints if no argument)."));
16447
16448   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16449      respond to changes - contrary to the description.  */
16450   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16451                             &can_use_hw_watchpoints, _("\
16452 Set debugger's willingness to use watchpoint hardware."), _("\
16453 Show debugger's willingness to use watchpoint hardware."), _("\
16454 If zero, gdb will not use hardware for new watchpoints, even if\n\
16455 such is available.  (However, any hardware watchpoints that were\n\
16456 created before setting this to nonzero, will continue to use watchpoint\n\
16457 hardware.)"),
16458                             NULL,
16459                             show_can_use_hw_watchpoints,
16460                             &setlist, &showlist);
16461
16462   can_use_hw_watchpoints = 1;
16463
16464   /* Tracepoint manipulation commands.  */
16465
16466   c = add_com ("trace", class_breakpoint, trace_command, _("\
16467 Set a tracepoint at specified location.\n\
16468 \n"
16469 BREAK_ARGS_HELP ("trace") "\n\
16470 Do \"help tracepoints\" for info on other tracepoint commands."));
16471   set_cmd_completer (c, location_completer);
16472
16473   add_com_alias ("tp", "trace", class_alias, 0);
16474   add_com_alias ("tr", "trace", class_alias, 1);
16475   add_com_alias ("tra", "trace", class_alias, 1);
16476   add_com_alias ("trac", "trace", class_alias, 1);
16477
16478   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16479 Set a fast tracepoint at specified location.\n\
16480 \n"
16481 BREAK_ARGS_HELP ("ftrace") "\n\
16482 Do \"help tracepoints\" for info on other tracepoint commands."));
16483   set_cmd_completer (c, location_completer);
16484
16485   c = add_com ("strace", class_breakpoint, strace_command, _("\
16486 Set a static tracepoint at location or marker.\n\
16487 \n\
16488 strace [LOCATION] [if CONDITION]\n\
16489 LOCATION may be a linespec, explicit, or address location (described below) \n\
16490 or -m MARKER_ID.\n\n\
16491 If a marker id is specified, probe the marker with that name.  With\n\
16492 no LOCATION, uses current execution address of the selected stack frame.\n\
16493 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16494 This collects arbitrary user data passed in the probe point call to the\n\
16495 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16496 by printing the $_sdata variable like any other convenience variable.\n\
16497 \n\
16498 CONDITION is a boolean expression.\n\
16499 \n" LOCATION_HELP_STRING "\n\
16500 Multiple tracepoints at one place are permitted, and useful if their\n\
16501 conditions are different.\n\
16502 \n\
16503 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16504 Do \"help tracepoints\" for info on other tracepoint commands."));
16505   set_cmd_completer (c, location_completer);
16506
16507   add_info ("tracepoints", tracepoints_info, _("\
16508 Status of specified tracepoints (all tracepoints if no argument).\n\
16509 Convenience variable \"$tpnum\" contains the number of the\n\
16510 last tracepoint set."));
16511
16512   add_info_alias ("tp", "tracepoints", 1);
16513
16514   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16515 Delete specified tracepoints.\n\
16516 Arguments are tracepoint numbers, separated by spaces.\n\
16517 No argument means delete all tracepoints."),
16518            &deletelist);
16519   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16520
16521   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16522 Disable specified tracepoints.\n\
16523 Arguments are tracepoint numbers, separated by spaces.\n\
16524 No argument means disable all tracepoints."),
16525            &disablelist);
16526   deprecate_cmd (c, "disable");
16527
16528   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16529 Enable specified tracepoints.\n\
16530 Arguments are tracepoint numbers, separated by spaces.\n\
16531 No argument means enable all tracepoints."),
16532            &enablelist);
16533   deprecate_cmd (c, "enable");
16534
16535   add_com ("passcount", class_trace, trace_pass_command, _("\
16536 Set the passcount for a tracepoint.\n\
16537 The trace will end when the tracepoint has been passed 'count' times.\n\
16538 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16539 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16540
16541   add_prefix_cmd ("save", class_breakpoint, save_command,
16542                   _("Save breakpoint definitions as a script."),
16543                   &save_cmdlist, "save ",
16544                   0/*allow-unknown*/, &cmdlist);
16545
16546   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16547 Save current breakpoint definitions as a script.\n\
16548 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16549 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16550 session to restore them."),
16551                &save_cmdlist);
16552   set_cmd_completer (c, filename_completer);
16553
16554   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16555 Save current tracepoint definitions as a script.\n\
16556 Use the 'source' command in another debug session to restore them."),
16557                &save_cmdlist);
16558   set_cmd_completer (c, filename_completer);
16559
16560   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16561   deprecate_cmd (c, "save tracepoints");
16562
16563   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16564 Breakpoint specific settings\n\
16565 Configure various breakpoint-specific variables such as\n\
16566 pending breakpoint behavior"),
16567                   &breakpoint_set_cmdlist, "set breakpoint ",
16568                   0/*allow-unknown*/, &setlist);
16569   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16570 Breakpoint specific settings\n\
16571 Configure various breakpoint-specific variables such as\n\
16572 pending breakpoint behavior"),
16573                   &breakpoint_show_cmdlist, "show breakpoint ",
16574                   0/*allow-unknown*/, &showlist);
16575
16576   add_setshow_auto_boolean_cmd ("pending", no_class,
16577                                 &pending_break_support, _("\
16578 Set debugger's behavior regarding pending breakpoints."), _("\
16579 Show debugger's behavior regarding pending breakpoints."), _("\
16580 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16581 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16582 an error.  If auto, an unrecognized breakpoint location results in a\n\
16583 user-query to see if a pending breakpoint should be created."),
16584                                 NULL,
16585                                 show_pending_break_support,
16586                                 &breakpoint_set_cmdlist,
16587                                 &breakpoint_show_cmdlist);
16588
16589   pending_break_support = AUTO_BOOLEAN_AUTO;
16590
16591   add_setshow_boolean_cmd ("auto-hw", no_class,
16592                            &automatic_hardware_breakpoints, _("\
16593 Set automatic usage of hardware breakpoints."), _("\
16594 Show automatic usage of hardware breakpoints."), _("\
16595 If set, the debugger will automatically use hardware breakpoints for\n\
16596 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16597 a warning will be emitted for such breakpoints."),
16598                            NULL,
16599                            show_automatic_hardware_breakpoints,
16600                            &breakpoint_set_cmdlist,
16601                            &breakpoint_show_cmdlist);
16602
16603   add_setshow_boolean_cmd ("always-inserted", class_support,
16604                            &always_inserted_mode, _("\
16605 Set mode for inserting breakpoints."), _("\
16606 Show mode for inserting breakpoints."), _("\
16607 When this mode is on, breakpoints are inserted immediately as soon as\n\
16608 they're created, kept inserted even when execution stops, and removed\n\
16609 only when the user deletes them.  When this mode is off (the default),\n\
16610 breakpoints are inserted only when execution continues, and removed\n\
16611 when execution stops."),
16612                                 NULL,
16613                                 &show_always_inserted_mode,
16614                                 &breakpoint_set_cmdlist,
16615                                 &breakpoint_show_cmdlist);
16616
16617   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16618                         condition_evaluation_enums,
16619                         &condition_evaluation_mode_1, _("\
16620 Set mode of breakpoint condition evaluation."), _("\
16621 Show mode of breakpoint condition evaluation."), _("\
16622 When this is set to \"host\", breakpoint conditions will be\n\
16623 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16624 breakpoint conditions will be downloaded to the target (if the target\n\
16625 supports such feature) and conditions will be evaluated on the target's side.\n\
16626 If this is set to \"auto\" (default), this will be automatically set to\n\
16627 \"target\" if it supports condition evaluation, otherwise it will\n\
16628 be set to \"gdb\""),
16629                            &set_condition_evaluation_mode,
16630                            &show_condition_evaluation_mode,
16631                            &breakpoint_set_cmdlist,
16632                            &breakpoint_show_cmdlist);
16633
16634   add_com ("break-range", class_breakpoint, break_range_command, _("\
16635 Set a breakpoint for an address range.\n\
16636 break-range START-LOCATION, END-LOCATION\n\
16637 where START-LOCATION and END-LOCATION can be one of the following:\n\
16638   LINENUM, for that line in the current file,\n\
16639   FILE:LINENUM, for that line in that file,\n\
16640   +OFFSET, for that number of lines after the current line\n\
16641            or the start of the range\n\
16642   FUNCTION, for the first line in that function,\n\
16643   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16644   *ADDRESS, for the instruction at that address.\n\
16645 \n\
16646 The breakpoint will stop execution of the inferior whenever it executes\n\
16647 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16648 range (including START-LOCATION and END-LOCATION)."));
16649
16650   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16651 Set a dynamic printf at specified location.\n\
16652 dprintf location,format string,arg1,arg2,...\n\
16653 location may be a linespec, explicit, or address location.\n"
16654 "\n" LOCATION_HELP_STRING));
16655   set_cmd_completer (c, location_completer);
16656
16657   add_setshow_enum_cmd ("dprintf-style", class_support,
16658                         dprintf_style_enums, &dprintf_style, _("\
16659 Set the style of usage for dynamic printf."), _("\
16660 Show the style of usage for dynamic printf."), _("\
16661 This setting chooses how GDB will do a dynamic printf.\n\
16662 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16663 console, as with the \"printf\" command.\n\
16664 If the value is \"call\", the print is done by calling a function in your\n\
16665 program; by default printf(), but you can choose a different function or\n\
16666 output stream by setting dprintf-function and dprintf-channel."),
16667                         update_dprintf_commands, NULL,
16668                         &setlist, &showlist);
16669
16670   dprintf_function = xstrdup ("printf");
16671   add_setshow_string_cmd ("dprintf-function", class_support,
16672                           &dprintf_function, _("\
16673 Set the function to use for dynamic printf"), _("\
16674 Show the function to use for dynamic printf"), NULL,
16675                           update_dprintf_commands, NULL,
16676                           &setlist, &showlist);
16677
16678   dprintf_channel = xstrdup ("");
16679   add_setshow_string_cmd ("dprintf-channel", class_support,
16680                           &dprintf_channel, _("\
16681 Set the channel to use for dynamic printf"), _("\
16682 Show the channel to use for dynamic printf"), NULL,
16683                           update_dprintf_commands, NULL,
16684                           &setlist, &showlist);
16685
16686   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16687                            &disconnected_dprintf, _("\
16688 Set whether dprintf continues after GDB disconnects."), _("\
16689 Show whether dprintf continues after GDB disconnects."), _("\
16690 Use this to let dprintf commands continue to hit and produce output\n\
16691 even if GDB disconnects or detaches from the target."),
16692                            NULL,
16693                            NULL,
16694                            &setlist, &showlist);
16695
16696   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16697 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16698 (target agent only) This is useful for formatted output in user-defined commands."));
16699
16700   automatic_hardware_breakpoints = 1;
16701
16702   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16703   observer_attach_thread_exit (remove_threaded_breakpoints);
16704 }