Remove duplicated xmalloc in update_dprintf_command_list
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2015 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "continuations.h"
64 #include "stack.h"
65 #include "skip.h"
66 #include "ax-gdb.h"
67 #include "dummy-frame.h"
68 #include "interps.h"
69 #include "format.h"
70
71 /* readline include files */
72 #include "readline/readline.h"
73 #include "readline/history.h"
74
75 /* readline defines this.  */
76 #undef savestring
77
78 #include "mi/mi-common.h"
79 #include "extension.h"
80
81 /* Enums for exception-handling support.  */
82 enum exception_event_kind
83 {
84   EX_EVENT_THROW,
85   EX_EVENT_RETHROW,
86   EX_EVENT_CATCH
87 };
88
89 /* Prototypes for local functions.  */
90
91 static void enable_delete_command (char *, int);
92
93 static void enable_once_command (char *, int);
94
95 static void enable_count_command (char *, int);
96
97 static void disable_command (char *, int);
98
99 static void enable_command (char *, int);
100
101 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
102                                                       void *),
103                                     void *);
104
105 static void ignore_command (char *, int);
106
107 static int breakpoint_re_set_one (void *);
108
109 static void breakpoint_re_set_default (struct breakpoint *);
110
111 static void create_sals_from_address_default (char **,
112                                               struct linespec_result *,
113                                               enum bptype, char *,
114                                               char **);
115
116 static void create_breakpoints_sal_default (struct gdbarch *,
117                                             struct linespec_result *,
118                                             char *, char *, enum bptype,
119                                             enum bpdisp, int, int,
120                                             int,
121                                             const struct breakpoint_ops *,
122                                             int, int, int, unsigned);
123
124 static void decode_linespec_default (struct breakpoint *, char **,
125                                      struct symtabs_and_lines *);
126
127 static void clear_command (char *, int);
128
129 static void catch_command (char *, int);
130
131 static int can_use_hardware_watchpoint (struct value *);
132
133 static void break_command_1 (char *, int, int);
134
135 static void mention (struct breakpoint *);
136
137 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
138                                                                enum bptype,
139                                                                const struct breakpoint_ops *);
140 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
141                                                        const struct symtab_and_line *);
142
143 /* This function is used in gdbtk sources and thus can not be made
144    static.  */
145 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
146                                        struct symtab_and_line,
147                                        enum bptype,
148                                        const struct breakpoint_ops *);
149
150 static struct breakpoint *
151   momentary_breakpoint_from_master (struct breakpoint *orig,
152                                     enum bptype type,
153                                     const struct breakpoint_ops *ops,
154                                     int loc_enabled);
155
156 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
157
158 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
159                                             CORE_ADDR bpaddr,
160                                             enum bptype bptype);
161
162 static void describe_other_breakpoints (struct gdbarch *,
163                                         struct program_space *, CORE_ADDR,
164                                         struct obj_section *, int);
165
166 static int watchpoint_locations_match (struct bp_location *loc1,
167                                        struct bp_location *loc2);
168
169 static int breakpoint_location_address_match (struct bp_location *bl,
170                                               struct address_space *aspace,
171                                               CORE_ADDR addr);
172
173 static void breakpoints_info (char *, int);
174
175 static void watchpoints_info (char *, int);
176
177 static int breakpoint_1 (char *, int, 
178                          int (*) (const struct breakpoint *));
179
180 static int breakpoint_cond_eval (void *);
181
182 static void cleanup_executing_breakpoints (void *);
183
184 static void commands_command (char *, int);
185
186 static void condition_command (char *, int);
187
188 typedef enum
189   {
190     mark_inserted,
191     mark_uninserted
192   }
193 insertion_state_t;
194
195 static int remove_breakpoint (struct bp_location *, insertion_state_t);
196 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
197
198 static enum print_stop_action print_bp_stop_message (bpstat bs);
199
200 static int watchpoint_check (void *);
201
202 static void maintenance_info_breakpoints (char *, int);
203
204 static int hw_breakpoint_used_count (void);
205
206 static int hw_watchpoint_use_count (struct breakpoint *);
207
208 static int hw_watchpoint_used_count_others (struct breakpoint *except,
209                                             enum bptype type,
210                                             int *other_type_used);
211
212 static void hbreak_command (char *, int);
213
214 static void thbreak_command (char *, int);
215
216 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
217                                     int count);
218
219 static void stop_command (char *arg, int from_tty);
220
221 static void stopin_command (char *arg, int from_tty);
222
223 static void stopat_command (char *arg, int from_tty);
224
225 static void tcatch_command (char *arg, int from_tty);
226
227 static void free_bp_location (struct bp_location *loc);
228 static void incref_bp_location (struct bp_location *loc);
229 static void decref_bp_location (struct bp_location **loc);
230
231 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
232
233 /* update_global_location_list's modes of operation wrt to whether to
234    insert locations now.  */
235 enum ugll_insert_mode
236 {
237   /* Don't insert any breakpoint locations into the inferior, only
238      remove already-inserted locations that no longer should be
239      inserted.  Functions that delete a breakpoint or breakpoints
240      should specify this mode, so that deleting a breakpoint doesn't
241      have the side effect of inserting the locations of other
242      breakpoints that are marked not-inserted, but should_be_inserted
243      returns true on them.
244
245      This behavior is useful is situations close to tear-down -- e.g.,
246      after an exec, while the target still has execution, but
247      breakpoint shadows of the previous executable image should *NOT*
248      be restored to the new image; or before detaching, where the
249      target still has execution and wants to delete breakpoints from
250      GDB's lists, and all breakpoints had already been removed from
251      the inferior.  */
252   UGLL_DONT_INSERT,
253
254   /* May insert breakpoints iff breakpoints_should_be_inserted_now
255      claims breakpoints should be inserted now.  */
256   UGLL_MAY_INSERT,
257
258   /* Insert locations now, irrespective of
259      breakpoints_should_be_inserted_now.  E.g., say all threads are
260      stopped right now, and the user did "continue".  We need to
261      insert breakpoints _before_ resuming the target, but
262      UGLL_MAY_INSERT wouldn't insert them, because
263      breakpoints_should_be_inserted_now returns false at that point,
264      as no thread is running yet.  */
265   UGLL_INSERT
266 };
267
268 static void update_global_location_list (enum ugll_insert_mode);
269
270 static void update_global_location_list_nothrow (enum ugll_insert_mode);
271
272 static int is_hardware_watchpoint (const struct breakpoint *bpt);
273
274 static void insert_breakpoint_locations (void);
275
276 static void tracepoints_info (char *, int);
277
278 static void delete_trace_command (char *, int);
279
280 static void enable_trace_command (char *, int);
281
282 static void disable_trace_command (char *, int);
283
284 static void trace_pass_command (char *, int);
285
286 static void set_tracepoint_count (int num);
287
288 static int is_masked_watchpoint (const struct breakpoint *b);
289
290 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
291
292 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
293    otherwise.  */
294
295 static int strace_marker_p (struct breakpoint *b);
296
297 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
298    that are implemented on top of software or hardware breakpoints
299    (user breakpoints, internal and momentary breakpoints, etc.).  */
300 static struct breakpoint_ops bkpt_base_breakpoint_ops;
301
302 /* Internal breakpoints class type.  */
303 static struct breakpoint_ops internal_breakpoint_ops;
304
305 /* Momentary breakpoints class type.  */
306 static struct breakpoint_ops momentary_breakpoint_ops;
307
308 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
309 static struct breakpoint_ops longjmp_breakpoint_ops;
310
311 /* The breakpoint_ops structure to be used in regular user created
312    breakpoints.  */
313 struct breakpoint_ops bkpt_breakpoint_ops;
314
315 /* Breakpoints set on probes.  */
316 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
317
318 /* Dynamic printf class type.  */
319 struct breakpoint_ops dprintf_breakpoint_ops;
320
321 /* The style in which to perform a dynamic printf.  This is a user
322    option because different output options have different tradeoffs;
323    if GDB does the printing, there is better error handling if there
324    is a problem with any of the arguments, but using an inferior
325    function lets you have special-purpose printers and sending of
326    output to the same place as compiled-in print functions.  */
327
328 static const char dprintf_style_gdb[] = "gdb";
329 static const char dprintf_style_call[] = "call";
330 static const char dprintf_style_agent[] = "agent";
331 static const char *const dprintf_style_enums[] = {
332   dprintf_style_gdb,
333   dprintf_style_call,
334   dprintf_style_agent,
335   NULL
336 };
337 static const char *dprintf_style = dprintf_style_gdb;
338
339 /* The function to use for dynamic printf if the preferred style is to
340    call into the inferior.  The value is simply a string that is
341    copied into the command, so it can be anything that GDB can
342    evaluate to a callable address, not necessarily a function name.  */
343
344 static char *dprintf_function = "";
345
346 /* The channel to use for dynamic printf if the preferred style is to
347    call into the inferior; if a nonempty string, it will be passed to
348    the call as the first argument, with the format string as the
349    second.  As with the dprintf function, this can be anything that
350    GDB knows how to evaluate, so in addition to common choices like
351    "stderr", this could be an app-specific expression like
352    "mystreams[curlogger]".  */
353
354 static char *dprintf_channel = "";
355
356 /* True if dprintf commands should continue to operate even if GDB
357    has disconnected.  */
358 static int disconnected_dprintf = 1;
359
360 /* A reference-counted struct command_line.  This lets multiple
361    breakpoints share a single command list.  */
362 struct counted_command_line
363 {
364   /* The reference count.  */
365   int refc;
366
367   /* The command list.  */
368   struct command_line *commands;
369 };
370
371 struct command_line *
372 breakpoint_commands (struct breakpoint *b)
373 {
374   return b->commands ? b->commands->commands : NULL;
375 }
376
377 /* Flag indicating that a command has proceeded the inferior past the
378    current breakpoint.  */
379
380 static int breakpoint_proceeded;
381
382 const char *
383 bpdisp_text (enum bpdisp disp)
384 {
385   /* NOTE: the following values are a part of MI protocol and
386      represent values of 'disp' field returned when inferior stops at
387      a breakpoint.  */
388   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
389
390   return bpdisps[(int) disp];
391 }
392
393 /* Prototypes for exported functions.  */
394 /* If FALSE, gdb will not use hardware support for watchpoints, even
395    if such is available.  */
396 static int can_use_hw_watchpoints;
397
398 static void
399 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
400                              struct cmd_list_element *c,
401                              const char *value)
402 {
403   fprintf_filtered (file,
404                     _("Debugger's willingness to use "
405                       "watchpoint hardware is %s.\n"),
406                     value);
407 }
408
409 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
410    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
411    for unrecognized breakpoint locations.
412    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
413 static enum auto_boolean pending_break_support;
414 static void
415 show_pending_break_support (struct ui_file *file, int from_tty,
416                             struct cmd_list_element *c,
417                             const char *value)
418 {
419   fprintf_filtered (file,
420                     _("Debugger's behavior regarding "
421                       "pending breakpoints is %s.\n"),
422                     value);
423 }
424
425 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
426    set with "break" but falling in read-only memory.
427    If 0, gdb will warn about such breakpoints, but won't automatically
428    use hardware breakpoints.  */
429 static int automatic_hardware_breakpoints;
430 static void
431 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
432                                      struct cmd_list_element *c,
433                                      const char *value)
434 {
435   fprintf_filtered (file,
436                     _("Automatic usage of hardware breakpoints is %s.\n"),
437                     value);
438 }
439
440 /* If on, GDB keeps breakpoints inserted even if the inferior is
441    stopped, and immediately inserts any new breakpoints as soon as
442    they're created.  If off (default), GDB keeps breakpoints off of
443    the target as long as possible.  That is, it delays inserting
444    breakpoints until the next resume, and removes them again when the
445    target fully stops.  This is a bit safer in case GDB crashes while
446    processing user input.  */
447 static int always_inserted_mode = 0;
448
449 static void
450 show_always_inserted_mode (struct ui_file *file, int from_tty,
451                      struct cmd_list_element *c, const char *value)
452 {
453   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
454                     value);
455 }
456
457 /* See breakpoint.h.  */
458
459 int
460 breakpoints_should_be_inserted_now (void)
461 {
462   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
463     {
464       /* If breakpoints are global, they should be inserted even if no
465          thread under gdb's control is running, or even if there are
466          no threads under GDB's control yet.  */
467       return 1;
468     }
469   else if (target_has_execution)
470     {
471       if (always_inserted_mode)
472         {
473           /* The user wants breakpoints inserted even if all threads
474              are stopped.  */
475           return 1;
476         }
477
478       if (threads_are_executing ())
479         return 1;
480     }
481   return 0;
482 }
483
484 static const char condition_evaluation_both[] = "host or target";
485
486 /* Modes for breakpoint condition evaluation.  */
487 static const char condition_evaluation_auto[] = "auto";
488 static const char condition_evaluation_host[] = "host";
489 static const char condition_evaluation_target[] = "target";
490 static const char *const condition_evaluation_enums[] = {
491   condition_evaluation_auto,
492   condition_evaluation_host,
493   condition_evaluation_target,
494   NULL
495 };
496
497 /* Global that holds the current mode for breakpoint condition evaluation.  */
498 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
499
500 /* Global that we use to display information to the user (gets its value from
501    condition_evaluation_mode_1.  */
502 static const char *condition_evaluation_mode = condition_evaluation_auto;
503
504 /* Translate a condition evaluation mode MODE into either "host"
505    or "target".  This is used mostly to translate from "auto" to the
506    real setting that is being used.  It returns the translated
507    evaluation mode.  */
508
509 static const char *
510 translate_condition_evaluation_mode (const char *mode)
511 {
512   if (mode == condition_evaluation_auto)
513     {
514       if (target_supports_evaluation_of_breakpoint_conditions ())
515         return condition_evaluation_target;
516       else
517         return condition_evaluation_host;
518     }
519   else
520     return mode;
521 }
522
523 /* Discovers what condition_evaluation_auto translates to.  */
524
525 static const char *
526 breakpoint_condition_evaluation_mode (void)
527 {
528   return translate_condition_evaluation_mode (condition_evaluation_mode);
529 }
530
531 /* Return true if GDB should evaluate breakpoint conditions or false
532    otherwise.  */
533
534 static int
535 gdb_evaluates_breakpoint_condition_p (void)
536 {
537   const char *mode = breakpoint_condition_evaluation_mode ();
538
539   return (mode == condition_evaluation_host);
540 }
541
542 void _initialize_breakpoint (void);
543
544 /* Are we executing breakpoint commands?  */
545 static int executing_breakpoint_commands;
546
547 /* Are overlay event breakpoints enabled? */
548 static int overlay_events_enabled;
549
550 /* See description in breakpoint.h. */
551 int target_exact_watchpoints = 0;
552
553 /* Walk the following statement or block through all breakpoints.
554    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
555    current breakpoint.  */
556
557 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
558
559 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
560         for (B = breakpoint_chain;      \
561              B ? (TMP=B->next, 1): 0;   \
562              B = TMP)
563
564 /* Similar iterator for the low-level breakpoints.  SAFE variant is
565    not provided so update_global_location_list must not be called
566    while executing the block of ALL_BP_LOCATIONS.  */
567
568 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
569         for (BP_TMP = bp_location;                                      \
570              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
571              BP_TMP++)
572
573 /* Iterates through locations with address ADDRESS for the currently selected
574    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
575    to where the loop should start from.
576    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
577    appropriate location to start with.  */
578
579 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
580         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
581              BP_LOCP_TMP = BP_LOCP_START;                               \
582              BP_LOCP_START                                              \
583              && (BP_LOCP_TMP < bp_location + bp_location_count          \
584              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
585              BP_LOCP_TMP++)
586
587 /* Iterator for tracepoints only.  */
588
589 #define ALL_TRACEPOINTS(B)  \
590   for (B = breakpoint_chain; B; B = B->next)  \
591     if (is_tracepoint (B))
592
593 /* Chains of all breakpoints defined.  */
594
595 struct breakpoint *breakpoint_chain;
596
597 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
598
599 static struct bp_location **bp_location;
600
601 /* Number of elements of BP_LOCATION.  */
602
603 static unsigned bp_location_count;
604
605 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
606    ADDRESS for the current elements of BP_LOCATION which get a valid
607    result from bp_location_has_shadow.  You can use it for roughly
608    limiting the subrange of BP_LOCATION to scan for shadow bytes for
609    an address you need to read.  */
610
611 static CORE_ADDR bp_location_placed_address_before_address_max;
612
613 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
614    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
615    BP_LOCATION which get a valid result from bp_location_has_shadow.
616    You can use it for roughly limiting the subrange of BP_LOCATION to
617    scan for shadow bytes for an address you need to read.  */
618
619 static CORE_ADDR bp_location_shadow_len_after_address_max;
620
621 /* The locations that no longer correspond to any breakpoint, unlinked
622    from bp_location array, but for which a hit may still be reported
623    by a target.  */
624 VEC(bp_location_p) *moribund_locations = NULL;
625
626 /* Number of last breakpoint made.  */
627
628 static int breakpoint_count;
629
630 /* The value of `breakpoint_count' before the last command that
631    created breakpoints.  If the last (break-like) command created more
632    than one breakpoint, then the difference between BREAKPOINT_COUNT
633    and PREV_BREAKPOINT_COUNT is more than one.  */
634 static int prev_breakpoint_count;
635
636 /* Number of last tracepoint made.  */
637
638 static int tracepoint_count;
639
640 static struct cmd_list_element *breakpoint_set_cmdlist;
641 static struct cmd_list_element *breakpoint_show_cmdlist;
642 struct cmd_list_element *save_cmdlist;
643
644 /* See declaration at breakpoint.h.  */
645
646 struct breakpoint *
647 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
648                     void *user_data)
649 {
650   struct breakpoint *b = NULL;
651
652   ALL_BREAKPOINTS (b)
653     {
654       if (func (b, user_data) != 0)
655         break;
656     }
657
658   return b;
659 }
660
661 /* Return whether a breakpoint is an active enabled breakpoint.  */
662 static int
663 breakpoint_enabled (struct breakpoint *b)
664 {
665   return (b->enable_state == bp_enabled);
666 }
667
668 /* Set breakpoint count to NUM.  */
669
670 static void
671 set_breakpoint_count (int num)
672 {
673   prev_breakpoint_count = breakpoint_count;
674   breakpoint_count = num;
675   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
676 }
677
678 /* Used by `start_rbreak_breakpoints' below, to record the current
679    breakpoint count before "rbreak" creates any breakpoint.  */
680 static int rbreak_start_breakpoint_count;
681
682 /* Called at the start an "rbreak" command to record the first
683    breakpoint made.  */
684
685 void
686 start_rbreak_breakpoints (void)
687 {
688   rbreak_start_breakpoint_count = breakpoint_count;
689 }
690
691 /* Called at the end of an "rbreak" command to record the last
692    breakpoint made.  */
693
694 void
695 end_rbreak_breakpoints (void)
696 {
697   prev_breakpoint_count = rbreak_start_breakpoint_count;
698 }
699
700 /* Used in run_command to zero the hit count when a new run starts.  */
701
702 void
703 clear_breakpoint_hit_counts (void)
704 {
705   struct breakpoint *b;
706
707   ALL_BREAKPOINTS (b)
708     b->hit_count = 0;
709 }
710
711 /* Allocate a new counted_command_line with reference count of 1.
712    The new structure owns COMMANDS.  */
713
714 static struct counted_command_line *
715 alloc_counted_command_line (struct command_line *commands)
716 {
717   struct counted_command_line *result
718     = xmalloc (sizeof (struct counted_command_line));
719
720   result->refc = 1;
721   result->commands = commands;
722   return result;
723 }
724
725 /* Increment reference count.  This does nothing if CMD is NULL.  */
726
727 static void
728 incref_counted_command_line (struct counted_command_line *cmd)
729 {
730   if (cmd)
731     ++cmd->refc;
732 }
733
734 /* Decrement reference count.  If the reference count reaches 0,
735    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
736    nothing if *CMDP is NULL.  */
737
738 static void
739 decref_counted_command_line (struct counted_command_line **cmdp)
740 {
741   if (*cmdp)
742     {
743       if (--(*cmdp)->refc == 0)
744         {
745           free_command_lines (&(*cmdp)->commands);
746           xfree (*cmdp);
747         }
748       *cmdp = NULL;
749     }
750 }
751
752 /* A cleanup function that calls decref_counted_command_line.  */
753
754 static void
755 do_cleanup_counted_command_line (void *arg)
756 {
757   decref_counted_command_line (arg);
758 }
759
760 /* Create a cleanup that calls decref_counted_command_line on the
761    argument.  */
762
763 static struct cleanup *
764 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
765 {
766   return make_cleanup (do_cleanup_counted_command_line, cmdp);
767 }
768
769 \f
770 /* Return the breakpoint with the specified number, or NULL
771    if the number does not refer to an existing breakpoint.  */
772
773 struct breakpoint *
774 get_breakpoint (int num)
775 {
776   struct breakpoint *b;
777
778   ALL_BREAKPOINTS (b)
779     if (b->number == num)
780       return b;
781   
782   return NULL;
783 }
784
785 \f
786
787 /* Mark locations as "conditions have changed" in case the target supports
788    evaluating conditions on its side.  */
789
790 static void
791 mark_breakpoint_modified (struct breakpoint *b)
792 {
793   struct bp_location *loc;
794
795   /* This is only meaningful if the target is
796      evaluating conditions and if the user has
797      opted for condition evaluation on the target's
798      side.  */
799   if (gdb_evaluates_breakpoint_condition_p ()
800       || !target_supports_evaluation_of_breakpoint_conditions ())
801     return;
802
803   if (!is_breakpoint (b))
804     return;
805
806   for (loc = b->loc; loc; loc = loc->next)
807     loc->condition_changed = condition_modified;
808 }
809
810 /* Mark location as "conditions have changed" in case the target supports
811    evaluating conditions on its side.  */
812
813 static void
814 mark_breakpoint_location_modified (struct bp_location *loc)
815 {
816   /* This is only meaningful if the target is
817      evaluating conditions and if the user has
818      opted for condition evaluation on the target's
819      side.  */
820   if (gdb_evaluates_breakpoint_condition_p ()
821       || !target_supports_evaluation_of_breakpoint_conditions ())
822
823     return;
824
825   if (!is_breakpoint (loc->owner))
826     return;
827
828   loc->condition_changed = condition_modified;
829 }
830
831 /* Sets the condition-evaluation mode using the static global
832    condition_evaluation_mode.  */
833
834 static void
835 set_condition_evaluation_mode (char *args, int from_tty,
836                                struct cmd_list_element *c)
837 {
838   const char *old_mode, *new_mode;
839
840   if ((condition_evaluation_mode_1 == condition_evaluation_target)
841       && !target_supports_evaluation_of_breakpoint_conditions ())
842     {
843       condition_evaluation_mode_1 = condition_evaluation_mode;
844       warning (_("Target does not support breakpoint condition evaluation.\n"
845                  "Using host evaluation mode instead."));
846       return;
847     }
848
849   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
850   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
851
852   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
853      settings was "auto".  */
854   condition_evaluation_mode = condition_evaluation_mode_1;
855
856   /* Only update the mode if the user picked a different one.  */
857   if (new_mode != old_mode)
858     {
859       struct bp_location *loc, **loc_tmp;
860       /* If the user switched to a different evaluation mode, we
861          need to synch the changes with the target as follows:
862
863          "host" -> "target": Send all (valid) conditions to the target.
864          "target" -> "host": Remove all the conditions from the target.
865       */
866
867       if (new_mode == condition_evaluation_target)
868         {
869           /* Mark everything modified and synch conditions with the
870              target.  */
871           ALL_BP_LOCATIONS (loc, loc_tmp)
872             mark_breakpoint_location_modified (loc);
873         }
874       else
875         {
876           /* Manually mark non-duplicate locations to synch conditions
877              with the target.  We do this to remove all the conditions the
878              target knows about.  */
879           ALL_BP_LOCATIONS (loc, loc_tmp)
880             if (is_breakpoint (loc->owner) && loc->inserted)
881               loc->needs_update = 1;
882         }
883
884       /* Do the update.  */
885       update_global_location_list (UGLL_MAY_INSERT);
886     }
887
888   return;
889 }
890
891 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
892    what "auto" is translating to.  */
893
894 static void
895 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
896                                 struct cmd_list_element *c, const char *value)
897 {
898   if (condition_evaluation_mode == condition_evaluation_auto)
899     fprintf_filtered (file,
900                       _("Breakpoint condition evaluation "
901                         "mode is %s (currently %s).\n"),
902                       value,
903                       breakpoint_condition_evaluation_mode ());
904   else
905     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
906                       value);
907 }
908
909 /* A comparison function for bp_location AP and BP that is used by
910    bsearch.  This comparison function only cares about addresses, unlike
911    the more general bp_location_compare function.  */
912
913 static int
914 bp_location_compare_addrs (const void *ap, const void *bp)
915 {
916   struct bp_location *a = *(void **) ap;
917   struct bp_location *b = *(void **) bp;
918
919   if (a->address == b->address)
920     return 0;
921   else
922     return ((a->address > b->address) - (a->address < b->address));
923 }
924
925 /* Helper function to skip all bp_locations with addresses
926    less than ADDRESS.  It returns the first bp_location that
927    is greater than or equal to ADDRESS.  If none is found, just
928    return NULL.  */
929
930 static struct bp_location **
931 get_first_locp_gte_addr (CORE_ADDR address)
932 {
933   struct bp_location dummy_loc;
934   struct bp_location *dummy_locp = &dummy_loc;
935   struct bp_location **locp_found = NULL;
936
937   /* Initialize the dummy location's address field.  */
938   memset (&dummy_loc, 0, sizeof (struct bp_location));
939   dummy_loc.address = address;
940
941   /* Find a close match to the first location at ADDRESS.  */
942   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
943                         sizeof (struct bp_location **),
944                         bp_location_compare_addrs);
945
946   /* Nothing was found, nothing left to do.  */
947   if (locp_found == NULL)
948     return NULL;
949
950   /* We may have found a location that is at ADDRESS but is not the first in the
951      location's list.  Go backwards (if possible) and locate the first one.  */
952   while ((locp_found - 1) >= bp_location
953          && (*(locp_found - 1))->address == address)
954     locp_found--;
955
956   return locp_found;
957 }
958
959 void
960 set_breakpoint_condition (struct breakpoint *b, const char *exp,
961                           int from_tty)
962 {
963   xfree (b->cond_string);
964   b->cond_string = NULL;
965
966   if (is_watchpoint (b))
967     {
968       struct watchpoint *w = (struct watchpoint *) b;
969
970       xfree (w->cond_exp);
971       w->cond_exp = NULL;
972     }
973   else
974     {
975       struct bp_location *loc;
976
977       for (loc = b->loc; loc; loc = loc->next)
978         {
979           xfree (loc->cond);
980           loc->cond = NULL;
981
982           /* No need to free the condition agent expression
983              bytecode (if we have one).  We will handle this
984              when we go through update_global_location_list.  */
985         }
986     }
987
988   if (*exp == 0)
989     {
990       if (from_tty)
991         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
992     }
993   else
994     {
995       const char *arg = exp;
996
997       /* I don't know if it matters whether this is the string the user
998          typed in or the decompiled expression.  */
999       b->cond_string = xstrdup (arg);
1000       b->condition_not_parsed = 0;
1001
1002       if (is_watchpoint (b))
1003         {
1004           struct watchpoint *w = (struct watchpoint *) b;
1005
1006           innermost_block = NULL;
1007           arg = exp;
1008           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1009           if (*arg)
1010             error (_("Junk at end of expression"));
1011           w->cond_exp_valid_block = innermost_block;
1012         }
1013       else
1014         {
1015           struct bp_location *loc;
1016
1017           for (loc = b->loc; loc; loc = loc->next)
1018             {
1019               arg = exp;
1020               loc->cond =
1021                 parse_exp_1 (&arg, loc->address,
1022                              block_for_pc (loc->address), 0);
1023               if (*arg)
1024                 error (_("Junk at end of expression"));
1025             }
1026         }
1027     }
1028   mark_breakpoint_modified (b);
1029
1030   observer_notify_breakpoint_modified (b);
1031 }
1032
1033 /* Completion for the "condition" command.  */
1034
1035 static VEC (char_ptr) *
1036 condition_completer (struct cmd_list_element *cmd,
1037                      const char *text, const char *word)
1038 {
1039   const char *space;
1040
1041   text = skip_spaces_const (text);
1042   space = skip_to_space_const (text);
1043   if (*space == '\0')
1044     {
1045       int len;
1046       struct breakpoint *b;
1047       VEC (char_ptr) *result = NULL;
1048
1049       if (text[0] == '$')
1050         {
1051           /* We don't support completion of history indices.  */
1052           if (isdigit (text[1]))
1053             return NULL;
1054           return complete_internalvar (&text[1]);
1055         }
1056
1057       /* We're completing the breakpoint number.  */
1058       len = strlen (text);
1059
1060       ALL_BREAKPOINTS (b)
1061         {
1062           char number[50];
1063
1064           xsnprintf (number, sizeof (number), "%d", b->number);
1065
1066           if (strncmp (number, text, len) == 0)
1067             VEC_safe_push (char_ptr, result, xstrdup (number));
1068         }
1069
1070       return result;
1071     }
1072
1073   /* We're completing the expression part.  */
1074   text = skip_spaces_const (space);
1075   return expression_completer (cmd, text, word);
1076 }
1077
1078 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1079
1080 static void
1081 condition_command (char *arg, int from_tty)
1082 {
1083   struct breakpoint *b;
1084   char *p;
1085   int bnum;
1086
1087   if (arg == 0)
1088     error_no_arg (_("breakpoint number"));
1089
1090   p = arg;
1091   bnum = get_number (&p);
1092   if (bnum == 0)
1093     error (_("Bad breakpoint argument: '%s'"), arg);
1094
1095   ALL_BREAKPOINTS (b)
1096     if (b->number == bnum)
1097       {
1098         /* Check if this breakpoint has a "stop" method implemented in an
1099            extension language.  This method and conditions entered into GDB
1100            from the CLI are mutually exclusive.  */
1101         const struct extension_language_defn *extlang
1102           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1103
1104         if (extlang != NULL)
1105           {
1106             error (_("Only one stop condition allowed.  There is currently"
1107                      " a %s stop condition defined for this breakpoint."),
1108                    ext_lang_capitalized_name (extlang));
1109           }
1110         set_breakpoint_condition (b, p, from_tty);
1111
1112         if (is_breakpoint (b))
1113           update_global_location_list (UGLL_MAY_INSERT);
1114
1115         return;
1116       }
1117
1118   error (_("No breakpoint number %d."), bnum);
1119 }
1120
1121 /* Check that COMMAND do not contain commands that are suitable
1122    only for tracepoints and not suitable for ordinary breakpoints.
1123    Throw if any such commands is found.  */
1124
1125 static void
1126 check_no_tracepoint_commands (struct command_line *commands)
1127 {
1128   struct command_line *c;
1129
1130   for (c = commands; c; c = c->next)
1131     {
1132       int i;
1133
1134       if (c->control_type == while_stepping_control)
1135         error (_("The 'while-stepping' command can "
1136                  "only be used for tracepoints"));
1137
1138       for (i = 0; i < c->body_count; ++i)
1139         check_no_tracepoint_commands ((c->body_list)[i]);
1140
1141       /* Not that command parsing removes leading whitespace and comment
1142          lines and also empty lines.  So, we only need to check for
1143          command directly.  */
1144       if (strstr (c->line, "collect ") == c->line)
1145         error (_("The 'collect' command can only be used for tracepoints"));
1146
1147       if (strstr (c->line, "teval ") == c->line)
1148         error (_("The 'teval' command can only be used for tracepoints"));
1149     }
1150 }
1151
1152 /* Encapsulate tests for different types of tracepoints.  */
1153
1154 static int
1155 is_tracepoint_type (enum bptype type)
1156 {
1157   return (type == bp_tracepoint
1158           || type == bp_fast_tracepoint
1159           || type == bp_static_tracepoint);
1160 }
1161
1162 int
1163 is_tracepoint (const struct breakpoint *b)
1164 {
1165   return is_tracepoint_type (b->type);
1166 }
1167
1168 /* A helper function that validates that COMMANDS are valid for a
1169    breakpoint.  This function will throw an exception if a problem is
1170    found.  */
1171
1172 static void
1173 validate_commands_for_breakpoint (struct breakpoint *b,
1174                                   struct command_line *commands)
1175 {
1176   if (is_tracepoint (b))
1177     {
1178       struct tracepoint *t = (struct tracepoint *) b;
1179       struct command_line *c;
1180       struct command_line *while_stepping = 0;
1181
1182       /* Reset the while-stepping step count.  The previous commands
1183          might have included a while-stepping action, while the new
1184          ones might not.  */
1185       t->step_count = 0;
1186
1187       /* We need to verify that each top-level element of commands is
1188          valid for tracepoints, that there's at most one
1189          while-stepping element, and that the while-stepping's body
1190          has valid tracing commands excluding nested while-stepping.
1191          We also need to validate the tracepoint action line in the
1192          context of the tracepoint --- validate_actionline actually
1193          has side effects, like setting the tracepoint's
1194          while-stepping STEP_COUNT, in addition to checking if the
1195          collect/teval actions parse and make sense in the
1196          tracepoint's context.  */
1197       for (c = commands; c; c = c->next)
1198         {
1199           if (c->control_type == while_stepping_control)
1200             {
1201               if (b->type == bp_fast_tracepoint)
1202                 error (_("The 'while-stepping' command "
1203                          "cannot be used for fast tracepoint"));
1204               else if (b->type == bp_static_tracepoint)
1205                 error (_("The 'while-stepping' command "
1206                          "cannot be used for static tracepoint"));
1207
1208               if (while_stepping)
1209                 error (_("The 'while-stepping' command "
1210                          "can be used only once"));
1211               else
1212                 while_stepping = c;
1213             }
1214
1215           validate_actionline (c->line, b);
1216         }
1217       if (while_stepping)
1218         {
1219           struct command_line *c2;
1220
1221           gdb_assert (while_stepping->body_count == 1);
1222           c2 = while_stepping->body_list[0];
1223           for (; c2; c2 = c2->next)
1224             {
1225               if (c2->control_type == while_stepping_control)
1226                 error (_("The 'while-stepping' command cannot be nested"));
1227             }
1228         }
1229     }
1230   else
1231     {
1232       check_no_tracepoint_commands (commands);
1233     }
1234 }
1235
1236 /* Return a vector of all the static tracepoints set at ADDR.  The
1237    caller is responsible for releasing the vector.  */
1238
1239 VEC(breakpoint_p) *
1240 static_tracepoints_here (CORE_ADDR addr)
1241 {
1242   struct breakpoint *b;
1243   VEC(breakpoint_p) *found = 0;
1244   struct bp_location *loc;
1245
1246   ALL_BREAKPOINTS (b)
1247     if (b->type == bp_static_tracepoint)
1248       {
1249         for (loc = b->loc; loc; loc = loc->next)
1250           if (loc->address == addr)
1251             VEC_safe_push(breakpoint_p, found, b);
1252       }
1253
1254   return found;
1255 }
1256
1257 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1258    validate that only allowed commands are included.  */
1259
1260 void
1261 breakpoint_set_commands (struct breakpoint *b, 
1262                          struct command_line *commands)
1263 {
1264   validate_commands_for_breakpoint (b, commands);
1265
1266   decref_counted_command_line (&b->commands);
1267   b->commands = alloc_counted_command_line (commands);
1268   observer_notify_breakpoint_modified (b);
1269 }
1270
1271 /* Set the internal `silent' flag on the breakpoint.  Note that this
1272    is not the same as the "silent" that may appear in the breakpoint's
1273    commands.  */
1274
1275 void
1276 breakpoint_set_silent (struct breakpoint *b, int silent)
1277 {
1278   int old_silent = b->silent;
1279
1280   b->silent = silent;
1281   if (old_silent != silent)
1282     observer_notify_breakpoint_modified (b);
1283 }
1284
1285 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1286    breakpoint work for any thread.  */
1287
1288 void
1289 breakpoint_set_thread (struct breakpoint *b, int thread)
1290 {
1291   int old_thread = b->thread;
1292
1293   b->thread = thread;
1294   if (old_thread != thread)
1295     observer_notify_breakpoint_modified (b);
1296 }
1297
1298 /* Set the task for this breakpoint.  If TASK is 0, make the
1299    breakpoint work for any task.  */
1300
1301 void
1302 breakpoint_set_task (struct breakpoint *b, int task)
1303 {
1304   int old_task = b->task;
1305
1306   b->task = task;
1307   if (old_task != task)
1308     observer_notify_breakpoint_modified (b);
1309 }
1310
1311 void
1312 check_tracepoint_command (char *line, void *closure)
1313 {
1314   struct breakpoint *b = closure;
1315
1316   validate_actionline (line, b);
1317 }
1318
1319 /* A structure used to pass information through
1320    map_breakpoint_numbers.  */
1321
1322 struct commands_info
1323 {
1324   /* True if the command was typed at a tty.  */
1325   int from_tty;
1326
1327   /* The breakpoint range spec.  */
1328   char *arg;
1329
1330   /* Non-NULL if the body of the commands are being read from this
1331      already-parsed command.  */
1332   struct command_line *control;
1333
1334   /* The command lines read from the user, or NULL if they have not
1335      yet been read.  */
1336   struct counted_command_line *cmd;
1337 };
1338
1339 /* A callback for map_breakpoint_numbers that sets the commands for
1340    commands_command.  */
1341
1342 static void
1343 do_map_commands_command (struct breakpoint *b, void *data)
1344 {
1345   struct commands_info *info = data;
1346
1347   if (info->cmd == NULL)
1348     {
1349       struct command_line *l;
1350
1351       if (info->control != NULL)
1352         l = copy_command_lines (info->control->body_list[0]);
1353       else
1354         {
1355           struct cleanup *old_chain;
1356           char *str;
1357
1358           str = xstrprintf (_("Type commands for breakpoint(s) "
1359                               "%s, one per line."),
1360                             info->arg);
1361
1362           old_chain = make_cleanup (xfree, str);
1363
1364           l = read_command_lines (str,
1365                                   info->from_tty, 1,
1366                                   (is_tracepoint (b)
1367                                    ? check_tracepoint_command : 0),
1368                                   b);
1369
1370           do_cleanups (old_chain);
1371         }
1372
1373       info->cmd = alloc_counted_command_line (l);
1374     }
1375
1376   /* If a breakpoint was on the list more than once, we don't need to
1377      do anything.  */
1378   if (b->commands != info->cmd)
1379     {
1380       validate_commands_for_breakpoint (b, info->cmd->commands);
1381       incref_counted_command_line (info->cmd);
1382       decref_counted_command_line (&b->commands);
1383       b->commands = info->cmd;
1384       observer_notify_breakpoint_modified (b);
1385     }
1386 }
1387
1388 static void
1389 commands_command_1 (char *arg, int from_tty, 
1390                     struct command_line *control)
1391 {
1392   struct cleanup *cleanups;
1393   struct commands_info info;
1394
1395   info.from_tty = from_tty;
1396   info.control = control;
1397   info.cmd = NULL;
1398   /* If we read command lines from the user, then `info' will hold an
1399      extra reference to the commands that we must clean up.  */
1400   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1401
1402   if (arg == NULL || !*arg)
1403     {
1404       if (breakpoint_count - prev_breakpoint_count > 1)
1405         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1406                           breakpoint_count);
1407       else if (breakpoint_count > 0)
1408         arg = xstrprintf ("%d", breakpoint_count);
1409       else
1410         {
1411           /* So that we don't try to free the incoming non-NULL
1412              argument in the cleanup below.  Mapping breakpoint
1413              numbers will fail in this case.  */
1414           arg = NULL;
1415         }
1416     }
1417   else
1418     /* The command loop has some static state, so we need to preserve
1419        our argument.  */
1420     arg = xstrdup (arg);
1421
1422   if (arg != NULL)
1423     make_cleanup (xfree, arg);
1424
1425   info.arg = arg;
1426
1427   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1428
1429   if (info.cmd == NULL)
1430     error (_("No breakpoints specified."));
1431
1432   do_cleanups (cleanups);
1433 }
1434
1435 static void
1436 commands_command (char *arg, int from_tty)
1437 {
1438   commands_command_1 (arg, from_tty, NULL);
1439 }
1440
1441 /* Like commands_command, but instead of reading the commands from
1442    input stream, takes them from an already parsed command structure.
1443
1444    This is used by cli-script.c to DTRT with breakpoint commands
1445    that are part of if and while bodies.  */
1446 enum command_control_type
1447 commands_from_control_command (char *arg, struct command_line *cmd)
1448 {
1449   commands_command_1 (arg, 0, cmd);
1450   return simple_control;
1451 }
1452
1453 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1454
1455 static int
1456 bp_location_has_shadow (struct bp_location *bl)
1457 {
1458   if (bl->loc_type != bp_loc_software_breakpoint)
1459     return 0;
1460   if (!bl->inserted)
1461     return 0;
1462   if (bl->target_info.shadow_len == 0)
1463     /* BL isn't valid, or doesn't shadow memory.  */
1464     return 0;
1465   return 1;
1466 }
1467
1468 /* Update BUF, which is LEN bytes read from the target address
1469    MEMADDR, by replacing a memory breakpoint with its shadowed
1470    contents.
1471
1472    If READBUF is not NULL, this buffer must not overlap with the of
1473    the breakpoint location's shadow_contents buffer.  Otherwise, a
1474    failed assertion internal error will be raised.  */
1475
1476 static void
1477 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1478                             const gdb_byte *writebuf_org,
1479                             ULONGEST memaddr, LONGEST len,
1480                             struct bp_target_info *target_info,
1481                             struct gdbarch *gdbarch)
1482 {
1483   /* Now do full processing of the found relevant range of elements.  */
1484   CORE_ADDR bp_addr = 0;
1485   int bp_size = 0;
1486   int bptoffset = 0;
1487
1488   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1489                                  current_program_space->aspace, 0))
1490     {
1491       /* The breakpoint is inserted in a different address space.  */
1492       return;
1493     }
1494
1495   /* Addresses and length of the part of the breakpoint that
1496      we need to copy.  */
1497   bp_addr = target_info->placed_address;
1498   bp_size = target_info->shadow_len;
1499
1500   if (bp_addr + bp_size <= memaddr)
1501     {
1502       /* The breakpoint is entirely before the chunk of memory we are
1503          reading.  */
1504       return;
1505     }
1506
1507   if (bp_addr >= memaddr + len)
1508     {
1509       /* The breakpoint is entirely after the chunk of memory we are
1510          reading.  */
1511       return;
1512     }
1513
1514   /* Offset within shadow_contents.  */
1515   if (bp_addr < memaddr)
1516     {
1517       /* Only copy the second part of the breakpoint.  */
1518       bp_size -= memaddr - bp_addr;
1519       bptoffset = memaddr - bp_addr;
1520       bp_addr = memaddr;
1521     }
1522
1523   if (bp_addr + bp_size > memaddr + len)
1524     {
1525       /* Only copy the first part of the breakpoint.  */
1526       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1527     }
1528
1529   if (readbuf != NULL)
1530     {
1531       /* Verify that the readbuf buffer does not overlap with the
1532          shadow_contents buffer.  */
1533       gdb_assert (target_info->shadow_contents >= readbuf + len
1534                   || readbuf >= (target_info->shadow_contents
1535                                  + target_info->shadow_len));
1536
1537       /* Update the read buffer with this inserted breakpoint's
1538          shadow.  */
1539       memcpy (readbuf + bp_addr - memaddr,
1540               target_info->shadow_contents + bptoffset, bp_size);
1541     }
1542   else
1543     {
1544       const unsigned char *bp;
1545       CORE_ADDR addr = target_info->reqstd_address;
1546       int placed_size;
1547
1548       /* Update the shadow with what we want to write to memory.  */
1549       memcpy (target_info->shadow_contents + bptoffset,
1550               writebuf_org + bp_addr - memaddr, bp_size);
1551
1552       /* Determine appropriate breakpoint contents and size for this
1553          address.  */
1554       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1555
1556       /* Update the final write buffer with this inserted
1557          breakpoint's INSN.  */
1558       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1559     }
1560 }
1561
1562 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1563    by replacing any memory breakpoints with their shadowed contents.
1564
1565    If READBUF is not NULL, this buffer must not overlap with any of
1566    the breakpoint location's shadow_contents buffers.  Otherwise,
1567    a failed assertion internal error will be raised.
1568
1569    The range of shadowed area by each bp_location is:
1570      bl->address - bp_location_placed_address_before_address_max
1571      up to bl->address + bp_location_shadow_len_after_address_max
1572    The range we were requested to resolve shadows for is:
1573      memaddr ... memaddr + len
1574    Thus the safe cutoff boundaries for performance optimization are
1575      memaddr + len <= (bl->address
1576                        - bp_location_placed_address_before_address_max)
1577    and:
1578      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1579
1580 void
1581 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1582                         const gdb_byte *writebuf_org,
1583                         ULONGEST memaddr, LONGEST len)
1584 {
1585   /* Left boundary, right boundary and median element of our binary
1586      search.  */
1587   unsigned bc_l, bc_r, bc;
1588   size_t i;
1589
1590   /* Find BC_L which is a leftmost element which may affect BUF
1591      content.  It is safe to report lower value but a failure to
1592      report higher one.  */
1593
1594   bc_l = 0;
1595   bc_r = bp_location_count;
1596   while (bc_l + 1 < bc_r)
1597     {
1598       struct bp_location *bl;
1599
1600       bc = (bc_l + bc_r) / 2;
1601       bl = bp_location[bc];
1602
1603       /* Check first BL->ADDRESS will not overflow due to the added
1604          constant.  Then advance the left boundary only if we are sure
1605          the BC element can in no way affect the BUF content (MEMADDR
1606          to MEMADDR + LEN range).
1607
1608          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1609          offset so that we cannot miss a breakpoint with its shadow
1610          range tail still reaching MEMADDR.  */
1611
1612       if ((bl->address + bp_location_shadow_len_after_address_max
1613            >= bl->address)
1614           && (bl->address + bp_location_shadow_len_after_address_max
1615               <= memaddr))
1616         bc_l = bc;
1617       else
1618         bc_r = bc;
1619     }
1620
1621   /* Due to the binary search above, we need to make sure we pick the
1622      first location that's at BC_L's address.  E.g., if there are
1623      multiple locations at the same address, BC_L may end up pointing
1624      at a duplicate location, and miss the "master"/"inserted"
1625      location.  Say, given locations L1, L2 and L3 at addresses A and
1626      B:
1627
1628       L1@A, L2@A, L3@B, ...
1629
1630      BC_L could end up pointing at location L2, while the "master"
1631      location could be L1.  Since the `loc->inserted' flag is only set
1632      on "master" locations, we'd forget to restore the shadow of L1
1633      and L2.  */
1634   while (bc_l > 0
1635          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1636     bc_l--;
1637
1638   /* Now do full processing of the found relevant range of elements.  */
1639
1640   for (bc = bc_l; bc < bp_location_count; bc++)
1641   {
1642     struct bp_location *bl = bp_location[bc];
1643     CORE_ADDR bp_addr = 0;
1644     int bp_size = 0;
1645     int bptoffset = 0;
1646
1647     /* bp_location array has BL->OWNER always non-NULL.  */
1648     if (bl->owner->type == bp_none)
1649       warning (_("reading through apparently deleted breakpoint #%d?"),
1650                bl->owner->number);
1651
1652     /* Performance optimization: any further element can no longer affect BUF
1653        content.  */
1654
1655     if (bl->address >= bp_location_placed_address_before_address_max
1656         && memaddr + len <= (bl->address
1657                              - bp_location_placed_address_before_address_max))
1658       break;
1659
1660     if (!bp_location_has_shadow (bl))
1661       continue;
1662
1663     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1664                                 memaddr, len, &bl->target_info, bl->gdbarch);
1665   }
1666 }
1667
1668 \f
1669
1670 /* Return true if BPT is either a software breakpoint or a hardware
1671    breakpoint.  */
1672
1673 int
1674 is_breakpoint (const struct breakpoint *bpt)
1675 {
1676   return (bpt->type == bp_breakpoint
1677           || bpt->type == bp_hardware_breakpoint
1678           || bpt->type == bp_dprintf);
1679 }
1680
1681 /* Return true if BPT is of any hardware watchpoint kind.  */
1682
1683 static int
1684 is_hardware_watchpoint (const struct breakpoint *bpt)
1685 {
1686   return (bpt->type == bp_hardware_watchpoint
1687           || bpt->type == bp_read_watchpoint
1688           || bpt->type == bp_access_watchpoint);
1689 }
1690
1691 /* Return true if BPT is of any watchpoint kind, hardware or
1692    software.  */
1693
1694 int
1695 is_watchpoint (const struct breakpoint *bpt)
1696 {
1697   return (is_hardware_watchpoint (bpt)
1698           || bpt->type == bp_watchpoint);
1699 }
1700
1701 /* Returns true if the current thread and its running state are safe
1702    to evaluate or update watchpoint B.  Watchpoints on local
1703    expressions need to be evaluated in the context of the thread that
1704    was current when the watchpoint was created, and, that thread needs
1705    to be stopped to be able to select the correct frame context.
1706    Watchpoints on global expressions can be evaluated on any thread,
1707    and in any state.  It is presently left to the target allowing
1708    memory accesses when threads are running.  */
1709
1710 static int
1711 watchpoint_in_thread_scope (struct watchpoint *b)
1712 {
1713   return (b->base.pspace == current_program_space
1714           && (ptid_equal (b->watchpoint_thread, null_ptid)
1715               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1716                   && !is_executing (inferior_ptid))));
1717 }
1718
1719 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1720    associated bp_watchpoint_scope breakpoint.  */
1721
1722 static void
1723 watchpoint_del_at_next_stop (struct watchpoint *w)
1724 {
1725   struct breakpoint *b = &w->base;
1726
1727   if (b->related_breakpoint != b)
1728     {
1729       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1730       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1731       b->related_breakpoint->disposition = disp_del_at_next_stop;
1732       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1733       b->related_breakpoint = b;
1734     }
1735   b->disposition = disp_del_at_next_stop;
1736 }
1737
1738 /* Extract a bitfield value from value VAL using the bit parameters contained in
1739    watchpoint W.  */
1740
1741 static struct value *
1742 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1743 {
1744   struct value *bit_val;
1745
1746   if (val == NULL)
1747     return NULL;
1748
1749   bit_val = allocate_value (value_type (val));
1750
1751   unpack_value_bitfield (bit_val,
1752                          w->val_bitpos,
1753                          w->val_bitsize,
1754                          value_contents_for_printing (val),
1755                          value_offset (val),
1756                          val);
1757
1758   return bit_val;
1759 }
1760
1761 /* Assuming that B is a watchpoint:
1762    - Reparse watchpoint expression, if REPARSE is non-zero
1763    - Evaluate expression and store the result in B->val
1764    - Evaluate the condition if there is one, and store the result
1765      in b->loc->cond.
1766    - Update the list of values that must be watched in B->loc.
1767
1768    If the watchpoint disposition is disp_del_at_next_stop, then do
1769    nothing.  If this is local watchpoint that is out of scope, delete
1770    it.
1771
1772    Even with `set breakpoint always-inserted on' the watchpoints are
1773    removed + inserted on each stop here.  Normal breakpoints must
1774    never be removed because they might be missed by a running thread
1775    when debugging in non-stop mode.  On the other hand, hardware
1776    watchpoints (is_hardware_watchpoint; processed here) are specific
1777    to each LWP since they are stored in each LWP's hardware debug
1778    registers.  Therefore, such LWP must be stopped first in order to
1779    be able to modify its hardware watchpoints.
1780
1781    Hardware watchpoints must be reset exactly once after being
1782    presented to the user.  It cannot be done sooner, because it would
1783    reset the data used to present the watchpoint hit to the user.  And
1784    it must not be done later because it could display the same single
1785    watchpoint hit during multiple GDB stops.  Note that the latter is
1786    relevant only to the hardware watchpoint types bp_read_watchpoint
1787    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1788    not user-visible - its hit is suppressed if the memory content has
1789    not changed.
1790
1791    The following constraints influence the location where we can reset
1792    hardware watchpoints:
1793
1794    * target_stopped_by_watchpoint and target_stopped_data_address are
1795      called several times when GDB stops.
1796
1797    [linux] 
1798    * Multiple hardware watchpoints can be hit at the same time,
1799      causing GDB to stop.  GDB only presents one hardware watchpoint
1800      hit at a time as the reason for stopping, and all the other hits
1801      are presented later, one after the other, each time the user
1802      requests the execution to be resumed.  Execution is not resumed
1803      for the threads still having pending hit event stored in
1804      LWP_INFO->STATUS.  While the watchpoint is already removed from
1805      the inferior on the first stop the thread hit event is kept being
1806      reported from its cached value by linux_nat_stopped_data_address
1807      until the real thread resume happens after the watchpoint gets
1808      presented and thus its LWP_INFO->STATUS gets reset.
1809
1810    Therefore the hardware watchpoint hit can get safely reset on the
1811    watchpoint removal from inferior.  */
1812
1813 static void
1814 update_watchpoint (struct watchpoint *b, int reparse)
1815 {
1816   int within_current_scope;
1817   struct frame_id saved_frame_id;
1818   int frame_saved;
1819
1820   /* If this is a local watchpoint, we only want to check if the
1821      watchpoint frame is in scope if the current thread is the thread
1822      that was used to create the watchpoint.  */
1823   if (!watchpoint_in_thread_scope (b))
1824     return;
1825
1826   if (b->base.disposition == disp_del_at_next_stop)
1827     return;
1828  
1829   frame_saved = 0;
1830
1831   /* Determine if the watchpoint is within scope.  */
1832   if (b->exp_valid_block == NULL)
1833     within_current_scope = 1;
1834   else
1835     {
1836       struct frame_info *fi = get_current_frame ();
1837       struct gdbarch *frame_arch = get_frame_arch (fi);
1838       CORE_ADDR frame_pc = get_frame_pc (fi);
1839
1840       /* If we're in a function epilogue, unwinding may not work
1841          properly, so do not attempt to recreate locations at this
1842          point.  See similar comments in watchpoint_check.  */
1843       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1844         return;
1845
1846       /* Save the current frame's ID so we can restore it after
1847          evaluating the watchpoint expression on its own frame.  */
1848       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1849          took a frame parameter, so that we didn't have to change the
1850          selected frame.  */
1851       frame_saved = 1;
1852       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1853
1854       fi = frame_find_by_id (b->watchpoint_frame);
1855       within_current_scope = (fi != NULL);
1856       if (within_current_scope)
1857         select_frame (fi);
1858     }
1859
1860   /* We don't free locations.  They are stored in the bp_location array
1861      and update_global_location_list will eventually delete them and
1862      remove breakpoints if needed.  */
1863   b->base.loc = NULL;
1864
1865   if (within_current_scope && reparse)
1866     {
1867       const char *s;
1868
1869       if (b->exp)
1870         {
1871           xfree (b->exp);
1872           b->exp = NULL;
1873         }
1874       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1875       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1876       /* If the meaning of expression itself changed, the old value is
1877          no longer relevant.  We don't want to report a watchpoint hit
1878          to the user when the old value and the new value may actually
1879          be completely different objects.  */
1880       value_free (b->val);
1881       b->val = NULL;
1882       b->val_valid = 0;
1883
1884       /* Note that unlike with breakpoints, the watchpoint's condition
1885          expression is stored in the breakpoint object, not in the
1886          locations (re)created below.  */
1887       if (b->base.cond_string != NULL)
1888         {
1889           if (b->cond_exp != NULL)
1890             {
1891               xfree (b->cond_exp);
1892               b->cond_exp = NULL;
1893             }
1894
1895           s = b->base.cond_string;
1896           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1897         }
1898     }
1899
1900   /* If we failed to parse the expression, for example because
1901      it refers to a global variable in a not-yet-loaded shared library,
1902      don't try to insert watchpoint.  We don't automatically delete
1903      such watchpoint, though, since failure to parse expression
1904      is different from out-of-scope watchpoint.  */
1905   if (!target_has_execution)
1906     {
1907       /* Without execution, memory can't change.  No use to try and
1908          set watchpoint locations.  The watchpoint will be reset when
1909          the target gains execution, through breakpoint_re_set.  */
1910       if (!can_use_hw_watchpoints)
1911         {
1912           if (b->base.ops->works_in_software_mode (&b->base))
1913             b->base.type = bp_watchpoint;
1914           else
1915             error (_("Can't set read/access watchpoint when "
1916                      "hardware watchpoints are disabled."));
1917         }
1918     }
1919   else if (within_current_scope && b->exp)
1920     {
1921       int pc = 0;
1922       struct value *val_chain, *v, *result, *next;
1923       struct program_space *frame_pspace;
1924
1925       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1926
1927       /* Avoid setting b->val if it's already set.  The meaning of
1928          b->val is 'the last value' user saw, and we should update
1929          it only if we reported that last value to user.  As it
1930          happens, the code that reports it updates b->val directly.
1931          We don't keep track of the memory value for masked
1932          watchpoints.  */
1933       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1934         {
1935           if (b->val_bitsize != 0)
1936             {
1937               v = extract_bitfield_from_watchpoint_value (b, v);
1938               if (v != NULL)
1939                 release_value (v);
1940             }
1941           b->val = v;
1942           b->val_valid = 1;
1943         }
1944
1945       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1946
1947       /* Look at each value on the value chain.  */
1948       for (v = val_chain; v; v = value_next (v))
1949         {
1950           /* If it's a memory location, and GDB actually needed
1951              its contents to evaluate the expression, then we
1952              must watch it.  If the first value returned is
1953              still lazy, that means an error occurred reading it;
1954              watch it anyway in case it becomes readable.  */
1955           if (VALUE_LVAL (v) == lval_memory
1956               && (v == val_chain || ! value_lazy (v)))
1957             {
1958               struct type *vtype = check_typedef (value_type (v));
1959
1960               /* We only watch structs and arrays if user asked
1961                  for it explicitly, never if they just happen to
1962                  appear in the middle of some value chain.  */
1963               if (v == result
1964                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1965                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1966                 {
1967                   CORE_ADDR addr;
1968                   int type;
1969                   struct bp_location *loc, **tmp;
1970                   int bitpos = 0, bitsize = 0;
1971
1972                   if (value_bitsize (v) != 0)
1973                     {
1974                       /* Extract the bit parameters out from the bitfield
1975                          sub-expression.  */
1976                       bitpos = value_bitpos (v);
1977                       bitsize = value_bitsize (v);
1978                     }
1979                   else if (v == result && b->val_bitsize != 0)
1980                     {
1981                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1982                         lvalue whose bit parameters are saved in the fields
1983                         VAL_BITPOS and VAL_BITSIZE.  */
1984                       bitpos = b->val_bitpos;
1985                       bitsize = b->val_bitsize;
1986                     }
1987
1988                   addr = value_address (v);
1989                   if (bitsize != 0)
1990                     {
1991                       /* Skip the bytes that don't contain the bitfield.  */
1992                       addr += bitpos / 8;
1993                     }
1994
1995                   type = hw_write;
1996                   if (b->base.type == bp_read_watchpoint)
1997                     type = hw_read;
1998                   else if (b->base.type == bp_access_watchpoint)
1999                     type = hw_access;
2000
2001                   loc = allocate_bp_location (&b->base);
2002                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2003                     ;
2004                   *tmp = loc;
2005                   loc->gdbarch = get_type_arch (value_type (v));
2006
2007                   loc->pspace = frame_pspace;
2008                   loc->address = addr;
2009
2010                   if (bitsize != 0)
2011                     {
2012                       /* Just cover the bytes that make up the bitfield.  */
2013                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2014                     }
2015                   else
2016                     loc->length = TYPE_LENGTH (value_type (v));
2017
2018                   loc->watchpoint_type = type;
2019                 }
2020             }
2021         }
2022
2023       /* Change the type of breakpoint between hardware assisted or
2024          an ordinary watchpoint depending on the hardware support
2025          and free hardware slots.  REPARSE is set when the inferior
2026          is started.  */
2027       if (reparse)
2028         {
2029           int reg_cnt;
2030           enum bp_loc_type loc_type;
2031           struct bp_location *bl;
2032
2033           reg_cnt = can_use_hardware_watchpoint (val_chain);
2034
2035           if (reg_cnt)
2036             {
2037               int i, target_resources_ok, other_type_used;
2038               enum bptype type;
2039
2040               /* Use an exact watchpoint when there's only one memory region to be
2041                  watched, and only one debug register is needed to watch it.  */
2042               b->exact = target_exact_watchpoints && reg_cnt == 1;
2043
2044               /* We need to determine how many resources are already
2045                  used for all other hardware watchpoints plus this one
2046                  to see if we still have enough resources to also fit
2047                  this watchpoint in as well.  */
2048
2049               /* If this is a software watchpoint, we try to turn it
2050                  to a hardware one -- count resources as if B was of
2051                  hardware watchpoint type.  */
2052               type = b->base.type;
2053               if (type == bp_watchpoint)
2054                 type = bp_hardware_watchpoint;
2055
2056               /* This watchpoint may or may not have been placed on
2057                  the list yet at this point (it won't be in the list
2058                  if we're trying to create it for the first time,
2059                  through watch_command), so always account for it
2060                  manually.  */
2061
2062               /* Count resources used by all watchpoints except B.  */
2063               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2064
2065               /* Add in the resources needed for B.  */
2066               i += hw_watchpoint_use_count (&b->base);
2067
2068               target_resources_ok
2069                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2070               if (target_resources_ok <= 0)
2071                 {
2072                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2073
2074                   if (target_resources_ok == 0 && !sw_mode)
2075                     error (_("Target does not support this type of "
2076                              "hardware watchpoint."));
2077                   else if (target_resources_ok < 0 && !sw_mode)
2078                     error (_("There are not enough available hardware "
2079                              "resources for this watchpoint."));
2080
2081                   /* Downgrade to software watchpoint.  */
2082                   b->base.type = bp_watchpoint;
2083                 }
2084               else
2085                 {
2086                   /* If this was a software watchpoint, we've just
2087                      found we have enough resources to turn it to a
2088                      hardware watchpoint.  Otherwise, this is a
2089                      nop.  */
2090                   b->base.type = type;
2091                 }
2092             }
2093           else if (!b->base.ops->works_in_software_mode (&b->base))
2094             {
2095               if (!can_use_hw_watchpoints)
2096                 error (_("Can't set read/access watchpoint when "
2097                          "hardware watchpoints are disabled."));
2098               else
2099                 error (_("Expression cannot be implemented with "
2100                          "read/access watchpoint."));
2101             }
2102           else
2103             b->base.type = bp_watchpoint;
2104
2105           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2106                       : bp_loc_hardware_watchpoint);
2107           for (bl = b->base.loc; bl; bl = bl->next)
2108             bl->loc_type = loc_type;
2109         }
2110
2111       for (v = val_chain; v; v = next)
2112         {
2113           next = value_next (v);
2114           if (v != b->val)
2115             value_free (v);
2116         }
2117
2118       /* If a software watchpoint is not watching any memory, then the
2119          above left it without any location set up.  But,
2120          bpstat_stop_status requires a location to be able to report
2121          stops, so make sure there's at least a dummy one.  */
2122       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2123         {
2124           struct breakpoint *base = &b->base;
2125           base->loc = allocate_bp_location (base);
2126           base->loc->pspace = frame_pspace;
2127           base->loc->address = -1;
2128           base->loc->length = -1;
2129           base->loc->watchpoint_type = -1;
2130         }
2131     }
2132   else if (!within_current_scope)
2133     {
2134       printf_filtered (_("\
2135 Watchpoint %d deleted because the program has left the block\n\
2136 in which its expression is valid.\n"),
2137                        b->base.number);
2138       watchpoint_del_at_next_stop (b);
2139     }
2140
2141   /* Restore the selected frame.  */
2142   if (frame_saved)
2143     select_frame (frame_find_by_id (saved_frame_id));
2144 }
2145
2146
2147 /* Returns 1 iff breakpoint location should be
2148    inserted in the inferior.  We don't differentiate the type of BL's owner
2149    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2150    breakpoint_ops is not defined, because in insert_bp_location,
2151    tracepoint's insert_location will not be called.  */
2152 static int
2153 should_be_inserted (struct bp_location *bl)
2154 {
2155   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2156     return 0;
2157
2158   if (bl->owner->disposition == disp_del_at_next_stop)
2159     return 0;
2160
2161   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2162     return 0;
2163
2164   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2165     return 0;
2166
2167   /* This is set for example, when we're attached to the parent of a
2168      vfork, and have detached from the child.  The child is running
2169      free, and we expect it to do an exec or exit, at which point the
2170      OS makes the parent schedulable again (and the target reports
2171      that the vfork is done).  Until the child is done with the shared
2172      memory region, do not insert breakpoints in the parent, otherwise
2173      the child could still trip on the parent's breakpoints.  Since
2174      the parent is blocked anyway, it won't miss any breakpoint.  */
2175   if (bl->pspace->breakpoints_not_allowed)
2176     return 0;
2177
2178   /* Don't insert a breakpoint if we're trying to step past its
2179      location.  */
2180   if ((bl->loc_type == bp_loc_software_breakpoint
2181        || bl->loc_type == bp_loc_hardware_breakpoint)
2182       && stepping_past_instruction_at (bl->pspace->aspace,
2183                                        bl->address))
2184     {
2185       if (debug_infrun)
2186         {
2187           fprintf_unfiltered (gdb_stdlog,
2188                               "infrun: skipping breakpoint: "
2189                               "stepping past insn at: %s\n",
2190                               paddress (bl->gdbarch, bl->address));
2191         }
2192       return 0;
2193     }
2194
2195   /* Don't insert watchpoints if we're trying to step past the
2196      instruction that triggered one.  */
2197   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2198       && stepping_past_nonsteppable_watchpoint ())
2199     {
2200       if (debug_infrun)
2201         {
2202           fprintf_unfiltered (gdb_stdlog,
2203                               "infrun: stepping past non-steppable watchpoint. "
2204                               "skipping watchpoint at %s:%d\n",
2205                               paddress (bl->gdbarch, bl->address),
2206                               bl->length);
2207         }
2208       return 0;
2209     }
2210
2211   return 1;
2212 }
2213
2214 /* Same as should_be_inserted but does the check assuming
2215    that the location is not duplicated.  */
2216
2217 static int
2218 unduplicated_should_be_inserted (struct bp_location *bl)
2219 {
2220   int result;
2221   const int save_duplicate = bl->duplicate;
2222
2223   bl->duplicate = 0;
2224   result = should_be_inserted (bl);
2225   bl->duplicate = save_duplicate;
2226   return result;
2227 }
2228
2229 /* Parses a conditional described by an expression COND into an
2230    agent expression bytecode suitable for evaluation
2231    by the bytecode interpreter.  Return NULL if there was
2232    any error during parsing.  */
2233
2234 static struct agent_expr *
2235 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2236 {
2237   struct agent_expr *aexpr = NULL;
2238
2239   if (!cond)
2240     return NULL;
2241
2242   /* We don't want to stop processing, so catch any errors
2243      that may show up.  */
2244   TRY
2245     {
2246       aexpr = gen_eval_for_expr (scope, cond);
2247     }
2248
2249   CATCH (ex, RETURN_MASK_ERROR)
2250     {
2251       /* If we got here, it means the condition could not be parsed to a valid
2252          bytecode expression and thus can't be evaluated on the target's side.
2253          It's no use iterating through the conditions.  */
2254       return NULL;
2255     }
2256   END_CATCH
2257
2258   /* We have a valid agent expression.  */
2259   return aexpr;
2260 }
2261
2262 /* Based on location BL, create a list of breakpoint conditions to be
2263    passed on to the target.  If we have duplicated locations with different
2264    conditions, we will add such conditions to the list.  The idea is that the
2265    target will evaluate the list of conditions and will only notify GDB when
2266    one of them is true.  */
2267
2268 static void
2269 build_target_condition_list (struct bp_location *bl)
2270 {
2271   struct bp_location **locp = NULL, **loc2p;
2272   int null_condition_or_parse_error = 0;
2273   int modified = bl->needs_update;
2274   struct bp_location *loc;
2275
2276   /* Release conditions left over from a previous insert.  */
2277   VEC_free (agent_expr_p, bl->target_info.conditions);
2278
2279   /* This is only meaningful if the target is
2280      evaluating conditions and if the user has
2281      opted for condition evaluation on the target's
2282      side.  */
2283   if (gdb_evaluates_breakpoint_condition_p ()
2284       || !target_supports_evaluation_of_breakpoint_conditions ())
2285     return;
2286
2287   /* Do a first pass to check for locations with no assigned
2288      conditions or conditions that fail to parse to a valid agent expression
2289      bytecode.  If any of these happen, then it's no use to send conditions
2290      to the target since this location will always trigger and generate a
2291      response back to GDB.  */
2292   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2293     {
2294       loc = (*loc2p);
2295       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2296         {
2297           if (modified)
2298             {
2299               struct agent_expr *aexpr;
2300
2301               /* Re-parse the conditions since something changed.  In that
2302                  case we already freed the condition bytecodes (see
2303                  force_breakpoint_reinsertion).  We just
2304                  need to parse the condition to bytecodes again.  */
2305               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2306               loc->cond_bytecode = aexpr;
2307
2308               /* Check if we managed to parse the conditional expression
2309                  correctly.  If not, we will not send this condition
2310                  to the target.  */
2311               if (aexpr)
2312                 continue;
2313             }
2314
2315           /* If we have a NULL bytecode expression, it means something
2316              went wrong or we have a null condition expression.  */
2317           if (!loc->cond_bytecode)
2318             {
2319               null_condition_or_parse_error = 1;
2320               break;
2321             }
2322         }
2323     }
2324
2325   /* If any of these happened, it means we will have to evaluate the conditions
2326      for the location's address on gdb's side.  It is no use keeping bytecodes
2327      for all the other duplicate locations, thus we free all of them here.
2328
2329      This is so we have a finer control over which locations' conditions are
2330      being evaluated by GDB or the remote stub.  */
2331   if (null_condition_or_parse_error)
2332     {
2333       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2334         {
2335           loc = (*loc2p);
2336           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2337             {
2338               /* Only go as far as the first NULL bytecode is
2339                  located.  */
2340               if (!loc->cond_bytecode)
2341                 return;
2342
2343               free_agent_expr (loc->cond_bytecode);
2344               loc->cond_bytecode = NULL;
2345             }
2346         }
2347     }
2348
2349   /* No NULL conditions or failed bytecode generation.  Build a condition list
2350      for this location's address.  */
2351   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2352     {
2353       loc = (*loc2p);
2354       if (loc->cond
2355           && is_breakpoint (loc->owner)
2356           && loc->pspace->num == bl->pspace->num
2357           && loc->owner->enable_state == bp_enabled
2358           && loc->enabled)
2359         /* Add the condition to the vector.  This will be used later to send the
2360            conditions to the target.  */
2361         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2362                        loc->cond_bytecode);
2363     }
2364
2365   return;
2366 }
2367
2368 /* Parses a command described by string CMD into an agent expression
2369    bytecode suitable for evaluation by the bytecode interpreter.
2370    Return NULL if there was any error during parsing.  */
2371
2372 static struct agent_expr *
2373 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2374 {
2375   struct cleanup *old_cleanups = 0;
2376   struct expression *expr, **argvec;
2377   struct agent_expr *aexpr = NULL;
2378   const char *cmdrest;
2379   const char *format_start, *format_end;
2380   struct format_piece *fpieces;
2381   int nargs;
2382   struct gdbarch *gdbarch = get_current_arch ();
2383
2384   if (!cmd)
2385     return NULL;
2386
2387   cmdrest = cmd;
2388
2389   if (*cmdrest == ',')
2390     ++cmdrest;
2391   cmdrest = skip_spaces_const (cmdrest);
2392
2393   if (*cmdrest++ != '"')
2394     error (_("No format string following the location"));
2395
2396   format_start = cmdrest;
2397
2398   fpieces = parse_format_string (&cmdrest);
2399
2400   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2401
2402   format_end = cmdrest;
2403
2404   if (*cmdrest++ != '"')
2405     error (_("Bad format string, non-terminated '\"'."));
2406   
2407   cmdrest = skip_spaces_const (cmdrest);
2408
2409   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2410     error (_("Invalid argument syntax"));
2411
2412   if (*cmdrest == ',')
2413     cmdrest++;
2414   cmdrest = skip_spaces_const (cmdrest);
2415
2416   /* For each argument, make an expression.  */
2417
2418   argvec = (struct expression **) alloca (strlen (cmd)
2419                                          * sizeof (struct expression *));
2420
2421   nargs = 0;
2422   while (*cmdrest != '\0')
2423     {
2424       const char *cmd1;
2425
2426       cmd1 = cmdrest;
2427       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2428       argvec[nargs++] = expr;
2429       cmdrest = cmd1;
2430       if (*cmdrest == ',')
2431         ++cmdrest;
2432     }
2433
2434   /* We don't want to stop processing, so catch any errors
2435      that may show up.  */
2436   TRY
2437     {
2438       aexpr = gen_printf (scope, gdbarch, 0, 0,
2439                           format_start, format_end - format_start,
2440                           fpieces, nargs, argvec);
2441     }
2442   CATCH (ex, RETURN_MASK_ERROR)
2443     {
2444       /* If we got here, it means the command could not be parsed to a valid
2445          bytecode expression and thus can't be evaluated on the target's side.
2446          It's no use iterating through the other commands.  */
2447       aexpr = NULL;
2448     }
2449   END_CATCH
2450
2451   do_cleanups (old_cleanups);
2452
2453   /* We have a valid agent expression, return it.  */
2454   return aexpr;
2455 }
2456
2457 /* Based on location BL, create a list of breakpoint commands to be
2458    passed on to the target.  If we have duplicated locations with
2459    different commands, we will add any such to the list.  */
2460
2461 static void
2462 build_target_command_list (struct bp_location *bl)
2463 {
2464   struct bp_location **locp = NULL, **loc2p;
2465   int null_command_or_parse_error = 0;
2466   int modified = bl->needs_update;
2467   struct bp_location *loc;
2468
2469   /* Release commands left over from a previous insert.  */
2470   VEC_free (agent_expr_p, bl->target_info.tcommands);
2471
2472   if (!target_can_run_breakpoint_commands ())
2473     return;
2474
2475   /* For now, limit to agent-style dprintf breakpoints.  */
2476   if (dprintf_style != dprintf_style_agent)
2477     return;
2478
2479   /* For now, if we have any duplicate location that isn't a dprintf,
2480      don't install the target-side commands, as that would make the
2481      breakpoint not be reported to the core, and we'd lose
2482      control.  */
2483   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2484     {
2485       loc = (*loc2p);
2486       if (is_breakpoint (loc->owner)
2487           && loc->pspace->num == bl->pspace->num
2488           && loc->owner->type != bp_dprintf)
2489         return;
2490     }
2491
2492   /* Do a first pass to check for locations with no assigned
2493      conditions or conditions that fail to parse to a valid agent expression
2494      bytecode.  If any of these happen, then it's no use to send conditions
2495      to the target since this location will always trigger and generate a
2496      response back to GDB.  */
2497   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2498     {
2499       loc = (*loc2p);
2500       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2501         {
2502           if (modified)
2503             {
2504               struct agent_expr *aexpr;
2505
2506               /* Re-parse the commands since something changed.  In that
2507                  case we already freed the command bytecodes (see
2508                  force_breakpoint_reinsertion).  We just
2509                  need to parse the command to bytecodes again.  */
2510               aexpr = parse_cmd_to_aexpr (bl->address,
2511                                           loc->owner->extra_string);
2512               loc->cmd_bytecode = aexpr;
2513
2514               if (!aexpr)
2515                 continue;
2516             }
2517
2518           /* If we have a NULL bytecode expression, it means something
2519              went wrong or we have a null command expression.  */
2520           if (!loc->cmd_bytecode)
2521             {
2522               null_command_or_parse_error = 1;
2523               break;
2524             }
2525         }
2526     }
2527
2528   /* If anything failed, then we're not doing target-side commands,
2529      and so clean up.  */
2530   if (null_command_or_parse_error)
2531     {
2532       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2533         {
2534           loc = (*loc2p);
2535           if (is_breakpoint (loc->owner)
2536               && loc->pspace->num == bl->pspace->num)
2537             {
2538               /* Only go as far as the first NULL bytecode is
2539                  located.  */
2540               if (loc->cmd_bytecode == NULL)
2541                 return;
2542
2543               free_agent_expr (loc->cmd_bytecode);
2544               loc->cmd_bytecode = NULL;
2545             }
2546         }
2547     }
2548
2549   /* No NULL commands or failed bytecode generation.  Build a command list
2550      for this location's address.  */
2551   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2552     {
2553       loc = (*loc2p);
2554       if (loc->owner->extra_string
2555           && is_breakpoint (loc->owner)
2556           && loc->pspace->num == bl->pspace->num
2557           && loc->owner->enable_state == bp_enabled
2558           && loc->enabled)
2559         /* Add the command to the vector.  This will be used later
2560            to send the commands to the target.  */
2561         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2562                        loc->cmd_bytecode);
2563     }
2564
2565   bl->target_info.persist = 0;
2566   /* Maybe flag this location as persistent.  */
2567   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2568     bl->target_info.persist = 1;
2569 }
2570
2571 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2572    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2573    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2574    Returns 0 for success, 1 if the bp_location type is not supported or
2575    -1 for failure.
2576
2577    NOTE drow/2003-09-09: This routine could be broken down to an
2578    object-style method for each breakpoint or catchpoint type.  */
2579 static int
2580 insert_bp_location (struct bp_location *bl,
2581                     struct ui_file *tmp_error_stream,
2582                     int *disabled_breaks,
2583                     int *hw_breakpoint_error,
2584                     int *hw_bp_error_explained_already)
2585 {
2586   enum errors bp_err = GDB_NO_ERROR;
2587   const char *bp_err_message = NULL;
2588
2589   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2590     return 0;
2591
2592   /* Note we don't initialize bl->target_info, as that wipes out
2593      the breakpoint location's shadow_contents if the breakpoint
2594      is still inserted at that location.  This in turn breaks
2595      target_read_memory which depends on these buffers when
2596      a memory read is requested at the breakpoint location:
2597      Once the target_info has been wiped, we fail to see that
2598      we have a breakpoint inserted at that address and thus
2599      read the breakpoint instead of returning the data saved in
2600      the breakpoint location's shadow contents.  */
2601   bl->target_info.reqstd_address = bl->address;
2602   bl->target_info.placed_address_space = bl->pspace->aspace;
2603   bl->target_info.length = bl->length;
2604
2605   /* When working with target-side conditions, we must pass all the conditions
2606      for the same breakpoint address down to the target since GDB will not
2607      insert those locations.  With a list of breakpoint conditions, the target
2608      can decide when to stop and notify GDB.  */
2609
2610   if (is_breakpoint (bl->owner))
2611     {
2612       build_target_condition_list (bl);
2613       build_target_command_list (bl);
2614       /* Reset the modification marker.  */
2615       bl->needs_update = 0;
2616     }
2617
2618   if (bl->loc_type == bp_loc_software_breakpoint
2619       || bl->loc_type == bp_loc_hardware_breakpoint)
2620     {
2621       if (bl->owner->type != bp_hardware_breakpoint)
2622         {
2623           /* If the explicitly specified breakpoint type
2624              is not hardware breakpoint, check the memory map to see
2625              if the breakpoint address is in read only memory or not.
2626
2627              Two important cases are:
2628              - location type is not hardware breakpoint, memory
2629              is readonly.  We change the type of the location to
2630              hardware breakpoint.
2631              - location type is hardware breakpoint, memory is
2632              read-write.  This means we've previously made the
2633              location hardware one, but then the memory map changed,
2634              so we undo.
2635              
2636              When breakpoints are removed, remove_breakpoints will use
2637              location types we've just set here, the only possible
2638              problem is that memory map has changed during running
2639              program, but it's not going to work anyway with current
2640              gdb.  */
2641           struct mem_region *mr 
2642             = lookup_mem_region (bl->target_info.reqstd_address);
2643           
2644           if (mr)
2645             {
2646               if (automatic_hardware_breakpoints)
2647                 {
2648                   enum bp_loc_type new_type;
2649                   
2650                   if (mr->attrib.mode != MEM_RW)
2651                     new_type = bp_loc_hardware_breakpoint;
2652                   else 
2653                     new_type = bp_loc_software_breakpoint;
2654                   
2655                   if (new_type != bl->loc_type)
2656                     {
2657                       static int said = 0;
2658
2659                       bl->loc_type = new_type;
2660                       if (!said)
2661                         {
2662                           fprintf_filtered (gdb_stdout,
2663                                             _("Note: automatically using "
2664                                               "hardware breakpoints for "
2665                                               "read-only addresses.\n"));
2666                           said = 1;
2667                         }
2668                     }
2669                 }
2670               else if (bl->loc_type == bp_loc_software_breakpoint
2671                        && mr->attrib.mode != MEM_RW)
2672                 {
2673                   fprintf_unfiltered (tmp_error_stream,
2674                                       _("Cannot insert breakpoint %d.\n"
2675                                         "Cannot set software breakpoint "
2676                                         "at read-only address %s\n"),
2677                                       bl->owner->number,
2678                                       paddress (bl->gdbarch, bl->address));
2679                   return 1;
2680                 }
2681             }
2682         }
2683         
2684       /* First check to see if we have to handle an overlay.  */
2685       if (overlay_debugging == ovly_off
2686           || bl->section == NULL
2687           || !(section_is_overlay (bl->section)))
2688         {
2689           /* No overlay handling: just set the breakpoint.  */
2690           TRY
2691             {
2692               int val;
2693
2694               val = bl->owner->ops->insert_location (bl);
2695               if (val)
2696                 bp_err = GENERIC_ERROR;
2697             }
2698           CATCH (e, RETURN_MASK_ALL)
2699             {
2700               bp_err = e.error;
2701               bp_err_message = e.message;
2702             }
2703           END_CATCH
2704         }
2705       else
2706         {
2707           /* This breakpoint is in an overlay section.
2708              Shall we set a breakpoint at the LMA?  */
2709           if (!overlay_events_enabled)
2710             {
2711               /* Yes -- overlay event support is not active, 
2712                  so we must try to set a breakpoint at the LMA.
2713                  This will not work for a hardware breakpoint.  */
2714               if (bl->loc_type == bp_loc_hardware_breakpoint)
2715                 warning (_("hardware breakpoint %d not supported in overlay!"),
2716                          bl->owner->number);
2717               else
2718                 {
2719                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2720                                                              bl->section);
2721                   /* Set a software (trap) breakpoint at the LMA.  */
2722                   bl->overlay_target_info = bl->target_info;
2723                   bl->overlay_target_info.reqstd_address = addr;
2724
2725                   /* No overlay handling: just set the breakpoint.  */
2726                   TRY
2727                     {
2728                       int val;
2729
2730                       val = target_insert_breakpoint (bl->gdbarch,
2731                                                       &bl->overlay_target_info);
2732                       if (val)
2733                         bp_err = GENERIC_ERROR;
2734                     }
2735                   CATCH (e, RETURN_MASK_ALL)
2736                     {
2737                       bp_err = e.error;
2738                       bp_err_message = e.message;
2739                     }
2740                   END_CATCH
2741
2742                   if (bp_err != GDB_NO_ERROR)
2743                     fprintf_unfiltered (tmp_error_stream,
2744                                         "Overlay breakpoint %d "
2745                                         "failed: in ROM?\n",
2746                                         bl->owner->number);
2747                 }
2748             }
2749           /* Shall we set a breakpoint at the VMA? */
2750           if (section_is_mapped (bl->section))
2751             {
2752               /* Yes.  This overlay section is mapped into memory.  */
2753               TRY
2754                 {
2755                   int val;
2756
2757                   val = bl->owner->ops->insert_location (bl);
2758                   if (val)
2759                     bp_err = GENERIC_ERROR;
2760                 }
2761               CATCH (e, RETURN_MASK_ALL)
2762                 {
2763                   bp_err = e.error;
2764                   bp_err_message = e.message;
2765                 }
2766               END_CATCH
2767             }
2768           else
2769             {
2770               /* No.  This breakpoint will not be inserted.  
2771                  No error, but do not mark the bp as 'inserted'.  */
2772               return 0;
2773             }
2774         }
2775
2776       if (bp_err != GDB_NO_ERROR)
2777         {
2778           /* Can't set the breakpoint.  */
2779
2780           /* In some cases, we might not be able to insert a
2781              breakpoint in a shared library that has already been
2782              removed, but we have not yet processed the shlib unload
2783              event.  Unfortunately, some targets that implement
2784              breakpoint insertion themselves can't tell why the
2785              breakpoint insertion failed (e.g., the remote target
2786              doesn't define error codes), so we must treat generic
2787              errors as memory errors.  */
2788           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2789               && bl->loc_type == bp_loc_software_breakpoint
2790               && (solib_name_from_address (bl->pspace, bl->address)
2791                   || shared_objfile_contains_address_p (bl->pspace,
2792                                                         bl->address)))
2793             {
2794               /* See also: disable_breakpoints_in_shlibs.  */
2795               bl->shlib_disabled = 1;
2796               observer_notify_breakpoint_modified (bl->owner);
2797               if (!*disabled_breaks)
2798                 {
2799                   fprintf_unfiltered (tmp_error_stream, 
2800                                       "Cannot insert breakpoint %d.\n", 
2801                                       bl->owner->number);
2802                   fprintf_unfiltered (tmp_error_stream, 
2803                                       "Temporarily disabling shared "
2804                                       "library breakpoints:\n");
2805                 }
2806               *disabled_breaks = 1;
2807               fprintf_unfiltered (tmp_error_stream,
2808                                   "breakpoint #%d\n", bl->owner->number);
2809               return 0;
2810             }
2811           else
2812             {
2813               if (bl->loc_type == bp_loc_hardware_breakpoint)
2814                 {
2815                   *hw_breakpoint_error = 1;
2816                   *hw_bp_error_explained_already = bp_err_message != NULL;
2817                   fprintf_unfiltered (tmp_error_stream,
2818                                       "Cannot insert hardware breakpoint %d%s",
2819                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2820                   if (bp_err_message != NULL)
2821                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2822                 }
2823               else
2824                 {
2825                   if (bp_err_message == NULL)
2826                     {
2827                       char *message
2828                         = memory_error_message (TARGET_XFER_E_IO,
2829                                                 bl->gdbarch, bl->address);
2830                       struct cleanup *old_chain = make_cleanup (xfree, message);
2831
2832                       fprintf_unfiltered (tmp_error_stream,
2833                                           "Cannot insert breakpoint %d.\n"
2834                                           "%s\n",
2835                                           bl->owner->number, message);
2836                       do_cleanups (old_chain);
2837                     }
2838                   else
2839                     {
2840                       fprintf_unfiltered (tmp_error_stream,
2841                                           "Cannot insert breakpoint %d: %s\n",
2842                                           bl->owner->number,
2843                                           bp_err_message);
2844                     }
2845                 }
2846               return 1;
2847
2848             }
2849         }
2850       else
2851         bl->inserted = 1;
2852
2853       return 0;
2854     }
2855
2856   else if (bl->loc_type == bp_loc_hardware_watchpoint
2857            /* NOTE drow/2003-09-08: This state only exists for removing
2858               watchpoints.  It's not clear that it's necessary...  */
2859            && bl->owner->disposition != disp_del_at_next_stop)
2860     {
2861       int val;
2862
2863       gdb_assert (bl->owner->ops != NULL
2864                   && bl->owner->ops->insert_location != NULL);
2865
2866       val = bl->owner->ops->insert_location (bl);
2867
2868       /* If trying to set a read-watchpoint, and it turns out it's not
2869          supported, try emulating one with an access watchpoint.  */
2870       if (val == 1 && bl->watchpoint_type == hw_read)
2871         {
2872           struct bp_location *loc, **loc_temp;
2873
2874           /* But don't try to insert it, if there's already another
2875              hw_access location that would be considered a duplicate
2876              of this one.  */
2877           ALL_BP_LOCATIONS (loc, loc_temp)
2878             if (loc != bl
2879                 && loc->watchpoint_type == hw_access
2880                 && watchpoint_locations_match (bl, loc))
2881               {
2882                 bl->duplicate = 1;
2883                 bl->inserted = 1;
2884                 bl->target_info = loc->target_info;
2885                 bl->watchpoint_type = hw_access;
2886                 val = 0;
2887                 break;
2888               }
2889
2890           if (val == 1)
2891             {
2892               bl->watchpoint_type = hw_access;
2893               val = bl->owner->ops->insert_location (bl);
2894
2895               if (val)
2896                 /* Back to the original value.  */
2897                 bl->watchpoint_type = hw_read;
2898             }
2899         }
2900
2901       bl->inserted = (val == 0);
2902     }
2903
2904   else if (bl->owner->type == bp_catchpoint)
2905     {
2906       int val;
2907
2908       gdb_assert (bl->owner->ops != NULL
2909                   && bl->owner->ops->insert_location != NULL);
2910
2911       val = bl->owner->ops->insert_location (bl);
2912       if (val)
2913         {
2914           bl->owner->enable_state = bp_disabled;
2915
2916           if (val == 1)
2917             warning (_("\
2918 Error inserting catchpoint %d: Your system does not support this type\n\
2919 of catchpoint."), bl->owner->number);
2920           else
2921             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2922         }
2923
2924       bl->inserted = (val == 0);
2925
2926       /* We've already printed an error message if there was a problem
2927          inserting this catchpoint, and we've disabled the catchpoint,
2928          so just return success.  */
2929       return 0;
2930     }
2931
2932   return 0;
2933 }
2934
2935 /* This function is called when program space PSPACE is about to be
2936    deleted.  It takes care of updating breakpoints to not reference
2937    PSPACE anymore.  */
2938
2939 void
2940 breakpoint_program_space_exit (struct program_space *pspace)
2941 {
2942   struct breakpoint *b, *b_temp;
2943   struct bp_location *loc, **loc_temp;
2944
2945   /* Remove any breakpoint that was set through this program space.  */
2946   ALL_BREAKPOINTS_SAFE (b, b_temp)
2947     {
2948       if (b->pspace == pspace)
2949         delete_breakpoint (b);
2950     }
2951
2952   /* Breakpoints set through other program spaces could have locations
2953      bound to PSPACE as well.  Remove those.  */
2954   ALL_BP_LOCATIONS (loc, loc_temp)
2955     {
2956       struct bp_location *tmp;
2957
2958       if (loc->pspace == pspace)
2959         {
2960           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2961           if (loc->owner->loc == loc)
2962             loc->owner->loc = loc->next;
2963           else
2964             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2965               if (tmp->next == loc)
2966                 {
2967                   tmp->next = loc->next;
2968                   break;
2969                 }
2970         }
2971     }
2972
2973   /* Now update the global location list to permanently delete the
2974      removed locations above.  */
2975   update_global_location_list (UGLL_DONT_INSERT);
2976 }
2977
2978 /* Make sure all breakpoints are inserted in inferior.
2979    Throws exception on any error.
2980    A breakpoint that is already inserted won't be inserted
2981    again, so calling this function twice is safe.  */
2982 void
2983 insert_breakpoints (void)
2984 {
2985   struct breakpoint *bpt;
2986
2987   ALL_BREAKPOINTS (bpt)
2988     if (is_hardware_watchpoint (bpt))
2989       {
2990         struct watchpoint *w = (struct watchpoint *) bpt;
2991
2992         update_watchpoint (w, 0 /* don't reparse.  */);
2993       }
2994
2995   /* Updating watchpoints creates new locations, so update the global
2996      location list.  Explicitly tell ugll to insert locations and
2997      ignore breakpoints_always_inserted_mode.  */
2998   update_global_location_list (UGLL_INSERT);
2999 }
3000
3001 /* Invoke CALLBACK for each of bp_location.  */
3002
3003 void
3004 iterate_over_bp_locations (walk_bp_location_callback callback)
3005 {
3006   struct bp_location *loc, **loc_tmp;
3007
3008   ALL_BP_LOCATIONS (loc, loc_tmp)
3009     {
3010       callback (loc, NULL);
3011     }
3012 }
3013
3014 /* This is used when we need to synch breakpoint conditions between GDB and the
3015    target.  It is the case with deleting and disabling of breakpoints when using
3016    always-inserted mode.  */
3017
3018 static void
3019 update_inserted_breakpoint_locations (void)
3020 {
3021   struct bp_location *bl, **blp_tmp;
3022   int error_flag = 0;
3023   int val = 0;
3024   int disabled_breaks = 0;
3025   int hw_breakpoint_error = 0;
3026   int hw_bp_details_reported = 0;
3027
3028   struct ui_file *tmp_error_stream = mem_fileopen ();
3029   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3030
3031   /* Explicitly mark the warning -- this will only be printed if
3032      there was an error.  */
3033   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3034
3035   save_current_space_and_thread ();
3036
3037   ALL_BP_LOCATIONS (bl, blp_tmp)
3038     {
3039       /* We only want to update software breakpoints and hardware
3040          breakpoints.  */
3041       if (!is_breakpoint (bl->owner))
3042         continue;
3043
3044       /* We only want to update locations that are already inserted
3045          and need updating.  This is to avoid unwanted insertion during
3046          deletion of breakpoints.  */
3047       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3048         continue;
3049
3050       switch_to_program_space_and_thread (bl->pspace);
3051
3052       /* For targets that support global breakpoints, there's no need
3053          to select an inferior to insert breakpoint to.  In fact, even
3054          if we aren't attached to any process yet, we should still
3055          insert breakpoints.  */
3056       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3057           && ptid_equal (inferior_ptid, null_ptid))
3058         continue;
3059
3060       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3061                                     &hw_breakpoint_error, &hw_bp_details_reported);
3062       if (val)
3063         error_flag = val;
3064     }
3065
3066   if (error_flag)
3067     {
3068       target_terminal_ours_for_output ();
3069       error_stream (tmp_error_stream);
3070     }
3071
3072   do_cleanups (cleanups);
3073 }
3074
3075 /* Used when starting or continuing the program.  */
3076
3077 static void
3078 insert_breakpoint_locations (void)
3079 {
3080   struct breakpoint *bpt;
3081   struct bp_location *bl, **blp_tmp;
3082   int error_flag = 0;
3083   int val = 0;
3084   int disabled_breaks = 0;
3085   int hw_breakpoint_error = 0;
3086   int hw_bp_error_explained_already = 0;
3087
3088   struct ui_file *tmp_error_stream = mem_fileopen ();
3089   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3090   
3091   /* Explicitly mark the warning -- this will only be printed if
3092      there was an error.  */
3093   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3094
3095   save_current_space_and_thread ();
3096
3097   ALL_BP_LOCATIONS (bl, blp_tmp)
3098     {
3099       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3100         continue;
3101
3102       /* There is no point inserting thread-specific breakpoints if
3103          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3104          has BL->OWNER always non-NULL.  */
3105       if (bl->owner->thread != -1
3106           && !valid_thread_id (bl->owner->thread))
3107         continue;
3108
3109       switch_to_program_space_and_thread (bl->pspace);
3110
3111       /* For targets that support global breakpoints, there's no need
3112          to select an inferior to insert breakpoint to.  In fact, even
3113          if we aren't attached to any process yet, we should still
3114          insert breakpoints.  */
3115       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3116           && ptid_equal (inferior_ptid, null_ptid))
3117         continue;
3118
3119       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3120                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3121       if (val)
3122         error_flag = val;
3123     }
3124
3125   /* If we failed to insert all locations of a watchpoint, remove
3126      them, as half-inserted watchpoint is of limited use.  */
3127   ALL_BREAKPOINTS (bpt)  
3128     {
3129       int some_failed = 0;
3130       struct bp_location *loc;
3131
3132       if (!is_hardware_watchpoint (bpt))
3133         continue;
3134
3135       if (!breakpoint_enabled (bpt))
3136         continue;
3137
3138       if (bpt->disposition == disp_del_at_next_stop)
3139         continue;
3140       
3141       for (loc = bpt->loc; loc; loc = loc->next)
3142         if (!loc->inserted && should_be_inserted (loc))
3143           {
3144             some_failed = 1;
3145             break;
3146           }
3147       if (some_failed)
3148         {
3149           for (loc = bpt->loc; loc; loc = loc->next)
3150             if (loc->inserted)
3151               remove_breakpoint (loc, mark_uninserted);
3152
3153           hw_breakpoint_error = 1;
3154           fprintf_unfiltered (tmp_error_stream,
3155                               "Could not insert hardware watchpoint %d.\n", 
3156                               bpt->number);
3157           error_flag = -1;
3158         }
3159     }
3160
3161   if (error_flag)
3162     {
3163       /* If a hardware breakpoint or watchpoint was inserted, add a
3164          message about possibly exhausted resources.  */
3165       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3166         {
3167           fprintf_unfiltered (tmp_error_stream, 
3168                               "Could not insert hardware breakpoints:\n\
3169 You may have requested too many hardware breakpoints/watchpoints.\n");
3170         }
3171       target_terminal_ours_for_output ();
3172       error_stream (tmp_error_stream);
3173     }
3174
3175   do_cleanups (cleanups);
3176 }
3177
3178 /* Used when the program stops.
3179    Returns zero if successful, or non-zero if there was a problem
3180    removing a breakpoint location.  */
3181
3182 int
3183 remove_breakpoints (void)
3184 {
3185   struct bp_location *bl, **blp_tmp;
3186   int val = 0;
3187
3188   ALL_BP_LOCATIONS (bl, blp_tmp)
3189   {
3190     if (bl->inserted && !is_tracepoint (bl->owner))
3191       val |= remove_breakpoint (bl, mark_uninserted);
3192   }
3193   return val;
3194 }
3195
3196 /* When a thread exits, remove breakpoints that are related to
3197    that thread.  */
3198
3199 static void
3200 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3201 {
3202   struct breakpoint *b, *b_tmp;
3203
3204   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3205     {
3206       if (b->thread == tp->num && user_breakpoint_p (b))
3207         {
3208           b->disposition = disp_del_at_next_stop;
3209
3210           printf_filtered (_("\
3211 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3212                           b->number, tp->num);
3213
3214           /* Hide it from the user.  */
3215           b->number = 0;
3216        }
3217     }
3218 }
3219
3220 /* Remove breakpoints of process PID.  */
3221
3222 int
3223 remove_breakpoints_pid (int pid)
3224 {
3225   struct bp_location *bl, **blp_tmp;
3226   int val;
3227   struct inferior *inf = find_inferior_pid (pid);
3228
3229   ALL_BP_LOCATIONS (bl, blp_tmp)
3230   {
3231     if (bl->pspace != inf->pspace)
3232       continue;
3233
3234     if (bl->inserted && !bl->target_info.persist)
3235       {
3236         val = remove_breakpoint (bl, mark_uninserted);
3237         if (val != 0)
3238           return val;
3239       }
3240   }
3241   return 0;
3242 }
3243
3244 int
3245 reattach_breakpoints (int pid)
3246 {
3247   struct cleanup *old_chain;
3248   struct bp_location *bl, **blp_tmp;
3249   int val;
3250   struct ui_file *tmp_error_stream;
3251   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3252   struct inferior *inf;
3253   struct thread_info *tp;
3254
3255   tp = any_live_thread_of_process (pid);
3256   if (tp == NULL)
3257     return 1;
3258
3259   inf = find_inferior_pid (pid);
3260   old_chain = save_inferior_ptid ();
3261
3262   inferior_ptid = tp->ptid;
3263
3264   tmp_error_stream = mem_fileopen ();
3265   make_cleanup_ui_file_delete (tmp_error_stream);
3266
3267   ALL_BP_LOCATIONS (bl, blp_tmp)
3268   {
3269     if (bl->pspace != inf->pspace)
3270       continue;
3271
3272     if (bl->inserted)
3273       {
3274         bl->inserted = 0;
3275         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3276         if (val != 0)
3277           {
3278             do_cleanups (old_chain);
3279             return val;
3280           }
3281       }
3282   }
3283   do_cleanups (old_chain);
3284   return 0;
3285 }
3286
3287 static int internal_breakpoint_number = -1;
3288
3289 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3290    If INTERNAL is non-zero, the breakpoint number will be populated
3291    from internal_breakpoint_number and that variable decremented.
3292    Otherwise the breakpoint number will be populated from
3293    breakpoint_count and that value incremented.  Internal breakpoints
3294    do not set the internal var bpnum.  */
3295 static void
3296 set_breakpoint_number (int internal, struct breakpoint *b)
3297 {
3298   if (internal)
3299     b->number = internal_breakpoint_number--;
3300   else
3301     {
3302       set_breakpoint_count (breakpoint_count + 1);
3303       b->number = breakpoint_count;
3304     }
3305 }
3306
3307 static struct breakpoint *
3308 create_internal_breakpoint (struct gdbarch *gdbarch,
3309                             CORE_ADDR address, enum bptype type,
3310                             const struct breakpoint_ops *ops)
3311 {
3312   struct symtab_and_line sal;
3313   struct breakpoint *b;
3314
3315   init_sal (&sal);              /* Initialize to zeroes.  */
3316
3317   sal.pc = address;
3318   sal.section = find_pc_overlay (sal.pc);
3319   sal.pspace = current_program_space;
3320
3321   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3322   b->number = internal_breakpoint_number--;
3323   b->disposition = disp_donttouch;
3324
3325   return b;
3326 }
3327
3328 static const char *const longjmp_names[] =
3329   {
3330     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3331   };
3332 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3333
3334 /* Per-objfile data private to breakpoint.c.  */
3335 struct breakpoint_objfile_data
3336 {
3337   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3338   struct bound_minimal_symbol overlay_msym;
3339
3340   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3341   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3342
3343   /* True if we have looked for longjmp probes.  */
3344   int longjmp_searched;
3345
3346   /* SystemTap probe points for longjmp (if any).  */
3347   VEC (probe_p) *longjmp_probes;
3348
3349   /* Minimal symbol for "std::terminate()" (if any).  */
3350   struct bound_minimal_symbol terminate_msym;
3351
3352   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3353   struct bound_minimal_symbol exception_msym;
3354
3355   /* True if we have looked for exception probes.  */
3356   int exception_searched;
3357
3358   /* SystemTap probe points for unwinding (if any).  */
3359   VEC (probe_p) *exception_probes;
3360 };
3361
3362 static const struct objfile_data *breakpoint_objfile_key;
3363
3364 /* Minimal symbol not found sentinel.  */
3365 static struct minimal_symbol msym_not_found;
3366
3367 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3368
3369 static int
3370 msym_not_found_p (const struct minimal_symbol *msym)
3371 {
3372   return msym == &msym_not_found;
3373 }
3374
3375 /* Return per-objfile data needed by breakpoint.c.
3376    Allocate the data if necessary.  */
3377
3378 static struct breakpoint_objfile_data *
3379 get_breakpoint_objfile_data (struct objfile *objfile)
3380 {
3381   struct breakpoint_objfile_data *bp_objfile_data;
3382
3383   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3384   if (bp_objfile_data == NULL)
3385     {
3386       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3387                                        sizeof (*bp_objfile_data));
3388
3389       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3390       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3391     }
3392   return bp_objfile_data;
3393 }
3394
3395 static void
3396 free_breakpoint_probes (struct objfile *obj, void *data)
3397 {
3398   struct breakpoint_objfile_data *bp_objfile_data = data;
3399
3400   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3401   VEC_free (probe_p, bp_objfile_data->exception_probes);
3402 }
3403
3404 static void
3405 create_overlay_event_breakpoint (void)
3406 {
3407   struct objfile *objfile;
3408   const char *const func_name = "_ovly_debug_event";
3409
3410   ALL_OBJFILES (objfile)
3411     {
3412       struct breakpoint *b;
3413       struct breakpoint_objfile_data *bp_objfile_data;
3414       CORE_ADDR addr;
3415
3416       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3417
3418       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3419         continue;
3420
3421       if (bp_objfile_data->overlay_msym.minsym == NULL)
3422         {
3423           struct bound_minimal_symbol m;
3424
3425           m = lookup_minimal_symbol_text (func_name, objfile);
3426           if (m.minsym == NULL)
3427             {
3428               /* Avoid future lookups in this objfile.  */
3429               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3430               continue;
3431             }
3432           bp_objfile_data->overlay_msym = m;
3433         }
3434
3435       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3436       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3437                                       bp_overlay_event,
3438                                       &internal_breakpoint_ops);
3439       b->addr_string = xstrdup (func_name);
3440
3441       if (overlay_debugging == ovly_auto)
3442         {
3443           b->enable_state = bp_enabled;
3444           overlay_events_enabled = 1;
3445         }
3446       else
3447        {
3448          b->enable_state = bp_disabled;
3449          overlay_events_enabled = 0;
3450        }
3451     }
3452   update_global_location_list (UGLL_MAY_INSERT);
3453 }
3454
3455 static void
3456 create_longjmp_master_breakpoint (void)
3457 {
3458   struct program_space *pspace;
3459   struct cleanup *old_chain;
3460
3461   old_chain = save_current_program_space ();
3462
3463   ALL_PSPACES (pspace)
3464   {
3465     struct objfile *objfile;
3466
3467     set_current_program_space (pspace);
3468
3469     ALL_OBJFILES (objfile)
3470     {
3471       int i;
3472       struct gdbarch *gdbarch;
3473       struct breakpoint_objfile_data *bp_objfile_data;
3474
3475       gdbarch = get_objfile_arch (objfile);
3476
3477       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3478
3479       if (!bp_objfile_data->longjmp_searched)
3480         {
3481           VEC (probe_p) *ret;
3482
3483           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3484           if (ret != NULL)
3485             {
3486               /* We are only interested in checking one element.  */
3487               struct probe *p = VEC_index (probe_p, ret, 0);
3488
3489               if (!can_evaluate_probe_arguments (p))
3490                 {
3491                   /* We cannot use the probe interface here, because it does
3492                      not know how to evaluate arguments.  */
3493                   VEC_free (probe_p, ret);
3494                   ret = NULL;
3495                 }
3496             }
3497           bp_objfile_data->longjmp_probes = ret;
3498           bp_objfile_data->longjmp_searched = 1;
3499         }
3500
3501       if (bp_objfile_data->longjmp_probes != NULL)
3502         {
3503           int i;
3504           struct probe *probe;
3505           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3506
3507           for (i = 0;
3508                VEC_iterate (probe_p,
3509                             bp_objfile_data->longjmp_probes,
3510                             i, probe);
3511                ++i)
3512             {
3513               struct breakpoint *b;
3514
3515               b = create_internal_breakpoint (gdbarch,
3516                                               get_probe_address (probe,
3517                                                                  objfile),
3518                                               bp_longjmp_master,
3519                                               &internal_breakpoint_ops);
3520               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3521               b->enable_state = bp_disabled;
3522             }
3523
3524           continue;
3525         }
3526
3527       if (!gdbarch_get_longjmp_target_p (gdbarch))
3528         continue;
3529
3530       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3531         {
3532           struct breakpoint *b;
3533           const char *func_name;
3534           CORE_ADDR addr;
3535
3536           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3537             continue;
3538
3539           func_name = longjmp_names[i];
3540           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3541             {
3542               struct bound_minimal_symbol m;
3543
3544               m = lookup_minimal_symbol_text (func_name, objfile);
3545               if (m.minsym == NULL)
3546                 {
3547                   /* Prevent future lookups in this objfile.  */
3548                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3549                   continue;
3550                 }
3551               bp_objfile_data->longjmp_msym[i] = m;
3552             }
3553
3554           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3555           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3556                                           &internal_breakpoint_ops);
3557           b->addr_string = xstrdup (func_name);
3558           b->enable_state = bp_disabled;
3559         }
3560     }
3561   }
3562   update_global_location_list (UGLL_MAY_INSERT);
3563
3564   do_cleanups (old_chain);
3565 }
3566
3567 /* Create a master std::terminate breakpoint.  */
3568 static void
3569 create_std_terminate_master_breakpoint (void)
3570 {
3571   struct program_space *pspace;
3572   struct cleanup *old_chain;
3573   const char *const func_name = "std::terminate()";
3574
3575   old_chain = save_current_program_space ();
3576
3577   ALL_PSPACES (pspace)
3578   {
3579     struct objfile *objfile;
3580     CORE_ADDR addr;
3581
3582     set_current_program_space (pspace);
3583
3584     ALL_OBJFILES (objfile)
3585     {
3586       struct breakpoint *b;
3587       struct breakpoint_objfile_data *bp_objfile_data;
3588
3589       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3590
3591       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3592         continue;
3593
3594       if (bp_objfile_data->terminate_msym.minsym == NULL)
3595         {
3596           struct bound_minimal_symbol m;
3597
3598           m = lookup_minimal_symbol (func_name, NULL, objfile);
3599           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3600                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3601             {
3602               /* Prevent future lookups in this objfile.  */
3603               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3604               continue;
3605             }
3606           bp_objfile_data->terminate_msym = m;
3607         }
3608
3609       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3610       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3611                                       bp_std_terminate_master,
3612                                       &internal_breakpoint_ops);
3613       b->addr_string = xstrdup (func_name);
3614       b->enable_state = bp_disabled;
3615     }
3616   }
3617
3618   update_global_location_list (UGLL_MAY_INSERT);
3619
3620   do_cleanups (old_chain);
3621 }
3622
3623 /* Install a master breakpoint on the unwinder's debug hook.  */
3624
3625 static void
3626 create_exception_master_breakpoint (void)
3627 {
3628   struct objfile *objfile;
3629   const char *const func_name = "_Unwind_DebugHook";
3630
3631   ALL_OBJFILES (objfile)
3632     {
3633       struct breakpoint *b;
3634       struct gdbarch *gdbarch;
3635       struct breakpoint_objfile_data *bp_objfile_data;
3636       CORE_ADDR addr;
3637
3638       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3639
3640       /* We prefer the SystemTap probe point if it exists.  */
3641       if (!bp_objfile_data->exception_searched)
3642         {
3643           VEC (probe_p) *ret;
3644
3645           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3646
3647           if (ret != NULL)
3648             {
3649               /* We are only interested in checking one element.  */
3650               struct probe *p = VEC_index (probe_p, ret, 0);
3651
3652               if (!can_evaluate_probe_arguments (p))
3653                 {
3654                   /* We cannot use the probe interface here, because it does
3655                      not know how to evaluate arguments.  */
3656                   VEC_free (probe_p, ret);
3657                   ret = NULL;
3658                 }
3659             }
3660           bp_objfile_data->exception_probes = ret;
3661           bp_objfile_data->exception_searched = 1;
3662         }
3663
3664       if (bp_objfile_data->exception_probes != NULL)
3665         {
3666           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3667           int i;
3668           struct probe *probe;
3669
3670           for (i = 0;
3671                VEC_iterate (probe_p,
3672                             bp_objfile_data->exception_probes,
3673                             i, probe);
3674                ++i)
3675             {
3676               struct breakpoint *b;
3677
3678               b = create_internal_breakpoint (gdbarch,
3679                                               get_probe_address (probe,
3680                                                                  objfile),
3681                                               bp_exception_master,
3682                                               &internal_breakpoint_ops);
3683               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3684               b->enable_state = bp_disabled;
3685             }
3686
3687           continue;
3688         }
3689
3690       /* Otherwise, try the hook function.  */
3691
3692       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3693         continue;
3694
3695       gdbarch = get_objfile_arch (objfile);
3696
3697       if (bp_objfile_data->exception_msym.minsym == NULL)
3698         {
3699           struct bound_minimal_symbol debug_hook;
3700
3701           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3702           if (debug_hook.minsym == NULL)
3703             {
3704               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3705               continue;
3706             }
3707
3708           bp_objfile_data->exception_msym = debug_hook;
3709         }
3710
3711       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3712       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3713                                                  &current_target);
3714       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3715                                       &internal_breakpoint_ops);
3716       b->addr_string = xstrdup (func_name);
3717       b->enable_state = bp_disabled;
3718     }
3719
3720   update_global_location_list (UGLL_MAY_INSERT);
3721 }
3722
3723 void
3724 update_breakpoints_after_exec (void)
3725 {
3726   struct breakpoint *b, *b_tmp;
3727   struct bp_location *bploc, **bplocp_tmp;
3728
3729   /* We're about to delete breakpoints from GDB's lists.  If the
3730      INSERTED flag is true, GDB will try to lift the breakpoints by
3731      writing the breakpoints' "shadow contents" back into memory.  The
3732      "shadow contents" are NOT valid after an exec, so GDB should not
3733      do that.  Instead, the target is responsible from marking
3734      breakpoints out as soon as it detects an exec.  We don't do that
3735      here instead, because there may be other attempts to delete
3736      breakpoints after detecting an exec and before reaching here.  */
3737   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3738     if (bploc->pspace == current_program_space)
3739       gdb_assert (!bploc->inserted);
3740
3741   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3742   {
3743     if (b->pspace != current_program_space)
3744       continue;
3745
3746     /* Solib breakpoints must be explicitly reset after an exec().  */
3747     if (b->type == bp_shlib_event)
3748       {
3749         delete_breakpoint (b);
3750         continue;
3751       }
3752
3753     /* JIT breakpoints must be explicitly reset after an exec().  */
3754     if (b->type == bp_jit_event)
3755       {
3756         delete_breakpoint (b);
3757         continue;
3758       }
3759
3760     /* Thread event breakpoints must be set anew after an exec(),
3761        as must overlay event and longjmp master breakpoints.  */
3762     if (b->type == bp_thread_event || b->type == bp_overlay_event
3763         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3764         || b->type == bp_exception_master)
3765       {
3766         delete_breakpoint (b);
3767         continue;
3768       }
3769
3770     /* Step-resume breakpoints are meaningless after an exec().  */
3771     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3772       {
3773         delete_breakpoint (b);
3774         continue;
3775       }
3776
3777     /* Just like single-step breakpoints.  */
3778     if (b->type == bp_single_step)
3779       {
3780         delete_breakpoint (b);
3781         continue;
3782       }
3783
3784     /* Longjmp and longjmp-resume breakpoints are also meaningless
3785        after an exec.  */
3786     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3787         || b->type == bp_longjmp_call_dummy
3788         || b->type == bp_exception || b->type == bp_exception_resume)
3789       {
3790         delete_breakpoint (b);
3791         continue;
3792       }
3793
3794     if (b->type == bp_catchpoint)
3795       {
3796         /* For now, none of the bp_catchpoint breakpoints need to
3797            do anything at this point.  In the future, if some of
3798            the catchpoints need to something, we will need to add
3799            a new method, and call this method from here.  */
3800         continue;
3801       }
3802
3803     /* bp_finish is a special case.  The only way we ought to be able
3804        to see one of these when an exec() has happened, is if the user
3805        caught a vfork, and then said "finish".  Ordinarily a finish just
3806        carries them to the call-site of the current callee, by setting
3807        a temporary bp there and resuming.  But in this case, the finish
3808        will carry them entirely through the vfork & exec.
3809
3810        We don't want to allow a bp_finish to remain inserted now.  But
3811        we can't safely delete it, 'cause finish_command has a handle to
3812        the bp on a bpstat, and will later want to delete it.  There's a
3813        chance (and I've seen it happen) that if we delete the bp_finish
3814        here, that its storage will get reused by the time finish_command
3815        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3816        We really must allow finish_command to delete a bp_finish.
3817
3818        In the absence of a general solution for the "how do we know
3819        it's safe to delete something others may have handles to?"
3820        problem, what we'll do here is just uninsert the bp_finish, and
3821        let finish_command delete it.
3822
3823        (We know the bp_finish is "doomed" in the sense that it's
3824        momentary, and will be deleted as soon as finish_command sees
3825        the inferior stopped.  So it doesn't matter that the bp's
3826        address is probably bogus in the new a.out, unlike e.g., the
3827        solib breakpoints.)  */
3828
3829     if (b->type == bp_finish)
3830       {
3831         continue;
3832       }
3833
3834     /* Without a symbolic address, we have little hope of the
3835        pre-exec() address meaning the same thing in the post-exec()
3836        a.out.  */
3837     if (b->addr_string == NULL)
3838       {
3839         delete_breakpoint (b);
3840         continue;
3841       }
3842   }
3843 }
3844
3845 int
3846 detach_breakpoints (ptid_t ptid)
3847 {
3848   struct bp_location *bl, **blp_tmp;
3849   int val = 0;
3850   struct cleanup *old_chain = save_inferior_ptid ();
3851   struct inferior *inf = current_inferior ();
3852
3853   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3854     error (_("Cannot detach breakpoints of inferior_ptid"));
3855
3856   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3857   inferior_ptid = ptid;
3858   ALL_BP_LOCATIONS (bl, blp_tmp)
3859   {
3860     if (bl->pspace != inf->pspace)
3861       continue;
3862
3863     /* This function must physically remove breakpoints locations
3864        from the specified ptid, without modifying the breakpoint
3865        package's state.  Locations of type bp_loc_other are only
3866        maintained at GDB side.  So, there is no need to remove
3867        these bp_loc_other locations.  Moreover, removing these
3868        would modify the breakpoint package's state.  */
3869     if (bl->loc_type == bp_loc_other)
3870       continue;
3871
3872     if (bl->inserted)
3873       val |= remove_breakpoint_1 (bl, mark_inserted);
3874   }
3875
3876   do_cleanups (old_chain);
3877   return val;
3878 }
3879
3880 /* Remove the breakpoint location BL from the current address space.
3881    Note that this is used to detach breakpoints from a child fork.
3882    When we get here, the child isn't in the inferior list, and neither
3883    do we have objects to represent its address space --- we should
3884    *not* look at bl->pspace->aspace here.  */
3885
3886 static int
3887 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3888 {
3889   int val;
3890
3891   /* BL is never in moribund_locations by our callers.  */
3892   gdb_assert (bl->owner != NULL);
3893
3894   if (bl->permanent)
3895     /* Permanent breakpoints cannot be inserted or removed.  */
3896     return 0;
3897
3898   /* The type of none suggests that owner is actually deleted.
3899      This should not ever happen.  */
3900   gdb_assert (bl->owner->type != bp_none);
3901
3902   if (bl->loc_type == bp_loc_software_breakpoint
3903       || bl->loc_type == bp_loc_hardware_breakpoint)
3904     {
3905       /* "Normal" instruction breakpoint: either the standard
3906          trap-instruction bp (bp_breakpoint), or a
3907          bp_hardware_breakpoint.  */
3908
3909       /* First check to see if we have to handle an overlay.  */
3910       if (overlay_debugging == ovly_off
3911           || bl->section == NULL
3912           || !(section_is_overlay (bl->section)))
3913         {
3914           /* No overlay handling: just remove the breakpoint.  */
3915
3916           /* If we're trying to uninsert a memory breakpoint that we
3917              know is set in a dynamic object that is marked
3918              shlib_disabled, then either the dynamic object was
3919              removed with "remove-symbol-file" or with
3920              "nosharedlibrary".  In the former case, we don't know
3921              whether another dynamic object might have loaded over the
3922              breakpoint's address -- the user might well let us know
3923              about it next with add-symbol-file (the whole point of
3924              add-symbol-file is letting the user manually maintain a
3925              list of dynamically loaded objects).  If we have the
3926              breakpoint's shadow memory, that is, this is a software
3927              breakpoint managed by GDB, check whether the breakpoint
3928              is still inserted in memory, to avoid overwriting wrong
3929              code with stale saved shadow contents.  Note that HW
3930              breakpoints don't have shadow memory, as they're
3931              implemented using a mechanism that is not dependent on
3932              being able to modify the target's memory, and as such
3933              they should always be removed.  */
3934           if (bl->shlib_disabled
3935               && bl->target_info.shadow_len != 0
3936               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3937             val = 0;
3938           else
3939             val = bl->owner->ops->remove_location (bl);
3940         }
3941       else
3942         {
3943           /* This breakpoint is in an overlay section.
3944              Did we set a breakpoint at the LMA?  */
3945           if (!overlay_events_enabled)
3946               {
3947                 /* Yes -- overlay event support is not active, so we
3948                    should have set a breakpoint at the LMA.  Remove it.  
3949                 */
3950                 /* Ignore any failures: if the LMA is in ROM, we will
3951                    have already warned when we failed to insert it.  */
3952                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3953                   target_remove_hw_breakpoint (bl->gdbarch,
3954                                                &bl->overlay_target_info);
3955                 else
3956                   target_remove_breakpoint (bl->gdbarch,
3957                                             &bl->overlay_target_info);
3958               }
3959           /* Did we set a breakpoint at the VMA? 
3960              If so, we will have marked the breakpoint 'inserted'.  */
3961           if (bl->inserted)
3962             {
3963               /* Yes -- remove it.  Previously we did not bother to
3964                  remove the breakpoint if the section had been
3965                  unmapped, but let's not rely on that being safe.  We
3966                  don't know what the overlay manager might do.  */
3967
3968               /* However, we should remove *software* breakpoints only
3969                  if the section is still mapped, or else we overwrite
3970                  wrong code with the saved shadow contents.  */
3971               if (bl->loc_type == bp_loc_hardware_breakpoint
3972                   || section_is_mapped (bl->section))
3973                 val = bl->owner->ops->remove_location (bl);
3974               else
3975                 val = 0;
3976             }
3977           else
3978             {
3979               /* No -- not inserted, so no need to remove.  No error.  */
3980               val = 0;
3981             }
3982         }
3983
3984       /* In some cases, we might not be able to remove a breakpoint in
3985          a shared library that has already been removed, but we have
3986          not yet processed the shlib unload event.  Similarly for an
3987          unloaded add-symbol-file object - the user might not yet have
3988          had the chance to remove-symbol-file it.  shlib_disabled will
3989          be set if the library/object has already been removed, but
3990          the breakpoint hasn't been uninserted yet, e.g., after
3991          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3992          always-inserted mode.  */
3993       if (val
3994           && (bl->loc_type == bp_loc_software_breakpoint
3995               && (bl->shlib_disabled
3996                   || solib_name_from_address (bl->pspace, bl->address)
3997                   || shared_objfile_contains_address_p (bl->pspace,
3998                                                         bl->address))))
3999         val = 0;
4000
4001       if (val)
4002         return val;
4003       bl->inserted = (is == mark_inserted);
4004     }
4005   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4006     {
4007       gdb_assert (bl->owner->ops != NULL
4008                   && bl->owner->ops->remove_location != NULL);
4009
4010       bl->inserted = (is == mark_inserted);
4011       bl->owner->ops->remove_location (bl);
4012
4013       /* Failure to remove any of the hardware watchpoints comes here.  */
4014       if ((is == mark_uninserted) && (bl->inserted))
4015         warning (_("Could not remove hardware watchpoint %d."),
4016                  bl->owner->number);
4017     }
4018   else if (bl->owner->type == bp_catchpoint
4019            && breakpoint_enabled (bl->owner)
4020            && !bl->duplicate)
4021     {
4022       gdb_assert (bl->owner->ops != NULL
4023                   && bl->owner->ops->remove_location != NULL);
4024
4025       val = bl->owner->ops->remove_location (bl);
4026       if (val)
4027         return val;
4028
4029       bl->inserted = (is == mark_inserted);
4030     }
4031
4032   return 0;
4033 }
4034
4035 static int
4036 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4037 {
4038   int ret;
4039   struct cleanup *old_chain;
4040
4041   /* BL is never in moribund_locations by our callers.  */
4042   gdb_assert (bl->owner != NULL);
4043
4044   if (bl->permanent)
4045     /* Permanent breakpoints cannot be inserted or removed.  */
4046     return 0;
4047
4048   /* The type of none suggests that owner is actually deleted.
4049      This should not ever happen.  */
4050   gdb_assert (bl->owner->type != bp_none);
4051
4052   old_chain = save_current_space_and_thread ();
4053
4054   switch_to_program_space_and_thread (bl->pspace);
4055
4056   ret = remove_breakpoint_1 (bl, is);
4057
4058   do_cleanups (old_chain);
4059   return ret;
4060 }
4061
4062 /* Clear the "inserted" flag in all breakpoints.  */
4063
4064 void
4065 mark_breakpoints_out (void)
4066 {
4067   struct bp_location *bl, **blp_tmp;
4068
4069   ALL_BP_LOCATIONS (bl, blp_tmp)
4070     if (bl->pspace == current_program_space
4071         && !bl->permanent)
4072       bl->inserted = 0;
4073 }
4074
4075 /* Clear the "inserted" flag in all breakpoints and delete any
4076    breakpoints which should go away between runs of the program.
4077
4078    Plus other such housekeeping that has to be done for breakpoints
4079    between runs.
4080
4081    Note: this function gets called at the end of a run (by
4082    generic_mourn_inferior) and when a run begins (by
4083    init_wait_for_inferior).  */
4084
4085
4086
4087 void
4088 breakpoint_init_inferior (enum inf_context context)
4089 {
4090   struct breakpoint *b, *b_tmp;
4091   struct bp_location *bl, **blp_tmp;
4092   int ix;
4093   struct program_space *pspace = current_program_space;
4094
4095   /* If breakpoint locations are shared across processes, then there's
4096      nothing to do.  */
4097   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4098     return;
4099
4100   mark_breakpoints_out ();
4101
4102   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4103   {
4104     if (b->loc && b->loc->pspace != pspace)
4105       continue;
4106
4107     switch (b->type)
4108       {
4109       case bp_call_dummy:
4110       case bp_longjmp_call_dummy:
4111
4112         /* If the call dummy breakpoint is at the entry point it will
4113            cause problems when the inferior is rerun, so we better get
4114            rid of it.  */
4115
4116       case bp_watchpoint_scope:
4117
4118         /* Also get rid of scope breakpoints.  */
4119
4120       case bp_shlib_event:
4121
4122         /* Also remove solib event breakpoints.  Their addresses may
4123            have changed since the last time we ran the program.
4124            Actually we may now be debugging against different target;
4125            and so the solib backend that installed this breakpoint may
4126            not be used in by the target.  E.g.,
4127
4128            (gdb) file prog-linux
4129            (gdb) run               # native linux target
4130            ...
4131            (gdb) kill
4132            (gdb) file prog-win.exe
4133            (gdb) tar rem :9999     # remote Windows gdbserver.
4134         */
4135
4136       case bp_step_resume:
4137
4138         /* Also remove step-resume breakpoints.  */
4139
4140       case bp_single_step:
4141
4142         /* Also remove single-step breakpoints.  */
4143
4144         delete_breakpoint (b);
4145         break;
4146
4147       case bp_watchpoint:
4148       case bp_hardware_watchpoint:
4149       case bp_read_watchpoint:
4150       case bp_access_watchpoint:
4151         {
4152           struct watchpoint *w = (struct watchpoint *) b;
4153
4154           /* Likewise for watchpoints on local expressions.  */
4155           if (w->exp_valid_block != NULL)
4156             delete_breakpoint (b);
4157           else if (context == inf_starting)
4158             {
4159               /* Reset val field to force reread of starting value in
4160                  insert_breakpoints.  */
4161               if (w->val)
4162                 value_free (w->val);
4163               w->val = NULL;
4164               w->val_valid = 0;
4165           }
4166         }
4167         break;
4168       default:
4169         break;
4170       }
4171   }
4172
4173   /* Get rid of the moribund locations.  */
4174   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4175     decref_bp_location (&bl);
4176   VEC_free (bp_location_p, moribund_locations);
4177 }
4178
4179 /* These functions concern about actual breakpoints inserted in the
4180    target --- to e.g. check if we need to do decr_pc adjustment or if
4181    we need to hop over the bkpt --- so we check for address space
4182    match, not program space.  */
4183
4184 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4185    exists at PC.  It returns ordinary_breakpoint_here if it's an
4186    ordinary breakpoint, or permanent_breakpoint_here if it's a
4187    permanent breakpoint.
4188    - When continuing from a location with an ordinary breakpoint, we
4189      actually single step once before calling insert_breakpoints.
4190    - When continuing from a location with a permanent breakpoint, we
4191      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4192      the target, to advance the PC past the breakpoint.  */
4193
4194 enum breakpoint_here
4195 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4196 {
4197   struct bp_location *bl, **blp_tmp;
4198   int any_breakpoint_here = 0;
4199
4200   ALL_BP_LOCATIONS (bl, blp_tmp)
4201     {
4202       if (bl->loc_type != bp_loc_software_breakpoint
4203           && bl->loc_type != bp_loc_hardware_breakpoint)
4204         continue;
4205
4206       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4207       if ((breakpoint_enabled (bl->owner)
4208            || bl->permanent)
4209           && breakpoint_location_address_match (bl, aspace, pc))
4210         {
4211           if (overlay_debugging 
4212               && section_is_overlay (bl->section)
4213               && !section_is_mapped (bl->section))
4214             continue;           /* unmapped overlay -- can't be a match */
4215           else if (bl->permanent)
4216             return permanent_breakpoint_here;
4217           else
4218             any_breakpoint_here = 1;
4219         }
4220     }
4221
4222   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4223 }
4224
4225 /* Return true if there's a moribund breakpoint at PC.  */
4226
4227 int
4228 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4229 {
4230   struct bp_location *loc;
4231   int ix;
4232
4233   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4234     if (breakpoint_location_address_match (loc, aspace, pc))
4235       return 1;
4236
4237   return 0;
4238 }
4239
4240 /* Returns non-zero iff BL is inserted at PC, in address space
4241    ASPACE.  */
4242
4243 static int
4244 bp_location_inserted_here_p (struct bp_location *bl,
4245                              struct address_space *aspace, CORE_ADDR pc)
4246 {
4247   if (bl->inserted
4248       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4249                                    aspace, pc))
4250     {
4251       if (overlay_debugging
4252           && section_is_overlay (bl->section)
4253           && !section_is_mapped (bl->section))
4254         return 0;               /* unmapped overlay -- can't be a match */
4255       else
4256         return 1;
4257     }
4258   return 0;
4259 }
4260
4261 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4262
4263 int
4264 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4265 {
4266   struct bp_location **blp, **blp_tmp = NULL;
4267   struct bp_location *bl;
4268
4269   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4270     {
4271       struct bp_location *bl = *blp;
4272
4273       if (bl->loc_type != bp_loc_software_breakpoint
4274           && bl->loc_type != bp_loc_hardware_breakpoint)
4275         continue;
4276
4277       if (bp_location_inserted_here_p (bl, aspace, pc))
4278         return 1;
4279     }
4280   return 0;
4281 }
4282
4283 /* This function returns non-zero iff there is a software breakpoint
4284    inserted at PC.  */
4285
4286 int
4287 software_breakpoint_inserted_here_p (struct address_space *aspace,
4288                                      CORE_ADDR pc)
4289 {
4290   struct bp_location **blp, **blp_tmp = NULL;
4291   struct bp_location *bl;
4292
4293   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4294     {
4295       struct bp_location *bl = *blp;
4296
4297       if (bl->loc_type != bp_loc_software_breakpoint)
4298         continue;
4299
4300       if (bp_location_inserted_here_p (bl, aspace, pc))
4301         return 1;
4302     }
4303
4304   return 0;
4305 }
4306
4307 /* See breakpoint.h.  */
4308
4309 int
4310 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4311                                      CORE_ADDR pc)
4312 {
4313   struct bp_location **blp, **blp_tmp = NULL;
4314   struct bp_location *bl;
4315
4316   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4317     {
4318       struct bp_location *bl = *blp;
4319
4320       if (bl->loc_type != bp_loc_hardware_breakpoint)
4321         continue;
4322
4323       if (bp_location_inserted_here_p (bl, aspace, pc))
4324         return 1;
4325     }
4326
4327   return 0;
4328 }
4329
4330 int
4331 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4332                                        CORE_ADDR addr, ULONGEST len)
4333 {
4334   struct breakpoint *bpt;
4335
4336   ALL_BREAKPOINTS (bpt)
4337     {
4338       struct bp_location *loc;
4339
4340       if (bpt->type != bp_hardware_watchpoint
4341           && bpt->type != bp_access_watchpoint)
4342         continue;
4343
4344       if (!breakpoint_enabled (bpt))
4345         continue;
4346
4347       for (loc = bpt->loc; loc; loc = loc->next)
4348         if (loc->pspace->aspace == aspace && loc->inserted)
4349           {
4350             CORE_ADDR l, h;
4351
4352             /* Check for intersection.  */
4353             l = max (loc->address, addr);
4354             h = min (loc->address + loc->length, addr + len);
4355             if (l < h)
4356               return 1;
4357           }
4358     }
4359   return 0;
4360 }
4361 \f
4362
4363 /* bpstat stuff.  External routines' interfaces are documented
4364    in breakpoint.h.  */
4365
4366 int
4367 is_catchpoint (struct breakpoint *ep)
4368 {
4369   return (ep->type == bp_catchpoint);
4370 }
4371
4372 /* Frees any storage that is part of a bpstat.  Does not walk the
4373    'next' chain.  */
4374
4375 static void
4376 bpstat_free (bpstat bs)
4377 {
4378   if (bs->old_val != NULL)
4379     value_free (bs->old_val);
4380   decref_counted_command_line (&bs->commands);
4381   decref_bp_location (&bs->bp_location_at);
4382   xfree (bs);
4383 }
4384
4385 /* Clear a bpstat so that it says we are not at any breakpoint.
4386    Also free any storage that is part of a bpstat.  */
4387
4388 void
4389 bpstat_clear (bpstat *bsp)
4390 {
4391   bpstat p;
4392   bpstat q;
4393
4394   if (bsp == 0)
4395     return;
4396   p = *bsp;
4397   while (p != NULL)
4398     {
4399       q = p->next;
4400       bpstat_free (p);
4401       p = q;
4402     }
4403   *bsp = NULL;
4404 }
4405
4406 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4407    is part of the bpstat is copied as well.  */
4408
4409 bpstat
4410 bpstat_copy (bpstat bs)
4411 {
4412   bpstat p = NULL;
4413   bpstat tmp;
4414   bpstat retval = NULL;
4415
4416   if (bs == NULL)
4417     return bs;
4418
4419   for (; bs != NULL; bs = bs->next)
4420     {
4421       tmp = (bpstat) xmalloc (sizeof (*tmp));
4422       memcpy (tmp, bs, sizeof (*tmp));
4423       incref_counted_command_line (tmp->commands);
4424       incref_bp_location (tmp->bp_location_at);
4425       if (bs->old_val != NULL)
4426         {
4427           tmp->old_val = value_copy (bs->old_val);
4428           release_value (tmp->old_val);
4429         }
4430
4431       if (p == NULL)
4432         /* This is the first thing in the chain.  */
4433         retval = tmp;
4434       else
4435         p->next = tmp;
4436       p = tmp;
4437     }
4438   p->next = NULL;
4439   return retval;
4440 }
4441
4442 /* Find the bpstat associated with this breakpoint.  */
4443
4444 bpstat
4445 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4446 {
4447   if (bsp == NULL)
4448     return NULL;
4449
4450   for (; bsp != NULL; bsp = bsp->next)
4451     {
4452       if (bsp->breakpoint_at == breakpoint)
4453         return bsp;
4454     }
4455   return NULL;
4456 }
4457
4458 /* See breakpoint.h.  */
4459
4460 int
4461 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4462 {
4463   for (; bsp != NULL; bsp = bsp->next)
4464     {
4465       if (bsp->breakpoint_at == NULL)
4466         {
4467           /* A moribund location can never explain a signal other than
4468              GDB_SIGNAL_TRAP.  */
4469           if (sig == GDB_SIGNAL_TRAP)
4470             return 1;
4471         }
4472       else
4473         {
4474           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4475                                                         sig))
4476             return 1;
4477         }
4478     }
4479
4480   return 0;
4481 }
4482
4483 /* Put in *NUM the breakpoint number of the first breakpoint we are
4484    stopped at.  *BSP upon return is a bpstat which points to the
4485    remaining breakpoints stopped at (but which is not guaranteed to be
4486    good for anything but further calls to bpstat_num).
4487
4488    Return 0 if passed a bpstat which does not indicate any breakpoints.
4489    Return -1 if stopped at a breakpoint that has been deleted since
4490    we set it.
4491    Return 1 otherwise.  */
4492
4493 int
4494 bpstat_num (bpstat *bsp, int *num)
4495 {
4496   struct breakpoint *b;
4497
4498   if ((*bsp) == NULL)
4499     return 0;                   /* No more breakpoint values */
4500
4501   /* We assume we'll never have several bpstats that correspond to a
4502      single breakpoint -- otherwise, this function might return the
4503      same number more than once and this will look ugly.  */
4504   b = (*bsp)->breakpoint_at;
4505   *bsp = (*bsp)->next;
4506   if (b == NULL)
4507     return -1;                  /* breakpoint that's been deleted since */
4508
4509   *num = b->number;             /* We have its number */
4510   return 1;
4511 }
4512
4513 /* See breakpoint.h.  */
4514
4515 void
4516 bpstat_clear_actions (void)
4517 {
4518   struct thread_info *tp;
4519   bpstat bs;
4520
4521   if (ptid_equal (inferior_ptid, null_ptid))
4522     return;
4523
4524   tp = find_thread_ptid (inferior_ptid);
4525   if (tp == NULL)
4526     return;
4527
4528   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4529     {
4530       decref_counted_command_line (&bs->commands);
4531
4532       if (bs->old_val != NULL)
4533         {
4534           value_free (bs->old_val);
4535           bs->old_val = NULL;
4536         }
4537     }
4538 }
4539
4540 /* Called when a command is about to proceed the inferior.  */
4541
4542 static void
4543 breakpoint_about_to_proceed (void)
4544 {
4545   if (!ptid_equal (inferior_ptid, null_ptid))
4546     {
4547       struct thread_info *tp = inferior_thread ();
4548
4549       /* Allow inferior function calls in breakpoint commands to not
4550          interrupt the command list.  When the call finishes
4551          successfully, the inferior will be standing at the same
4552          breakpoint as if nothing happened.  */
4553       if (tp->control.in_infcall)
4554         return;
4555     }
4556
4557   breakpoint_proceeded = 1;
4558 }
4559
4560 /* Stub for cleaning up our state if we error-out of a breakpoint
4561    command.  */
4562 static void
4563 cleanup_executing_breakpoints (void *ignore)
4564 {
4565   executing_breakpoint_commands = 0;
4566 }
4567
4568 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4569    or its equivalent.  */
4570
4571 static int
4572 command_line_is_silent (struct command_line *cmd)
4573 {
4574   return cmd && (strcmp ("silent", cmd->line) == 0);
4575 }
4576
4577 /* Execute all the commands associated with all the breakpoints at
4578    this location.  Any of these commands could cause the process to
4579    proceed beyond this point, etc.  We look out for such changes by
4580    checking the global "breakpoint_proceeded" after each command.
4581
4582    Returns true if a breakpoint command resumed the inferior.  In that
4583    case, it is the caller's responsibility to recall it again with the
4584    bpstat of the current thread.  */
4585
4586 static int
4587 bpstat_do_actions_1 (bpstat *bsp)
4588 {
4589   bpstat bs;
4590   struct cleanup *old_chain;
4591   int again = 0;
4592
4593   /* Avoid endless recursion if a `source' command is contained
4594      in bs->commands.  */
4595   if (executing_breakpoint_commands)
4596     return 0;
4597
4598   executing_breakpoint_commands = 1;
4599   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4600
4601   prevent_dont_repeat ();
4602
4603   /* This pointer will iterate over the list of bpstat's.  */
4604   bs = *bsp;
4605
4606   breakpoint_proceeded = 0;
4607   for (; bs != NULL; bs = bs->next)
4608     {
4609       struct counted_command_line *ccmd;
4610       struct command_line *cmd;
4611       struct cleanup *this_cmd_tree_chain;
4612
4613       /* Take ownership of the BSP's command tree, if it has one.
4614
4615          The command tree could legitimately contain commands like
4616          'step' and 'next', which call clear_proceed_status, which
4617          frees stop_bpstat's command tree.  To make sure this doesn't
4618          free the tree we're executing out from under us, we need to
4619          take ownership of the tree ourselves.  Since a given bpstat's
4620          commands are only executed once, we don't need to copy it; we
4621          can clear the pointer in the bpstat, and make sure we free
4622          the tree when we're done.  */
4623       ccmd = bs->commands;
4624       bs->commands = NULL;
4625       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4626       cmd = ccmd ? ccmd->commands : NULL;
4627       if (command_line_is_silent (cmd))
4628         {
4629           /* The action has been already done by bpstat_stop_status.  */
4630           cmd = cmd->next;
4631         }
4632
4633       while (cmd != NULL)
4634         {
4635           execute_control_command (cmd);
4636
4637           if (breakpoint_proceeded)
4638             break;
4639           else
4640             cmd = cmd->next;
4641         }
4642
4643       /* We can free this command tree now.  */
4644       do_cleanups (this_cmd_tree_chain);
4645
4646       if (breakpoint_proceeded)
4647         {
4648           if (interpreter_async && target_can_async_p ())
4649             /* If we are in async mode, then the target might be still
4650                running, not stopped at any breakpoint, so nothing for
4651                us to do here -- just return to the event loop.  */
4652             ;
4653           else
4654             /* In sync mode, when execute_control_command returns
4655                we're already standing on the next breakpoint.
4656                Breakpoint commands for that stop were not run, since
4657                execute_command does not run breakpoint commands --
4658                only command_line_handler does, but that one is not
4659                involved in execution of breakpoint commands.  So, we
4660                can now execute breakpoint commands.  It should be
4661                noted that making execute_command do bpstat actions is
4662                not an option -- in this case we'll have recursive
4663                invocation of bpstat for each breakpoint with a
4664                command, and can easily blow up GDB stack.  Instead, we
4665                return true, which will trigger the caller to recall us
4666                with the new stop_bpstat.  */
4667             again = 1;
4668           break;
4669         }
4670     }
4671   do_cleanups (old_chain);
4672   return again;
4673 }
4674
4675 void
4676 bpstat_do_actions (void)
4677 {
4678   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4679
4680   /* Do any commands attached to breakpoint we are stopped at.  */
4681   while (!ptid_equal (inferior_ptid, null_ptid)
4682          && target_has_execution
4683          && !is_exited (inferior_ptid)
4684          && !is_executing (inferior_ptid))
4685     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4686        and only return when it is stopped at the next breakpoint, we
4687        keep doing breakpoint actions until it returns false to
4688        indicate the inferior was not resumed.  */
4689     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4690       break;
4691
4692   discard_cleanups (cleanup_if_error);
4693 }
4694
4695 /* Print out the (old or new) value associated with a watchpoint.  */
4696
4697 static void
4698 watchpoint_value_print (struct value *val, struct ui_file *stream)
4699 {
4700   if (val == NULL)
4701     fprintf_unfiltered (stream, _("<unreadable>"));
4702   else
4703     {
4704       struct value_print_options opts;
4705       get_user_print_options (&opts);
4706       value_print (val, stream, &opts);
4707     }
4708 }
4709
4710 /* Generic routine for printing messages indicating why we
4711    stopped.  The behavior of this function depends on the value
4712    'print_it' in the bpstat structure.  Under some circumstances we
4713    may decide not to print anything here and delegate the task to
4714    normal_stop().  */
4715
4716 static enum print_stop_action
4717 print_bp_stop_message (bpstat bs)
4718 {
4719   switch (bs->print_it)
4720     {
4721     case print_it_noop:
4722       /* Nothing should be printed for this bpstat entry.  */
4723       return PRINT_UNKNOWN;
4724       break;
4725
4726     case print_it_done:
4727       /* We still want to print the frame, but we already printed the
4728          relevant messages.  */
4729       return PRINT_SRC_AND_LOC;
4730       break;
4731
4732     case print_it_normal:
4733       {
4734         struct breakpoint *b = bs->breakpoint_at;
4735
4736         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4737            which has since been deleted.  */
4738         if (b == NULL)
4739           return PRINT_UNKNOWN;
4740
4741         /* Normal case.  Call the breakpoint's print_it method.  */
4742         return b->ops->print_it (bs);
4743       }
4744       break;
4745
4746     default:
4747       internal_error (__FILE__, __LINE__,
4748                       _("print_bp_stop_message: unrecognized enum value"));
4749       break;
4750     }
4751 }
4752
4753 /* A helper function that prints a shared library stopped event.  */
4754
4755 static void
4756 print_solib_event (int is_catchpoint)
4757 {
4758   int any_deleted
4759     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4760   int any_added
4761     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4762
4763   if (!is_catchpoint)
4764     {
4765       if (any_added || any_deleted)
4766         ui_out_text (current_uiout,
4767                      _("Stopped due to shared library event:\n"));
4768       else
4769         ui_out_text (current_uiout,
4770                      _("Stopped due to shared library event (no "
4771                        "libraries added or removed)\n"));
4772     }
4773
4774   if (ui_out_is_mi_like_p (current_uiout))
4775     ui_out_field_string (current_uiout, "reason",
4776                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4777
4778   if (any_deleted)
4779     {
4780       struct cleanup *cleanup;
4781       char *name;
4782       int ix;
4783
4784       ui_out_text (current_uiout, _("  Inferior unloaded "));
4785       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4786                                                     "removed");
4787       for (ix = 0;
4788            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4789                         ix, name);
4790            ++ix)
4791         {
4792           if (ix > 0)
4793             ui_out_text (current_uiout, "    ");
4794           ui_out_field_string (current_uiout, "library", name);
4795           ui_out_text (current_uiout, "\n");
4796         }
4797
4798       do_cleanups (cleanup);
4799     }
4800
4801   if (any_added)
4802     {
4803       struct so_list *iter;
4804       int ix;
4805       struct cleanup *cleanup;
4806
4807       ui_out_text (current_uiout, _("  Inferior loaded "));
4808       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4809                                                     "added");
4810       for (ix = 0;
4811            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4812                         ix, iter);
4813            ++ix)
4814         {
4815           if (ix > 0)
4816             ui_out_text (current_uiout, "    ");
4817           ui_out_field_string (current_uiout, "library", iter->so_name);
4818           ui_out_text (current_uiout, "\n");
4819         }
4820
4821       do_cleanups (cleanup);
4822     }
4823 }
4824
4825 /* Print a message indicating what happened.  This is called from
4826    normal_stop().  The input to this routine is the head of the bpstat
4827    list - a list of the eventpoints that caused this stop.  KIND is
4828    the target_waitkind for the stopping event.  This
4829    routine calls the generic print routine for printing a message
4830    about reasons for stopping.  This will print (for example) the
4831    "Breakpoint n," part of the output.  The return value of this
4832    routine is one of:
4833
4834    PRINT_UNKNOWN: Means we printed nothing.
4835    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4836    code to print the location.  An example is 
4837    "Breakpoint 1, " which should be followed by
4838    the location.
4839    PRINT_SRC_ONLY: Means we printed something, but there is no need
4840    to also print the location part of the message.
4841    An example is the catch/throw messages, which
4842    don't require a location appended to the end.
4843    PRINT_NOTHING: We have done some printing and we don't need any 
4844    further info to be printed.  */
4845
4846 enum print_stop_action
4847 bpstat_print (bpstat bs, int kind)
4848 {
4849   int val;
4850
4851   /* Maybe another breakpoint in the chain caused us to stop.
4852      (Currently all watchpoints go on the bpstat whether hit or not.
4853      That probably could (should) be changed, provided care is taken
4854      with respect to bpstat_explains_signal).  */
4855   for (; bs; bs = bs->next)
4856     {
4857       val = print_bp_stop_message (bs);
4858       if (val == PRINT_SRC_ONLY 
4859           || val == PRINT_SRC_AND_LOC 
4860           || val == PRINT_NOTHING)
4861         return val;
4862     }
4863
4864   /* If we had hit a shared library event breakpoint,
4865      print_bp_stop_message would print out this message.  If we hit an
4866      OS-level shared library event, do the same thing.  */
4867   if (kind == TARGET_WAITKIND_LOADED)
4868     {
4869       print_solib_event (0);
4870       return PRINT_NOTHING;
4871     }
4872
4873   /* We reached the end of the chain, or we got a null BS to start
4874      with and nothing was printed.  */
4875   return PRINT_UNKNOWN;
4876 }
4877
4878 /* Evaluate the expression EXP and return 1 if value is zero.
4879    This returns the inverse of the condition because it is called
4880    from catch_errors which returns 0 if an exception happened, and if an
4881    exception happens we want execution to stop.
4882    The argument is a "struct expression *" that has been cast to a
4883    "void *" to make it pass through catch_errors.  */
4884
4885 static int
4886 breakpoint_cond_eval (void *exp)
4887 {
4888   struct value *mark = value_mark ();
4889   int i = !value_true (evaluate_expression ((struct expression *) exp));
4890
4891   value_free_to_mark (mark);
4892   return i;
4893 }
4894
4895 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4896
4897 static bpstat
4898 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4899 {
4900   bpstat bs;
4901
4902   bs = (bpstat) xmalloc (sizeof (*bs));
4903   bs->next = NULL;
4904   **bs_link_pointer = bs;
4905   *bs_link_pointer = &bs->next;
4906   bs->breakpoint_at = bl->owner;
4907   bs->bp_location_at = bl;
4908   incref_bp_location (bl);
4909   /* If the condition is false, etc., don't do the commands.  */
4910   bs->commands = NULL;
4911   bs->old_val = NULL;
4912   bs->print_it = print_it_normal;
4913   return bs;
4914 }
4915 \f
4916 /* The target has stopped with waitstatus WS.  Check if any hardware
4917    watchpoints have triggered, according to the target.  */
4918
4919 int
4920 watchpoints_triggered (struct target_waitstatus *ws)
4921 {
4922   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4923   CORE_ADDR addr;
4924   struct breakpoint *b;
4925
4926   if (!stopped_by_watchpoint)
4927     {
4928       /* We were not stopped by a watchpoint.  Mark all watchpoints
4929          as not triggered.  */
4930       ALL_BREAKPOINTS (b)
4931         if (is_hardware_watchpoint (b))
4932           {
4933             struct watchpoint *w = (struct watchpoint *) b;
4934
4935             w->watchpoint_triggered = watch_triggered_no;
4936           }
4937
4938       return 0;
4939     }
4940
4941   if (!target_stopped_data_address (&current_target, &addr))
4942     {
4943       /* We were stopped by a watchpoint, but we don't know where.
4944          Mark all watchpoints as unknown.  */
4945       ALL_BREAKPOINTS (b)
4946         if (is_hardware_watchpoint (b))
4947           {
4948             struct watchpoint *w = (struct watchpoint *) b;
4949
4950             w->watchpoint_triggered = watch_triggered_unknown;
4951           }
4952
4953       return 1;
4954     }
4955
4956   /* The target could report the data address.  Mark watchpoints
4957      affected by this data address as triggered, and all others as not
4958      triggered.  */
4959
4960   ALL_BREAKPOINTS (b)
4961     if (is_hardware_watchpoint (b))
4962       {
4963         struct watchpoint *w = (struct watchpoint *) b;
4964         struct bp_location *loc;
4965
4966         w->watchpoint_triggered = watch_triggered_no;
4967         for (loc = b->loc; loc; loc = loc->next)
4968           {
4969             if (is_masked_watchpoint (b))
4970               {
4971                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4972                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4973
4974                 if (newaddr == start)
4975                   {
4976                     w->watchpoint_triggered = watch_triggered_yes;
4977                     break;
4978                   }
4979               }
4980             /* Exact match not required.  Within range is sufficient.  */
4981             else if (target_watchpoint_addr_within_range (&current_target,
4982                                                          addr, loc->address,
4983                                                          loc->length))
4984               {
4985                 w->watchpoint_triggered = watch_triggered_yes;
4986                 break;
4987               }
4988           }
4989       }
4990
4991   return 1;
4992 }
4993
4994 /* Possible return values for watchpoint_check (this can't be an enum
4995    because of check_errors).  */
4996 /* The watchpoint has been deleted.  */
4997 #define WP_DELETED 1
4998 /* The value has changed.  */
4999 #define WP_VALUE_CHANGED 2
5000 /* The value has not changed.  */
5001 #define WP_VALUE_NOT_CHANGED 3
5002 /* Ignore this watchpoint, no matter if the value changed or not.  */
5003 #define WP_IGNORE 4
5004
5005 #define BP_TEMPFLAG 1
5006 #define BP_HARDWAREFLAG 2
5007
5008 /* Evaluate watchpoint condition expression and check if its value
5009    changed.
5010
5011    P should be a pointer to struct bpstat, but is defined as a void *
5012    in order for this function to be usable with catch_errors.  */
5013
5014 static int
5015 watchpoint_check (void *p)
5016 {
5017   bpstat bs = (bpstat) p;
5018   struct watchpoint *b;
5019   struct frame_info *fr;
5020   int within_current_scope;
5021
5022   /* BS is built from an existing struct breakpoint.  */
5023   gdb_assert (bs->breakpoint_at != NULL);
5024   b = (struct watchpoint *) bs->breakpoint_at;
5025
5026   /* If this is a local watchpoint, we only want to check if the
5027      watchpoint frame is in scope if the current thread is the thread
5028      that was used to create the watchpoint.  */
5029   if (!watchpoint_in_thread_scope (b))
5030     return WP_IGNORE;
5031
5032   if (b->exp_valid_block == NULL)
5033     within_current_scope = 1;
5034   else
5035     {
5036       struct frame_info *frame = get_current_frame ();
5037       struct gdbarch *frame_arch = get_frame_arch (frame);
5038       CORE_ADDR frame_pc = get_frame_pc (frame);
5039
5040       /* in_function_epilogue_p() returns a non-zero value if we're
5041          still in the function but the stack frame has already been
5042          invalidated.  Since we can't rely on the values of local
5043          variables after the stack has been destroyed, we are treating
5044          the watchpoint in that state as `not changed' without further
5045          checking.  Don't mark watchpoints as changed if the current
5046          frame is in an epilogue - even if they are in some other
5047          frame, our view of the stack is likely to be wrong and
5048          frame_find_by_id could error out.  */
5049       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5050         return WP_IGNORE;
5051
5052       fr = frame_find_by_id (b->watchpoint_frame);
5053       within_current_scope = (fr != NULL);
5054
5055       /* If we've gotten confused in the unwinder, we might have
5056          returned a frame that can't describe this variable.  */
5057       if (within_current_scope)
5058         {
5059           struct symbol *function;
5060
5061           function = get_frame_function (fr);
5062           if (function == NULL
5063               || !contained_in (b->exp_valid_block,
5064                                 SYMBOL_BLOCK_VALUE (function)))
5065             within_current_scope = 0;
5066         }
5067
5068       if (within_current_scope)
5069         /* If we end up stopping, the current frame will get selected
5070            in normal_stop.  So this call to select_frame won't affect
5071            the user.  */
5072         select_frame (fr);
5073     }
5074
5075   if (within_current_scope)
5076     {
5077       /* We use value_{,free_to_}mark because it could be a *long*
5078          time before we return to the command level and call
5079          free_all_values.  We can't call free_all_values because we
5080          might be in the middle of evaluating a function call.  */
5081
5082       int pc = 0;
5083       struct value *mark;
5084       struct value *new_val;
5085
5086       if (is_masked_watchpoint (&b->base))
5087         /* Since we don't know the exact trigger address (from
5088            stopped_data_address), just tell the user we've triggered
5089            a mask watchpoint.  */
5090         return WP_VALUE_CHANGED;
5091
5092       mark = value_mark ();
5093       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5094
5095       if (b->val_bitsize != 0)
5096         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5097
5098       /* We use value_equal_contents instead of value_equal because
5099          the latter coerces an array to a pointer, thus comparing just
5100          the address of the array instead of its contents.  This is
5101          not what we want.  */
5102       if ((b->val != NULL) != (new_val != NULL)
5103           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5104         {
5105           if (new_val != NULL)
5106             {
5107               release_value (new_val);
5108               value_free_to_mark (mark);
5109             }
5110           bs->old_val = b->val;
5111           b->val = new_val;
5112           b->val_valid = 1;
5113           return WP_VALUE_CHANGED;
5114         }
5115       else
5116         {
5117           /* Nothing changed.  */
5118           value_free_to_mark (mark);
5119           return WP_VALUE_NOT_CHANGED;
5120         }
5121     }
5122   else
5123     {
5124       struct ui_out *uiout = current_uiout;
5125
5126       /* This seems like the only logical thing to do because
5127          if we temporarily ignored the watchpoint, then when
5128          we reenter the block in which it is valid it contains
5129          garbage (in the case of a function, it may have two
5130          garbage values, one before and one after the prologue).
5131          So we can't even detect the first assignment to it and
5132          watch after that (since the garbage may or may not equal
5133          the first value assigned).  */
5134       /* We print all the stop information in
5135          breakpoint_ops->print_it, but in this case, by the time we
5136          call breakpoint_ops->print_it this bp will be deleted
5137          already.  So we have no choice but print the information
5138          here.  */
5139       if (ui_out_is_mi_like_p (uiout))
5140         ui_out_field_string
5141           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5142       ui_out_text (uiout, "\nWatchpoint ");
5143       ui_out_field_int (uiout, "wpnum", b->base.number);
5144       ui_out_text (uiout,
5145                    " deleted because the program has left the block in\n\
5146 which its expression is valid.\n");     
5147
5148       /* Make sure the watchpoint's commands aren't executed.  */
5149       decref_counted_command_line (&b->base.commands);
5150       watchpoint_del_at_next_stop (b);
5151
5152       return WP_DELETED;
5153     }
5154 }
5155
5156 /* Return true if it looks like target has stopped due to hitting
5157    breakpoint location BL.  This function does not check if we should
5158    stop, only if BL explains the stop.  */
5159
5160 static int
5161 bpstat_check_location (const struct bp_location *bl,
5162                        struct address_space *aspace, CORE_ADDR bp_addr,
5163                        const struct target_waitstatus *ws)
5164 {
5165   struct breakpoint *b = bl->owner;
5166
5167   /* BL is from an existing breakpoint.  */
5168   gdb_assert (b != NULL);
5169
5170   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5171 }
5172
5173 /* Determine if the watched values have actually changed, and we
5174    should stop.  If not, set BS->stop to 0.  */
5175
5176 static void
5177 bpstat_check_watchpoint (bpstat bs)
5178 {
5179   const struct bp_location *bl;
5180   struct watchpoint *b;
5181
5182   /* BS is built for existing struct breakpoint.  */
5183   bl = bs->bp_location_at;
5184   gdb_assert (bl != NULL);
5185   b = (struct watchpoint *) bs->breakpoint_at;
5186   gdb_assert (b != NULL);
5187
5188     {
5189       int must_check_value = 0;
5190       
5191       if (b->base.type == bp_watchpoint)
5192         /* For a software watchpoint, we must always check the
5193            watched value.  */
5194         must_check_value = 1;
5195       else if (b->watchpoint_triggered == watch_triggered_yes)
5196         /* We have a hardware watchpoint (read, write, or access)
5197            and the target earlier reported an address watched by
5198            this watchpoint.  */
5199         must_check_value = 1;
5200       else if (b->watchpoint_triggered == watch_triggered_unknown
5201                && b->base.type == bp_hardware_watchpoint)
5202         /* We were stopped by a hardware watchpoint, but the target could
5203            not report the data address.  We must check the watchpoint's
5204            value.  Access and read watchpoints are out of luck; without
5205            a data address, we can't figure it out.  */
5206         must_check_value = 1;
5207
5208       if (must_check_value)
5209         {
5210           char *message
5211             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5212                           b->base.number);
5213           struct cleanup *cleanups = make_cleanup (xfree, message);
5214           int e = catch_errors (watchpoint_check, bs, message,
5215                                 RETURN_MASK_ALL);
5216           do_cleanups (cleanups);
5217           switch (e)
5218             {
5219             case WP_DELETED:
5220               /* We've already printed what needs to be printed.  */
5221               bs->print_it = print_it_done;
5222               /* Stop.  */
5223               break;
5224             case WP_IGNORE:
5225               bs->print_it = print_it_noop;
5226               bs->stop = 0;
5227               break;
5228             case WP_VALUE_CHANGED:
5229               if (b->base.type == bp_read_watchpoint)
5230                 {
5231                   /* There are two cases to consider here:
5232
5233                      1. We're watching the triggered memory for reads.
5234                      In that case, trust the target, and always report
5235                      the watchpoint hit to the user.  Even though
5236                      reads don't cause value changes, the value may
5237                      have changed since the last time it was read, and
5238                      since we're not trapping writes, we will not see
5239                      those, and as such we should ignore our notion of
5240                      old value.
5241
5242                      2. We're watching the triggered memory for both
5243                      reads and writes.  There are two ways this may
5244                      happen:
5245
5246                      2.1. This is a target that can't break on data
5247                      reads only, but can break on accesses (reads or
5248                      writes), such as e.g., x86.  We detect this case
5249                      at the time we try to insert read watchpoints.
5250
5251                      2.2. Otherwise, the target supports read
5252                      watchpoints, but, the user set an access or write
5253                      watchpoint watching the same memory as this read
5254                      watchpoint.
5255
5256                      If we're watching memory writes as well as reads,
5257                      ignore watchpoint hits when we find that the
5258                      value hasn't changed, as reads don't cause
5259                      changes.  This still gives false positives when
5260                      the program writes the same value to memory as
5261                      what there was already in memory (we will confuse
5262                      it for a read), but it's much better than
5263                      nothing.  */
5264
5265                   int other_write_watchpoint = 0;
5266
5267                   if (bl->watchpoint_type == hw_read)
5268                     {
5269                       struct breakpoint *other_b;
5270
5271                       ALL_BREAKPOINTS (other_b)
5272                         if (other_b->type == bp_hardware_watchpoint
5273                             || other_b->type == bp_access_watchpoint)
5274                           {
5275                             struct watchpoint *other_w =
5276                               (struct watchpoint *) other_b;
5277
5278                             if (other_w->watchpoint_triggered
5279                                 == watch_triggered_yes)
5280                               {
5281                                 other_write_watchpoint = 1;
5282                                 break;
5283                               }
5284                           }
5285                     }
5286
5287                   if (other_write_watchpoint
5288                       || bl->watchpoint_type == hw_access)
5289                     {
5290                       /* We're watching the same memory for writes,
5291                          and the value changed since the last time we
5292                          updated it, so this trap must be for a write.
5293                          Ignore it.  */
5294                       bs->print_it = print_it_noop;
5295                       bs->stop = 0;
5296                     }
5297                 }
5298               break;
5299             case WP_VALUE_NOT_CHANGED:
5300               if (b->base.type == bp_hardware_watchpoint
5301                   || b->base.type == bp_watchpoint)
5302                 {
5303                   /* Don't stop: write watchpoints shouldn't fire if
5304                      the value hasn't changed.  */
5305                   bs->print_it = print_it_noop;
5306                   bs->stop = 0;
5307                 }
5308               /* Stop.  */
5309               break;
5310             default:
5311               /* Can't happen.  */
5312             case 0:
5313               /* Error from catch_errors.  */
5314               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5315               watchpoint_del_at_next_stop (b);
5316               /* We've already printed what needs to be printed.  */
5317               bs->print_it = print_it_done;
5318               break;
5319             }
5320         }
5321       else      /* must_check_value == 0 */
5322         {
5323           /* This is a case where some watchpoint(s) triggered, but
5324              not at the address of this watchpoint, or else no
5325              watchpoint triggered after all.  So don't print
5326              anything for this watchpoint.  */
5327           bs->print_it = print_it_noop;
5328           bs->stop = 0;
5329         }
5330     }
5331 }
5332
5333 /* For breakpoints that are currently marked as telling gdb to stop,
5334    check conditions (condition proper, frame, thread and ignore count)
5335    of breakpoint referred to by BS.  If we should not stop for this
5336    breakpoint, set BS->stop to 0.  */
5337
5338 static void
5339 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5340 {
5341   const struct bp_location *bl;
5342   struct breakpoint *b;
5343   int value_is_zero = 0;
5344   struct expression *cond;
5345
5346   gdb_assert (bs->stop);
5347
5348   /* BS is built for existing struct breakpoint.  */
5349   bl = bs->bp_location_at;
5350   gdb_assert (bl != NULL);
5351   b = bs->breakpoint_at;
5352   gdb_assert (b != NULL);
5353
5354   /* Even if the target evaluated the condition on its end and notified GDB, we
5355      need to do so again since GDB does not know if we stopped due to a
5356      breakpoint or a single step breakpoint.  */
5357
5358   if (frame_id_p (b->frame_id)
5359       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5360     {
5361       bs->stop = 0;
5362       return;
5363     }
5364
5365   /* If this is a thread/task-specific breakpoint, don't waste cpu
5366      evaluating the condition if this isn't the specified
5367      thread/task.  */
5368   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5369       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5370
5371     {
5372       bs->stop = 0;
5373       return;
5374     }
5375
5376   /* Evaluate extension language breakpoints that have a "stop" method
5377      implemented.  */
5378   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5379
5380   if (is_watchpoint (b))
5381     {
5382       struct watchpoint *w = (struct watchpoint *) b;
5383
5384       cond = w->cond_exp;
5385     }
5386   else
5387     cond = bl->cond;
5388
5389   if (cond && b->disposition != disp_del_at_next_stop)
5390     {
5391       int within_current_scope = 1;
5392       struct watchpoint * w;
5393
5394       /* We use value_mark and value_free_to_mark because it could
5395          be a long time before we return to the command level and
5396          call free_all_values.  We can't call free_all_values
5397          because we might be in the middle of evaluating a
5398          function call.  */
5399       struct value *mark = value_mark ();
5400
5401       if (is_watchpoint (b))
5402         w = (struct watchpoint *) b;
5403       else
5404         w = NULL;
5405
5406       /* Need to select the frame, with all that implies so that
5407          the conditions will have the right context.  Because we
5408          use the frame, we will not see an inlined function's
5409          variables when we arrive at a breakpoint at the start
5410          of the inlined function; the current frame will be the
5411          call site.  */
5412       if (w == NULL || w->cond_exp_valid_block == NULL)
5413         select_frame (get_current_frame ());
5414       else
5415         {
5416           struct frame_info *frame;
5417
5418           /* For local watchpoint expressions, which particular
5419              instance of a local is being watched matters, so we
5420              keep track of the frame to evaluate the expression
5421              in.  To evaluate the condition however, it doesn't
5422              really matter which instantiation of the function
5423              where the condition makes sense triggers the
5424              watchpoint.  This allows an expression like "watch
5425              global if q > 10" set in `func', catch writes to
5426              global on all threads that call `func', or catch
5427              writes on all recursive calls of `func' by a single
5428              thread.  We simply always evaluate the condition in
5429              the innermost frame that's executing where it makes
5430              sense to evaluate the condition.  It seems
5431              intuitive.  */
5432           frame = block_innermost_frame (w->cond_exp_valid_block);
5433           if (frame != NULL)
5434             select_frame (frame);
5435           else
5436             within_current_scope = 0;
5437         }
5438       if (within_current_scope)
5439         value_is_zero
5440           = catch_errors (breakpoint_cond_eval, cond,
5441                           "Error in testing breakpoint condition:\n",
5442                           RETURN_MASK_ALL);
5443       else
5444         {
5445           warning (_("Watchpoint condition cannot be tested "
5446                      "in the current scope"));
5447           /* If we failed to set the right context for this
5448              watchpoint, unconditionally report it.  */
5449           value_is_zero = 0;
5450         }
5451       /* FIXME-someday, should give breakpoint #.  */
5452       value_free_to_mark (mark);
5453     }
5454
5455   if (cond && value_is_zero)
5456     {
5457       bs->stop = 0;
5458     }
5459   else if (b->ignore_count > 0)
5460     {
5461       b->ignore_count--;
5462       bs->stop = 0;
5463       /* Increase the hit count even though we don't stop.  */
5464       ++(b->hit_count);
5465       observer_notify_breakpoint_modified (b);
5466     }   
5467 }
5468
5469 /* Returns true if we need to track moribund locations of LOC's type
5470    on the current target.  */
5471
5472 static int
5473 need_moribund_for_location_type (struct bp_location *loc)
5474 {
5475   return ((loc->loc_type == bp_loc_software_breakpoint
5476            && !target_supports_stopped_by_sw_breakpoint ())
5477           || (loc->loc_type == bp_loc_hardware_breakpoint
5478               && !target_supports_stopped_by_hw_breakpoint ()));
5479 }
5480
5481
5482 /* Get a bpstat associated with having just stopped at address
5483    BP_ADDR in thread PTID.
5484
5485    Determine whether we stopped at a breakpoint, etc, or whether we
5486    don't understand this stop.  Result is a chain of bpstat's such
5487    that:
5488
5489    if we don't understand the stop, the result is a null pointer.
5490
5491    if we understand why we stopped, the result is not null.
5492
5493    Each element of the chain refers to a particular breakpoint or
5494    watchpoint at which we have stopped.  (We may have stopped for
5495    several reasons concurrently.)
5496
5497    Each element of the chain has valid next, breakpoint_at,
5498    commands, FIXME??? fields.  */
5499
5500 bpstat
5501 bpstat_stop_status (struct address_space *aspace,
5502                     CORE_ADDR bp_addr, ptid_t ptid,
5503                     const struct target_waitstatus *ws)
5504 {
5505   struct breakpoint *b = NULL;
5506   struct bp_location *bl;
5507   struct bp_location *loc;
5508   /* First item of allocated bpstat's.  */
5509   bpstat bs_head = NULL, *bs_link = &bs_head;
5510   /* Pointer to the last thing in the chain currently.  */
5511   bpstat bs;
5512   int ix;
5513   int need_remove_insert;
5514   int removed_any;
5515
5516   /* First, build the bpstat chain with locations that explain a
5517      target stop, while being careful to not set the target running,
5518      as that may invalidate locations (in particular watchpoint
5519      locations are recreated).  Resuming will happen here with
5520      breakpoint conditions or watchpoint expressions that include
5521      inferior function calls.  */
5522
5523   ALL_BREAKPOINTS (b)
5524     {
5525       if (!breakpoint_enabled (b))
5526         continue;
5527
5528       for (bl = b->loc; bl != NULL; bl = bl->next)
5529         {
5530           /* For hardware watchpoints, we look only at the first
5531              location.  The watchpoint_check function will work on the
5532              entire expression, not the individual locations.  For
5533              read watchpoints, the watchpoints_triggered function has
5534              checked all locations already.  */
5535           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5536             break;
5537
5538           if (!bl->enabled || bl->shlib_disabled)
5539             continue;
5540
5541           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5542             continue;
5543
5544           /* Come here if it's a watchpoint, or if the break address
5545              matches.  */
5546
5547           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5548                                                    explain stop.  */
5549
5550           /* Assume we stop.  Should we find a watchpoint that is not
5551              actually triggered, or if the condition of the breakpoint
5552              evaluates as false, we'll reset 'stop' to 0.  */
5553           bs->stop = 1;
5554           bs->print = 1;
5555
5556           /* If this is a scope breakpoint, mark the associated
5557              watchpoint as triggered so that we will handle the
5558              out-of-scope event.  We'll get to the watchpoint next
5559              iteration.  */
5560           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5561             {
5562               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5563
5564               w->watchpoint_triggered = watch_triggered_yes;
5565             }
5566         }
5567     }
5568
5569   /* Check if a moribund breakpoint explains the stop.  */
5570   if (!target_supports_stopped_by_sw_breakpoint ()
5571       || !target_supports_stopped_by_hw_breakpoint ())
5572     {
5573       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5574         {
5575           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5576               && need_moribund_for_location_type (loc))
5577             {
5578               bs = bpstat_alloc (loc, &bs_link);
5579               /* For hits of moribund locations, we should just proceed.  */
5580               bs->stop = 0;
5581               bs->print = 0;
5582               bs->print_it = print_it_noop;
5583             }
5584         }
5585     }
5586
5587   /* A bit of special processing for shlib breakpoints.  We need to
5588      process solib loading here, so that the lists of loaded and
5589      unloaded libraries are correct before we handle "catch load" and
5590      "catch unload".  */
5591   for (bs = bs_head; bs != NULL; bs = bs->next)
5592     {
5593       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5594         {
5595           handle_solib_event ();
5596           break;
5597         }
5598     }
5599
5600   /* Now go through the locations that caused the target to stop, and
5601      check whether we're interested in reporting this stop to higher
5602      layers, or whether we should resume the target transparently.  */
5603
5604   removed_any = 0;
5605
5606   for (bs = bs_head; bs != NULL; bs = bs->next)
5607     {
5608       if (!bs->stop)
5609         continue;
5610
5611       b = bs->breakpoint_at;
5612       b->ops->check_status (bs);
5613       if (bs->stop)
5614         {
5615           bpstat_check_breakpoint_conditions (bs, ptid);
5616
5617           if (bs->stop)
5618             {
5619               ++(b->hit_count);
5620               observer_notify_breakpoint_modified (b);
5621
5622               /* We will stop here.  */
5623               if (b->disposition == disp_disable)
5624                 {
5625                   --(b->enable_count);
5626                   if (b->enable_count <= 0)
5627                     b->enable_state = bp_disabled;
5628                   removed_any = 1;
5629                 }
5630               if (b->silent)
5631                 bs->print = 0;
5632               bs->commands = b->commands;
5633               incref_counted_command_line (bs->commands);
5634               if (command_line_is_silent (bs->commands
5635                                           ? bs->commands->commands : NULL))
5636                 bs->print = 0;
5637
5638               b->ops->after_condition_true (bs);
5639             }
5640
5641         }
5642
5643       /* Print nothing for this entry if we don't stop or don't
5644          print.  */
5645       if (!bs->stop || !bs->print)
5646         bs->print_it = print_it_noop;
5647     }
5648
5649   /* If we aren't stopping, the value of some hardware watchpoint may
5650      not have changed, but the intermediate memory locations we are
5651      watching may have.  Don't bother if we're stopping; this will get
5652      done later.  */
5653   need_remove_insert = 0;
5654   if (! bpstat_causes_stop (bs_head))
5655     for (bs = bs_head; bs != NULL; bs = bs->next)
5656       if (!bs->stop
5657           && bs->breakpoint_at
5658           && is_hardware_watchpoint (bs->breakpoint_at))
5659         {
5660           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5661
5662           update_watchpoint (w, 0 /* don't reparse.  */);
5663           need_remove_insert = 1;
5664         }
5665
5666   if (need_remove_insert)
5667     update_global_location_list (UGLL_MAY_INSERT);
5668   else if (removed_any)
5669     update_global_location_list (UGLL_DONT_INSERT);
5670
5671   return bs_head;
5672 }
5673
5674 static void
5675 handle_jit_event (void)
5676 {
5677   struct frame_info *frame;
5678   struct gdbarch *gdbarch;
5679
5680   /* Switch terminal for any messages produced by
5681      breakpoint_re_set.  */
5682   target_terminal_ours_for_output ();
5683
5684   frame = get_current_frame ();
5685   gdbarch = get_frame_arch (frame);
5686
5687   jit_event_handler (gdbarch);
5688
5689   target_terminal_inferior ();
5690 }
5691
5692 /* Prepare WHAT final decision for infrun.  */
5693
5694 /* Decide what infrun needs to do with this bpstat.  */
5695
5696 struct bpstat_what
5697 bpstat_what (bpstat bs_head)
5698 {
5699   struct bpstat_what retval;
5700   int jit_event = 0;
5701   bpstat bs;
5702
5703   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5704   retval.call_dummy = STOP_NONE;
5705   retval.is_longjmp = 0;
5706
5707   for (bs = bs_head; bs != NULL; bs = bs->next)
5708     {
5709       /* Extract this BS's action.  After processing each BS, we check
5710          if its action overrides all we've seem so far.  */
5711       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5712       enum bptype bptype;
5713
5714       if (bs->breakpoint_at == NULL)
5715         {
5716           /* I suspect this can happen if it was a momentary
5717              breakpoint which has since been deleted.  */
5718           bptype = bp_none;
5719         }
5720       else
5721         bptype = bs->breakpoint_at->type;
5722
5723       switch (bptype)
5724         {
5725         case bp_none:
5726           break;
5727         case bp_breakpoint:
5728         case bp_hardware_breakpoint:
5729         case bp_single_step:
5730         case bp_until:
5731         case bp_finish:
5732         case bp_shlib_event:
5733           if (bs->stop)
5734             {
5735               if (bs->print)
5736                 this_action = BPSTAT_WHAT_STOP_NOISY;
5737               else
5738                 this_action = BPSTAT_WHAT_STOP_SILENT;
5739             }
5740           else
5741             this_action = BPSTAT_WHAT_SINGLE;
5742           break;
5743         case bp_watchpoint:
5744         case bp_hardware_watchpoint:
5745         case bp_read_watchpoint:
5746         case bp_access_watchpoint:
5747           if (bs->stop)
5748             {
5749               if (bs->print)
5750                 this_action = BPSTAT_WHAT_STOP_NOISY;
5751               else
5752                 this_action = BPSTAT_WHAT_STOP_SILENT;
5753             }
5754           else
5755             {
5756               /* There was a watchpoint, but we're not stopping.
5757                  This requires no further action.  */
5758             }
5759           break;
5760         case bp_longjmp:
5761         case bp_longjmp_call_dummy:
5762         case bp_exception:
5763           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5764           retval.is_longjmp = bptype != bp_exception;
5765           break;
5766         case bp_longjmp_resume:
5767         case bp_exception_resume:
5768           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5769           retval.is_longjmp = bptype == bp_longjmp_resume;
5770           break;
5771         case bp_step_resume:
5772           if (bs->stop)
5773             this_action = BPSTAT_WHAT_STEP_RESUME;
5774           else
5775             {
5776               /* It is for the wrong frame.  */
5777               this_action = BPSTAT_WHAT_SINGLE;
5778             }
5779           break;
5780         case bp_hp_step_resume:
5781           if (bs->stop)
5782             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5783           else
5784             {
5785               /* It is for the wrong frame.  */
5786               this_action = BPSTAT_WHAT_SINGLE;
5787             }
5788           break;
5789         case bp_watchpoint_scope:
5790         case bp_thread_event:
5791         case bp_overlay_event:
5792         case bp_longjmp_master:
5793         case bp_std_terminate_master:
5794         case bp_exception_master:
5795           this_action = BPSTAT_WHAT_SINGLE;
5796           break;
5797         case bp_catchpoint:
5798           if (bs->stop)
5799             {
5800               if (bs->print)
5801                 this_action = BPSTAT_WHAT_STOP_NOISY;
5802               else
5803                 this_action = BPSTAT_WHAT_STOP_SILENT;
5804             }
5805           else
5806             {
5807               /* There was a catchpoint, but we're not stopping.
5808                  This requires no further action.  */
5809             }
5810           break;
5811         case bp_jit_event:
5812           jit_event = 1;
5813           this_action = BPSTAT_WHAT_SINGLE;
5814           break;
5815         case bp_call_dummy:
5816           /* Make sure the action is stop (silent or noisy),
5817              so infrun.c pops the dummy frame.  */
5818           retval.call_dummy = STOP_STACK_DUMMY;
5819           this_action = BPSTAT_WHAT_STOP_SILENT;
5820           break;
5821         case bp_std_terminate:
5822           /* Make sure the action is stop (silent or noisy),
5823              so infrun.c pops the dummy frame.  */
5824           retval.call_dummy = STOP_STD_TERMINATE;
5825           this_action = BPSTAT_WHAT_STOP_SILENT;
5826           break;
5827         case bp_tracepoint:
5828         case bp_fast_tracepoint:
5829         case bp_static_tracepoint:
5830           /* Tracepoint hits should not be reported back to GDB, and
5831              if one got through somehow, it should have been filtered
5832              out already.  */
5833           internal_error (__FILE__, __LINE__,
5834                           _("bpstat_what: tracepoint encountered"));
5835           break;
5836         case bp_gnu_ifunc_resolver:
5837           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5838           this_action = BPSTAT_WHAT_SINGLE;
5839           break;
5840         case bp_gnu_ifunc_resolver_return:
5841           /* The breakpoint will be removed, execution will restart from the
5842              PC of the former breakpoint.  */
5843           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5844           break;
5845
5846         case bp_dprintf:
5847           if (bs->stop)
5848             this_action = BPSTAT_WHAT_STOP_SILENT;
5849           else
5850             this_action = BPSTAT_WHAT_SINGLE;
5851           break;
5852
5853         default:
5854           internal_error (__FILE__, __LINE__,
5855                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5856         }
5857
5858       retval.main_action = max (retval.main_action, this_action);
5859     }
5860
5861   /* These operations may affect the bs->breakpoint_at state so they are
5862      delayed after MAIN_ACTION is decided above.  */
5863
5864   if (jit_event)
5865     {
5866       if (debug_infrun)
5867         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5868
5869       handle_jit_event ();
5870     }
5871
5872   for (bs = bs_head; bs != NULL; bs = bs->next)
5873     {
5874       struct breakpoint *b = bs->breakpoint_at;
5875
5876       if (b == NULL)
5877         continue;
5878       switch (b->type)
5879         {
5880         case bp_gnu_ifunc_resolver:
5881           gnu_ifunc_resolver_stop (b);
5882           break;
5883         case bp_gnu_ifunc_resolver_return:
5884           gnu_ifunc_resolver_return_stop (b);
5885           break;
5886         }
5887     }
5888
5889   return retval;
5890 }
5891
5892 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5893    without hardware support).  This isn't related to a specific bpstat,
5894    just to things like whether watchpoints are set.  */
5895
5896 int
5897 bpstat_should_step (void)
5898 {
5899   struct breakpoint *b;
5900
5901   ALL_BREAKPOINTS (b)
5902     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5903       return 1;
5904   return 0;
5905 }
5906
5907 int
5908 bpstat_causes_stop (bpstat bs)
5909 {
5910   for (; bs != NULL; bs = bs->next)
5911     if (bs->stop)
5912       return 1;
5913
5914   return 0;
5915 }
5916
5917 \f
5918
5919 /* Compute a string of spaces suitable to indent the next line
5920    so it starts at the position corresponding to the table column
5921    named COL_NAME in the currently active table of UIOUT.  */
5922
5923 static char *
5924 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5925 {
5926   static char wrap_indent[80];
5927   int i, total_width, width, align;
5928   char *text;
5929
5930   total_width = 0;
5931   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5932     {
5933       if (strcmp (text, col_name) == 0)
5934         {
5935           gdb_assert (total_width < sizeof wrap_indent);
5936           memset (wrap_indent, ' ', total_width);
5937           wrap_indent[total_width] = 0;
5938
5939           return wrap_indent;
5940         }
5941
5942       total_width += width + 1;
5943     }
5944
5945   return NULL;
5946 }
5947
5948 /* Determine if the locations of this breakpoint will have their conditions
5949    evaluated by the target, host or a mix of both.  Returns the following:
5950
5951     "host": Host evals condition.
5952     "host or target": Host or Target evals condition.
5953     "target": Target evals condition.
5954 */
5955
5956 static const char *
5957 bp_condition_evaluator (struct breakpoint *b)
5958 {
5959   struct bp_location *bl;
5960   char host_evals = 0;
5961   char target_evals = 0;
5962
5963   if (!b)
5964     return NULL;
5965
5966   if (!is_breakpoint (b))
5967     return NULL;
5968
5969   if (gdb_evaluates_breakpoint_condition_p ()
5970       || !target_supports_evaluation_of_breakpoint_conditions ())
5971     return condition_evaluation_host;
5972
5973   for (bl = b->loc; bl; bl = bl->next)
5974     {
5975       if (bl->cond_bytecode)
5976         target_evals++;
5977       else
5978         host_evals++;
5979     }
5980
5981   if (host_evals && target_evals)
5982     return condition_evaluation_both;
5983   else if (target_evals)
5984     return condition_evaluation_target;
5985   else
5986     return condition_evaluation_host;
5987 }
5988
5989 /* Determine the breakpoint location's condition evaluator.  This is
5990    similar to bp_condition_evaluator, but for locations.  */
5991
5992 static const char *
5993 bp_location_condition_evaluator (struct bp_location *bl)
5994 {
5995   if (bl && !is_breakpoint (bl->owner))
5996     return NULL;
5997
5998   if (gdb_evaluates_breakpoint_condition_p ()
5999       || !target_supports_evaluation_of_breakpoint_conditions ())
6000     return condition_evaluation_host;
6001
6002   if (bl && bl->cond_bytecode)
6003     return condition_evaluation_target;
6004   else
6005     return condition_evaluation_host;
6006 }
6007
6008 /* Print the LOC location out of the list of B->LOC locations.  */
6009
6010 static void
6011 print_breakpoint_location (struct breakpoint *b,
6012                            struct bp_location *loc)
6013 {
6014   struct ui_out *uiout = current_uiout;
6015   struct cleanup *old_chain = save_current_program_space ();
6016
6017   if (loc != NULL && loc->shlib_disabled)
6018     loc = NULL;
6019
6020   if (loc != NULL)
6021     set_current_program_space (loc->pspace);
6022
6023   if (b->display_canonical)
6024     ui_out_field_string (uiout, "what", b->addr_string);
6025   else if (loc && loc->symtab)
6026     {
6027       struct symbol *sym 
6028         = find_pc_sect_function (loc->address, loc->section);
6029       if (sym)
6030         {
6031           ui_out_text (uiout, "in ");
6032           ui_out_field_string (uiout, "func",
6033                                SYMBOL_PRINT_NAME (sym));
6034           ui_out_text (uiout, " ");
6035           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6036           ui_out_text (uiout, "at ");
6037         }
6038       ui_out_field_string (uiout, "file",
6039                            symtab_to_filename_for_display (loc->symtab));
6040       ui_out_text (uiout, ":");
6041
6042       if (ui_out_is_mi_like_p (uiout))
6043         ui_out_field_string (uiout, "fullname",
6044                              symtab_to_fullname (loc->symtab));
6045       
6046       ui_out_field_int (uiout, "line", loc->line_number);
6047     }
6048   else if (loc)
6049     {
6050       struct ui_file *stb = mem_fileopen ();
6051       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6052
6053       print_address_symbolic (loc->gdbarch, loc->address, stb,
6054                               demangle, "");
6055       ui_out_field_stream (uiout, "at", stb);
6056
6057       do_cleanups (stb_chain);
6058     }
6059   else
6060     ui_out_field_string (uiout, "pending", b->addr_string);
6061
6062   if (loc && is_breakpoint (b)
6063       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6064       && bp_condition_evaluator (b) == condition_evaluation_both)
6065     {
6066       ui_out_text (uiout, " (");
6067       ui_out_field_string (uiout, "evaluated-by",
6068                            bp_location_condition_evaluator (loc));
6069       ui_out_text (uiout, ")");
6070     }
6071
6072   do_cleanups (old_chain);
6073 }
6074
6075 static const char *
6076 bptype_string (enum bptype type)
6077 {
6078   struct ep_type_description
6079     {
6080       enum bptype type;
6081       char *description;
6082     };
6083   static struct ep_type_description bptypes[] =
6084   {
6085     {bp_none, "?deleted?"},
6086     {bp_breakpoint, "breakpoint"},
6087     {bp_hardware_breakpoint, "hw breakpoint"},
6088     {bp_single_step, "sw single-step"},
6089     {bp_until, "until"},
6090     {bp_finish, "finish"},
6091     {bp_watchpoint, "watchpoint"},
6092     {bp_hardware_watchpoint, "hw watchpoint"},
6093     {bp_read_watchpoint, "read watchpoint"},
6094     {bp_access_watchpoint, "acc watchpoint"},
6095     {bp_longjmp, "longjmp"},
6096     {bp_longjmp_resume, "longjmp resume"},
6097     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6098     {bp_exception, "exception"},
6099     {bp_exception_resume, "exception resume"},
6100     {bp_step_resume, "step resume"},
6101     {bp_hp_step_resume, "high-priority step resume"},
6102     {bp_watchpoint_scope, "watchpoint scope"},
6103     {bp_call_dummy, "call dummy"},
6104     {bp_std_terminate, "std::terminate"},
6105     {bp_shlib_event, "shlib events"},
6106     {bp_thread_event, "thread events"},
6107     {bp_overlay_event, "overlay events"},
6108     {bp_longjmp_master, "longjmp master"},
6109     {bp_std_terminate_master, "std::terminate master"},
6110     {bp_exception_master, "exception master"},
6111     {bp_catchpoint, "catchpoint"},
6112     {bp_tracepoint, "tracepoint"},
6113     {bp_fast_tracepoint, "fast tracepoint"},
6114     {bp_static_tracepoint, "static tracepoint"},
6115     {bp_dprintf, "dprintf"},
6116     {bp_jit_event, "jit events"},
6117     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6118     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6119   };
6120
6121   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6122       || ((int) type != bptypes[(int) type].type))
6123     internal_error (__FILE__, __LINE__,
6124                     _("bptypes table does not describe type #%d."),
6125                     (int) type);
6126
6127   return bptypes[(int) type].description;
6128 }
6129
6130 /* For MI, output a field named 'thread-groups' with a list as the value.
6131    For CLI, prefix the list with the string 'inf'. */
6132
6133 static void
6134 output_thread_groups (struct ui_out *uiout,
6135                       const char *field_name,
6136                       VEC(int) *inf_num,
6137                       int mi_only)
6138 {
6139   struct cleanup *back_to;
6140   int is_mi = ui_out_is_mi_like_p (uiout);
6141   int inf;
6142   int i;
6143
6144   /* For backward compatibility, don't display inferiors in CLI unless
6145      there are several.  Always display them for MI. */
6146   if (!is_mi && mi_only)
6147     return;
6148
6149   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6150
6151   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6152     {
6153       if (is_mi)
6154         {
6155           char mi_group[10];
6156
6157           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6158           ui_out_field_string (uiout, NULL, mi_group);
6159         }
6160       else
6161         {
6162           if (i == 0)
6163             ui_out_text (uiout, " inf ");
6164           else
6165             ui_out_text (uiout, ", ");
6166         
6167           ui_out_text (uiout, plongest (inf));
6168         }
6169     }
6170
6171   do_cleanups (back_to);
6172 }
6173
6174 /* Print B to gdb_stdout.  */
6175
6176 static void
6177 print_one_breakpoint_location (struct breakpoint *b,
6178                                struct bp_location *loc,
6179                                int loc_number,
6180                                struct bp_location **last_loc,
6181                                int allflag)
6182 {
6183   struct command_line *l;
6184   static char bpenables[] = "nynny";
6185
6186   struct ui_out *uiout = current_uiout;
6187   int header_of_multiple = 0;
6188   int part_of_multiple = (loc != NULL);
6189   struct value_print_options opts;
6190
6191   get_user_print_options (&opts);
6192
6193   gdb_assert (!loc || loc_number != 0);
6194   /* See comment in print_one_breakpoint concerning treatment of
6195      breakpoints with single disabled location.  */
6196   if (loc == NULL 
6197       && (b->loc != NULL 
6198           && (b->loc->next != NULL || !b->loc->enabled)))
6199     header_of_multiple = 1;
6200   if (loc == NULL)
6201     loc = b->loc;
6202
6203   annotate_record ();
6204
6205   /* 1 */
6206   annotate_field (0);
6207   if (part_of_multiple)
6208     {
6209       char *formatted;
6210       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6211       ui_out_field_string (uiout, "number", formatted);
6212       xfree (formatted);
6213     }
6214   else
6215     {
6216       ui_out_field_int (uiout, "number", b->number);
6217     }
6218
6219   /* 2 */
6220   annotate_field (1);
6221   if (part_of_multiple)
6222     ui_out_field_skip (uiout, "type");
6223   else
6224     ui_out_field_string (uiout, "type", bptype_string (b->type));
6225
6226   /* 3 */
6227   annotate_field (2);
6228   if (part_of_multiple)
6229     ui_out_field_skip (uiout, "disp");
6230   else
6231     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6232
6233
6234   /* 4 */
6235   annotate_field (3);
6236   if (part_of_multiple)
6237     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6238   else
6239     ui_out_field_fmt (uiout, "enabled", "%c", 
6240                       bpenables[(int) b->enable_state]);
6241   ui_out_spaces (uiout, 2);
6242
6243   
6244   /* 5 and 6 */
6245   if (b->ops != NULL && b->ops->print_one != NULL)
6246     {
6247       /* Although the print_one can possibly print all locations,
6248          calling it here is not likely to get any nice result.  So,
6249          make sure there's just one location.  */
6250       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6251       b->ops->print_one (b, last_loc);
6252     }
6253   else
6254     switch (b->type)
6255       {
6256       case bp_none:
6257         internal_error (__FILE__, __LINE__,
6258                         _("print_one_breakpoint: bp_none encountered\n"));
6259         break;
6260
6261       case bp_watchpoint:
6262       case bp_hardware_watchpoint:
6263       case bp_read_watchpoint:
6264       case bp_access_watchpoint:
6265         {
6266           struct watchpoint *w = (struct watchpoint *) b;
6267
6268           /* Field 4, the address, is omitted (which makes the columns
6269              not line up too nicely with the headers, but the effect
6270              is relatively readable).  */
6271           if (opts.addressprint)
6272             ui_out_field_skip (uiout, "addr");
6273           annotate_field (5);
6274           ui_out_field_string (uiout, "what", w->exp_string);
6275         }
6276         break;
6277
6278       case bp_breakpoint:
6279       case bp_hardware_breakpoint:
6280       case bp_single_step:
6281       case bp_until:
6282       case bp_finish:
6283       case bp_longjmp:
6284       case bp_longjmp_resume:
6285       case bp_longjmp_call_dummy:
6286       case bp_exception:
6287       case bp_exception_resume:
6288       case bp_step_resume:
6289       case bp_hp_step_resume:
6290       case bp_watchpoint_scope:
6291       case bp_call_dummy:
6292       case bp_std_terminate:
6293       case bp_shlib_event:
6294       case bp_thread_event:
6295       case bp_overlay_event:
6296       case bp_longjmp_master:
6297       case bp_std_terminate_master:
6298       case bp_exception_master:
6299       case bp_tracepoint:
6300       case bp_fast_tracepoint:
6301       case bp_static_tracepoint:
6302       case bp_dprintf:
6303       case bp_jit_event:
6304       case bp_gnu_ifunc_resolver:
6305       case bp_gnu_ifunc_resolver_return:
6306         if (opts.addressprint)
6307           {
6308             annotate_field (4);
6309             if (header_of_multiple)
6310               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6311             else if (b->loc == NULL || loc->shlib_disabled)
6312               ui_out_field_string (uiout, "addr", "<PENDING>");
6313             else
6314               ui_out_field_core_addr (uiout, "addr",
6315                                       loc->gdbarch, loc->address);
6316           }
6317         annotate_field (5);
6318         if (!header_of_multiple)
6319           print_breakpoint_location (b, loc);
6320         if (b->loc)
6321           *last_loc = b->loc;
6322         break;
6323       }
6324
6325
6326   if (loc != NULL && !header_of_multiple)
6327     {
6328       struct inferior *inf;
6329       VEC(int) *inf_num = NULL;
6330       int mi_only = 1;
6331
6332       ALL_INFERIORS (inf)
6333         {
6334           if (inf->pspace == loc->pspace)
6335             VEC_safe_push (int, inf_num, inf->num);
6336         }
6337
6338         /* For backward compatibility, don't display inferiors in CLI unless
6339            there are several.  Always display for MI. */
6340         if (allflag
6341             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6342                 && (number_of_program_spaces () > 1
6343                     || number_of_inferiors () > 1)
6344                 /* LOC is for existing B, it cannot be in
6345                    moribund_locations and thus having NULL OWNER.  */
6346                 && loc->owner->type != bp_catchpoint))
6347         mi_only = 0;
6348       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6349       VEC_free (int, inf_num);
6350     }
6351
6352   if (!part_of_multiple)
6353     {
6354       if (b->thread != -1)
6355         {
6356           /* FIXME: This seems to be redundant and lost here; see the
6357              "stop only in" line a little further down.  */
6358           ui_out_text (uiout, " thread ");
6359           ui_out_field_int (uiout, "thread", b->thread);
6360         }
6361       else if (b->task != 0)
6362         {
6363           ui_out_text (uiout, " task ");
6364           ui_out_field_int (uiout, "task", b->task);
6365         }
6366     }
6367
6368   ui_out_text (uiout, "\n");
6369
6370   if (!part_of_multiple)
6371     b->ops->print_one_detail (b, uiout);
6372
6373   if (part_of_multiple && frame_id_p (b->frame_id))
6374     {
6375       annotate_field (6);
6376       ui_out_text (uiout, "\tstop only in stack frame at ");
6377       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6378          the frame ID.  */
6379       ui_out_field_core_addr (uiout, "frame",
6380                               b->gdbarch, b->frame_id.stack_addr);
6381       ui_out_text (uiout, "\n");
6382     }
6383   
6384   if (!part_of_multiple && b->cond_string)
6385     {
6386       annotate_field (7);
6387       if (is_tracepoint (b))
6388         ui_out_text (uiout, "\ttrace only if ");
6389       else
6390         ui_out_text (uiout, "\tstop only if ");
6391       ui_out_field_string (uiout, "cond", b->cond_string);
6392
6393       /* Print whether the target is doing the breakpoint's condition
6394          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6395       if (is_breakpoint (b)
6396           && breakpoint_condition_evaluation_mode ()
6397           == condition_evaluation_target)
6398         {
6399           ui_out_text (uiout, " (");
6400           ui_out_field_string (uiout, "evaluated-by",
6401                                bp_condition_evaluator (b));
6402           ui_out_text (uiout, " evals)");
6403         }
6404       ui_out_text (uiout, "\n");
6405     }
6406
6407   if (!part_of_multiple && b->thread != -1)
6408     {
6409       /* FIXME should make an annotation for this.  */
6410       ui_out_text (uiout, "\tstop only in thread ");
6411       ui_out_field_int (uiout, "thread", b->thread);
6412       ui_out_text (uiout, "\n");
6413     }
6414   
6415   if (!part_of_multiple)
6416     {
6417       if (b->hit_count)
6418         {
6419           /* FIXME should make an annotation for this.  */
6420           if (is_catchpoint (b))
6421             ui_out_text (uiout, "\tcatchpoint");
6422           else if (is_tracepoint (b))
6423             ui_out_text (uiout, "\ttracepoint");
6424           else
6425             ui_out_text (uiout, "\tbreakpoint");
6426           ui_out_text (uiout, " already hit ");
6427           ui_out_field_int (uiout, "times", b->hit_count);
6428           if (b->hit_count == 1)
6429             ui_out_text (uiout, " time\n");
6430           else
6431             ui_out_text (uiout, " times\n");
6432         }
6433       else
6434         {
6435           /* Output the count also if it is zero, but only if this is mi.  */
6436           if (ui_out_is_mi_like_p (uiout))
6437             ui_out_field_int (uiout, "times", b->hit_count);
6438         }
6439     }
6440
6441   if (!part_of_multiple && b->ignore_count)
6442     {
6443       annotate_field (8);
6444       ui_out_text (uiout, "\tignore next ");
6445       ui_out_field_int (uiout, "ignore", b->ignore_count);
6446       ui_out_text (uiout, " hits\n");
6447     }
6448
6449   /* Note that an enable count of 1 corresponds to "enable once"
6450      behavior, which is reported by the combination of enablement and
6451      disposition, so we don't need to mention it here.  */
6452   if (!part_of_multiple && b->enable_count > 1)
6453     {
6454       annotate_field (8);
6455       ui_out_text (uiout, "\tdisable after ");
6456       /* Tweak the wording to clarify that ignore and enable counts
6457          are distinct, and have additive effect.  */
6458       if (b->ignore_count)
6459         ui_out_text (uiout, "additional ");
6460       else
6461         ui_out_text (uiout, "next ");
6462       ui_out_field_int (uiout, "enable", b->enable_count);
6463       ui_out_text (uiout, " hits\n");
6464     }
6465
6466   if (!part_of_multiple && is_tracepoint (b))
6467     {
6468       struct tracepoint *tp = (struct tracepoint *) b;
6469
6470       if (tp->traceframe_usage)
6471         {
6472           ui_out_text (uiout, "\ttrace buffer usage ");
6473           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6474           ui_out_text (uiout, " bytes\n");
6475         }
6476     }
6477
6478   l = b->commands ? b->commands->commands : NULL;
6479   if (!part_of_multiple && l)
6480     {
6481       struct cleanup *script_chain;
6482
6483       annotate_field (9);
6484       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6485       print_command_lines (uiout, l, 4);
6486       do_cleanups (script_chain);
6487     }
6488
6489   if (is_tracepoint (b))
6490     {
6491       struct tracepoint *t = (struct tracepoint *) b;
6492
6493       if (!part_of_multiple && t->pass_count)
6494         {
6495           annotate_field (10);
6496           ui_out_text (uiout, "\tpass count ");
6497           ui_out_field_int (uiout, "pass", t->pass_count);
6498           ui_out_text (uiout, " \n");
6499         }
6500
6501       /* Don't display it when tracepoint or tracepoint location is
6502          pending.   */
6503       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6504         {
6505           annotate_field (11);
6506
6507           if (ui_out_is_mi_like_p (uiout))
6508             ui_out_field_string (uiout, "installed",
6509                                  loc->inserted ? "y" : "n");
6510           else
6511             {
6512               if (loc->inserted)
6513                 ui_out_text (uiout, "\t");
6514               else
6515                 ui_out_text (uiout, "\tnot ");
6516               ui_out_text (uiout, "installed on target\n");
6517             }
6518         }
6519     }
6520
6521   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6522     {
6523       if (is_watchpoint (b))
6524         {
6525           struct watchpoint *w = (struct watchpoint *) b;
6526
6527           ui_out_field_string (uiout, "original-location", w->exp_string);
6528         }
6529       else if (b->addr_string)
6530         ui_out_field_string (uiout, "original-location", b->addr_string);
6531     }
6532 }
6533
6534 static void
6535 print_one_breakpoint (struct breakpoint *b,
6536                       struct bp_location **last_loc, 
6537                       int allflag)
6538 {
6539   struct cleanup *bkpt_chain;
6540   struct ui_out *uiout = current_uiout;
6541
6542   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6543
6544   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6545   do_cleanups (bkpt_chain);
6546
6547   /* If this breakpoint has custom print function,
6548      it's already printed.  Otherwise, print individual
6549      locations, if any.  */
6550   if (b->ops == NULL || b->ops->print_one == NULL)
6551     {
6552       /* If breakpoint has a single location that is disabled, we
6553          print it as if it had several locations, since otherwise it's
6554          hard to represent "breakpoint enabled, location disabled"
6555          situation.
6556
6557          Note that while hardware watchpoints have several locations
6558          internally, that's not a property exposed to user.  */
6559       if (b->loc 
6560           && !is_hardware_watchpoint (b)
6561           && (b->loc->next || !b->loc->enabled))
6562         {
6563           struct bp_location *loc;
6564           int n = 1;
6565
6566           for (loc = b->loc; loc; loc = loc->next, ++n)
6567             {
6568               struct cleanup *inner2 =
6569                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6570               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6571               do_cleanups (inner2);
6572             }
6573         }
6574     }
6575 }
6576
6577 static int
6578 breakpoint_address_bits (struct breakpoint *b)
6579 {
6580   int print_address_bits = 0;
6581   struct bp_location *loc;
6582
6583   for (loc = b->loc; loc; loc = loc->next)
6584     {
6585       int addr_bit;
6586
6587       /* Software watchpoints that aren't watching memory don't have
6588          an address to print.  */
6589       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6590         continue;
6591
6592       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6593       if (addr_bit > print_address_bits)
6594         print_address_bits = addr_bit;
6595     }
6596
6597   return print_address_bits;
6598 }
6599
6600 struct captured_breakpoint_query_args
6601   {
6602     int bnum;
6603   };
6604
6605 static int
6606 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6607 {
6608   struct captured_breakpoint_query_args *args = data;
6609   struct breakpoint *b;
6610   struct bp_location *dummy_loc = NULL;
6611
6612   ALL_BREAKPOINTS (b)
6613     {
6614       if (args->bnum == b->number)
6615         {
6616           print_one_breakpoint (b, &dummy_loc, 0);
6617           return GDB_RC_OK;
6618         }
6619     }
6620   return GDB_RC_NONE;
6621 }
6622
6623 enum gdb_rc
6624 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6625                       char **error_message)
6626 {
6627   struct captured_breakpoint_query_args args;
6628
6629   args.bnum = bnum;
6630   /* For the moment we don't trust print_one_breakpoint() to not throw
6631      an error.  */
6632   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6633                                  error_message, RETURN_MASK_ALL) < 0)
6634     return GDB_RC_FAIL;
6635   else
6636     return GDB_RC_OK;
6637 }
6638
6639 /* Return true if this breakpoint was set by the user, false if it is
6640    internal or momentary.  */
6641
6642 int
6643 user_breakpoint_p (struct breakpoint *b)
6644 {
6645   return b->number > 0;
6646 }
6647
6648 /* Print information on user settable breakpoint (watchpoint, etc)
6649    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6650    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6651    FILTER is non-NULL, call it on each breakpoint and only include the
6652    ones for which it returns non-zero.  Return the total number of
6653    breakpoints listed.  */
6654
6655 static int
6656 breakpoint_1 (char *args, int allflag, 
6657               int (*filter) (const struct breakpoint *))
6658 {
6659   struct breakpoint *b;
6660   struct bp_location *last_loc = NULL;
6661   int nr_printable_breakpoints;
6662   struct cleanup *bkpttbl_chain;
6663   struct value_print_options opts;
6664   int print_address_bits = 0;
6665   int print_type_col_width = 14;
6666   struct ui_out *uiout = current_uiout;
6667
6668   get_user_print_options (&opts);
6669
6670   /* Compute the number of rows in the table, as well as the size
6671      required for address fields.  */
6672   nr_printable_breakpoints = 0;
6673   ALL_BREAKPOINTS (b)
6674     {
6675       /* If we have a filter, only list the breakpoints it accepts.  */
6676       if (filter && !filter (b))
6677         continue;
6678
6679       /* If we have an "args" string, it is a list of breakpoints to 
6680          accept.  Skip the others.  */
6681       if (args != NULL && *args != '\0')
6682         {
6683           if (allflag && parse_and_eval_long (args) != b->number)
6684             continue;
6685           if (!allflag && !number_is_in_list (args, b->number))
6686             continue;
6687         }
6688
6689       if (allflag || user_breakpoint_p (b))
6690         {
6691           int addr_bit, type_len;
6692
6693           addr_bit = breakpoint_address_bits (b);
6694           if (addr_bit > print_address_bits)
6695             print_address_bits = addr_bit;
6696
6697           type_len = strlen (bptype_string (b->type));
6698           if (type_len > print_type_col_width)
6699             print_type_col_width = type_len;
6700
6701           nr_printable_breakpoints++;
6702         }
6703     }
6704
6705   if (opts.addressprint)
6706     bkpttbl_chain 
6707       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6708                                              nr_printable_breakpoints,
6709                                              "BreakpointTable");
6710   else
6711     bkpttbl_chain 
6712       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6713                                              nr_printable_breakpoints,
6714                                              "BreakpointTable");
6715
6716   if (nr_printable_breakpoints > 0)
6717     annotate_breakpoints_headers ();
6718   if (nr_printable_breakpoints > 0)
6719     annotate_field (0);
6720   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6721   if (nr_printable_breakpoints > 0)
6722     annotate_field (1);
6723   ui_out_table_header (uiout, print_type_col_width, ui_left,
6724                        "type", "Type");                         /* 2 */
6725   if (nr_printable_breakpoints > 0)
6726     annotate_field (2);
6727   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6728   if (nr_printable_breakpoints > 0)
6729     annotate_field (3);
6730   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6731   if (opts.addressprint)
6732     {
6733       if (nr_printable_breakpoints > 0)
6734         annotate_field (4);
6735       if (print_address_bits <= 32)
6736         ui_out_table_header (uiout, 10, ui_left, 
6737                              "addr", "Address");                /* 5 */
6738       else
6739         ui_out_table_header (uiout, 18, ui_left, 
6740                              "addr", "Address");                /* 5 */
6741     }
6742   if (nr_printable_breakpoints > 0)
6743     annotate_field (5);
6744   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6745   ui_out_table_body (uiout);
6746   if (nr_printable_breakpoints > 0)
6747     annotate_breakpoints_table ();
6748
6749   ALL_BREAKPOINTS (b)
6750     {
6751       QUIT;
6752       /* If we have a filter, only list the breakpoints it accepts.  */
6753       if (filter && !filter (b))
6754         continue;
6755
6756       /* If we have an "args" string, it is a list of breakpoints to 
6757          accept.  Skip the others.  */
6758
6759       if (args != NULL && *args != '\0')
6760         {
6761           if (allflag)  /* maintenance info breakpoint */
6762             {
6763               if (parse_and_eval_long (args) != b->number)
6764                 continue;
6765             }
6766           else          /* all others */
6767             {
6768               if (!number_is_in_list (args, b->number))
6769                 continue;
6770             }
6771         }
6772       /* We only print out user settable breakpoints unless the
6773          allflag is set.  */
6774       if (allflag || user_breakpoint_p (b))
6775         print_one_breakpoint (b, &last_loc, allflag);
6776     }
6777
6778   do_cleanups (bkpttbl_chain);
6779
6780   if (nr_printable_breakpoints == 0)
6781     {
6782       /* If there's a filter, let the caller decide how to report
6783          empty list.  */
6784       if (!filter)
6785         {
6786           if (args == NULL || *args == '\0')
6787             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6788           else
6789             ui_out_message (uiout, 0, 
6790                             "No breakpoint or watchpoint matching '%s'.\n",
6791                             args);
6792         }
6793     }
6794   else
6795     {
6796       if (last_loc && !server_command)
6797         set_next_address (last_loc->gdbarch, last_loc->address);
6798     }
6799
6800   /* FIXME?  Should this be moved up so that it is only called when
6801      there have been breakpoints? */
6802   annotate_breakpoints_table_end ();
6803
6804   return nr_printable_breakpoints;
6805 }
6806
6807 /* Display the value of default-collect in a way that is generally
6808    compatible with the breakpoint list.  */
6809
6810 static void
6811 default_collect_info (void)
6812 {
6813   struct ui_out *uiout = current_uiout;
6814
6815   /* If it has no value (which is frequently the case), say nothing; a
6816      message like "No default-collect." gets in user's face when it's
6817      not wanted.  */
6818   if (!*default_collect)
6819     return;
6820
6821   /* The following phrase lines up nicely with per-tracepoint collect
6822      actions.  */
6823   ui_out_text (uiout, "default collect ");
6824   ui_out_field_string (uiout, "default-collect", default_collect);
6825   ui_out_text (uiout, " \n");
6826 }
6827   
6828 static void
6829 breakpoints_info (char *args, int from_tty)
6830 {
6831   breakpoint_1 (args, 0, NULL);
6832
6833   default_collect_info ();
6834 }
6835
6836 static void
6837 watchpoints_info (char *args, int from_tty)
6838 {
6839   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6840   struct ui_out *uiout = current_uiout;
6841
6842   if (num_printed == 0)
6843     {
6844       if (args == NULL || *args == '\0')
6845         ui_out_message (uiout, 0, "No watchpoints.\n");
6846       else
6847         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6848     }
6849 }
6850
6851 static void
6852 maintenance_info_breakpoints (char *args, int from_tty)
6853 {
6854   breakpoint_1 (args, 1, NULL);
6855
6856   default_collect_info ();
6857 }
6858
6859 static int
6860 breakpoint_has_pc (struct breakpoint *b,
6861                    struct program_space *pspace,
6862                    CORE_ADDR pc, struct obj_section *section)
6863 {
6864   struct bp_location *bl = b->loc;
6865
6866   for (; bl; bl = bl->next)
6867     {
6868       if (bl->pspace == pspace
6869           && bl->address == pc
6870           && (!overlay_debugging || bl->section == section))
6871         return 1;         
6872     }
6873   return 0;
6874 }
6875
6876 /* Print a message describing any user-breakpoints set at PC.  This
6877    concerns with logical breakpoints, so we match program spaces, not
6878    address spaces.  */
6879
6880 static void
6881 describe_other_breakpoints (struct gdbarch *gdbarch,
6882                             struct program_space *pspace, CORE_ADDR pc,
6883                             struct obj_section *section, int thread)
6884 {
6885   int others = 0;
6886   struct breakpoint *b;
6887
6888   ALL_BREAKPOINTS (b)
6889     others += (user_breakpoint_p (b)
6890                && breakpoint_has_pc (b, pspace, pc, section));
6891   if (others > 0)
6892     {
6893       if (others == 1)
6894         printf_filtered (_("Note: breakpoint "));
6895       else /* if (others == ???) */
6896         printf_filtered (_("Note: breakpoints "));
6897       ALL_BREAKPOINTS (b)
6898         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6899           {
6900             others--;
6901             printf_filtered ("%d", b->number);
6902             if (b->thread == -1 && thread != -1)
6903               printf_filtered (" (all threads)");
6904             else if (b->thread != -1)
6905               printf_filtered (" (thread %d)", b->thread);
6906             printf_filtered ("%s%s ",
6907                              ((b->enable_state == bp_disabled
6908                                || b->enable_state == bp_call_disabled)
6909                               ? " (disabled)"
6910                               : ""),
6911                              (others > 1) ? "," 
6912                              : ((others == 1) ? " and" : ""));
6913           }
6914       printf_filtered (_("also set at pc "));
6915       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6916       printf_filtered (".\n");
6917     }
6918 }
6919 \f
6920
6921 /* Return true iff it is meaningful to use the address member of
6922    BPT.  For some breakpoint types, the address member is irrelevant
6923    and it makes no sense to attempt to compare it to other addresses
6924    (or use it for any other purpose either).
6925
6926    More specifically, each of the following breakpoint types will
6927    always have a zero valued address and we don't want to mark
6928    breakpoints of any of these types to be a duplicate of an actual
6929    breakpoint at address zero:
6930
6931       bp_watchpoint
6932       bp_catchpoint
6933
6934 */
6935
6936 static int
6937 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6938 {
6939   enum bptype type = bpt->type;
6940
6941   return (type != bp_watchpoint && type != bp_catchpoint);
6942 }
6943
6944 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6945    true if LOC1 and LOC2 represent the same watchpoint location.  */
6946
6947 static int
6948 watchpoint_locations_match (struct bp_location *loc1, 
6949                             struct bp_location *loc2)
6950 {
6951   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6952   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6953
6954   /* Both of them must exist.  */
6955   gdb_assert (w1 != NULL);
6956   gdb_assert (w2 != NULL);
6957
6958   /* If the target can evaluate the condition expression in hardware,
6959      then we we need to insert both watchpoints even if they are at
6960      the same place.  Otherwise the watchpoint will only trigger when
6961      the condition of whichever watchpoint was inserted evaluates to
6962      true, not giving a chance for GDB to check the condition of the
6963      other watchpoint.  */
6964   if ((w1->cond_exp
6965        && target_can_accel_watchpoint_condition (loc1->address, 
6966                                                  loc1->length,
6967                                                  loc1->watchpoint_type,
6968                                                  w1->cond_exp))
6969       || (w2->cond_exp
6970           && target_can_accel_watchpoint_condition (loc2->address, 
6971                                                     loc2->length,
6972                                                     loc2->watchpoint_type,
6973                                                     w2->cond_exp)))
6974     return 0;
6975
6976   /* Note that this checks the owner's type, not the location's.  In
6977      case the target does not support read watchpoints, but does
6978      support access watchpoints, we'll have bp_read_watchpoint
6979      watchpoints with hw_access locations.  Those should be considered
6980      duplicates of hw_read locations.  The hw_read locations will
6981      become hw_access locations later.  */
6982   return (loc1->owner->type == loc2->owner->type
6983           && loc1->pspace->aspace == loc2->pspace->aspace
6984           && loc1->address == loc2->address
6985           && loc1->length == loc2->length);
6986 }
6987
6988 /* See breakpoint.h.  */
6989
6990 int
6991 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6992                           struct address_space *aspace2, CORE_ADDR addr2)
6993 {
6994   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6995            || aspace1 == aspace2)
6996           && addr1 == addr2);
6997 }
6998
6999 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7000    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7001    matches ASPACE2.  On targets that have global breakpoints, the address
7002    space doesn't really matter.  */
7003
7004 static int
7005 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7006                                 int len1, struct address_space *aspace2,
7007                                 CORE_ADDR addr2)
7008 {
7009   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7010            || aspace1 == aspace2)
7011           && addr2 >= addr1 && addr2 < addr1 + len1);
7012 }
7013
7014 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7015    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7016    matches the breakpoint's address space.  On targets that have global
7017    breakpoints, the address space doesn't really matter.  */
7018
7019 static int
7020 breakpoint_location_address_match (struct bp_location *bl,
7021                                    struct address_space *aspace,
7022                                    CORE_ADDR addr)
7023 {
7024   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7025                                     aspace, addr)
7026           || (bl->length
7027               && breakpoint_address_match_range (bl->pspace->aspace,
7028                                                  bl->address, bl->length,
7029                                                  aspace, addr)));
7030 }
7031
7032 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7033    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7034    true, otherwise returns false.  */
7035
7036 static int
7037 tracepoint_locations_match (struct bp_location *loc1,
7038                             struct bp_location *loc2)
7039 {
7040   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7041     /* Since tracepoint locations are never duplicated with others', tracepoint
7042        locations at the same address of different tracepoints are regarded as
7043        different locations.  */
7044     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7045   else
7046     return 0;
7047 }
7048
7049 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7050    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7051    represent the same location.  */
7052
7053 static int
7054 breakpoint_locations_match (struct bp_location *loc1, 
7055                             struct bp_location *loc2)
7056 {
7057   int hw_point1, hw_point2;
7058
7059   /* Both of them must not be in moribund_locations.  */
7060   gdb_assert (loc1->owner != NULL);
7061   gdb_assert (loc2->owner != NULL);
7062
7063   hw_point1 = is_hardware_watchpoint (loc1->owner);
7064   hw_point2 = is_hardware_watchpoint (loc2->owner);
7065
7066   if (hw_point1 != hw_point2)
7067     return 0;
7068   else if (hw_point1)
7069     return watchpoint_locations_match (loc1, loc2);
7070   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7071     return tracepoint_locations_match (loc1, loc2);
7072   else
7073     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7074     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7075                                      loc2->pspace->aspace, loc2->address)
7076             && loc1->length == loc2->length);
7077 }
7078
7079 static void
7080 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7081                                int bnum, int have_bnum)
7082 {
7083   /* The longest string possibly returned by hex_string_custom
7084      is 50 chars.  These must be at least that big for safety.  */
7085   char astr1[64];
7086   char astr2[64];
7087
7088   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7089   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7090   if (have_bnum)
7091     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7092              bnum, astr1, astr2);
7093   else
7094     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7095 }
7096
7097 /* Adjust a breakpoint's address to account for architectural
7098    constraints on breakpoint placement.  Return the adjusted address.
7099    Note: Very few targets require this kind of adjustment.  For most
7100    targets, this function is simply the identity function.  */
7101
7102 static CORE_ADDR
7103 adjust_breakpoint_address (struct gdbarch *gdbarch,
7104                            CORE_ADDR bpaddr, enum bptype bptype)
7105 {
7106   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7107     {
7108       /* Very few targets need any kind of breakpoint adjustment.  */
7109       return bpaddr;
7110     }
7111   else if (bptype == bp_watchpoint
7112            || bptype == bp_hardware_watchpoint
7113            || bptype == bp_read_watchpoint
7114            || bptype == bp_access_watchpoint
7115            || bptype == bp_catchpoint)
7116     {
7117       /* Watchpoints and the various bp_catch_* eventpoints should not
7118          have their addresses modified.  */
7119       return bpaddr;
7120     }
7121   else if (bptype == bp_single_step)
7122     {
7123       /* Single-step breakpoints should not have their addresses
7124          modified.  If there's any architectural constrain that
7125          applies to this address, then it should have already been
7126          taken into account when the breakpoint was created in the
7127          first place.  If we didn't do this, stepping through e.g.,
7128          Thumb-2 IT blocks would break.  */
7129       return bpaddr;
7130     }
7131   else
7132     {
7133       CORE_ADDR adjusted_bpaddr;
7134
7135       /* Some targets have architectural constraints on the placement
7136          of breakpoint instructions.  Obtain the adjusted address.  */
7137       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7138
7139       /* An adjusted breakpoint address can significantly alter
7140          a user's expectations.  Print a warning if an adjustment
7141          is required.  */
7142       if (adjusted_bpaddr != bpaddr)
7143         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7144
7145       return adjusted_bpaddr;
7146     }
7147 }
7148
7149 void
7150 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7151                   struct breakpoint *owner)
7152 {
7153   memset (loc, 0, sizeof (*loc));
7154
7155   gdb_assert (ops != NULL);
7156
7157   loc->ops = ops;
7158   loc->owner = owner;
7159   loc->cond = NULL;
7160   loc->cond_bytecode = NULL;
7161   loc->shlib_disabled = 0;
7162   loc->enabled = 1;
7163
7164   switch (owner->type)
7165     {
7166     case bp_breakpoint:
7167     case bp_single_step:
7168     case bp_until:
7169     case bp_finish:
7170     case bp_longjmp:
7171     case bp_longjmp_resume:
7172     case bp_longjmp_call_dummy:
7173     case bp_exception:
7174     case bp_exception_resume:
7175     case bp_step_resume:
7176     case bp_hp_step_resume:
7177     case bp_watchpoint_scope:
7178     case bp_call_dummy:
7179     case bp_std_terminate:
7180     case bp_shlib_event:
7181     case bp_thread_event:
7182     case bp_overlay_event:
7183     case bp_jit_event:
7184     case bp_longjmp_master:
7185     case bp_std_terminate_master:
7186     case bp_exception_master:
7187     case bp_gnu_ifunc_resolver:
7188     case bp_gnu_ifunc_resolver_return:
7189     case bp_dprintf:
7190       loc->loc_type = bp_loc_software_breakpoint;
7191       mark_breakpoint_location_modified (loc);
7192       break;
7193     case bp_hardware_breakpoint:
7194       loc->loc_type = bp_loc_hardware_breakpoint;
7195       mark_breakpoint_location_modified (loc);
7196       break;
7197     case bp_hardware_watchpoint:
7198     case bp_read_watchpoint:
7199     case bp_access_watchpoint:
7200       loc->loc_type = bp_loc_hardware_watchpoint;
7201       break;
7202     case bp_watchpoint:
7203     case bp_catchpoint:
7204     case bp_tracepoint:
7205     case bp_fast_tracepoint:
7206     case bp_static_tracepoint:
7207       loc->loc_type = bp_loc_other;
7208       break;
7209     default:
7210       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7211     }
7212
7213   loc->refc = 1;
7214 }
7215
7216 /* Allocate a struct bp_location.  */
7217
7218 static struct bp_location *
7219 allocate_bp_location (struct breakpoint *bpt)
7220 {
7221   return bpt->ops->allocate_location (bpt);
7222 }
7223
7224 static void
7225 free_bp_location (struct bp_location *loc)
7226 {
7227   loc->ops->dtor (loc);
7228   xfree (loc);
7229 }
7230
7231 /* Increment reference count.  */
7232
7233 static void
7234 incref_bp_location (struct bp_location *bl)
7235 {
7236   ++bl->refc;
7237 }
7238
7239 /* Decrement reference count.  If the reference count reaches 0,
7240    destroy the bp_location.  Sets *BLP to NULL.  */
7241
7242 static void
7243 decref_bp_location (struct bp_location **blp)
7244 {
7245   gdb_assert ((*blp)->refc > 0);
7246
7247   if (--(*blp)->refc == 0)
7248     free_bp_location (*blp);
7249   *blp = NULL;
7250 }
7251
7252 /* Add breakpoint B at the end of the global breakpoint chain.  */
7253
7254 static void
7255 add_to_breakpoint_chain (struct breakpoint *b)
7256 {
7257   struct breakpoint *b1;
7258
7259   /* Add this breakpoint to the end of the chain so that a list of
7260      breakpoints will come out in order of increasing numbers.  */
7261
7262   b1 = breakpoint_chain;
7263   if (b1 == 0)
7264     breakpoint_chain = b;
7265   else
7266     {
7267       while (b1->next)
7268         b1 = b1->next;
7269       b1->next = b;
7270     }
7271 }
7272
7273 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7274
7275 static void
7276 init_raw_breakpoint_without_location (struct breakpoint *b,
7277                                       struct gdbarch *gdbarch,
7278                                       enum bptype bptype,
7279                                       const struct breakpoint_ops *ops)
7280 {
7281   memset (b, 0, sizeof (*b));
7282
7283   gdb_assert (ops != NULL);
7284
7285   b->ops = ops;
7286   b->type = bptype;
7287   b->gdbarch = gdbarch;
7288   b->language = current_language->la_language;
7289   b->input_radix = input_radix;
7290   b->thread = -1;
7291   b->enable_state = bp_enabled;
7292   b->next = 0;
7293   b->silent = 0;
7294   b->ignore_count = 0;
7295   b->commands = NULL;
7296   b->frame_id = null_frame_id;
7297   b->condition_not_parsed = 0;
7298   b->py_bp_object = NULL;
7299   b->related_breakpoint = b;
7300 }
7301
7302 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7303    that has type BPTYPE and has no locations as yet.  */
7304
7305 static struct breakpoint *
7306 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7307                                      enum bptype bptype,
7308                                      const struct breakpoint_ops *ops)
7309 {
7310   struct breakpoint *b = XNEW (struct breakpoint);
7311
7312   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7313   add_to_breakpoint_chain (b);
7314   return b;
7315 }
7316
7317 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7318    resolutions should be made as the user specified the location explicitly
7319    enough.  */
7320
7321 static void
7322 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7323 {
7324   gdb_assert (loc->owner != NULL);
7325
7326   if (loc->owner->type == bp_breakpoint
7327       || loc->owner->type == bp_hardware_breakpoint
7328       || is_tracepoint (loc->owner))
7329     {
7330       int is_gnu_ifunc;
7331       const char *function_name;
7332       CORE_ADDR func_addr;
7333
7334       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7335                                           &func_addr, NULL, &is_gnu_ifunc);
7336
7337       if (is_gnu_ifunc && !explicit_loc)
7338         {
7339           struct breakpoint *b = loc->owner;
7340
7341           gdb_assert (loc->pspace == current_program_space);
7342           if (gnu_ifunc_resolve_name (function_name,
7343                                       &loc->requested_address))
7344             {
7345               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7346               loc->address = adjust_breakpoint_address (loc->gdbarch,
7347                                                         loc->requested_address,
7348                                                         b->type);
7349             }
7350           else if (b->type == bp_breakpoint && b->loc == loc
7351                    && loc->next == NULL && b->related_breakpoint == b)
7352             {
7353               /* Create only the whole new breakpoint of this type but do not
7354                  mess more complicated breakpoints with multiple locations.  */
7355               b->type = bp_gnu_ifunc_resolver;
7356               /* Remember the resolver's address for use by the return
7357                  breakpoint.  */
7358               loc->related_address = func_addr;
7359             }
7360         }
7361
7362       if (function_name)
7363         loc->function_name = xstrdup (function_name);
7364     }
7365 }
7366
7367 /* Attempt to determine architecture of location identified by SAL.  */
7368 struct gdbarch *
7369 get_sal_arch (struct symtab_and_line sal)
7370 {
7371   if (sal.section)
7372     return get_objfile_arch (sal.section->objfile);
7373   if (sal.symtab)
7374     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7375
7376   return NULL;
7377 }
7378
7379 /* Low level routine for partially initializing a breakpoint of type
7380    BPTYPE.  The newly created breakpoint's address, section, source
7381    file name, and line number are provided by SAL.
7382
7383    It is expected that the caller will complete the initialization of
7384    the newly created breakpoint struct as well as output any status
7385    information regarding the creation of a new breakpoint.  */
7386
7387 static void
7388 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7389                      struct symtab_and_line sal, enum bptype bptype,
7390                      const struct breakpoint_ops *ops)
7391 {
7392   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7393
7394   add_location_to_breakpoint (b, &sal);
7395
7396   if (bptype != bp_catchpoint)
7397     gdb_assert (sal.pspace != NULL);
7398
7399   /* Store the program space that was used to set the breakpoint,
7400      except for ordinary breakpoints, which are independent of the
7401      program space.  */
7402   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7403     b->pspace = sal.pspace;
7404 }
7405
7406 /* set_raw_breakpoint is a low level routine for allocating and
7407    partially initializing a breakpoint of type BPTYPE.  The newly
7408    created breakpoint's address, section, source file name, and line
7409    number are provided by SAL.  The newly created and partially
7410    initialized breakpoint is added to the breakpoint chain and
7411    is also returned as the value of this function.
7412
7413    It is expected that the caller will complete the initialization of
7414    the newly created breakpoint struct as well as output any status
7415    information regarding the creation of a new breakpoint.  In
7416    particular, set_raw_breakpoint does NOT set the breakpoint
7417    number!  Care should be taken to not allow an error to occur
7418    prior to completing the initialization of the breakpoint.  If this
7419    should happen, a bogus breakpoint will be left on the chain.  */
7420
7421 struct breakpoint *
7422 set_raw_breakpoint (struct gdbarch *gdbarch,
7423                     struct symtab_and_line sal, enum bptype bptype,
7424                     const struct breakpoint_ops *ops)
7425 {
7426   struct breakpoint *b = XNEW (struct breakpoint);
7427
7428   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7429   add_to_breakpoint_chain (b);
7430   return b;
7431 }
7432
7433
7434 /* Note that the breakpoint object B describes a permanent breakpoint
7435    instruction, hard-wired into the inferior's code.  */
7436 void
7437 make_breakpoint_permanent (struct breakpoint *b)
7438 {
7439   struct bp_location *bl;
7440
7441   /* By definition, permanent breakpoints are already present in the
7442      code.  Mark all locations as inserted.  For now,
7443      make_breakpoint_permanent is called in just one place, so it's
7444      hard to say if it's reasonable to have permanent breakpoint with
7445      multiple locations or not, but it's easy to implement.  */
7446   for (bl = b->loc; bl; bl = bl->next)
7447     {
7448       bl->permanent = 1;
7449       bl->inserted = 1;
7450     }
7451 }
7452
7453 /* Call this routine when stepping and nexting to enable a breakpoint
7454    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7455    initiated the operation.  */
7456
7457 void
7458 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7459 {
7460   struct breakpoint *b, *b_tmp;
7461   int thread = tp->num;
7462
7463   /* To avoid having to rescan all objfile symbols at every step,
7464      we maintain a list of continually-inserted but always disabled
7465      longjmp "master" breakpoints.  Here, we simply create momentary
7466      clones of those and enable them for the requested thread.  */
7467   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7468     if (b->pspace == current_program_space
7469         && (b->type == bp_longjmp_master
7470             || b->type == bp_exception_master))
7471       {
7472         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7473         struct breakpoint *clone;
7474
7475         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7476            after their removal.  */
7477         clone = momentary_breakpoint_from_master (b, type,
7478                                                   &longjmp_breakpoint_ops, 1);
7479         clone->thread = thread;
7480       }
7481
7482   tp->initiating_frame = frame;
7483 }
7484
7485 /* Delete all longjmp breakpoints from THREAD.  */
7486 void
7487 delete_longjmp_breakpoint (int thread)
7488 {
7489   struct breakpoint *b, *b_tmp;
7490
7491   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7492     if (b->type == bp_longjmp || b->type == bp_exception)
7493       {
7494         if (b->thread == thread)
7495           delete_breakpoint (b);
7496       }
7497 }
7498
7499 void
7500 delete_longjmp_breakpoint_at_next_stop (int thread)
7501 {
7502   struct breakpoint *b, *b_tmp;
7503
7504   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7505     if (b->type == bp_longjmp || b->type == bp_exception)
7506       {
7507         if (b->thread == thread)
7508           b->disposition = disp_del_at_next_stop;
7509       }
7510 }
7511
7512 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7513    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7514    pointer to any of them.  Return NULL if this system cannot place longjmp
7515    breakpoints.  */
7516
7517 struct breakpoint *
7518 set_longjmp_breakpoint_for_call_dummy (void)
7519 {
7520   struct breakpoint *b, *retval = NULL;
7521
7522   ALL_BREAKPOINTS (b)
7523     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7524       {
7525         struct breakpoint *new_b;
7526
7527         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7528                                                   &momentary_breakpoint_ops,
7529                                                   1);
7530         new_b->thread = pid_to_thread_id (inferior_ptid);
7531
7532         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7533
7534         gdb_assert (new_b->related_breakpoint == new_b);
7535         if (retval == NULL)
7536           retval = new_b;
7537         new_b->related_breakpoint = retval;
7538         while (retval->related_breakpoint != new_b->related_breakpoint)
7539           retval = retval->related_breakpoint;
7540         retval->related_breakpoint = new_b;
7541       }
7542
7543   return retval;
7544 }
7545
7546 /* Verify all existing dummy frames and their associated breakpoints for
7547    TP.  Remove those which can no longer be found in the current frame
7548    stack.
7549
7550    You should call this function only at places where it is safe to currently
7551    unwind the whole stack.  Failed stack unwind would discard live dummy
7552    frames.  */
7553
7554 void
7555 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7556 {
7557   struct breakpoint *b, *b_tmp;
7558
7559   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7560     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7561       {
7562         struct breakpoint *dummy_b = b->related_breakpoint;
7563
7564         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7565           dummy_b = dummy_b->related_breakpoint;
7566         if (dummy_b->type != bp_call_dummy
7567             || frame_find_by_id (dummy_b->frame_id) != NULL)
7568           continue;
7569         
7570         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7571
7572         while (b->related_breakpoint != b)
7573           {
7574             if (b_tmp == b->related_breakpoint)
7575               b_tmp = b->related_breakpoint->next;
7576             delete_breakpoint (b->related_breakpoint);
7577           }
7578         delete_breakpoint (b);
7579       }
7580 }
7581
7582 void
7583 enable_overlay_breakpoints (void)
7584 {
7585   struct breakpoint *b;
7586
7587   ALL_BREAKPOINTS (b)
7588     if (b->type == bp_overlay_event)
7589     {
7590       b->enable_state = bp_enabled;
7591       update_global_location_list (UGLL_MAY_INSERT);
7592       overlay_events_enabled = 1;
7593     }
7594 }
7595
7596 void
7597 disable_overlay_breakpoints (void)
7598 {
7599   struct breakpoint *b;
7600
7601   ALL_BREAKPOINTS (b)
7602     if (b->type == bp_overlay_event)
7603     {
7604       b->enable_state = bp_disabled;
7605       update_global_location_list (UGLL_DONT_INSERT);
7606       overlay_events_enabled = 0;
7607     }
7608 }
7609
7610 /* Set an active std::terminate breakpoint for each std::terminate
7611    master breakpoint.  */
7612 void
7613 set_std_terminate_breakpoint (void)
7614 {
7615   struct breakpoint *b, *b_tmp;
7616
7617   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7618     if (b->pspace == current_program_space
7619         && b->type == bp_std_terminate_master)
7620       {
7621         momentary_breakpoint_from_master (b, bp_std_terminate,
7622                                           &momentary_breakpoint_ops, 1);
7623       }
7624 }
7625
7626 /* Delete all the std::terminate breakpoints.  */
7627 void
7628 delete_std_terminate_breakpoint (void)
7629 {
7630   struct breakpoint *b, *b_tmp;
7631
7632   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7633     if (b->type == bp_std_terminate)
7634       delete_breakpoint (b);
7635 }
7636
7637 struct breakpoint *
7638 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7639 {
7640   struct breakpoint *b;
7641
7642   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7643                                   &internal_breakpoint_ops);
7644
7645   b->enable_state = bp_enabled;
7646   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7647   b->addr_string
7648     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7649
7650   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7651
7652   return b;
7653 }
7654
7655 void
7656 remove_thread_event_breakpoints (void)
7657 {
7658   struct breakpoint *b, *b_tmp;
7659
7660   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7661     if (b->type == bp_thread_event
7662         && b->loc->pspace == current_program_space)
7663       delete_breakpoint (b);
7664 }
7665
7666 struct lang_and_radix
7667   {
7668     enum language lang;
7669     int radix;
7670   };
7671
7672 /* Create a breakpoint for JIT code registration and unregistration.  */
7673
7674 struct breakpoint *
7675 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7676 {
7677   struct breakpoint *b;
7678
7679   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7680                                   &internal_breakpoint_ops);
7681   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7682   return b;
7683 }
7684
7685 /* Remove JIT code registration and unregistration breakpoint(s).  */
7686
7687 void
7688 remove_jit_event_breakpoints (void)
7689 {
7690   struct breakpoint *b, *b_tmp;
7691
7692   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7693     if (b->type == bp_jit_event
7694         && b->loc->pspace == current_program_space)
7695       delete_breakpoint (b);
7696 }
7697
7698 void
7699 remove_solib_event_breakpoints (void)
7700 {
7701   struct breakpoint *b, *b_tmp;
7702
7703   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7704     if (b->type == bp_shlib_event
7705         && b->loc->pspace == current_program_space)
7706       delete_breakpoint (b);
7707 }
7708
7709 /* See breakpoint.h.  */
7710
7711 void
7712 remove_solib_event_breakpoints_at_next_stop (void)
7713 {
7714   struct breakpoint *b, *b_tmp;
7715
7716   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7717     if (b->type == bp_shlib_event
7718         && b->loc->pspace == current_program_space)
7719       b->disposition = disp_del_at_next_stop;
7720 }
7721
7722 /* Helper for create_solib_event_breakpoint /
7723    create_and_insert_solib_event_breakpoint.  Allows specifying which
7724    INSERT_MODE to pass through to update_global_location_list.  */
7725
7726 static struct breakpoint *
7727 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7728                                  enum ugll_insert_mode insert_mode)
7729 {
7730   struct breakpoint *b;
7731
7732   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7733                                   &internal_breakpoint_ops);
7734   update_global_location_list_nothrow (insert_mode);
7735   return b;
7736 }
7737
7738 struct breakpoint *
7739 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7740 {
7741   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7742 }
7743
7744 /* See breakpoint.h.  */
7745
7746 struct breakpoint *
7747 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7748 {
7749   struct breakpoint *b;
7750
7751   /* Explicitly tell update_global_location_list to insert
7752      locations.  */
7753   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7754   if (!b->loc->inserted)
7755     {
7756       delete_breakpoint (b);
7757       return NULL;
7758     }
7759   return b;
7760 }
7761
7762 /* Disable any breakpoints that are on code in shared libraries.  Only
7763    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7764
7765 void
7766 disable_breakpoints_in_shlibs (void)
7767 {
7768   struct bp_location *loc, **locp_tmp;
7769
7770   ALL_BP_LOCATIONS (loc, locp_tmp)
7771   {
7772     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7773     struct breakpoint *b = loc->owner;
7774
7775     /* We apply the check to all breakpoints, including disabled for
7776        those with loc->duplicate set.  This is so that when breakpoint
7777        becomes enabled, or the duplicate is removed, gdb will try to
7778        insert all breakpoints.  If we don't set shlib_disabled here,
7779        we'll try to insert those breakpoints and fail.  */
7780     if (((b->type == bp_breakpoint)
7781          || (b->type == bp_jit_event)
7782          || (b->type == bp_hardware_breakpoint)
7783          || (is_tracepoint (b)))
7784         && loc->pspace == current_program_space
7785         && !loc->shlib_disabled
7786         && solib_name_from_address (loc->pspace, loc->address)
7787         )
7788       {
7789         loc->shlib_disabled = 1;
7790       }
7791   }
7792 }
7793
7794 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7795    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7796    disabled ones can just stay disabled.  */
7797
7798 static void
7799 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7800 {
7801   struct bp_location *loc, **locp_tmp;
7802   int disabled_shlib_breaks = 0;
7803
7804   /* SunOS a.out shared libraries are always mapped, so do not
7805      disable breakpoints; they will only be reported as unloaded
7806      through clear_solib when GDB discards its shared library
7807      list.  See clear_solib for more information.  */
7808   if (exec_bfd != NULL
7809       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7810     return;
7811
7812   ALL_BP_LOCATIONS (loc, locp_tmp)
7813   {
7814     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7815     struct breakpoint *b = loc->owner;
7816
7817     if (solib->pspace == loc->pspace
7818         && !loc->shlib_disabled
7819         && (((b->type == bp_breakpoint
7820               || b->type == bp_jit_event
7821               || b->type == bp_hardware_breakpoint)
7822              && (loc->loc_type == bp_loc_hardware_breakpoint
7823                  || loc->loc_type == bp_loc_software_breakpoint))
7824             || is_tracepoint (b))
7825         && solib_contains_address_p (solib, loc->address))
7826       {
7827         loc->shlib_disabled = 1;
7828         /* At this point, we cannot rely on remove_breakpoint
7829            succeeding so we must mark the breakpoint as not inserted
7830            to prevent future errors occurring in remove_breakpoints.  */
7831         loc->inserted = 0;
7832
7833         /* This may cause duplicate notifications for the same breakpoint.  */
7834         observer_notify_breakpoint_modified (b);
7835
7836         if (!disabled_shlib_breaks)
7837           {
7838             target_terminal_ours_for_output ();
7839             warning (_("Temporarily disabling breakpoints "
7840                        "for unloaded shared library \"%s\""),
7841                      solib->so_name);
7842           }
7843         disabled_shlib_breaks = 1;
7844       }
7845   }
7846 }
7847
7848 /* Disable any breakpoints and tracepoints in OBJFILE upon
7849    notification of free_objfile.  Only apply to enabled breakpoints,
7850    disabled ones can just stay disabled.  */
7851
7852 static void
7853 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7854 {
7855   struct breakpoint *b;
7856
7857   if (objfile == NULL)
7858     return;
7859
7860   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7861      managed by the user with add-symbol-file/remove-symbol-file.
7862      Similarly to how breakpoints in shared libraries are handled in
7863      response to "nosharedlibrary", mark breakpoints in such modules
7864      shlib_disabled so they end up uninserted on the next global
7865      location list update.  Shared libraries not loaded by the user
7866      aren't handled here -- they're already handled in
7867      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7868      solib_unloaded observer.  We skip objfiles that are not
7869      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7870      main objfile).  */
7871   if ((objfile->flags & OBJF_SHARED) == 0
7872       || (objfile->flags & OBJF_USERLOADED) == 0)
7873     return;
7874
7875   ALL_BREAKPOINTS (b)
7876     {
7877       struct bp_location *loc;
7878       int bp_modified = 0;
7879
7880       if (!is_breakpoint (b) && !is_tracepoint (b))
7881         continue;
7882
7883       for (loc = b->loc; loc != NULL; loc = loc->next)
7884         {
7885           CORE_ADDR loc_addr = loc->address;
7886
7887           if (loc->loc_type != bp_loc_hardware_breakpoint
7888               && loc->loc_type != bp_loc_software_breakpoint)
7889             continue;
7890
7891           if (loc->shlib_disabled != 0)
7892             continue;
7893
7894           if (objfile->pspace != loc->pspace)
7895             continue;
7896
7897           if (loc->loc_type != bp_loc_hardware_breakpoint
7898               && loc->loc_type != bp_loc_software_breakpoint)
7899             continue;
7900
7901           if (is_addr_in_objfile (loc_addr, objfile))
7902             {
7903               loc->shlib_disabled = 1;
7904               /* At this point, we don't know whether the object was
7905                  unmapped from the inferior or not, so leave the
7906                  inserted flag alone.  We'll handle failure to
7907                  uninsert quietly, in case the object was indeed
7908                  unmapped.  */
7909
7910               mark_breakpoint_location_modified (loc);
7911
7912               bp_modified = 1;
7913             }
7914         }
7915
7916       if (bp_modified)
7917         observer_notify_breakpoint_modified (b);
7918     }
7919 }
7920
7921 /* FORK & VFORK catchpoints.  */
7922
7923 /* An instance of this type is used to represent a fork or vfork
7924    catchpoint.  It includes a "struct breakpoint" as a kind of base
7925    class; users downcast to "struct breakpoint *" when needed.  A
7926    breakpoint is really of this type iff its ops pointer points to
7927    CATCH_FORK_BREAKPOINT_OPS.  */
7928
7929 struct fork_catchpoint
7930 {
7931   /* The base class.  */
7932   struct breakpoint base;
7933
7934   /* Process id of a child process whose forking triggered this
7935      catchpoint.  This field is only valid immediately after this
7936      catchpoint has triggered.  */
7937   ptid_t forked_inferior_pid;
7938 };
7939
7940 /* Implement the "insert" breakpoint_ops method for fork
7941    catchpoints.  */
7942
7943 static int
7944 insert_catch_fork (struct bp_location *bl)
7945 {
7946   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7947 }
7948
7949 /* Implement the "remove" breakpoint_ops method for fork
7950    catchpoints.  */
7951
7952 static int
7953 remove_catch_fork (struct bp_location *bl)
7954 {
7955   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7956 }
7957
7958 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7959    catchpoints.  */
7960
7961 static int
7962 breakpoint_hit_catch_fork (const struct bp_location *bl,
7963                            struct address_space *aspace, CORE_ADDR bp_addr,
7964                            const struct target_waitstatus *ws)
7965 {
7966   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7967
7968   if (ws->kind != TARGET_WAITKIND_FORKED)
7969     return 0;
7970
7971   c->forked_inferior_pid = ws->value.related_pid;
7972   return 1;
7973 }
7974
7975 /* Implement the "print_it" breakpoint_ops method for fork
7976    catchpoints.  */
7977
7978 static enum print_stop_action
7979 print_it_catch_fork (bpstat bs)
7980 {
7981   struct ui_out *uiout = current_uiout;
7982   struct breakpoint *b = bs->breakpoint_at;
7983   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7984
7985   annotate_catchpoint (b->number);
7986   if (b->disposition == disp_del)
7987     ui_out_text (uiout, "\nTemporary catchpoint ");
7988   else
7989     ui_out_text (uiout, "\nCatchpoint ");
7990   if (ui_out_is_mi_like_p (uiout))
7991     {
7992       ui_out_field_string (uiout, "reason",
7993                            async_reason_lookup (EXEC_ASYNC_FORK));
7994       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7995     }
7996   ui_out_field_int (uiout, "bkptno", b->number);
7997   ui_out_text (uiout, " (forked process ");
7998   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7999   ui_out_text (uiout, "), ");
8000   return PRINT_SRC_AND_LOC;
8001 }
8002
8003 /* Implement the "print_one" breakpoint_ops method for fork
8004    catchpoints.  */
8005
8006 static void
8007 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8008 {
8009   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8010   struct value_print_options opts;
8011   struct ui_out *uiout = current_uiout;
8012
8013   get_user_print_options (&opts);
8014
8015   /* Field 4, the address, is omitted (which makes the columns not
8016      line up too nicely with the headers, but the effect is relatively
8017      readable).  */
8018   if (opts.addressprint)
8019     ui_out_field_skip (uiout, "addr");
8020   annotate_field (5);
8021   ui_out_text (uiout, "fork");
8022   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8023     {
8024       ui_out_text (uiout, ", process ");
8025       ui_out_field_int (uiout, "what",
8026                         ptid_get_pid (c->forked_inferior_pid));
8027       ui_out_spaces (uiout, 1);
8028     }
8029
8030   if (ui_out_is_mi_like_p (uiout))
8031     ui_out_field_string (uiout, "catch-type", "fork");
8032 }
8033
8034 /* Implement the "print_mention" breakpoint_ops method for fork
8035    catchpoints.  */
8036
8037 static void
8038 print_mention_catch_fork (struct breakpoint *b)
8039 {
8040   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8041 }
8042
8043 /* Implement the "print_recreate" breakpoint_ops method for fork
8044    catchpoints.  */
8045
8046 static void
8047 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8048 {
8049   fprintf_unfiltered (fp, "catch fork");
8050   print_recreate_thread (b, fp);
8051 }
8052
8053 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8054
8055 static struct breakpoint_ops catch_fork_breakpoint_ops;
8056
8057 /* Implement the "insert" breakpoint_ops method for vfork
8058    catchpoints.  */
8059
8060 static int
8061 insert_catch_vfork (struct bp_location *bl)
8062 {
8063   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8064 }
8065
8066 /* Implement the "remove" breakpoint_ops method for vfork
8067    catchpoints.  */
8068
8069 static int
8070 remove_catch_vfork (struct bp_location *bl)
8071 {
8072   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8073 }
8074
8075 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8076    catchpoints.  */
8077
8078 static int
8079 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8080                             struct address_space *aspace, CORE_ADDR bp_addr,
8081                             const struct target_waitstatus *ws)
8082 {
8083   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8084
8085   if (ws->kind != TARGET_WAITKIND_VFORKED)
8086     return 0;
8087
8088   c->forked_inferior_pid = ws->value.related_pid;
8089   return 1;
8090 }
8091
8092 /* Implement the "print_it" breakpoint_ops method for vfork
8093    catchpoints.  */
8094
8095 static enum print_stop_action
8096 print_it_catch_vfork (bpstat bs)
8097 {
8098   struct ui_out *uiout = current_uiout;
8099   struct breakpoint *b = bs->breakpoint_at;
8100   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8101
8102   annotate_catchpoint (b->number);
8103   if (b->disposition == disp_del)
8104     ui_out_text (uiout, "\nTemporary catchpoint ");
8105   else
8106     ui_out_text (uiout, "\nCatchpoint ");
8107   if (ui_out_is_mi_like_p (uiout))
8108     {
8109       ui_out_field_string (uiout, "reason",
8110                            async_reason_lookup (EXEC_ASYNC_VFORK));
8111       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8112     }
8113   ui_out_field_int (uiout, "bkptno", b->number);
8114   ui_out_text (uiout, " (vforked process ");
8115   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8116   ui_out_text (uiout, "), ");
8117   return PRINT_SRC_AND_LOC;
8118 }
8119
8120 /* Implement the "print_one" breakpoint_ops method for vfork
8121    catchpoints.  */
8122
8123 static void
8124 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8125 {
8126   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8127   struct value_print_options opts;
8128   struct ui_out *uiout = current_uiout;
8129
8130   get_user_print_options (&opts);
8131   /* Field 4, the address, is omitted (which makes the columns not
8132      line up too nicely with the headers, but the effect is relatively
8133      readable).  */
8134   if (opts.addressprint)
8135     ui_out_field_skip (uiout, "addr");
8136   annotate_field (5);
8137   ui_out_text (uiout, "vfork");
8138   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8139     {
8140       ui_out_text (uiout, ", process ");
8141       ui_out_field_int (uiout, "what",
8142                         ptid_get_pid (c->forked_inferior_pid));
8143       ui_out_spaces (uiout, 1);
8144     }
8145
8146   if (ui_out_is_mi_like_p (uiout))
8147     ui_out_field_string (uiout, "catch-type", "vfork");
8148 }
8149
8150 /* Implement the "print_mention" breakpoint_ops method for vfork
8151    catchpoints.  */
8152
8153 static void
8154 print_mention_catch_vfork (struct breakpoint *b)
8155 {
8156   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8157 }
8158
8159 /* Implement the "print_recreate" breakpoint_ops method for vfork
8160    catchpoints.  */
8161
8162 static void
8163 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8164 {
8165   fprintf_unfiltered (fp, "catch vfork");
8166   print_recreate_thread (b, fp);
8167 }
8168
8169 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8170
8171 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8172
8173 /* An instance of this type is used to represent an solib catchpoint.
8174    It includes a "struct breakpoint" as a kind of base class; users
8175    downcast to "struct breakpoint *" when needed.  A breakpoint is
8176    really of this type iff its ops pointer points to
8177    CATCH_SOLIB_BREAKPOINT_OPS.  */
8178
8179 struct solib_catchpoint
8180 {
8181   /* The base class.  */
8182   struct breakpoint base;
8183
8184   /* True for "catch load", false for "catch unload".  */
8185   unsigned char is_load;
8186
8187   /* Regular expression to match, if any.  COMPILED is only valid when
8188      REGEX is non-NULL.  */
8189   char *regex;
8190   regex_t compiled;
8191 };
8192
8193 static void
8194 dtor_catch_solib (struct breakpoint *b)
8195 {
8196   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8197
8198   if (self->regex)
8199     regfree (&self->compiled);
8200   xfree (self->regex);
8201
8202   base_breakpoint_ops.dtor (b);
8203 }
8204
8205 static int
8206 insert_catch_solib (struct bp_location *ignore)
8207 {
8208   return 0;
8209 }
8210
8211 static int
8212 remove_catch_solib (struct bp_location *ignore)
8213 {
8214   return 0;
8215 }
8216
8217 static int
8218 breakpoint_hit_catch_solib (const struct bp_location *bl,
8219                             struct address_space *aspace,
8220                             CORE_ADDR bp_addr,
8221                             const struct target_waitstatus *ws)
8222 {
8223   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8224   struct breakpoint *other;
8225
8226   if (ws->kind == TARGET_WAITKIND_LOADED)
8227     return 1;
8228
8229   ALL_BREAKPOINTS (other)
8230   {
8231     struct bp_location *other_bl;
8232
8233     if (other == bl->owner)
8234       continue;
8235
8236     if (other->type != bp_shlib_event)
8237       continue;
8238
8239     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8240       continue;
8241
8242     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8243       {
8244         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8245           return 1;
8246       }
8247   }
8248
8249   return 0;
8250 }
8251
8252 static void
8253 check_status_catch_solib (struct bpstats *bs)
8254 {
8255   struct solib_catchpoint *self
8256     = (struct solib_catchpoint *) bs->breakpoint_at;
8257   int ix;
8258
8259   if (self->is_load)
8260     {
8261       struct so_list *iter;
8262
8263       for (ix = 0;
8264            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8265                         ix, iter);
8266            ++ix)
8267         {
8268           if (!self->regex
8269               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8270             return;
8271         }
8272     }
8273   else
8274     {
8275       char *iter;
8276
8277       for (ix = 0;
8278            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8279                         ix, iter);
8280            ++ix)
8281         {
8282           if (!self->regex
8283               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8284             return;
8285         }
8286     }
8287
8288   bs->stop = 0;
8289   bs->print_it = print_it_noop;
8290 }
8291
8292 static enum print_stop_action
8293 print_it_catch_solib (bpstat bs)
8294 {
8295   struct breakpoint *b = bs->breakpoint_at;
8296   struct ui_out *uiout = current_uiout;
8297
8298   annotate_catchpoint (b->number);
8299   if (b->disposition == disp_del)
8300     ui_out_text (uiout, "\nTemporary catchpoint ");
8301   else
8302     ui_out_text (uiout, "\nCatchpoint ");
8303   ui_out_field_int (uiout, "bkptno", b->number);
8304   ui_out_text (uiout, "\n");
8305   if (ui_out_is_mi_like_p (uiout))
8306     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8307   print_solib_event (1);
8308   return PRINT_SRC_AND_LOC;
8309 }
8310
8311 static void
8312 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8313 {
8314   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8315   struct value_print_options opts;
8316   struct ui_out *uiout = current_uiout;
8317   char *msg;
8318
8319   get_user_print_options (&opts);
8320   /* Field 4, the address, is omitted (which makes the columns not
8321      line up too nicely with the headers, but the effect is relatively
8322      readable).  */
8323   if (opts.addressprint)
8324     {
8325       annotate_field (4);
8326       ui_out_field_skip (uiout, "addr");
8327     }
8328
8329   annotate_field (5);
8330   if (self->is_load)
8331     {
8332       if (self->regex)
8333         msg = xstrprintf (_("load of library matching %s"), self->regex);
8334       else
8335         msg = xstrdup (_("load of library"));
8336     }
8337   else
8338     {
8339       if (self->regex)
8340         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8341       else
8342         msg = xstrdup (_("unload of library"));
8343     }
8344   ui_out_field_string (uiout, "what", msg);
8345   xfree (msg);
8346
8347   if (ui_out_is_mi_like_p (uiout))
8348     ui_out_field_string (uiout, "catch-type",
8349                          self->is_load ? "load" : "unload");
8350 }
8351
8352 static void
8353 print_mention_catch_solib (struct breakpoint *b)
8354 {
8355   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8356
8357   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8358                    self->is_load ? "load" : "unload");
8359 }
8360
8361 static void
8362 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8363 {
8364   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8365
8366   fprintf_unfiltered (fp, "%s %s",
8367                       b->disposition == disp_del ? "tcatch" : "catch",
8368                       self->is_load ? "load" : "unload");
8369   if (self->regex)
8370     fprintf_unfiltered (fp, " %s", self->regex);
8371   fprintf_unfiltered (fp, "\n");
8372 }
8373
8374 static struct breakpoint_ops catch_solib_breakpoint_ops;
8375
8376 /* Shared helper function (MI and CLI) for creating and installing
8377    a shared object event catchpoint.  If IS_LOAD is non-zero then
8378    the events to be caught are load events, otherwise they are
8379    unload events.  If IS_TEMP is non-zero the catchpoint is a
8380    temporary one.  If ENABLED is non-zero the catchpoint is
8381    created in an enabled state.  */
8382
8383 void
8384 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8385 {
8386   struct solib_catchpoint *c;
8387   struct gdbarch *gdbarch = get_current_arch ();
8388   struct cleanup *cleanup;
8389
8390   if (!arg)
8391     arg = "";
8392   arg = skip_spaces (arg);
8393
8394   c = XCNEW (struct solib_catchpoint);
8395   cleanup = make_cleanup (xfree, c);
8396
8397   if (*arg != '\0')
8398     {
8399       int errcode;
8400
8401       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8402       if (errcode != 0)
8403         {
8404           char *err = get_regcomp_error (errcode, &c->compiled);
8405
8406           make_cleanup (xfree, err);
8407           error (_("Invalid regexp (%s): %s"), err, arg);
8408         }
8409       c->regex = xstrdup (arg);
8410     }
8411
8412   c->is_load = is_load;
8413   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8414                    &catch_solib_breakpoint_ops);
8415
8416   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8417
8418   discard_cleanups (cleanup);
8419   install_breakpoint (0, &c->base, 1);
8420 }
8421
8422 /* A helper function that does all the work for "catch load" and
8423    "catch unload".  */
8424
8425 static void
8426 catch_load_or_unload (char *arg, int from_tty, int is_load,
8427                       struct cmd_list_element *command)
8428 {
8429   int tempflag;
8430   const int enabled = 1;
8431
8432   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8433
8434   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8435 }
8436
8437 static void
8438 catch_load_command_1 (char *arg, int from_tty,
8439                       struct cmd_list_element *command)
8440 {
8441   catch_load_or_unload (arg, from_tty, 1, command);
8442 }
8443
8444 static void
8445 catch_unload_command_1 (char *arg, int from_tty,
8446                         struct cmd_list_element *command)
8447 {
8448   catch_load_or_unload (arg, from_tty, 0, command);
8449 }
8450
8451 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8452    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8453    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8454    the breakpoint_ops structure associated to the catchpoint.  */
8455
8456 void
8457 init_catchpoint (struct breakpoint *b,
8458                  struct gdbarch *gdbarch, int tempflag,
8459                  char *cond_string,
8460                  const struct breakpoint_ops *ops)
8461 {
8462   struct symtab_and_line sal;
8463
8464   init_sal (&sal);
8465   sal.pspace = current_program_space;
8466
8467   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8468
8469   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8470   b->disposition = tempflag ? disp_del : disp_donttouch;
8471 }
8472
8473 void
8474 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8475 {
8476   add_to_breakpoint_chain (b);
8477   set_breakpoint_number (internal, b);
8478   if (is_tracepoint (b))
8479     set_tracepoint_count (breakpoint_count);
8480   if (!internal)
8481     mention (b);
8482   observer_notify_breakpoint_created (b);
8483
8484   if (update_gll)
8485     update_global_location_list (UGLL_MAY_INSERT);
8486 }
8487
8488 static void
8489 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8490                                     int tempflag, char *cond_string,
8491                                     const struct breakpoint_ops *ops)
8492 {
8493   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8494
8495   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8496
8497   c->forked_inferior_pid = null_ptid;
8498
8499   install_breakpoint (0, &c->base, 1);
8500 }
8501
8502 /* Exec catchpoints.  */
8503
8504 /* An instance of this type is used to represent an exec catchpoint.
8505    It includes a "struct breakpoint" as a kind of base class; users
8506    downcast to "struct breakpoint *" when needed.  A breakpoint is
8507    really of this type iff its ops pointer points to
8508    CATCH_EXEC_BREAKPOINT_OPS.  */
8509
8510 struct exec_catchpoint
8511 {
8512   /* The base class.  */
8513   struct breakpoint base;
8514
8515   /* Filename of a program whose exec triggered this catchpoint.
8516      This field is only valid immediately after this catchpoint has
8517      triggered.  */
8518   char *exec_pathname;
8519 };
8520
8521 /* Implement the "dtor" breakpoint_ops method for exec
8522    catchpoints.  */
8523
8524 static void
8525 dtor_catch_exec (struct breakpoint *b)
8526 {
8527   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8528
8529   xfree (c->exec_pathname);
8530
8531   base_breakpoint_ops.dtor (b);
8532 }
8533
8534 static int
8535 insert_catch_exec (struct bp_location *bl)
8536 {
8537   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8538 }
8539
8540 static int
8541 remove_catch_exec (struct bp_location *bl)
8542 {
8543   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8544 }
8545
8546 static int
8547 breakpoint_hit_catch_exec (const struct bp_location *bl,
8548                            struct address_space *aspace, CORE_ADDR bp_addr,
8549                            const struct target_waitstatus *ws)
8550 {
8551   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8552
8553   if (ws->kind != TARGET_WAITKIND_EXECD)
8554     return 0;
8555
8556   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8557   return 1;
8558 }
8559
8560 static enum print_stop_action
8561 print_it_catch_exec (bpstat bs)
8562 {
8563   struct ui_out *uiout = current_uiout;
8564   struct breakpoint *b = bs->breakpoint_at;
8565   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8566
8567   annotate_catchpoint (b->number);
8568   if (b->disposition == disp_del)
8569     ui_out_text (uiout, "\nTemporary catchpoint ");
8570   else
8571     ui_out_text (uiout, "\nCatchpoint ");
8572   if (ui_out_is_mi_like_p (uiout))
8573     {
8574       ui_out_field_string (uiout, "reason",
8575                            async_reason_lookup (EXEC_ASYNC_EXEC));
8576       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8577     }
8578   ui_out_field_int (uiout, "bkptno", b->number);
8579   ui_out_text (uiout, " (exec'd ");
8580   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8581   ui_out_text (uiout, "), ");
8582
8583   return PRINT_SRC_AND_LOC;
8584 }
8585
8586 static void
8587 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8588 {
8589   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8590   struct value_print_options opts;
8591   struct ui_out *uiout = current_uiout;
8592
8593   get_user_print_options (&opts);
8594
8595   /* Field 4, the address, is omitted (which makes the columns
8596      not line up too nicely with the headers, but the effect
8597      is relatively readable).  */
8598   if (opts.addressprint)
8599     ui_out_field_skip (uiout, "addr");
8600   annotate_field (5);
8601   ui_out_text (uiout, "exec");
8602   if (c->exec_pathname != NULL)
8603     {
8604       ui_out_text (uiout, ", program \"");
8605       ui_out_field_string (uiout, "what", c->exec_pathname);
8606       ui_out_text (uiout, "\" ");
8607     }
8608
8609   if (ui_out_is_mi_like_p (uiout))
8610     ui_out_field_string (uiout, "catch-type", "exec");
8611 }
8612
8613 static void
8614 print_mention_catch_exec (struct breakpoint *b)
8615 {
8616   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8617 }
8618
8619 /* Implement the "print_recreate" breakpoint_ops method for exec
8620    catchpoints.  */
8621
8622 static void
8623 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8624 {
8625   fprintf_unfiltered (fp, "catch exec");
8626   print_recreate_thread (b, fp);
8627 }
8628
8629 static struct breakpoint_ops catch_exec_breakpoint_ops;
8630
8631 static int
8632 hw_breakpoint_used_count (void)
8633 {
8634   int i = 0;
8635   struct breakpoint *b;
8636   struct bp_location *bl;
8637
8638   ALL_BREAKPOINTS (b)
8639   {
8640     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8641       for (bl = b->loc; bl; bl = bl->next)
8642         {
8643           /* Special types of hardware breakpoints may use more than
8644              one register.  */
8645           i += b->ops->resources_needed (bl);
8646         }
8647   }
8648
8649   return i;
8650 }
8651
8652 /* Returns the resources B would use if it were a hardware
8653    watchpoint.  */
8654
8655 static int
8656 hw_watchpoint_use_count (struct breakpoint *b)
8657 {
8658   int i = 0;
8659   struct bp_location *bl;
8660
8661   if (!breakpoint_enabled (b))
8662     return 0;
8663
8664   for (bl = b->loc; bl; bl = bl->next)
8665     {
8666       /* Special types of hardware watchpoints may use more than
8667          one register.  */
8668       i += b->ops->resources_needed (bl);
8669     }
8670
8671   return i;
8672 }
8673
8674 /* Returns the sum the used resources of all hardware watchpoints of
8675    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8676    the sum of the used resources of all hardware watchpoints of other
8677    types _not_ TYPE.  */
8678
8679 static int
8680 hw_watchpoint_used_count_others (struct breakpoint *except,
8681                                  enum bptype type, int *other_type_used)
8682 {
8683   int i = 0;
8684   struct breakpoint *b;
8685
8686   *other_type_used = 0;
8687   ALL_BREAKPOINTS (b)
8688     {
8689       if (b == except)
8690         continue;
8691       if (!breakpoint_enabled (b))
8692         continue;
8693
8694       if (b->type == type)
8695         i += hw_watchpoint_use_count (b);
8696       else if (is_hardware_watchpoint (b))
8697         *other_type_used = 1;
8698     }
8699
8700   return i;
8701 }
8702
8703 void
8704 disable_watchpoints_before_interactive_call_start (void)
8705 {
8706   struct breakpoint *b;
8707
8708   ALL_BREAKPOINTS (b)
8709   {
8710     if (is_watchpoint (b) && breakpoint_enabled (b))
8711       {
8712         b->enable_state = bp_call_disabled;
8713         update_global_location_list (UGLL_DONT_INSERT);
8714       }
8715   }
8716 }
8717
8718 void
8719 enable_watchpoints_after_interactive_call_stop (void)
8720 {
8721   struct breakpoint *b;
8722
8723   ALL_BREAKPOINTS (b)
8724   {
8725     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8726       {
8727         b->enable_state = bp_enabled;
8728         update_global_location_list (UGLL_MAY_INSERT);
8729       }
8730   }
8731 }
8732
8733 void
8734 disable_breakpoints_before_startup (void)
8735 {
8736   current_program_space->executing_startup = 1;
8737   update_global_location_list (UGLL_DONT_INSERT);
8738 }
8739
8740 void
8741 enable_breakpoints_after_startup (void)
8742 {
8743   current_program_space->executing_startup = 0;
8744   breakpoint_re_set ();
8745 }
8746
8747 /* Create a new single-step breakpoint for thread THREAD, with no
8748    locations.  */
8749
8750 static struct breakpoint *
8751 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8752 {
8753   struct breakpoint *b = XNEW (struct breakpoint);
8754
8755   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
8756                                         &momentary_breakpoint_ops);
8757
8758   b->disposition = disp_donttouch;
8759   b->frame_id = null_frame_id;
8760
8761   b->thread = thread;
8762   gdb_assert (b->thread != 0);
8763
8764   add_to_breakpoint_chain (b);
8765
8766   return b;
8767 }
8768
8769 /* Set a momentary breakpoint of type TYPE at address specified by
8770    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8771    frame.  */
8772
8773 struct breakpoint *
8774 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8775                           struct frame_id frame_id, enum bptype type)
8776 {
8777   struct breakpoint *b;
8778
8779   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8780      tail-called one.  */
8781   gdb_assert (!frame_id_artificial_p (frame_id));
8782
8783   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8784   b->enable_state = bp_enabled;
8785   b->disposition = disp_donttouch;
8786   b->frame_id = frame_id;
8787
8788   /* If we're debugging a multi-threaded program, then we want
8789      momentary breakpoints to be active in only a single thread of
8790      control.  */
8791   if (in_thread_list (inferior_ptid))
8792     b->thread = pid_to_thread_id (inferior_ptid);
8793
8794   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8795
8796   return b;
8797 }
8798
8799 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8800    The new breakpoint will have type TYPE, use OPS as its
8801    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8802
8803 static struct breakpoint *
8804 momentary_breakpoint_from_master (struct breakpoint *orig,
8805                                   enum bptype type,
8806                                   const struct breakpoint_ops *ops,
8807                                   int loc_enabled)
8808 {
8809   struct breakpoint *copy;
8810
8811   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8812   copy->loc = allocate_bp_location (copy);
8813   set_breakpoint_location_function (copy->loc, 1);
8814
8815   copy->loc->gdbarch = orig->loc->gdbarch;
8816   copy->loc->requested_address = orig->loc->requested_address;
8817   copy->loc->address = orig->loc->address;
8818   copy->loc->section = orig->loc->section;
8819   copy->loc->pspace = orig->loc->pspace;
8820   copy->loc->probe = orig->loc->probe;
8821   copy->loc->line_number = orig->loc->line_number;
8822   copy->loc->symtab = orig->loc->symtab;
8823   copy->loc->enabled = loc_enabled;
8824   copy->frame_id = orig->frame_id;
8825   copy->thread = orig->thread;
8826   copy->pspace = orig->pspace;
8827
8828   copy->enable_state = bp_enabled;
8829   copy->disposition = disp_donttouch;
8830   copy->number = internal_breakpoint_number--;
8831
8832   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8833   return copy;
8834 }
8835
8836 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8837    ORIG is NULL.  */
8838
8839 struct breakpoint *
8840 clone_momentary_breakpoint (struct breakpoint *orig)
8841 {
8842   /* If there's nothing to clone, then return nothing.  */
8843   if (orig == NULL)
8844     return NULL;
8845
8846   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8847 }
8848
8849 struct breakpoint *
8850 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8851                                 enum bptype type)
8852 {
8853   struct symtab_and_line sal;
8854
8855   sal = find_pc_line (pc, 0);
8856   sal.pc = pc;
8857   sal.section = find_pc_overlay (pc);
8858   sal.explicit_pc = 1;
8859
8860   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8861 }
8862 \f
8863
8864 /* Tell the user we have just set a breakpoint B.  */
8865
8866 static void
8867 mention (struct breakpoint *b)
8868 {
8869   b->ops->print_mention (b);
8870   if (ui_out_is_mi_like_p (current_uiout))
8871     return;
8872   printf_filtered ("\n");
8873 }
8874 \f
8875
8876 static int bp_loc_is_permanent (struct bp_location *loc);
8877
8878 static struct bp_location *
8879 add_location_to_breakpoint (struct breakpoint *b,
8880                             const struct symtab_and_line *sal)
8881 {
8882   struct bp_location *loc, **tmp;
8883   CORE_ADDR adjusted_address;
8884   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8885
8886   if (loc_gdbarch == NULL)
8887     loc_gdbarch = b->gdbarch;
8888
8889   /* Adjust the breakpoint's address prior to allocating a location.
8890      Once we call allocate_bp_location(), that mostly uninitialized
8891      location will be placed on the location chain.  Adjustment of the
8892      breakpoint may cause target_read_memory() to be called and we do
8893      not want its scan of the location chain to find a breakpoint and
8894      location that's only been partially initialized.  */
8895   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8896                                                 sal->pc, b->type);
8897
8898   /* Sort the locations by their ADDRESS.  */
8899   loc = allocate_bp_location (b);
8900   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8901        tmp = &((*tmp)->next))
8902     ;
8903   loc->next = *tmp;
8904   *tmp = loc;
8905
8906   loc->requested_address = sal->pc;
8907   loc->address = adjusted_address;
8908   loc->pspace = sal->pspace;
8909   loc->probe.probe = sal->probe;
8910   loc->probe.objfile = sal->objfile;
8911   gdb_assert (loc->pspace != NULL);
8912   loc->section = sal->section;
8913   loc->gdbarch = loc_gdbarch;
8914   loc->line_number = sal->line;
8915   loc->symtab = sal->symtab;
8916
8917   set_breakpoint_location_function (loc,
8918                                     sal->explicit_pc || sal->explicit_line);
8919
8920   if (bp_loc_is_permanent (loc))
8921     {
8922       loc->inserted = 1;
8923       loc->permanent = 1;
8924     }
8925
8926   return loc;
8927 }
8928 \f
8929
8930 /* See breakpoint.h.  */
8931
8932 int
8933 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8934 {
8935   int len;
8936   CORE_ADDR addr;
8937   const gdb_byte *bpoint;
8938   gdb_byte *target_mem;
8939   struct cleanup *cleanup;
8940   int retval = 0;
8941
8942   addr = address;
8943   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8944
8945   /* Software breakpoints unsupported?  */
8946   if (bpoint == NULL)
8947     return 0;
8948
8949   target_mem = alloca (len);
8950
8951   /* Enable the automatic memory restoration from breakpoints while
8952      we read the memory.  Otherwise we could say about our temporary
8953      breakpoints they are permanent.  */
8954   cleanup = make_show_memory_breakpoints_cleanup (0);
8955
8956   if (target_read_memory (address, target_mem, len) == 0
8957       && memcmp (target_mem, bpoint, len) == 0)
8958     retval = 1;
8959
8960   do_cleanups (cleanup);
8961
8962   return retval;
8963 }
8964
8965 /* Return 1 if LOC is pointing to a permanent breakpoint,
8966    return 0 otherwise.  */
8967
8968 static int
8969 bp_loc_is_permanent (struct bp_location *loc)
8970 {
8971   struct cleanup *cleanup;
8972   int retval;
8973
8974   gdb_assert (loc != NULL);
8975
8976   /* bp_call_dummy breakpoint locations are usually memory locations
8977      where GDB just wrote a breakpoint instruction, making it look
8978      as if there is a permanent breakpoint at that location.  Considering
8979      it permanent makes GDB rely on that breakpoint instruction to stop
8980      the program, thus removing the need to insert its own breakpoint
8981      there.  This is normally expected to work, except that some versions
8982      of QEMU (Eg: QEMU 2.0.0 for SPARC) just report a fatal problem (Trap
8983      0x02 while interrupts disabled, Error state) instead of reporting
8984      a SIGTRAP.  QEMU should probably be fixed, but in the interest of
8985      compatibility with versions that behave this way, we always consider
8986      bp_call_dummy breakpoint locations as non-permanent.  */
8987   if (loc->owner->type == bp_call_dummy)
8988     return 0;
8989
8990   cleanup = save_current_space_and_thread ();
8991   switch_to_program_space_and_thread (loc->pspace);
8992
8993   retval = program_breakpoint_here_p (loc->gdbarch, loc->address);
8994
8995   do_cleanups (cleanup);
8996
8997   return retval;
8998 }
8999
9000 /* Build a command list for the dprintf corresponding to the current
9001    settings of the dprintf style options.  */
9002
9003 static void
9004 update_dprintf_command_list (struct breakpoint *b)
9005 {
9006   char *dprintf_args = b->extra_string;
9007   char *printf_line = NULL;
9008
9009   if (!dprintf_args)
9010     return;
9011
9012   dprintf_args = skip_spaces (dprintf_args);
9013
9014   /* Allow a comma, as it may have terminated a location, but don't
9015      insist on it.  */
9016   if (*dprintf_args == ',')
9017     ++dprintf_args;
9018   dprintf_args = skip_spaces (dprintf_args);
9019
9020   if (*dprintf_args != '"')
9021     error (_("Bad format string, missing '\"'."));
9022
9023   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9024     printf_line = xstrprintf ("printf %s", dprintf_args);
9025   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9026     {
9027       if (!dprintf_function)
9028         error (_("No function supplied for dprintf call"));
9029
9030       if (dprintf_channel && strlen (dprintf_channel) > 0)
9031         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9032                                   dprintf_function,
9033                                   dprintf_channel,
9034                                   dprintf_args);
9035       else
9036         printf_line = xstrprintf ("call (void) %s (%s)",
9037                                   dprintf_function,
9038                                   dprintf_args);
9039     }
9040   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9041     {
9042       if (target_can_run_breakpoint_commands ())
9043         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9044       else
9045         {
9046           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9047           printf_line = xstrprintf ("printf %s", dprintf_args);
9048         }
9049     }
9050   else
9051     internal_error (__FILE__, __LINE__,
9052                     _("Invalid dprintf style."));
9053
9054   gdb_assert (printf_line != NULL);
9055   /* Manufacture a printf sequence.  */
9056   {
9057     struct command_line *printf_cmd_line
9058       = xmalloc (sizeof (struct command_line));
9059
9060     printf_cmd_line->control_type = simple_control;
9061     printf_cmd_line->body_count = 0;
9062     printf_cmd_line->body_list = NULL;
9063     printf_cmd_line->next = NULL;
9064     printf_cmd_line->line = printf_line;
9065
9066     breakpoint_set_commands (b, printf_cmd_line);
9067   }
9068 }
9069
9070 /* Update all dprintf commands, making their command lists reflect
9071    current style settings.  */
9072
9073 static void
9074 update_dprintf_commands (char *args, int from_tty,
9075                          struct cmd_list_element *c)
9076 {
9077   struct breakpoint *b;
9078
9079   ALL_BREAKPOINTS (b)
9080     {
9081       if (b->type == bp_dprintf)
9082         update_dprintf_command_list (b);
9083     }
9084 }
9085
9086 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9087    as textual description of the location, and COND_STRING
9088    as condition expression.  */
9089
9090 static void
9091 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9092                      struct symtabs_and_lines sals, char *addr_string,
9093                      char *filter, char *cond_string,
9094                      char *extra_string,
9095                      enum bptype type, enum bpdisp disposition,
9096                      int thread, int task, int ignore_count,
9097                      const struct breakpoint_ops *ops, int from_tty,
9098                      int enabled, int internal, unsigned flags,
9099                      int display_canonical)
9100 {
9101   int i;
9102
9103   if (type == bp_hardware_breakpoint)
9104     {
9105       int target_resources_ok;
9106
9107       i = hw_breakpoint_used_count ();
9108       target_resources_ok =
9109         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9110                                             i + 1, 0);
9111       if (target_resources_ok == 0)
9112         error (_("No hardware breakpoint support in the target."));
9113       else if (target_resources_ok < 0)
9114         error (_("Hardware breakpoints used exceeds limit."));
9115     }
9116
9117   gdb_assert (sals.nelts > 0);
9118
9119   for (i = 0; i < sals.nelts; ++i)
9120     {
9121       struct symtab_and_line sal = sals.sals[i];
9122       struct bp_location *loc;
9123
9124       if (from_tty)
9125         {
9126           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9127           if (!loc_gdbarch)
9128             loc_gdbarch = gdbarch;
9129
9130           describe_other_breakpoints (loc_gdbarch,
9131                                       sal.pspace, sal.pc, sal.section, thread);
9132         }
9133
9134       if (i == 0)
9135         {
9136           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9137           b->thread = thread;
9138           b->task = task;
9139
9140           b->cond_string = cond_string;
9141           b->extra_string = extra_string;
9142           b->ignore_count = ignore_count;
9143           b->enable_state = enabled ? bp_enabled : bp_disabled;
9144           b->disposition = disposition;
9145
9146           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9147             b->loc->inserted = 1;
9148
9149           if (type == bp_static_tracepoint)
9150             {
9151               struct tracepoint *t = (struct tracepoint *) b;
9152               struct static_tracepoint_marker marker;
9153
9154               if (strace_marker_p (b))
9155                 {
9156                   /* We already know the marker exists, otherwise, we
9157                      wouldn't see a sal for it.  */
9158                   char *p = &addr_string[3];
9159                   char *endp;
9160                   char *marker_str;
9161
9162                   p = skip_spaces (p);
9163
9164                   endp = skip_to_space (p);
9165
9166                   marker_str = savestring (p, endp - p);
9167                   t->static_trace_marker_id = marker_str;
9168
9169                   printf_filtered (_("Probed static tracepoint "
9170                                      "marker \"%s\"\n"),
9171                                    t->static_trace_marker_id);
9172                 }
9173               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9174                 {
9175                   t->static_trace_marker_id = xstrdup (marker.str_id);
9176                   release_static_tracepoint_marker (&marker);
9177
9178                   printf_filtered (_("Probed static tracepoint "
9179                                      "marker \"%s\"\n"),
9180                                    t->static_trace_marker_id);
9181                 }
9182               else
9183                 warning (_("Couldn't determine the static "
9184                            "tracepoint marker to probe"));
9185             }
9186
9187           loc = b->loc;
9188         }
9189       else
9190         {
9191           loc = add_location_to_breakpoint (b, &sal);
9192           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9193             loc->inserted = 1;
9194         }
9195
9196       if (b->cond_string)
9197         {
9198           const char *arg = b->cond_string;
9199
9200           loc->cond = parse_exp_1 (&arg, loc->address,
9201                                    block_for_pc (loc->address), 0);
9202           if (*arg)
9203               error (_("Garbage '%s' follows condition"), arg);
9204         }
9205
9206       /* Dynamic printf requires and uses additional arguments on the
9207          command line, otherwise it's an error.  */
9208       if (type == bp_dprintf)
9209         {
9210           if (b->extra_string)
9211             update_dprintf_command_list (b);
9212           else
9213             error (_("Format string required"));
9214         }
9215       else if (b->extra_string)
9216         error (_("Garbage '%s' at end of command"), b->extra_string);
9217     }
9218
9219   b->display_canonical = display_canonical;
9220   if (addr_string)
9221     b->addr_string = addr_string;
9222   else
9223     /* addr_string has to be used or breakpoint_re_set will delete
9224        me.  */
9225     b->addr_string
9226       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9227   b->filter = filter;
9228 }
9229
9230 static void
9231 create_breakpoint_sal (struct gdbarch *gdbarch,
9232                        struct symtabs_and_lines sals, char *addr_string,
9233                        char *filter, char *cond_string,
9234                        char *extra_string,
9235                        enum bptype type, enum bpdisp disposition,
9236                        int thread, int task, int ignore_count,
9237                        const struct breakpoint_ops *ops, int from_tty,
9238                        int enabled, int internal, unsigned flags,
9239                        int display_canonical)
9240 {
9241   struct breakpoint *b;
9242   struct cleanup *old_chain;
9243
9244   if (is_tracepoint_type (type))
9245     {
9246       struct tracepoint *t;
9247
9248       t = XCNEW (struct tracepoint);
9249       b = &t->base;
9250     }
9251   else
9252     b = XNEW (struct breakpoint);
9253
9254   old_chain = make_cleanup (xfree, b);
9255
9256   init_breakpoint_sal (b, gdbarch,
9257                        sals, addr_string,
9258                        filter, cond_string, extra_string,
9259                        type, disposition,
9260                        thread, task, ignore_count,
9261                        ops, from_tty,
9262                        enabled, internal, flags,
9263                        display_canonical);
9264   discard_cleanups (old_chain);
9265
9266   install_breakpoint (internal, b, 0);
9267 }
9268
9269 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9270    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9271    value.  COND_STRING, if not NULL, specified the condition to be
9272    used for all breakpoints.  Essentially the only case where
9273    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9274    function.  In that case, it's still not possible to specify
9275    separate conditions for different overloaded functions, so
9276    we take just a single condition string.
9277    
9278    NOTE: If the function succeeds, the caller is expected to cleanup
9279    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9280    array contents).  If the function fails (error() is called), the
9281    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9282    COND and SALS arrays and each of those arrays contents.  */
9283
9284 static void
9285 create_breakpoints_sal (struct gdbarch *gdbarch,
9286                         struct linespec_result *canonical,
9287                         char *cond_string, char *extra_string,
9288                         enum bptype type, enum bpdisp disposition,
9289                         int thread, int task, int ignore_count,
9290                         const struct breakpoint_ops *ops, int from_tty,
9291                         int enabled, int internal, unsigned flags)
9292 {
9293   int i;
9294   struct linespec_sals *lsal;
9295
9296   if (canonical->pre_expanded)
9297     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9298
9299   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9300     {
9301       /* Note that 'addr_string' can be NULL in the case of a plain
9302          'break', without arguments.  */
9303       char *addr_string = (canonical->addr_string
9304                            ? xstrdup (canonical->addr_string)
9305                            : NULL);
9306       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9307       struct cleanup *inner = make_cleanup (xfree, addr_string);
9308
9309       make_cleanup (xfree, filter_string);
9310       create_breakpoint_sal (gdbarch, lsal->sals,
9311                              addr_string,
9312                              filter_string,
9313                              cond_string, extra_string,
9314                              type, disposition,
9315                              thread, task, ignore_count, ops,
9316                              from_tty, enabled, internal, flags,
9317                              canonical->special_display);
9318       discard_cleanups (inner);
9319     }
9320 }
9321
9322 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9323    followed by conditionals.  On return, SALS contains an array of SAL
9324    addresses found.  ADDR_STRING contains a vector of (canonical)
9325    address strings.  ADDRESS points to the end of the SAL.
9326
9327    The array and the line spec strings are allocated on the heap, it is
9328    the caller's responsibility to free them.  */
9329
9330 static void
9331 parse_breakpoint_sals (char **address,
9332                        struct linespec_result *canonical)
9333 {
9334   /* If no arg given, or if first arg is 'if ', use the default
9335      breakpoint.  */
9336   if ((*address) == NULL || linespec_lexer_lex_keyword (*address))
9337     {
9338       /* The last displayed codepoint, if it's valid, is our default breakpoint
9339          address.  */
9340       if (last_displayed_sal_is_valid ())
9341         {
9342           struct linespec_sals lsal;
9343           struct symtab_and_line sal;
9344           CORE_ADDR pc;
9345
9346           init_sal (&sal);              /* Initialize to zeroes.  */
9347           lsal.sals.sals = (struct symtab_and_line *)
9348             xmalloc (sizeof (struct symtab_and_line));
9349
9350           /* Set sal's pspace, pc, symtab, and line to the values
9351              corresponding to the last call to print_frame_info.
9352              Be sure to reinitialize LINE with NOTCURRENT == 0
9353              as the breakpoint line number is inappropriate otherwise.
9354              find_pc_line would adjust PC, re-set it back.  */
9355           get_last_displayed_sal (&sal);
9356           pc = sal.pc;
9357           sal = find_pc_line (pc, 0);
9358
9359           /* "break" without arguments is equivalent to "break *PC"
9360              where PC is the last displayed codepoint's address.  So
9361              make sure to set sal.explicit_pc to prevent GDB from
9362              trying to expand the list of sals to include all other
9363              instances with the same symtab and line.  */
9364           sal.pc = pc;
9365           sal.explicit_pc = 1;
9366
9367           lsal.sals.sals[0] = sal;
9368           lsal.sals.nelts = 1;
9369           lsal.canonical = NULL;
9370
9371           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9372         }
9373       else
9374         error (_("No default breakpoint address now."));
9375     }
9376   else
9377     {
9378       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9379
9380       /* Force almost all breakpoints to be in terms of the
9381          current_source_symtab (which is decode_line_1's default).
9382          This should produce the results we want almost all of the
9383          time while leaving default_breakpoint_* alone.
9384
9385          ObjC: However, don't match an Objective-C method name which
9386          may have a '+' or '-' succeeded by a '['.  */
9387       if (last_displayed_sal_is_valid ()
9388           && (!cursal.symtab
9389               || ((strchr ("+-", (*address)[0]) != NULL)
9390                   && ((*address)[1] != '['))))
9391         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9392                           get_last_displayed_symtab (),
9393                           get_last_displayed_line (),
9394                           canonical, NULL, NULL);
9395       else
9396         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9397                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9398     }
9399 }
9400
9401
9402 /* Convert each SAL into a real PC.  Verify that the PC can be
9403    inserted as a breakpoint.  If it can't throw an error.  */
9404
9405 static void
9406 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9407 {    
9408   int i;
9409
9410   for (i = 0; i < sals->nelts; i++)
9411     resolve_sal_pc (&sals->sals[i]);
9412 }
9413
9414 /* Fast tracepoints may have restrictions on valid locations.  For
9415    instance, a fast tracepoint using a jump instead of a trap will
9416    likely have to overwrite more bytes than a trap would, and so can
9417    only be placed where the instruction is longer than the jump, or a
9418    multi-instruction sequence does not have a jump into the middle of
9419    it, etc.  */
9420
9421 static void
9422 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9423                             struct symtabs_and_lines *sals)
9424 {
9425   int i, rslt;
9426   struct symtab_and_line *sal;
9427   char *msg;
9428   struct cleanup *old_chain;
9429
9430   for (i = 0; i < sals->nelts; i++)
9431     {
9432       struct gdbarch *sarch;
9433
9434       sal = &sals->sals[i];
9435
9436       sarch = get_sal_arch (*sal);
9437       /* We fall back to GDBARCH if there is no architecture
9438          associated with SAL.  */
9439       if (sarch == NULL)
9440         sarch = gdbarch;
9441       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9442                                                NULL, &msg);
9443       old_chain = make_cleanup (xfree, msg);
9444
9445       if (!rslt)
9446         error (_("May not have a fast tracepoint at 0x%s%s"),
9447                paddress (sarch, sal->pc), (msg ? msg : ""));
9448
9449       do_cleanups (old_chain);
9450     }
9451 }
9452
9453 /* Issue an invalid thread ID error.  */
9454
9455 static void ATTRIBUTE_NORETURN
9456 invalid_thread_id_error (int id)
9457 {
9458   error (_("Unknown thread %d."), id);
9459 }
9460
9461 /* Given TOK, a string specification of condition and thread, as
9462    accepted by the 'break' command, extract the condition
9463    string and thread number and set *COND_STRING and *THREAD.
9464    PC identifies the context at which the condition should be parsed.
9465    If no condition is found, *COND_STRING is set to NULL.
9466    If no thread is found, *THREAD is set to -1.  */
9467
9468 static void
9469 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9470                            char **cond_string, int *thread, int *task,
9471                            char **rest)
9472 {
9473   *cond_string = NULL;
9474   *thread = -1;
9475   *task = 0;
9476   *rest = NULL;
9477
9478   while (tok && *tok)
9479     {
9480       const char *end_tok;
9481       int toklen;
9482       const char *cond_start = NULL;
9483       const char *cond_end = NULL;
9484
9485       tok = skip_spaces_const (tok);
9486
9487       if ((*tok == '"' || *tok == ',') && rest)
9488         {
9489           *rest = savestring (tok, strlen (tok));
9490           return;
9491         }
9492
9493       end_tok = skip_to_space_const (tok);
9494
9495       toklen = end_tok - tok;
9496
9497       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9498         {
9499           struct expression *expr;
9500
9501           tok = cond_start = end_tok + 1;
9502           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9503           xfree (expr);
9504           cond_end = tok;
9505           *cond_string = savestring (cond_start, cond_end - cond_start);
9506         }
9507       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9508         {
9509           char *tmptok;
9510
9511           tok = end_tok + 1;
9512           *thread = strtol (tok, &tmptok, 0);
9513           if (tok == tmptok)
9514             error (_("Junk after thread keyword."));
9515           if (!valid_thread_id (*thread))
9516             invalid_thread_id_error (*thread);
9517           tok = tmptok;
9518         }
9519       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9520         {
9521           char *tmptok;
9522
9523           tok = end_tok + 1;
9524           *task = strtol (tok, &tmptok, 0);
9525           if (tok == tmptok)
9526             error (_("Junk after task keyword."));
9527           if (!valid_task_id (*task))
9528             error (_("Unknown task %d."), *task);
9529           tok = tmptok;
9530         }
9531       else if (rest)
9532         {
9533           *rest = savestring (tok, strlen (tok));
9534           return;
9535         }
9536       else
9537         error (_("Junk at end of arguments."));
9538     }
9539 }
9540
9541 /* Decode a static tracepoint marker spec.  */
9542
9543 static struct symtabs_and_lines
9544 decode_static_tracepoint_spec (char **arg_p)
9545 {
9546   VEC(static_tracepoint_marker_p) *markers = NULL;
9547   struct symtabs_and_lines sals;
9548   struct cleanup *old_chain;
9549   char *p = &(*arg_p)[3];
9550   char *endp;
9551   char *marker_str;
9552   int i;
9553
9554   p = skip_spaces (p);
9555
9556   endp = skip_to_space (p);
9557
9558   marker_str = savestring (p, endp - p);
9559   old_chain = make_cleanup (xfree, marker_str);
9560
9561   markers = target_static_tracepoint_markers_by_strid (marker_str);
9562   if (VEC_empty(static_tracepoint_marker_p, markers))
9563     error (_("No known static tracepoint marker named %s"), marker_str);
9564
9565   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9566   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9567
9568   for (i = 0; i < sals.nelts; i++)
9569     {
9570       struct static_tracepoint_marker *marker;
9571
9572       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9573
9574       init_sal (&sals.sals[i]);
9575
9576       sals.sals[i] = find_pc_line (marker->address, 0);
9577       sals.sals[i].pc = marker->address;
9578
9579       release_static_tracepoint_marker (marker);
9580     }
9581
9582   do_cleanups (old_chain);
9583
9584   *arg_p = endp;
9585   return sals;
9586 }
9587
9588 /* Set a breakpoint.  This function is shared between CLI and MI
9589    functions for setting a breakpoint.  This function has two major
9590    modes of operations, selected by the PARSE_ARG parameter.  If
9591    non-zero, the function will parse ARG, extracting location,
9592    condition, thread and extra string.  Otherwise, ARG is just the
9593    breakpoint's location, with condition, thread, and extra string
9594    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9595    If INTERNAL is non-zero, the breakpoint number will be allocated
9596    from the internal breakpoint count.  Returns true if any breakpoint
9597    was created; false otherwise.  */
9598
9599 int
9600 create_breakpoint (struct gdbarch *gdbarch,
9601                    char *arg, char *cond_string,
9602                    int thread, char *extra_string,
9603                    int parse_arg,
9604                    int tempflag, enum bptype type_wanted,
9605                    int ignore_count,
9606                    enum auto_boolean pending_break_support,
9607                    const struct breakpoint_ops *ops,
9608                    int from_tty, int enabled, int internal,
9609                    unsigned flags)
9610 {
9611   char *copy_arg = NULL;
9612   char *addr_start = arg;
9613   struct linespec_result canonical;
9614   struct cleanup *old_chain;
9615   struct cleanup *bkpt_chain = NULL;
9616   int pending = 0;
9617   int task = 0;
9618   int prev_bkpt_count = breakpoint_count;
9619
9620   gdb_assert (ops != NULL);
9621
9622   init_linespec_result (&canonical);
9623
9624   TRY
9625     {
9626       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9627                                      addr_start, &copy_arg);
9628     }
9629   CATCH (e, RETURN_MASK_ERROR)
9630     {
9631       /* If caller is interested in rc value from parse, set
9632          value.  */
9633       if (e.error == NOT_FOUND_ERROR)
9634         {
9635           /* If pending breakpoint support is turned off, throw
9636              error.  */
9637
9638           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9639             throw_exception (e);
9640
9641           exception_print (gdb_stderr, e);
9642
9643           /* If pending breakpoint support is auto query and the user
9644              selects no, then simply return the error code.  */
9645           if (pending_break_support == AUTO_BOOLEAN_AUTO
9646               && !nquery (_("Make %s pending on future shared library load? "),
9647                           bptype_string (type_wanted)))
9648             return 0;
9649
9650           /* At this point, either the user was queried about setting
9651              a pending breakpoint and selected yes, or pending
9652              breakpoint behavior is on and thus a pending breakpoint
9653              is defaulted on behalf of the user.  */
9654           {
9655             struct linespec_sals lsal;
9656
9657             copy_arg = xstrdup (addr_start);
9658             lsal.canonical = xstrdup (copy_arg);
9659             lsal.sals.nelts = 1;
9660             lsal.sals.sals = XNEW (struct symtab_and_line);
9661             init_sal (&lsal.sals.sals[0]);
9662             pending = 1;
9663             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9664           }
9665         }
9666       else
9667         throw_exception (e);
9668     }
9669   END_CATCH
9670
9671   if (VEC_empty (linespec_sals, canonical.sals))
9672     return 0;
9673
9674   /* Create a chain of things that always need to be cleaned up.  */
9675   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9676
9677   /* ----------------------------- SNIP -----------------------------
9678      Anything added to the cleanup chain beyond this point is assumed
9679      to be part of a breakpoint.  If the breakpoint create succeeds
9680      then the memory is not reclaimed.  */
9681   bkpt_chain = make_cleanup (null_cleanup, 0);
9682
9683   /* Resolve all line numbers to PC's and verify that the addresses
9684      are ok for the target.  */
9685   if (!pending)
9686     {
9687       int ix;
9688       struct linespec_sals *iter;
9689
9690       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9691         breakpoint_sals_to_pc (&iter->sals);
9692     }
9693
9694   /* Fast tracepoints may have additional restrictions on location.  */
9695   if (!pending && type_wanted == bp_fast_tracepoint)
9696     {
9697       int ix;
9698       struct linespec_sals *iter;
9699
9700       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9701         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9702     }
9703
9704   /* Verify that condition can be parsed, before setting any
9705      breakpoints.  Allocate a separate condition expression for each
9706      breakpoint.  */
9707   if (!pending)
9708     {
9709       if (parse_arg)
9710         {
9711           char *rest;
9712           struct linespec_sals *lsal;
9713
9714           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9715
9716           /* Here we only parse 'arg' to separate condition
9717              from thread number, so parsing in context of first
9718              sal is OK.  When setting the breakpoint we'll
9719              re-parse it in context of each sal.  */
9720
9721           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9722                                      &thread, &task, &rest);
9723           if (cond_string)
9724             make_cleanup (xfree, cond_string);
9725           if (rest)
9726             make_cleanup (xfree, rest);
9727           if (rest)
9728             extra_string = rest;
9729         }
9730       else
9731         {
9732           if (*arg != '\0')
9733             error (_("Garbage '%s' at end of location"), arg);
9734
9735           /* Create a private copy of condition string.  */
9736           if (cond_string)
9737             {
9738               cond_string = xstrdup (cond_string);
9739               make_cleanup (xfree, cond_string);
9740             }
9741           /* Create a private copy of any extra string.  */
9742           if (extra_string)
9743             {
9744               extra_string = xstrdup (extra_string);
9745               make_cleanup (xfree, extra_string);
9746             }
9747         }
9748
9749       ops->create_breakpoints_sal (gdbarch, &canonical,
9750                                    cond_string, extra_string, type_wanted,
9751                                    tempflag ? disp_del : disp_donttouch,
9752                                    thread, task, ignore_count, ops,
9753                                    from_tty, enabled, internal, flags);
9754     }
9755   else
9756     {
9757       struct breakpoint *b;
9758
9759       make_cleanup (xfree, copy_arg);
9760
9761       if (is_tracepoint_type (type_wanted))
9762         {
9763           struct tracepoint *t;
9764
9765           t = XCNEW (struct tracepoint);
9766           b = &t->base;
9767         }
9768       else
9769         b = XNEW (struct breakpoint);
9770
9771       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9772
9773       b->addr_string = copy_arg;
9774       if (parse_arg)
9775         b->cond_string = NULL;
9776       else
9777         {
9778           /* Create a private copy of condition string.  */
9779           if (cond_string)
9780             {
9781               cond_string = xstrdup (cond_string);
9782               make_cleanup (xfree, cond_string);
9783             }
9784           b->cond_string = cond_string;
9785           b->thread = thread;
9786         }
9787       b->extra_string = NULL;
9788       b->ignore_count = ignore_count;
9789       b->disposition = tempflag ? disp_del : disp_donttouch;
9790       b->condition_not_parsed = 1;
9791       b->enable_state = enabled ? bp_enabled : bp_disabled;
9792       if ((type_wanted != bp_breakpoint
9793            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9794         b->pspace = current_program_space;
9795
9796       install_breakpoint (internal, b, 0);
9797     }
9798   
9799   if (VEC_length (linespec_sals, canonical.sals) > 1)
9800     {
9801       warning (_("Multiple breakpoints were set.\nUse the "
9802                  "\"delete\" command to delete unwanted breakpoints."));
9803       prev_breakpoint_count = prev_bkpt_count;
9804     }
9805
9806   /* That's it.  Discard the cleanups for data inserted into the
9807      breakpoint.  */
9808   discard_cleanups (bkpt_chain);
9809   /* But cleanup everything else.  */
9810   do_cleanups (old_chain);
9811
9812   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9813   update_global_location_list (UGLL_MAY_INSERT);
9814
9815   return 1;
9816 }
9817
9818 /* Set a breakpoint.
9819    ARG is a string describing breakpoint address,
9820    condition, and thread.
9821    FLAG specifies if a breakpoint is hardware on,
9822    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9823    and BP_TEMPFLAG.  */
9824
9825 static void
9826 break_command_1 (char *arg, int flag, int from_tty)
9827 {
9828   int tempflag = flag & BP_TEMPFLAG;
9829   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9830                              ? bp_hardware_breakpoint
9831                              : bp_breakpoint);
9832   struct breakpoint_ops *ops;
9833   const char *arg_cp = arg;
9834
9835   /* Matching breakpoints on probes.  */
9836   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9837     ops = &bkpt_probe_breakpoint_ops;
9838   else
9839     ops = &bkpt_breakpoint_ops;
9840
9841   create_breakpoint (get_current_arch (),
9842                      arg,
9843                      NULL, 0, NULL, 1 /* parse arg */,
9844                      tempflag, type_wanted,
9845                      0 /* Ignore count */,
9846                      pending_break_support,
9847                      ops,
9848                      from_tty,
9849                      1 /* enabled */,
9850                      0 /* internal */,
9851                      0);
9852 }
9853
9854 /* Helper function for break_command_1 and disassemble_command.  */
9855
9856 void
9857 resolve_sal_pc (struct symtab_and_line *sal)
9858 {
9859   CORE_ADDR pc;
9860
9861   if (sal->pc == 0 && sal->symtab != NULL)
9862     {
9863       if (!find_line_pc (sal->symtab, sal->line, &pc))
9864         error (_("No line %d in file \"%s\"."),
9865                sal->line, symtab_to_filename_for_display (sal->symtab));
9866       sal->pc = pc;
9867
9868       /* If this SAL corresponds to a breakpoint inserted using a line
9869          number, then skip the function prologue if necessary.  */
9870       if (sal->explicit_line)
9871         skip_prologue_sal (sal);
9872     }
9873
9874   if (sal->section == 0 && sal->symtab != NULL)
9875     {
9876       const struct blockvector *bv;
9877       const struct block *b;
9878       struct symbol *sym;
9879
9880       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9881                                     SYMTAB_COMPUNIT (sal->symtab));
9882       if (bv != NULL)
9883         {
9884           sym = block_linkage_function (b);
9885           if (sym != NULL)
9886             {
9887               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9888               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9889                                                  sym);
9890             }
9891           else
9892             {
9893               /* It really is worthwhile to have the section, so we'll
9894                  just have to look harder. This case can be executed
9895                  if we have line numbers but no functions (as can
9896                  happen in assembly source).  */
9897
9898               struct bound_minimal_symbol msym;
9899               struct cleanup *old_chain = save_current_space_and_thread ();
9900
9901               switch_to_program_space_and_thread (sal->pspace);
9902
9903               msym = lookup_minimal_symbol_by_pc (sal->pc);
9904               if (msym.minsym)
9905                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9906
9907               do_cleanups (old_chain);
9908             }
9909         }
9910     }
9911 }
9912
9913 void
9914 break_command (char *arg, int from_tty)
9915 {
9916   break_command_1 (arg, 0, from_tty);
9917 }
9918
9919 void
9920 tbreak_command (char *arg, int from_tty)
9921 {
9922   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9923 }
9924
9925 static void
9926 hbreak_command (char *arg, int from_tty)
9927 {
9928   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9929 }
9930
9931 static void
9932 thbreak_command (char *arg, int from_tty)
9933 {
9934   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9935 }
9936
9937 static void
9938 stop_command (char *arg, int from_tty)
9939 {
9940   printf_filtered (_("Specify the type of breakpoint to set.\n\
9941 Usage: stop in <function | address>\n\
9942        stop at <line>\n"));
9943 }
9944
9945 static void
9946 stopin_command (char *arg, int from_tty)
9947 {
9948   int badInput = 0;
9949
9950   if (arg == (char *) NULL)
9951     badInput = 1;
9952   else if (*arg != '*')
9953     {
9954       char *argptr = arg;
9955       int hasColon = 0;
9956
9957       /* Look for a ':'.  If this is a line number specification, then
9958          say it is bad, otherwise, it should be an address or
9959          function/method name.  */
9960       while (*argptr && !hasColon)
9961         {
9962           hasColon = (*argptr == ':');
9963           argptr++;
9964         }
9965
9966       if (hasColon)
9967         badInput = (*argptr != ':');    /* Not a class::method */
9968       else
9969         badInput = isdigit (*arg);      /* a simple line number */
9970     }
9971
9972   if (badInput)
9973     printf_filtered (_("Usage: stop in <function | address>\n"));
9974   else
9975     break_command_1 (arg, 0, from_tty);
9976 }
9977
9978 static void
9979 stopat_command (char *arg, int from_tty)
9980 {
9981   int badInput = 0;
9982
9983   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9984     badInput = 1;
9985   else
9986     {
9987       char *argptr = arg;
9988       int hasColon = 0;
9989
9990       /* Look for a ':'.  If there is a '::' then get out, otherwise
9991          it is probably a line number.  */
9992       while (*argptr && !hasColon)
9993         {
9994           hasColon = (*argptr == ':');
9995           argptr++;
9996         }
9997
9998       if (hasColon)
9999         badInput = (*argptr == ':');    /* we have class::method */
10000       else
10001         badInput = !isdigit (*arg);     /* not a line number */
10002     }
10003
10004   if (badInput)
10005     printf_filtered (_("Usage: stop at <line>\n"));
10006   else
10007     break_command_1 (arg, 0, from_tty);
10008 }
10009
10010 /* The dynamic printf command is mostly like a regular breakpoint, but
10011    with a prewired command list consisting of a single output command,
10012    built from extra arguments supplied on the dprintf command
10013    line.  */
10014
10015 static void
10016 dprintf_command (char *arg, int from_tty)
10017 {
10018   create_breakpoint (get_current_arch (),
10019                      arg,
10020                      NULL, 0, NULL, 1 /* parse arg */,
10021                      0, bp_dprintf,
10022                      0 /* Ignore count */,
10023                      pending_break_support,
10024                      &dprintf_breakpoint_ops,
10025                      from_tty,
10026                      1 /* enabled */,
10027                      0 /* internal */,
10028                      0);
10029 }
10030
10031 static void
10032 agent_printf_command (char *arg, int from_tty)
10033 {
10034   error (_("May only run agent-printf on the target"));
10035 }
10036
10037 /* Implement the "breakpoint_hit" breakpoint_ops method for
10038    ranged breakpoints.  */
10039
10040 static int
10041 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10042                                   struct address_space *aspace,
10043                                   CORE_ADDR bp_addr,
10044                                   const struct target_waitstatus *ws)
10045 {
10046   if (ws->kind != TARGET_WAITKIND_STOPPED
10047       || ws->value.sig != GDB_SIGNAL_TRAP)
10048     return 0;
10049
10050   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10051                                          bl->length, aspace, bp_addr);
10052 }
10053
10054 /* Implement the "resources_needed" breakpoint_ops method for
10055    ranged breakpoints.  */
10056
10057 static int
10058 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10059 {
10060   return target_ranged_break_num_registers ();
10061 }
10062
10063 /* Implement the "print_it" breakpoint_ops method for
10064    ranged breakpoints.  */
10065
10066 static enum print_stop_action
10067 print_it_ranged_breakpoint (bpstat bs)
10068 {
10069   struct breakpoint *b = bs->breakpoint_at;
10070   struct bp_location *bl = b->loc;
10071   struct ui_out *uiout = current_uiout;
10072
10073   gdb_assert (b->type == bp_hardware_breakpoint);
10074
10075   /* Ranged breakpoints have only one location.  */
10076   gdb_assert (bl && bl->next == NULL);
10077
10078   annotate_breakpoint (b->number);
10079   if (b->disposition == disp_del)
10080     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10081   else
10082     ui_out_text (uiout, "\nRanged breakpoint ");
10083   if (ui_out_is_mi_like_p (uiout))
10084     {
10085       ui_out_field_string (uiout, "reason",
10086                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10087       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10088     }
10089   ui_out_field_int (uiout, "bkptno", b->number);
10090   ui_out_text (uiout, ", ");
10091
10092   return PRINT_SRC_AND_LOC;
10093 }
10094
10095 /* Implement the "print_one" breakpoint_ops method for
10096    ranged breakpoints.  */
10097
10098 static void
10099 print_one_ranged_breakpoint (struct breakpoint *b,
10100                              struct bp_location **last_loc)
10101 {
10102   struct bp_location *bl = b->loc;
10103   struct value_print_options opts;
10104   struct ui_out *uiout = current_uiout;
10105
10106   /* Ranged breakpoints have only one location.  */
10107   gdb_assert (bl && bl->next == NULL);
10108
10109   get_user_print_options (&opts);
10110
10111   if (opts.addressprint)
10112     /* We don't print the address range here, it will be printed later
10113        by print_one_detail_ranged_breakpoint.  */
10114     ui_out_field_skip (uiout, "addr");
10115   annotate_field (5);
10116   print_breakpoint_location (b, bl);
10117   *last_loc = bl;
10118 }
10119
10120 /* Implement the "print_one_detail" breakpoint_ops method for
10121    ranged breakpoints.  */
10122
10123 static void
10124 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10125                                     struct ui_out *uiout)
10126 {
10127   CORE_ADDR address_start, address_end;
10128   struct bp_location *bl = b->loc;
10129   struct ui_file *stb = mem_fileopen ();
10130   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10131
10132   gdb_assert (bl);
10133
10134   address_start = bl->address;
10135   address_end = address_start + bl->length - 1;
10136
10137   ui_out_text (uiout, "\taddress range: ");
10138   fprintf_unfiltered (stb, "[%s, %s]",
10139                       print_core_address (bl->gdbarch, address_start),
10140                       print_core_address (bl->gdbarch, address_end));
10141   ui_out_field_stream (uiout, "addr", stb);
10142   ui_out_text (uiout, "\n");
10143
10144   do_cleanups (cleanup);
10145 }
10146
10147 /* Implement the "print_mention" breakpoint_ops method for
10148    ranged breakpoints.  */
10149
10150 static void
10151 print_mention_ranged_breakpoint (struct breakpoint *b)
10152 {
10153   struct bp_location *bl = b->loc;
10154   struct ui_out *uiout = current_uiout;
10155
10156   gdb_assert (bl);
10157   gdb_assert (b->type == bp_hardware_breakpoint);
10158
10159   if (ui_out_is_mi_like_p (uiout))
10160     return;
10161
10162   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10163                    b->number, paddress (bl->gdbarch, bl->address),
10164                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10165 }
10166
10167 /* Implement the "print_recreate" breakpoint_ops method for
10168    ranged breakpoints.  */
10169
10170 static void
10171 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10172 {
10173   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10174                       b->addr_string_range_end);
10175   print_recreate_thread (b, fp);
10176 }
10177
10178 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10179
10180 static struct breakpoint_ops ranged_breakpoint_ops;
10181
10182 /* Find the address where the end of the breakpoint range should be
10183    placed, given the SAL of the end of the range.  This is so that if
10184    the user provides a line number, the end of the range is set to the
10185    last instruction of the given line.  */
10186
10187 static CORE_ADDR
10188 find_breakpoint_range_end (struct symtab_and_line sal)
10189 {
10190   CORE_ADDR end;
10191
10192   /* If the user provided a PC value, use it.  Otherwise,
10193      find the address of the end of the given location.  */
10194   if (sal.explicit_pc)
10195     end = sal.pc;
10196   else
10197     {
10198       int ret;
10199       CORE_ADDR start;
10200
10201       ret = find_line_pc_range (sal, &start, &end);
10202       if (!ret)
10203         error (_("Could not find location of the end of the range."));
10204
10205       /* find_line_pc_range returns the start of the next line.  */
10206       end--;
10207     }
10208
10209   return end;
10210 }
10211
10212 /* Implement the "break-range" CLI command.  */
10213
10214 static void
10215 break_range_command (char *arg, int from_tty)
10216 {
10217   char *arg_start, *addr_string_start, *addr_string_end;
10218   struct linespec_result canonical_start, canonical_end;
10219   int bp_count, can_use_bp, length;
10220   CORE_ADDR end;
10221   struct breakpoint *b;
10222   struct symtab_and_line sal_start, sal_end;
10223   struct cleanup *cleanup_bkpt;
10224   struct linespec_sals *lsal_start, *lsal_end;
10225
10226   /* We don't support software ranged breakpoints.  */
10227   if (target_ranged_break_num_registers () < 0)
10228     error (_("This target does not support hardware ranged breakpoints."));
10229
10230   bp_count = hw_breakpoint_used_count ();
10231   bp_count += target_ranged_break_num_registers ();
10232   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10233                                                    bp_count, 0);
10234   if (can_use_bp < 0)
10235     error (_("Hardware breakpoints used exceeds limit."));
10236
10237   arg = skip_spaces (arg);
10238   if (arg == NULL || arg[0] == '\0')
10239     error(_("No address range specified."));
10240
10241   init_linespec_result (&canonical_start);
10242
10243   arg_start = arg;
10244   parse_breakpoint_sals (&arg, &canonical_start);
10245
10246   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10247
10248   if (arg[0] != ',')
10249     error (_("Too few arguments."));
10250   else if (VEC_empty (linespec_sals, canonical_start.sals))
10251     error (_("Could not find location of the beginning of the range."));
10252
10253   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10254
10255   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10256       || lsal_start->sals.nelts != 1)
10257     error (_("Cannot create a ranged breakpoint with multiple locations."));
10258
10259   sal_start = lsal_start->sals.sals[0];
10260   addr_string_start = savestring (arg_start, arg - arg_start);
10261   make_cleanup (xfree, addr_string_start);
10262
10263   arg++;        /* Skip the comma.  */
10264   arg = skip_spaces (arg);
10265
10266   /* Parse the end location.  */
10267
10268   init_linespec_result (&canonical_end);
10269   arg_start = arg;
10270
10271   /* We call decode_line_full directly here instead of using
10272      parse_breakpoint_sals because we need to specify the start location's
10273      symtab and line as the default symtab and line for the end of the
10274      range.  This makes it possible to have ranges like "foo.c:27, +14",
10275      where +14 means 14 lines from the start location.  */
10276   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10277                     sal_start.symtab, sal_start.line,
10278                     &canonical_end, NULL, NULL);
10279
10280   make_cleanup_destroy_linespec_result (&canonical_end);
10281
10282   if (VEC_empty (linespec_sals, canonical_end.sals))
10283     error (_("Could not find location of the end of the range."));
10284
10285   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10286   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10287       || lsal_end->sals.nelts != 1)
10288     error (_("Cannot create a ranged breakpoint with multiple locations."));
10289
10290   sal_end = lsal_end->sals.sals[0];
10291   addr_string_end = savestring (arg_start, arg - arg_start);
10292   make_cleanup (xfree, addr_string_end);
10293
10294   end = find_breakpoint_range_end (sal_end);
10295   if (sal_start.pc > end)
10296     error (_("Invalid address range, end precedes start."));
10297
10298   length = end - sal_start.pc + 1;
10299   if (length < 0)
10300     /* Length overflowed.  */
10301     error (_("Address range too large."));
10302   else if (length == 1)
10303     {
10304       /* This range is simple enough to be handled by
10305          the `hbreak' command.  */
10306       hbreak_command (addr_string_start, 1);
10307
10308       do_cleanups (cleanup_bkpt);
10309
10310       return;
10311     }
10312
10313   /* Now set up the breakpoint.  */
10314   b = set_raw_breakpoint (get_current_arch (), sal_start,
10315                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10316   set_breakpoint_count (breakpoint_count + 1);
10317   b->number = breakpoint_count;
10318   b->disposition = disp_donttouch;
10319   b->addr_string = xstrdup (addr_string_start);
10320   b->addr_string_range_end = xstrdup (addr_string_end);
10321   b->loc->length = length;
10322
10323   do_cleanups (cleanup_bkpt);
10324
10325   mention (b);
10326   observer_notify_breakpoint_created (b);
10327   update_global_location_list (UGLL_MAY_INSERT);
10328 }
10329
10330 /*  Return non-zero if EXP is verified as constant.  Returned zero
10331     means EXP is variable.  Also the constant detection may fail for
10332     some constant expressions and in such case still falsely return
10333     zero.  */
10334
10335 static int
10336 watchpoint_exp_is_const (const struct expression *exp)
10337 {
10338   int i = exp->nelts;
10339
10340   while (i > 0)
10341     {
10342       int oplenp, argsp;
10343
10344       /* We are only interested in the descriptor of each element.  */
10345       operator_length (exp, i, &oplenp, &argsp);
10346       i -= oplenp;
10347
10348       switch (exp->elts[i].opcode)
10349         {
10350         case BINOP_ADD:
10351         case BINOP_SUB:
10352         case BINOP_MUL:
10353         case BINOP_DIV:
10354         case BINOP_REM:
10355         case BINOP_MOD:
10356         case BINOP_LSH:
10357         case BINOP_RSH:
10358         case BINOP_LOGICAL_AND:
10359         case BINOP_LOGICAL_OR:
10360         case BINOP_BITWISE_AND:
10361         case BINOP_BITWISE_IOR:
10362         case BINOP_BITWISE_XOR:
10363         case BINOP_EQUAL:
10364         case BINOP_NOTEQUAL:
10365         case BINOP_LESS:
10366         case BINOP_GTR:
10367         case BINOP_LEQ:
10368         case BINOP_GEQ:
10369         case BINOP_REPEAT:
10370         case BINOP_COMMA:
10371         case BINOP_EXP:
10372         case BINOP_MIN:
10373         case BINOP_MAX:
10374         case BINOP_INTDIV:
10375         case BINOP_CONCAT:
10376         case TERNOP_COND:
10377         case TERNOP_SLICE:
10378
10379         case OP_LONG:
10380         case OP_DOUBLE:
10381         case OP_DECFLOAT:
10382         case OP_LAST:
10383         case OP_COMPLEX:
10384         case OP_STRING:
10385         case OP_ARRAY:
10386         case OP_TYPE:
10387         case OP_TYPEOF:
10388         case OP_DECLTYPE:
10389         case OP_TYPEID:
10390         case OP_NAME:
10391         case OP_OBJC_NSSTRING:
10392
10393         case UNOP_NEG:
10394         case UNOP_LOGICAL_NOT:
10395         case UNOP_COMPLEMENT:
10396         case UNOP_ADDR:
10397         case UNOP_HIGH:
10398         case UNOP_CAST:
10399
10400         case UNOP_CAST_TYPE:
10401         case UNOP_REINTERPRET_CAST:
10402         case UNOP_DYNAMIC_CAST:
10403           /* Unary, binary and ternary operators: We have to check
10404              their operands.  If they are constant, then so is the
10405              result of that operation.  For instance, if A and B are
10406              determined to be constants, then so is "A + B".
10407
10408              UNOP_IND is one exception to the rule above, because the
10409              value of *ADDR is not necessarily a constant, even when
10410              ADDR is.  */
10411           break;
10412
10413         case OP_VAR_VALUE:
10414           /* Check whether the associated symbol is a constant.
10415
10416              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10417              possible that a buggy compiler could mark a variable as
10418              constant even when it is not, and TYPE_CONST would return
10419              true in this case, while SYMBOL_CLASS wouldn't.
10420
10421              We also have to check for function symbols because they
10422              are always constant.  */
10423           {
10424             struct symbol *s = exp->elts[i + 2].symbol;
10425
10426             if (SYMBOL_CLASS (s) != LOC_BLOCK
10427                 && SYMBOL_CLASS (s) != LOC_CONST
10428                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10429               return 0;
10430             break;
10431           }
10432
10433         /* The default action is to return 0 because we are using
10434            the optimistic approach here: If we don't know something,
10435            then it is not a constant.  */
10436         default:
10437           return 0;
10438         }
10439     }
10440
10441   return 1;
10442 }
10443
10444 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10445
10446 static void
10447 dtor_watchpoint (struct breakpoint *self)
10448 {
10449   struct watchpoint *w = (struct watchpoint *) self;
10450
10451   xfree (w->cond_exp);
10452   xfree (w->exp);
10453   xfree (w->exp_string);
10454   xfree (w->exp_string_reparse);
10455   value_free (w->val);
10456
10457   base_breakpoint_ops.dtor (self);
10458 }
10459
10460 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10461
10462 static void
10463 re_set_watchpoint (struct breakpoint *b)
10464 {
10465   struct watchpoint *w = (struct watchpoint *) b;
10466
10467   /* Watchpoint can be either on expression using entirely global
10468      variables, or it can be on local variables.
10469
10470      Watchpoints of the first kind are never auto-deleted, and even
10471      persist across program restarts.  Since they can use variables
10472      from shared libraries, we need to reparse expression as libraries
10473      are loaded and unloaded.
10474
10475      Watchpoints on local variables can also change meaning as result
10476      of solib event.  For example, if a watchpoint uses both a local
10477      and a global variables in expression, it's a local watchpoint,
10478      but unloading of a shared library will make the expression
10479      invalid.  This is not a very common use case, but we still
10480      re-evaluate expression, to avoid surprises to the user.
10481
10482      Note that for local watchpoints, we re-evaluate it only if
10483      watchpoints frame id is still valid.  If it's not, it means the
10484      watchpoint is out of scope and will be deleted soon.  In fact,
10485      I'm not sure we'll ever be called in this case.
10486
10487      If a local watchpoint's frame id is still valid, then
10488      w->exp_valid_block is likewise valid, and we can safely use it.
10489
10490      Don't do anything about disabled watchpoints, since they will be
10491      reevaluated again when enabled.  */
10492   update_watchpoint (w, 1 /* reparse */);
10493 }
10494
10495 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10496
10497 static int
10498 insert_watchpoint (struct bp_location *bl)
10499 {
10500   struct watchpoint *w = (struct watchpoint *) bl->owner;
10501   int length = w->exact ? 1 : bl->length;
10502
10503   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10504                                    w->cond_exp);
10505 }
10506
10507 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10508
10509 static int
10510 remove_watchpoint (struct bp_location *bl)
10511 {
10512   struct watchpoint *w = (struct watchpoint *) bl->owner;
10513   int length = w->exact ? 1 : bl->length;
10514
10515   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10516                                    w->cond_exp);
10517 }
10518
10519 static int
10520 breakpoint_hit_watchpoint (const struct bp_location *bl,
10521                            struct address_space *aspace, CORE_ADDR bp_addr,
10522                            const struct target_waitstatus *ws)
10523 {
10524   struct breakpoint *b = bl->owner;
10525   struct watchpoint *w = (struct watchpoint *) b;
10526
10527   /* Continuable hardware watchpoints are treated as non-existent if the
10528      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10529      some data address).  Otherwise gdb won't stop on a break instruction
10530      in the code (not from a breakpoint) when a hardware watchpoint has
10531      been defined.  Also skip watchpoints which we know did not trigger
10532      (did not match the data address).  */
10533   if (is_hardware_watchpoint (b)
10534       && w->watchpoint_triggered == watch_triggered_no)
10535     return 0;
10536
10537   return 1;
10538 }
10539
10540 static void
10541 check_status_watchpoint (bpstat bs)
10542 {
10543   gdb_assert (is_watchpoint (bs->breakpoint_at));
10544
10545   bpstat_check_watchpoint (bs);
10546 }
10547
10548 /* Implement the "resources_needed" breakpoint_ops method for
10549    hardware watchpoints.  */
10550
10551 static int
10552 resources_needed_watchpoint (const struct bp_location *bl)
10553 {
10554   struct watchpoint *w = (struct watchpoint *) bl->owner;
10555   int length = w->exact? 1 : bl->length;
10556
10557   return target_region_ok_for_hw_watchpoint (bl->address, length);
10558 }
10559
10560 /* Implement the "works_in_software_mode" breakpoint_ops method for
10561    hardware watchpoints.  */
10562
10563 static int
10564 works_in_software_mode_watchpoint (const struct breakpoint *b)
10565 {
10566   /* Read and access watchpoints only work with hardware support.  */
10567   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10568 }
10569
10570 static enum print_stop_action
10571 print_it_watchpoint (bpstat bs)
10572 {
10573   struct cleanup *old_chain;
10574   struct breakpoint *b;
10575   struct ui_file *stb;
10576   enum print_stop_action result;
10577   struct watchpoint *w;
10578   struct ui_out *uiout = current_uiout;
10579
10580   gdb_assert (bs->bp_location_at != NULL);
10581
10582   b = bs->breakpoint_at;
10583   w = (struct watchpoint *) b;
10584
10585   stb = mem_fileopen ();
10586   old_chain = make_cleanup_ui_file_delete (stb);
10587
10588   switch (b->type)
10589     {
10590     case bp_watchpoint:
10591     case bp_hardware_watchpoint:
10592       annotate_watchpoint (b->number);
10593       if (ui_out_is_mi_like_p (uiout))
10594         ui_out_field_string
10595           (uiout, "reason",
10596            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10597       mention (b);
10598       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10599       ui_out_text (uiout, "\nOld value = ");
10600       watchpoint_value_print (bs->old_val, stb);
10601       ui_out_field_stream (uiout, "old", stb);
10602       ui_out_text (uiout, "\nNew value = ");
10603       watchpoint_value_print (w->val, stb);
10604       ui_out_field_stream (uiout, "new", stb);
10605       ui_out_text (uiout, "\n");
10606       /* More than one watchpoint may have been triggered.  */
10607       result = PRINT_UNKNOWN;
10608       break;
10609
10610     case bp_read_watchpoint:
10611       if (ui_out_is_mi_like_p (uiout))
10612         ui_out_field_string
10613           (uiout, "reason",
10614            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10615       mention (b);
10616       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10617       ui_out_text (uiout, "\nValue = ");
10618       watchpoint_value_print (w->val, stb);
10619       ui_out_field_stream (uiout, "value", stb);
10620       ui_out_text (uiout, "\n");
10621       result = PRINT_UNKNOWN;
10622       break;
10623
10624     case bp_access_watchpoint:
10625       if (bs->old_val != NULL)
10626         {
10627           annotate_watchpoint (b->number);
10628           if (ui_out_is_mi_like_p (uiout))
10629             ui_out_field_string
10630               (uiout, "reason",
10631                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10632           mention (b);
10633           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10634           ui_out_text (uiout, "\nOld value = ");
10635           watchpoint_value_print (bs->old_val, stb);
10636           ui_out_field_stream (uiout, "old", stb);
10637           ui_out_text (uiout, "\nNew value = ");
10638         }
10639       else
10640         {
10641           mention (b);
10642           if (ui_out_is_mi_like_p (uiout))
10643             ui_out_field_string
10644               (uiout, "reason",
10645                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10646           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10647           ui_out_text (uiout, "\nValue = ");
10648         }
10649       watchpoint_value_print (w->val, stb);
10650       ui_out_field_stream (uiout, "new", stb);
10651       ui_out_text (uiout, "\n");
10652       result = PRINT_UNKNOWN;
10653       break;
10654     default:
10655       result = PRINT_UNKNOWN;
10656     }
10657
10658   do_cleanups (old_chain);
10659   return result;
10660 }
10661
10662 /* Implement the "print_mention" breakpoint_ops method for hardware
10663    watchpoints.  */
10664
10665 static void
10666 print_mention_watchpoint (struct breakpoint *b)
10667 {
10668   struct cleanup *ui_out_chain;
10669   struct watchpoint *w = (struct watchpoint *) b;
10670   struct ui_out *uiout = current_uiout;
10671
10672   switch (b->type)
10673     {
10674     case bp_watchpoint:
10675       ui_out_text (uiout, "Watchpoint ");
10676       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10677       break;
10678     case bp_hardware_watchpoint:
10679       ui_out_text (uiout, "Hardware watchpoint ");
10680       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10681       break;
10682     case bp_read_watchpoint:
10683       ui_out_text (uiout, "Hardware read watchpoint ");
10684       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10685       break;
10686     case bp_access_watchpoint:
10687       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10688       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10689       break;
10690     default:
10691       internal_error (__FILE__, __LINE__,
10692                       _("Invalid hardware watchpoint type."));
10693     }
10694
10695   ui_out_field_int (uiout, "number", b->number);
10696   ui_out_text (uiout, ": ");
10697   ui_out_field_string (uiout, "exp", w->exp_string);
10698   do_cleanups (ui_out_chain);
10699 }
10700
10701 /* Implement the "print_recreate" breakpoint_ops method for
10702    watchpoints.  */
10703
10704 static void
10705 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10706 {
10707   struct watchpoint *w = (struct watchpoint *) b;
10708
10709   switch (b->type)
10710     {
10711     case bp_watchpoint:
10712     case bp_hardware_watchpoint:
10713       fprintf_unfiltered (fp, "watch");
10714       break;
10715     case bp_read_watchpoint:
10716       fprintf_unfiltered (fp, "rwatch");
10717       break;
10718     case bp_access_watchpoint:
10719       fprintf_unfiltered (fp, "awatch");
10720       break;
10721     default:
10722       internal_error (__FILE__, __LINE__,
10723                       _("Invalid watchpoint type."));
10724     }
10725
10726   fprintf_unfiltered (fp, " %s", w->exp_string);
10727   print_recreate_thread (b, fp);
10728 }
10729
10730 /* Implement the "explains_signal" breakpoint_ops method for
10731    watchpoints.  */
10732
10733 static int
10734 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10735 {
10736   /* A software watchpoint cannot cause a signal other than
10737      GDB_SIGNAL_TRAP.  */
10738   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10739     return 0;
10740
10741   return 1;
10742 }
10743
10744 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10745
10746 static struct breakpoint_ops watchpoint_breakpoint_ops;
10747
10748 /* Implement the "insert" breakpoint_ops method for
10749    masked hardware watchpoints.  */
10750
10751 static int
10752 insert_masked_watchpoint (struct bp_location *bl)
10753 {
10754   struct watchpoint *w = (struct watchpoint *) bl->owner;
10755
10756   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10757                                         bl->watchpoint_type);
10758 }
10759
10760 /* Implement the "remove" breakpoint_ops method for
10761    masked hardware watchpoints.  */
10762
10763 static int
10764 remove_masked_watchpoint (struct bp_location *bl)
10765 {
10766   struct watchpoint *w = (struct watchpoint *) bl->owner;
10767
10768   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10769                                         bl->watchpoint_type);
10770 }
10771
10772 /* Implement the "resources_needed" breakpoint_ops method for
10773    masked hardware watchpoints.  */
10774
10775 static int
10776 resources_needed_masked_watchpoint (const struct bp_location *bl)
10777 {
10778   struct watchpoint *w = (struct watchpoint *) bl->owner;
10779
10780   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10781 }
10782
10783 /* Implement the "works_in_software_mode" breakpoint_ops method for
10784    masked hardware watchpoints.  */
10785
10786 static int
10787 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10788 {
10789   return 0;
10790 }
10791
10792 /* Implement the "print_it" breakpoint_ops method for
10793    masked hardware watchpoints.  */
10794
10795 static enum print_stop_action
10796 print_it_masked_watchpoint (bpstat bs)
10797 {
10798   struct breakpoint *b = bs->breakpoint_at;
10799   struct ui_out *uiout = current_uiout;
10800
10801   /* Masked watchpoints have only one location.  */
10802   gdb_assert (b->loc && b->loc->next == NULL);
10803
10804   switch (b->type)
10805     {
10806     case bp_hardware_watchpoint:
10807       annotate_watchpoint (b->number);
10808       if (ui_out_is_mi_like_p (uiout))
10809         ui_out_field_string
10810           (uiout, "reason",
10811            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10812       break;
10813
10814     case bp_read_watchpoint:
10815       if (ui_out_is_mi_like_p (uiout))
10816         ui_out_field_string
10817           (uiout, "reason",
10818            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10819       break;
10820
10821     case bp_access_watchpoint:
10822       if (ui_out_is_mi_like_p (uiout))
10823         ui_out_field_string
10824           (uiout, "reason",
10825            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10826       break;
10827     default:
10828       internal_error (__FILE__, __LINE__,
10829                       _("Invalid hardware watchpoint type."));
10830     }
10831
10832   mention (b);
10833   ui_out_text (uiout, _("\n\
10834 Check the underlying instruction at PC for the memory\n\
10835 address and value which triggered this watchpoint.\n"));
10836   ui_out_text (uiout, "\n");
10837
10838   /* More than one watchpoint may have been triggered.  */
10839   return PRINT_UNKNOWN;
10840 }
10841
10842 /* Implement the "print_one_detail" breakpoint_ops method for
10843    masked hardware watchpoints.  */
10844
10845 static void
10846 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10847                                     struct ui_out *uiout)
10848 {
10849   struct watchpoint *w = (struct watchpoint *) b;
10850
10851   /* Masked watchpoints have only one location.  */
10852   gdb_assert (b->loc && b->loc->next == NULL);
10853
10854   ui_out_text (uiout, "\tmask ");
10855   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10856   ui_out_text (uiout, "\n");
10857 }
10858
10859 /* Implement the "print_mention" breakpoint_ops method for
10860    masked hardware watchpoints.  */
10861
10862 static void
10863 print_mention_masked_watchpoint (struct breakpoint *b)
10864 {
10865   struct watchpoint *w = (struct watchpoint *) b;
10866   struct ui_out *uiout = current_uiout;
10867   struct cleanup *ui_out_chain;
10868
10869   switch (b->type)
10870     {
10871     case bp_hardware_watchpoint:
10872       ui_out_text (uiout, "Masked hardware watchpoint ");
10873       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10874       break;
10875     case bp_read_watchpoint:
10876       ui_out_text (uiout, "Masked hardware read watchpoint ");
10877       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10878       break;
10879     case bp_access_watchpoint:
10880       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10881       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10882       break;
10883     default:
10884       internal_error (__FILE__, __LINE__,
10885                       _("Invalid hardware watchpoint type."));
10886     }
10887
10888   ui_out_field_int (uiout, "number", b->number);
10889   ui_out_text (uiout, ": ");
10890   ui_out_field_string (uiout, "exp", w->exp_string);
10891   do_cleanups (ui_out_chain);
10892 }
10893
10894 /* Implement the "print_recreate" breakpoint_ops method for
10895    masked hardware watchpoints.  */
10896
10897 static void
10898 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10899 {
10900   struct watchpoint *w = (struct watchpoint *) b;
10901   char tmp[40];
10902
10903   switch (b->type)
10904     {
10905     case bp_hardware_watchpoint:
10906       fprintf_unfiltered (fp, "watch");
10907       break;
10908     case bp_read_watchpoint:
10909       fprintf_unfiltered (fp, "rwatch");
10910       break;
10911     case bp_access_watchpoint:
10912       fprintf_unfiltered (fp, "awatch");
10913       break;
10914     default:
10915       internal_error (__FILE__, __LINE__,
10916                       _("Invalid hardware watchpoint type."));
10917     }
10918
10919   sprintf_vma (tmp, w->hw_wp_mask);
10920   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10921   print_recreate_thread (b, fp);
10922 }
10923
10924 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10925
10926 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10927
10928 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10929
10930 static int
10931 is_masked_watchpoint (const struct breakpoint *b)
10932 {
10933   return b->ops == &masked_watchpoint_breakpoint_ops;
10934 }
10935
10936 /* accessflag:  hw_write:  watch write, 
10937                 hw_read:   watch read, 
10938                 hw_access: watch access (read or write) */
10939 static void
10940 watch_command_1 (const char *arg, int accessflag, int from_tty,
10941                  int just_location, int internal)
10942 {
10943   struct breakpoint *b, *scope_breakpoint = NULL;
10944   struct expression *exp;
10945   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10946   struct value *val, *mark, *result;
10947   int saved_bitpos = 0, saved_bitsize = 0;
10948   struct frame_info *frame;
10949   const char *exp_start = NULL;
10950   const char *exp_end = NULL;
10951   const char *tok, *end_tok;
10952   int toklen = -1;
10953   const char *cond_start = NULL;
10954   const char *cond_end = NULL;
10955   enum bptype bp_type;
10956   int thread = -1;
10957   int pc = 0;
10958   /* Flag to indicate whether we are going to use masks for
10959      the hardware watchpoint.  */
10960   int use_mask = 0;
10961   CORE_ADDR mask = 0;
10962   struct watchpoint *w;
10963   char *expression;
10964   struct cleanup *back_to;
10965
10966   /* Make sure that we actually have parameters to parse.  */
10967   if (arg != NULL && arg[0] != '\0')
10968     {
10969       const char *value_start;
10970
10971       exp_end = arg + strlen (arg);
10972
10973       /* Look for "parameter value" pairs at the end
10974          of the arguments string.  */
10975       for (tok = exp_end - 1; tok > arg; tok--)
10976         {
10977           /* Skip whitespace at the end of the argument list.  */
10978           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10979             tok--;
10980
10981           /* Find the beginning of the last token.
10982              This is the value of the parameter.  */
10983           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10984             tok--;
10985           value_start = tok + 1;
10986
10987           /* Skip whitespace.  */
10988           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10989             tok--;
10990
10991           end_tok = tok;
10992
10993           /* Find the beginning of the second to last token.
10994              This is the parameter itself.  */
10995           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10996             tok--;
10997           tok++;
10998           toklen = end_tok - tok + 1;
10999
11000           if (toklen == 6 && startswith (tok, "thread"))
11001             {
11002               /* At this point we've found a "thread" token, which means
11003                  the user is trying to set a watchpoint that triggers
11004                  only in a specific thread.  */
11005               char *endp;
11006
11007               if (thread != -1)
11008                 error(_("You can specify only one thread."));
11009
11010               /* Extract the thread ID from the next token.  */
11011               thread = strtol (value_start, &endp, 0);
11012
11013               /* Check if the user provided a valid numeric value for the
11014                  thread ID.  */
11015               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11016                 error (_("Invalid thread ID specification %s."), value_start);
11017
11018               /* Check if the thread actually exists.  */
11019               if (!valid_thread_id (thread))
11020                 invalid_thread_id_error (thread);
11021             }
11022           else if (toklen == 4 && startswith (tok, "mask"))
11023             {
11024               /* We've found a "mask" token, which means the user wants to
11025                  create a hardware watchpoint that is going to have the mask
11026                  facility.  */
11027               struct value *mask_value, *mark;
11028
11029               if (use_mask)
11030                 error(_("You can specify only one mask."));
11031
11032               use_mask = just_location = 1;
11033
11034               mark = value_mark ();
11035               mask_value = parse_to_comma_and_eval (&value_start);
11036               mask = value_as_address (mask_value);
11037               value_free_to_mark (mark);
11038             }
11039           else
11040             /* We didn't recognize what we found.  We should stop here.  */
11041             break;
11042
11043           /* Truncate the string and get rid of the "parameter value" pair before
11044              the arguments string is parsed by the parse_exp_1 function.  */
11045           exp_end = tok;
11046         }
11047     }
11048   else
11049     exp_end = arg;
11050
11051   /* Parse the rest of the arguments.  From here on out, everything
11052      is in terms of a newly allocated string instead of the original
11053      ARG.  */
11054   innermost_block = NULL;
11055   expression = savestring (arg, exp_end - arg);
11056   back_to = make_cleanup (xfree, expression);
11057   exp_start = arg = expression;
11058   exp = parse_exp_1 (&arg, 0, 0, 0);
11059   exp_end = arg;
11060   /* Remove trailing whitespace from the expression before saving it.
11061      This makes the eventual display of the expression string a bit
11062      prettier.  */
11063   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11064     --exp_end;
11065
11066   /* Checking if the expression is not constant.  */
11067   if (watchpoint_exp_is_const (exp))
11068     {
11069       int len;
11070
11071       len = exp_end - exp_start;
11072       while (len > 0 && isspace (exp_start[len - 1]))
11073         len--;
11074       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11075     }
11076
11077   exp_valid_block = innermost_block;
11078   mark = value_mark ();
11079   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11080
11081   if (val != NULL && just_location)
11082     {
11083       saved_bitpos = value_bitpos (val);
11084       saved_bitsize = value_bitsize (val);
11085     }
11086
11087   if (just_location)
11088     {
11089       int ret;
11090
11091       exp_valid_block = NULL;
11092       val = value_addr (result);
11093       release_value (val);
11094       value_free_to_mark (mark);
11095
11096       if (use_mask)
11097         {
11098           ret = target_masked_watch_num_registers (value_as_address (val),
11099                                                    mask);
11100           if (ret == -1)
11101             error (_("This target does not support masked watchpoints."));
11102           else if (ret == -2)
11103             error (_("Invalid mask or memory region."));
11104         }
11105     }
11106   else if (val != NULL)
11107     release_value (val);
11108
11109   tok = skip_spaces_const (arg);
11110   end_tok = skip_to_space_const (tok);
11111
11112   toklen = end_tok - tok;
11113   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11114     {
11115       struct expression *cond;
11116
11117       innermost_block = NULL;
11118       tok = cond_start = end_tok + 1;
11119       cond = parse_exp_1 (&tok, 0, 0, 0);
11120
11121       /* The watchpoint expression may not be local, but the condition
11122          may still be.  E.g.: `watch global if local > 0'.  */
11123       cond_exp_valid_block = innermost_block;
11124
11125       xfree (cond);
11126       cond_end = tok;
11127     }
11128   if (*tok)
11129     error (_("Junk at end of command."));
11130
11131   frame = block_innermost_frame (exp_valid_block);
11132
11133   /* If the expression is "local", then set up a "watchpoint scope"
11134      breakpoint at the point where we've left the scope of the watchpoint
11135      expression.  Create the scope breakpoint before the watchpoint, so
11136      that we will encounter it first in bpstat_stop_status.  */
11137   if (exp_valid_block && frame)
11138     {
11139       if (frame_id_p (frame_unwind_caller_id (frame)))
11140         {
11141           scope_breakpoint
11142             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11143                                           frame_unwind_caller_pc (frame),
11144                                           bp_watchpoint_scope,
11145                                           &momentary_breakpoint_ops);
11146
11147           scope_breakpoint->enable_state = bp_enabled;
11148
11149           /* Automatically delete the breakpoint when it hits.  */
11150           scope_breakpoint->disposition = disp_del;
11151
11152           /* Only break in the proper frame (help with recursion).  */
11153           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11154
11155           /* Set the address at which we will stop.  */
11156           scope_breakpoint->loc->gdbarch
11157             = frame_unwind_caller_arch (frame);
11158           scope_breakpoint->loc->requested_address
11159             = frame_unwind_caller_pc (frame);
11160           scope_breakpoint->loc->address
11161             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11162                                          scope_breakpoint->loc->requested_address,
11163                                          scope_breakpoint->type);
11164         }
11165     }
11166
11167   /* Now set up the breakpoint.  We create all watchpoints as hardware
11168      watchpoints here even if hardware watchpoints are turned off, a call
11169      to update_watchpoint later in this function will cause the type to
11170      drop back to bp_watchpoint (software watchpoint) if required.  */
11171
11172   if (accessflag == hw_read)
11173     bp_type = bp_read_watchpoint;
11174   else if (accessflag == hw_access)
11175     bp_type = bp_access_watchpoint;
11176   else
11177     bp_type = bp_hardware_watchpoint;
11178
11179   w = XCNEW (struct watchpoint);
11180   b = &w->base;
11181   if (use_mask)
11182     init_raw_breakpoint_without_location (b, NULL, bp_type,
11183                                           &masked_watchpoint_breakpoint_ops);
11184   else
11185     init_raw_breakpoint_without_location (b, NULL, bp_type,
11186                                           &watchpoint_breakpoint_ops);
11187   b->thread = thread;
11188   b->disposition = disp_donttouch;
11189   b->pspace = current_program_space;
11190   w->exp = exp;
11191   w->exp_valid_block = exp_valid_block;
11192   w->cond_exp_valid_block = cond_exp_valid_block;
11193   if (just_location)
11194     {
11195       struct type *t = value_type (val);
11196       CORE_ADDR addr = value_as_address (val);
11197       char *name;
11198
11199       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11200       name = type_to_string (t);
11201
11202       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11203                                           core_addr_to_string (addr));
11204       xfree (name);
11205
11206       w->exp_string = xstrprintf ("-location %.*s",
11207                                   (int) (exp_end - exp_start), exp_start);
11208
11209       /* The above expression is in C.  */
11210       b->language = language_c;
11211     }
11212   else
11213     w->exp_string = savestring (exp_start, exp_end - exp_start);
11214
11215   if (use_mask)
11216     {
11217       w->hw_wp_mask = mask;
11218     }
11219   else
11220     {
11221       w->val = val;
11222       w->val_bitpos = saved_bitpos;
11223       w->val_bitsize = saved_bitsize;
11224       w->val_valid = 1;
11225     }
11226
11227   if (cond_start)
11228     b->cond_string = savestring (cond_start, cond_end - cond_start);
11229   else
11230     b->cond_string = 0;
11231
11232   if (frame)
11233     {
11234       w->watchpoint_frame = get_frame_id (frame);
11235       w->watchpoint_thread = inferior_ptid;
11236     }
11237   else
11238     {
11239       w->watchpoint_frame = null_frame_id;
11240       w->watchpoint_thread = null_ptid;
11241     }
11242
11243   if (scope_breakpoint != NULL)
11244     {
11245       /* The scope breakpoint is related to the watchpoint.  We will
11246          need to act on them together.  */
11247       b->related_breakpoint = scope_breakpoint;
11248       scope_breakpoint->related_breakpoint = b;
11249     }
11250
11251   if (!just_location)
11252     value_free_to_mark (mark);
11253
11254   TRY
11255     {
11256       /* Finally update the new watchpoint.  This creates the locations
11257          that should be inserted.  */
11258       update_watchpoint (w, 1);
11259     }
11260   CATCH (e, RETURN_MASK_ALL)
11261     {
11262       delete_breakpoint (b);
11263       throw_exception (e);
11264     }
11265   END_CATCH
11266
11267   install_breakpoint (internal, b, 1);
11268   do_cleanups (back_to);
11269 }
11270
11271 /* Return count of debug registers needed to watch the given expression.
11272    If the watchpoint cannot be handled in hardware return zero.  */
11273
11274 static int
11275 can_use_hardware_watchpoint (struct value *v)
11276 {
11277   int found_memory_cnt = 0;
11278   struct value *head = v;
11279
11280   /* Did the user specifically forbid us to use hardware watchpoints? */
11281   if (!can_use_hw_watchpoints)
11282     return 0;
11283
11284   /* Make sure that the value of the expression depends only upon
11285      memory contents, and values computed from them within GDB.  If we
11286      find any register references or function calls, we can't use a
11287      hardware watchpoint.
11288
11289      The idea here is that evaluating an expression generates a series
11290      of values, one holding the value of every subexpression.  (The
11291      expression a*b+c has five subexpressions: a, b, a*b, c, and
11292      a*b+c.)  GDB's values hold almost enough information to establish
11293      the criteria given above --- they identify memory lvalues,
11294      register lvalues, computed values, etcetera.  So we can evaluate
11295      the expression, and then scan the chain of values that leaves
11296      behind to decide whether we can detect any possible change to the
11297      expression's final value using only hardware watchpoints.
11298
11299      However, I don't think that the values returned by inferior
11300      function calls are special in any way.  So this function may not
11301      notice that an expression involving an inferior function call
11302      can't be watched with hardware watchpoints.  FIXME.  */
11303   for (; v; v = value_next (v))
11304     {
11305       if (VALUE_LVAL (v) == lval_memory)
11306         {
11307           if (v != head && value_lazy (v))
11308             /* A lazy memory lvalue in the chain is one that GDB never
11309                needed to fetch; we either just used its address (e.g.,
11310                `a' in `a.b') or we never needed it at all (e.g., `a'
11311                in `a,b').  This doesn't apply to HEAD; if that is
11312                lazy then it was not readable, but watch it anyway.  */
11313             ;
11314           else
11315             {
11316               /* Ahh, memory we actually used!  Check if we can cover
11317                  it with hardware watchpoints.  */
11318               struct type *vtype = check_typedef (value_type (v));
11319
11320               /* We only watch structs and arrays if user asked for it
11321                  explicitly, never if they just happen to appear in a
11322                  middle of some value chain.  */
11323               if (v == head
11324                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11325                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11326                 {
11327                   CORE_ADDR vaddr = value_address (v);
11328                   int len;
11329                   int num_regs;
11330
11331                   len = (target_exact_watchpoints
11332                          && is_scalar_type_recursive (vtype))?
11333                     1 : TYPE_LENGTH (value_type (v));
11334
11335                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11336                   if (!num_regs)
11337                     return 0;
11338                   else
11339                     found_memory_cnt += num_regs;
11340                 }
11341             }
11342         }
11343       else if (VALUE_LVAL (v) != not_lval
11344                && deprecated_value_modifiable (v) == 0)
11345         return 0;       /* These are values from the history (e.g., $1).  */
11346       else if (VALUE_LVAL (v) == lval_register)
11347         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11348     }
11349
11350   /* The expression itself looks suitable for using a hardware
11351      watchpoint, but give the target machine a chance to reject it.  */
11352   return found_memory_cnt;
11353 }
11354
11355 void
11356 watch_command_wrapper (char *arg, int from_tty, int internal)
11357 {
11358   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11359 }
11360
11361 /* A helper function that looks for the "-location" argument and then
11362    calls watch_command_1.  */
11363
11364 static void
11365 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11366 {
11367   int just_location = 0;
11368
11369   if (arg
11370       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11371           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11372     {
11373       arg = skip_spaces (arg);
11374       just_location = 1;
11375     }
11376
11377   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11378 }
11379
11380 static void
11381 watch_command (char *arg, int from_tty)
11382 {
11383   watch_maybe_just_location (arg, hw_write, from_tty);
11384 }
11385
11386 void
11387 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11388 {
11389   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11390 }
11391
11392 static void
11393 rwatch_command (char *arg, int from_tty)
11394 {
11395   watch_maybe_just_location (arg, hw_read, from_tty);
11396 }
11397
11398 void
11399 awatch_command_wrapper (char *arg, int from_tty, int internal)
11400 {
11401   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11402 }
11403
11404 static void
11405 awatch_command (char *arg, int from_tty)
11406 {
11407   watch_maybe_just_location (arg, hw_access, from_tty);
11408 }
11409 \f
11410
11411 /* Helper routines for the until_command routine in infcmd.c.  Here
11412    because it uses the mechanisms of breakpoints.  */
11413
11414 struct until_break_command_continuation_args
11415 {
11416   struct breakpoint *breakpoint;
11417   struct breakpoint *breakpoint2;
11418   int thread_num;
11419 };
11420
11421 /* This function is called by fetch_inferior_event via the
11422    cmd_continuation pointer, to complete the until command.  It takes
11423    care of cleaning up the temporary breakpoints set up by the until
11424    command.  */
11425 static void
11426 until_break_command_continuation (void *arg, int err)
11427 {
11428   struct until_break_command_continuation_args *a = arg;
11429
11430   delete_breakpoint (a->breakpoint);
11431   if (a->breakpoint2)
11432     delete_breakpoint (a->breakpoint2);
11433   delete_longjmp_breakpoint (a->thread_num);
11434 }
11435
11436 void
11437 until_break_command (char *arg, int from_tty, int anywhere)
11438 {
11439   struct symtabs_and_lines sals;
11440   struct symtab_and_line sal;
11441   struct frame_info *frame;
11442   struct gdbarch *frame_gdbarch;
11443   struct frame_id stack_frame_id;
11444   struct frame_id caller_frame_id;
11445   struct breakpoint *breakpoint;
11446   struct breakpoint *breakpoint2 = NULL;
11447   struct cleanup *old_chain;
11448   int thread;
11449   struct thread_info *tp;
11450
11451   clear_proceed_status (0);
11452
11453   /* Set a breakpoint where the user wants it and at return from
11454      this function.  */
11455
11456   if (last_displayed_sal_is_valid ())
11457     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11458                           get_last_displayed_symtab (),
11459                           get_last_displayed_line ());
11460   else
11461     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11462                           (struct symtab *) NULL, 0);
11463
11464   if (sals.nelts != 1)
11465     error (_("Couldn't get information on specified line."));
11466
11467   sal = sals.sals[0];
11468   xfree (sals.sals);    /* malloc'd, so freed.  */
11469
11470   if (*arg)
11471     error (_("Junk at end of arguments."));
11472
11473   resolve_sal_pc (&sal);
11474
11475   tp = inferior_thread ();
11476   thread = tp->num;
11477
11478   old_chain = make_cleanup (null_cleanup, NULL);
11479
11480   /* Note linespec handling above invalidates the frame chain.
11481      Installing a breakpoint also invalidates the frame chain (as it
11482      may need to switch threads), so do any frame handling before
11483      that.  */
11484
11485   frame = get_selected_frame (NULL);
11486   frame_gdbarch = get_frame_arch (frame);
11487   stack_frame_id = get_stack_frame_id (frame);
11488   caller_frame_id = frame_unwind_caller_id (frame);
11489
11490   /* Keep within the current frame, or in frames called by the current
11491      one.  */
11492
11493   if (frame_id_p (caller_frame_id))
11494     {
11495       struct symtab_and_line sal2;
11496
11497       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11498       sal2.pc = frame_unwind_caller_pc (frame);
11499       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11500                                               sal2,
11501                                               caller_frame_id,
11502                                               bp_until);
11503       make_cleanup_delete_breakpoint (breakpoint2);
11504
11505       set_longjmp_breakpoint (tp, caller_frame_id);
11506       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11507     }
11508
11509   /* set_momentary_breakpoint could invalidate FRAME.  */
11510   frame = NULL;
11511
11512   if (anywhere)
11513     /* If the user told us to continue until a specified location,
11514        we don't specify a frame at which we need to stop.  */
11515     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11516                                            null_frame_id, bp_until);
11517   else
11518     /* Otherwise, specify the selected frame, because we want to stop
11519        only at the very same frame.  */
11520     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11521                                            stack_frame_id, bp_until);
11522   make_cleanup_delete_breakpoint (breakpoint);
11523
11524   proceed (-1, GDB_SIGNAL_DEFAULT);
11525
11526   /* If we are running asynchronously, and proceed call above has
11527      actually managed to start the target, arrange for breakpoints to
11528      be deleted when the target stops.  Otherwise, we're already
11529      stopped and delete breakpoints via cleanup chain.  */
11530
11531   if (target_can_async_p () && is_running (inferior_ptid))
11532     {
11533       struct until_break_command_continuation_args *args;
11534       args = xmalloc (sizeof (*args));
11535
11536       args->breakpoint = breakpoint;
11537       args->breakpoint2 = breakpoint2;
11538       args->thread_num = thread;
11539
11540       discard_cleanups (old_chain);
11541       add_continuation (inferior_thread (),
11542                         until_break_command_continuation, args,
11543                         xfree);
11544     }
11545   else
11546     do_cleanups (old_chain);
11547 }
11548
11549 /* This function attempts to parse an optional "if <cond>" clause
11550    from the arg string.  If one is not found, it returns NULL.
11551
11552    Else, it returns a pointer to the condition string.  (It does not
11553    attempt to evaluate the string against a particular block.)  And,
11554    it updates arg to point to the first character following the parsed
11555    if clause in the arg string.  */
11556
11557 char *
11558 ep_parse_optional_if_clause (char **arg)
11559 {
11560   char *cond_string;
11561
11562   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11563     return NULL;
11564
11565   /* Skip the "if" keyword.  */
11566   (*arg) += 2;
11567
11568   /* Skip any extra leading whitespace, and record the start of the
11569      condition string.  */
11570   *arg = skip_spaces (*arg);
11571   cond_string = *arg;
11572
11573   /* Assume that the condition occupies the remainder of the arg
11574      string.  */
11575   (*arg) += strlen (cond_string);
11576
11577   return cond_string;
11578 }
11579
11580 /* Commands to deal with catching events, such as signals, exceptions,
11581    process start/exit, etc.  */
11582
11583 typedef enum
11584 {
11585   catch_fork_temporary, catch_vfork_temporary,
11586   catch_fork_permanent, catch_vfork_permanent
11587 }
11588 catch_fork_kind;
11589
11590 static void
11591 catch_fork_command_1 (char *arg, int from_tty, 
11592                       struct cmd_list_element *command)
11593 {
11594   struct gdbarch *gdbarch = get_current_arch ();
11595   char *cond_string = NULL;
11596   catch_fork_kind fork_kind;
11597   int tempflag;
11598
11599   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11600   tempflag = (fork_kind == catch_fork_temporary
11601               || fork_kind == catch_vfork_temporary);
11602
11603   if (!arg)
11604     arg = "";
11605   arg = skip_spaces (arg);
11606
11607   /* The allowed syntax is:
11608      catch [v]fork
11609      catch [v]fork if <cond>
11610
11611      First, check if there's an if clause.  */
11612   cond_string = ep_parse_optional_if_clause (&arg);
11613
11614   if ((*arg != '\0') && !isspace (*arg))
11615     error (_("Junk at end of arguments."));
11616
11617   /* If this target supports it, create a fork or vfork catchpoint
11618      and enable reporting of such events.  */
11619   switch (fork_kind)
11620     {
11621     case catch_fork_temporary:
11622     case catch_fork_permanent:
11623       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11624                                           &catch_fork_breakpoint_ops);
11625       break;
11626     case catch_vfork_temporary:
11627     case catch_vfork_permanent:
11628       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11629                                           &catch_vfork_breakpoint_ops);
11630       break;
11631     default:
11632       error (_("unsupported or unknown fork kind; cannot catch it"));
11633       break;
11634     }
11635 }
11636
11637 static void
11638 catch_exec_command_1 (char *arg, int from_tty, 
11639                       struct cmd_list_element *command)
11640 {
11641   struct exec_catchpoint *c;
11642   struct gdbarch *gdbarch = get_current_arch ();
11643   int tempflag;
11644   char *cond_string = NULL;
11645
11646   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11647
11648   if (!arg)
11649     arg = "";
11650   arg = skip_spaces (arg);
11651
11652   /* The allowed syntax is:
11653      catch exec
11654      catch exec if <cond>
11655
11656      First, check if there's an if clause.  */
11657   cond_string = ep_parse_optional_if_clause (&arg);
11658
11659   if ((*arg != '\0') && !isspace (*arg))
11660     error (_("Junk at end of arguments."));
11661
11662   c = XNEW (struct exec_catchpoint);
11663   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11664                    &catch_exec_breakpoint_ops);
11665   c->exec_pathname = NULL;
11666
11667   install_breakpoint (0, &c->base, 1);
11668 }
11669
11670 void
11671 init_ada_exception_breakpoint (struct breakpoint *b,
11672                                struct gdbarch *gdbarch,
11673                                struct symtab_and_line sal,
11674                                char *addr_string,
11675                                const struct breakpoint_ops *ops,
11676                                int tempflag,
11677                                int enabled,
11678                                int from_tty)
11679 {
11680   if (from_tty)
11681     {
11682       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11683       if (!loc_gdbarch)
11684         loc_gdbarch = gdbarch;
11685
11686       describe_other_breakpoints (loc_gdbarch,
11687                                   sal.pspace, sal.pc, sal.section, -1);
11688       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11689          version for exception catchpoints, because two catchpoints
11690          used for different exception names will use the same address.
11691          In this case, a "breakpoint ... also set at..." warning is
11692          unproductive.  Besides, the warning phrasing is also a bit
11693          inappropriate, we should use the word catchpoint, and tell
11694          the user what type of catchpoint it is.  The above is good
11695          enough for now, though.  */
11696     }
11697
11698   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11699
11700   b->enable_state = enabled ? bp_enabled : bp_disabled;
11701   b->disposition = tempflag ? disp_del : disp_donttouch;
11702   b->addr_string = addr_string;
11703   b->language = language_ada;
11704 }
11705
11706 static void
11707 catch_command (char *arg, int from_tty)
11708 {
11709   error (_("Catch requires an event name."));
11710 }
11711 \f
11712
11713 static void
11714 tcatch_command (char *arg, int from_tty)
11715 {
11716   error (_("Catch requires an event name."));
11717 }
11718
11719 /* A qsort comparison function that sorts breakpoints in order.  */
11720
11721 static int
11722 compare_breakpoints (const void *a, const void *b)
11723 {
11724   const breakpoint_p *ba = a;
11725   uintptr_t ua = (uintptr_t) *ba;
11726   const breakpoint_p *bb = b;
11727   uintptr_t ub = (uintptr_t) *bb;
11728
11729   if ((*ba)->number < (*bb)->number)
11730     return -1;
11731   else if ((*ba)->number > (*bb)->number)
11732     return 1;
11733
11734   /* Now sort by address, in case we see, e..g, two breakpoints with
11735      the number 0.  */
11736   if (ua < ub)
11737     return -1;
11738   return ua > ub ? 1 : 0;
11739 }
11740
11741 /* Delete breakpoints by address or line.  */
11742
11743 static void
11744 clear_command (char *arg, int from_tty)
11745 {
11746   struct breakpoint *b, *prev;
11747   VEC(breakpoint_p) *found = 0;
11748   int ix;
11749   int default_match;
11750   struct symtabs_and_lines sals;
11751   struct symtab_and_line sal;
11752   int i;
11753   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11754
11755   if (arg)
11756     {
11757       sals = decode_line_with_current_source (arg,
11758                                               (DECODE_LINE_FUNFIRSTLINE
11759                                                | DECODE_LINE_LIST_MODE));
11760       make_cleanup (xfree, sals.sals);
11761       default_match = 0;
11762     }
11763   else
11764     {
11765       sals.sals = (struct symtab_and_line *)
11766         xmalloc (sizeof (struct symtab_and_line));
11767       make_cleanup (xfree, sals.sals);
11768       init_sal (&sal);          /* Initialize to zeroes.  */
11769
11770       /* Set sal's line, symtab, pc, and pspace to the values
11771          corresponding to the last call to print_frame_info.  If the
11772          codepoint is not valid, this will set all the fields to 0.  */
11773       get_last_displayed_sal (&sal);
11774       if (sal.symtab == 0)
11775         error (_("No source file specified."));
11776
11777       sals.sals[0] = sal;
11778       sals.nelts = 1;
11779
11780       default_match = 1;
11781     }
11782
11783   /* We don't call resolve_sal_pc here.  That's not as bad as it
11784      seems, because all existing breakpoints typically have both
11785      file/line and pc set.  So, if clear is given file/line, we can
11786      match this to existing breakpoint without obtaining pc at all.
11787
11788      We only support clearing given the address explicitly 
11789      present in breakpoint table.  Say, we've set breakpoint 
11790      at file:line.  There were several PC values for that file:line,
11791      due to optimization, all in one block.
11792
11793      We've picked one PC value.  If "clear" is issued with another
11794      PC corresponding to the same file:line, the breakpoint won't
11795      be cleared.  We probably can still clear the breakpoint, but 
11796      since the other PC value is never presented to user, user
11797      can only find it by guessing, and it does not seem important
11798      to support that.  */
11799
11800   /* For each line spec given, delete bps which correspond to it.  Do
11801      it in two passes, solely to preserve the current behavior that
11802      from_tty is forced true if we delete more than one
11803      breakpoint.  */
11804
11805   found = NULL;
11806   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11807   for (i = 0; i < sals.nelts; i++)
11808     {
11809       const char *sal_fullname;
11810
11811       /* If exact pc given, clear bpts at that pc.
11812          If line given (pc == 0), clear all bpts on specified line.
11813          If defaulting, clear all bpts on default line
11814          or at default pc.
11815
11816          defaulting    sal.pc != 0    tests to do
11817
11818          0              1             pc
11819          1              1             pc _and_ line
11820          0              0             line
11821          1              0             <can't happen> */
11822
11823       sal = sals.sals[i];
11824       sal_fullname = (sal.symtab == NULL
11825                       ? NULL : symtab_to_fullname (sal.symtab));
11826
11827       /* Find all matching breakpoints and add them to 'found'.  */
11828       ALL_BREAKPOINTS (b)
11829         {
11830           int match = 0;
11831           /* Are we going to delete b?  */
11832           if (b->type != bp_none && !is_watchpoint (b))
11833             {
11834               struct bp_location *loc = b->loc;
11835               for (; loc; loc = loc->next)
11836                 {
11837                   /* If the user specified file:line, don't allow a PC
11838                      match.  This matches historical gdb behavior.  */
11839                   int pc_match = (!sal.explicit_line
11840                                   && sal.pc
11841                                   && (loc->pspace == sal.pspace)
11842                                   && (loc->address == sal.pc)
11843                                   && (!section_is_overlay (loc->section)
11844                                       || loc->section == sal.section));
11845                   int line_match = 0;
11846
11847                   if ((default_match || sal.explicit_line)
11848                       && loc->symtab != NULL
11849                       && sal_fullname != NULL
11850                       && sal.pspace == loc->pspace
11851                       && loc->line_number == sal.line
11852                       && filename_cmp (symtab_to_fullname (loc->symtab),
11853                                        sal_fullname) == 0)
11854                     line_match = 1;
11855
11856                   if (pc_match || line_match)
11857                     {
11858                       match = 1;
11859                       break;
11860                     }
11861                 }
11862             }
11863
11864           if (match)
11865             VEC_safe_push(breakpoint_p, found, b);
11866         }
11867     }
11868
11869   /* Now go thru the 'found' chain and delete them.  */
11870   if (VEC_empty(breakpoint_p, found))
11871     {
11872       if (arg)
11873         error (_("No breakpoint at %s."), arg);
11874       else
11875         error (_("No breakpoint at this line."));
11876     }
11877
11878   /* Remove duplicates from the vec.  */
11879   qsort (VEC_address (breakpoint_p, found),
11880          VEC_length (breakpoint_p, found),
11881          sizeof (breakpoint_p),
11882          compare_breakpoints);
11883   prev = VEC_index (breakpoint_p, found, 0);
11884   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11885     {
11886       if (b == prev)
11887         {
11888           VEC_ordered_remove (breakpoint_p, found, ix);
11889           --ix;
11890         }
11891     }
11892
11893   if (VEC_length(breakpoint_p, found) > 1)
11894     from_tty = 1;       /* Always report if deleted more than one.  */
11895   if (from_tty)
11896     {
11897       if (VEC_length(breakpoint_p, found) == 1)
11898         printf_unfiltered (_("Deleted breakpoint "));
11899       else
11900         printf_unfiltered (_("Deleted breakpoints "));
11901     }
11902
11903   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11904     {
11905       if (from_tty)
11906         printf_unfiltered ("%d ", b->number);
11907       delete_breakpoint (b);
11908     }
11909   if (from_tty)
11910     putchar_unfiltered ('\n');
11911
11912   do_cleanups (cleanups);
11913 }
11914 \f
11915 /* Delete breakpoint in BS if they are `delete' breakpoints and
11916    all breakpoints that are marked for deletion, whether hit or not.
11917    This is called after any breakpoint is hit, or after errors.  */
11918
11919 void
11920 breakpoint_auto_delete (bpstat bs)
11921 {
11922   struct breakpoint *b, *b_tmp;
11923
11924   for (; bs; bs = bs->next)
11925     if (bs->breakpoint_at
11926         && bs->breakpoint_at->disposition == disp_del
11927         && bs->stop)
11928       delete_breakpoint (bs->breakpoint_at);
11929
11930   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11931   {
11932     if (b->disposition == disp_del_at_next_stop)
11933       delete_breakpoint (b);
11934   }
11935 }
11936
11937 /* A comparison function for bp_location AP and BP being interfaced to
11938    qsort.  Sort elements primarily by their ADDRESS (no matter what
11939    does breakpoint_address_is_meaningful say for its OWNER),
11940    secondarily by ordering first permanent elements and
11941    terciarily just ensuring the array is sorted stable way despite
11942    qsort being an unstable algorithm.  */
11943
11944 static int
11945 bp_location_compare (const void *ap, const void *bp)
11946 {
11947   struct bp_location *a = *(void **) ap;
11948   struct bp_location *b = *(void **) bp;
11949
11950   if (a->address != b->address)
11951     return (a->address > b->address) - (a->address < b->address);
11952
11953   /* Sort locations at the same address by their pspace number, keeping
11954      locations of the same inferior (in a multi-inferior environment)
11955      grouped.  */
11956
11957   if (a->pspace->num != b->pspace->num)
11958     return ((a->pspace->num > b->pspace->num)
11959             - (a->pspace->num < b->pspace->num));
11960
11961   /* Sort permanent breakpoints first.  */
11962   if (a->permanent != b->permanent)
11963     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11964
11965   /* Make the internal GDB representation stable across GDB runs
11966      where A and B memory inside GDB can differ.  Breakpoint locations of
11967      the same type at the same address can be sorted in arbitrary order.  */
11968
11969   if (a->owner->number != b->owner->number)
11970     return ((a->owner->number > b->owner->number)
11971             - (a->owner->number < b->owner->number));
11972
11973   return (a > b) - (a < b);
11974 }
11975
11976 /* Set bp_location_placed_address_before_address_max and
11977    bp_location_shadow_len_after_address_max according to the current
11978    content of the bp_location array.  */
11979
11980 static void
11981 bp_location_target_extensions_update (void)
11982 {
11983   struct bp_location *bl, **blp_tmp;
11984
11985   bp_location_placed_address_before_address_max = 0;
11986   bp_location_shadow_len_after_address_max = 0;
11987
11988   ALL_BP_LOCATIONS (bl, blp_tmp)
11989     {
11990       CORE_ADDR start, end, addr;
11991
11992       if (!bp_location_has_shadow (bl))
11993         continue;
11994
11995       start = bl->target_info.placed_address;
11996       end = start + bl->target_info.shadow_len;
11997
11998       gdb_assert (bl->address >= start);
11999       addr = bl->address - start;
12000       if (addr > bp_location_placed_address_before_address_max)
12001         bp_location_placed_address_before_address_max = addr;
12002
12003       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12004
12005       gdb_assert (bl->address < end);
12006       addr = end - bl->address;
12007       if (addr > bp_location_shadow_len_after_address_max)
12008         bp_location_shadow_len_after_address_max = addr;
12009     }
12010 }
12011
12012 /* Download tracepoint locations if they haven't been.  */
12013
12014 static void
12015 download_tracepoint_locations (void)
12016 {
12017   struct breakpoint *b;
12018   struct cleanup *old_chain;
12019
12020   if (!target_can_download_tracepoint ())
12021     return;
12022
12023   old_chain = save_current_space_and_thread ();
12024
12025   ALL_TRACEPOINTS (b)
12026     {
12027       struct bp_location *bl;
12028       struct tracepoint *t;
12029       int bp_location_downloaded = 0;
12030
12031       if ((b->type == bp_fast_tracepoint
12032            ? !may_insert_fast_tracepoints
12033            : !may_insert_tracepoints))
12034         continue;
12035
12036       for (bl = b->loc; bl; bl = bl->next)
12037         {
12038           /* In tracepoint, locations are _never_ duplicated, so
12039              should_be_inserted is equivalent to
12040              unduplicated_should_be_inserted.  */
12041           if (!should_be_inserted (bl) || bl->inserted)
12042             continue;
12043
12044           switch_to_program_space_and_thread (bl->pspace);
12045
12046           target_download_tracepoint (bl);
12047
12048           bl->inserted = 1;
12049           bp_location_downloaded = 1;
12050         }
12051       t = (struct tracepoint *) b;
12052       t->number_on_target = b->number;
12053       if (bp_location_downloaded)
12054         observer_notify_breakpoint_modified (b);
12055     }
12056
12057   do_cleanups (old_chain);
12058 }
12059
12060 /* Swap the insertion/duplication state between two locations.  */
12061
12062 static void
12063 swap_insertion (struct bp_location *left, struct bp_location *right)
12064 {
12065   const int left_inserted = left->inserted;
12066   const int left_duplicate = left->duplicate;
12067   const int left_needs_update = left->needs_update;
12068   const struct bp_target_info left_target_info = left->target_info;
12069
12070   /* Locations of tracepoints can never be duplicated.  */
12071   if (is_tracepoint (left->owner))
12072     gdb_assert (!left->duplicate);
12073   if (is_tracepoint (right->owner))
12074     gdb_assert (!right->duplicate);
12075
12076   left->inserted = right->inserted;
12077   left->duplicate = right->duplicate;
12078   left->needs_update = right->needs_update;
12079   left->target_info = right->target_info;
12080   right->inserted = left_inserted;
12081   right->duplicate = left_duplicate;
12082   right->needs_update = left_needs_update;
12083   right->target_info = left_target_info;
12084 }
12085
12086 /* Force the re-insertion of the locations at ADDRESS.  This is called
12087    once a new/deleted/modified duplicate location is found and we are evaluating
12088    conditions on the target's side.  Such conditions need to be updated on
12089    the target.  */
12090
12091 static void
12092 force_breakpoint_reinsertion (struct bp_location *bl)
12093 {
12094   struct bp_location **locp = NULL, **loc2p;
12095   struct bp_location *loc;
12096   CORE_ADDR address = 0;
12097   int pspace_num;
12098
12099   address = bl->address;
12100   pspace_num = bl->pspace->num;
12101
12102   /* This is only meaningful if the target is
12103      evaluating conditions and if the user has
12104      opted for condition evaluation on the target's
12105      side.  */
12106   if (gdb_evaluates_breakpoint_condition_p ()
12107       || !target_supports_evaluation_of_breakpoint_conditions ())
12108     return;
12109
12110   /* Flag all breakpoint locations with this address and
12111      the same program space as the location
12112      as "its condition has changed".  We need to
12113      update the conditions on the target's side.  */
12114   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12115     {
12116       loc = *loc2p;
12117
12118       if (!is_breakpoint (loc->owner)
12119           || pspace_num != loc->pspace->num)
12120         continue;
12121
12122       /* Flag the location appropriately.  We use a different state to
12123          let everyone know that we already updated the set of locations
12124          with addr bl->address and program space bl->pspace.  This is so
12125          we don't have to keep calling these functions just to mark locations
12126          that have already been marked.  */
12127       loc->condition_changed = condition_updated;
12128
12129       /* Free the agent expression bytecode as well.  We will compute
12130          it later on.  */
12131       if (loc->cond_bytecode)
12132         {
12133           free_agent_expr (loc->cond_bytecode);
12134           loc->cond_bytecode = NULL;
12135         }
12136     }
12137 }
12138 /* Called whether new breakpoints are created, or existing breakpoints
12139    deleted, to update the global location list and recompute which
12140    locations are duplicate of which.
12141
12142    The INSERT_MODE flag determines whether locations may not, may, or
12143    shall be inserted now.  See 'enum ugll_insert_mode' for more
12144    info.  */
12145
12146 static void
12147 update_global_location_list (enum ugll_insert_mode insert_mode)
12148 {
12149   struct breakpoint *b;
12150   struct bp_location **locp, *loc;
12151   struct cleanup *cleanups;
12152   /* Last breakpoint location address that was marked for update.  */
12153   CORE_ADDR last_addr = 0;
12154   /* Last breakpoint location program space that was marked for update.  */
12155   int last_pspace_num = -1;
12156
12157   /* Used in the duplicates detection below.  When iterating over all
12158      bp_locations, points to the first bp_location of a given address.
12159      Breakpoints and watchpoints of different types are never
12160      duplicates of each other.  Keep one pointer for each type of
12161      breakpoint/watchpoint, so we only need to loop over all locations
12162      once.  */
12163   struct bp_location *bp_loc_first;  /* breakpoint */
12164   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12165   struct bp_location *awp_loc_first; /* access watchpoint */
12166   struct bp_location *rwp_loc_first; /* read watchpoint */
12167
12168   /* Saved former bp_location array which we compare against the newly
12169      built bp_location from the current state of ALL_BREAKPOINTS.  */
12170   struct bp_location **old_location, **old_locp;
12171   unsigned old_location_count;
12172
12173   old_location = bp_location;
12174   old_location_count = bp_location_count;
12175   bp_location = NULL;
12176   bp_location_count = 0;
12177   cleanups = make_cleanup (xfree, old_location);
12178
12179   ALL_BREAKPOINTS (b)
12180     for (loc = b->loc; loc; loc = loc->next)
12181       bp_location_count++;
12182
12183   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12184   locp = bp_location;
12185   ALL_BREAKPOINTS (b)
12186     for (loc = b->loc; loc; loc = loc->next)
12187       *locp++ = loc;
12188   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12189          bp_location_compare);
12190
12191   bp_location_target_extensions_update ();
12192
12193   /* Identify bp_location instances that are no longer present in the
12194      new list, and therefore should be freed.  Note that it's not
12195      necessary that those locations should be removed from inferior --
12196      if there's another location at the same address (previously
12197      marked as duplicate), we don't need to remove/insert the
12198      location.
12199      
12200      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12201      and former bp_location array state respectively.  */
12202
12203   locp = bp_location;
12204   for (old_locp = old_location; old_locp < old_location + old_location_count;
12205        old_locp++)
12206     {
12207       struct bp_location *old_loc = *old_locp;
12208       struct bp_location **loc2p;
12209
12210       /* Tells if 'old_loc' is found among the new locations.  If
12211          not, we have to free it.  */
12212       int found_object = 0;
12213       /* Tells if the location should remain inserted in the target.  */
12214       int keep_in_target = 0;
12215       int removed = 0;
12216
12217       /* Skip LOCP entries which will definitely never be needed.
12218          Stop either at or being the one matching OLD_LOC.  */
12219       while (locp < bp_location + bp_location_count
12220              && (*locp)->address < old_loc->address)
12221         locp++;
12222
12223       for (loc2p = locp;
12224            (loc2p < bp_location + bp_location_count
12225             && (*loc2p)->address == old_loc->address);
12226            loc2p++)
12227         {
12228           /* Check if this is a new/duplicated location or a duplicated
12229              location that had its condition modified.  If so, we want to send
12230              its condition to the target if evaluation of conditions is taking
12231              place there.  */
12232           if ((*loc2p)->condition_changed == condition_modified
12233               && (last_addr != old_loc->address
12234                   || last_pspace_num != old_loc->pspace->num))
12235             {
12236               force_breakpoint_reinsertion (*loc2p);
12237               last_pspace_num = old_loc->pspace->num;
12238             }
12239
12240           if (*loc2p == old_loc)
12241             found_object = 1;
12242         }
12243
12244       /* We have already handled this address, update it so that we don't
12245          have to go through updates again.  */
12246       last_addr = old_loc->address;
12247
12248       /* Target-side condition evaluation: Handle deleted locations.  */
12249       if (!found_object)
12250         force_breakpoint_reinsertion (old_loc);
12251
12252       /* If this location is no longer present, and inserted, look if
12253          there's maybe a new location at the same address.  If so,
12254          mark that one inserted, and don't remove this one.  This is
12255          needed so that we don't have a time window where a breakpoint
12256          at certain location is not inserted.  */
12257
12258       if (old_loc->inserted)
12259         {
12260           /* If the location is inserted now, we might have to remove
12261              it.  */
12262
12263           if (found_object && should_be_inserted (old_loc))
12264             {
12265               /* The location is still present in the location list,
12266                  and still should be inserted.  Don't do anything.  */
12267               keep_in_target = 1;
12268             }
12269           else
12270             {
12271               /* This location still exists, but it won't be kept in the
12272                  target since it may have been disabled.  We proceed to
12273                  remove its target-side condition.  */
12274
12275               /* The location is either no longer present, or got
12276                  disabled.  See if there's another location at the
12277                  same address, in which case we don't need to remove
12278                  this one from the target.  */
12279
12280               /* OLD_LOC comes from existing struct breakpoint.  */
12281               if (breakpoint_address_is_meaningful (old_loc->owner))
12282                 {
12283                   for (loc2p = locp;
12284                        (loc2p < bp_location + bp_location_count
12285                         && (*loc2p)->address == old_loc->address);
12286                        loc2p++)
12287                     {
12288                       struct bp_location *loc2 = *loc2p;
12289
12290                       if (breakpoint_locations_match (loc2, old_loc))
12291                         {
12292                           /* Read watchpoint locations are switched to
12293                              access watchpoints, if the former are not
12294                              supported, but the latter are.  */
12295                           if (is_hardware_watchpoint (old_loc->owner))
12296                             {
12297                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12298                               loc2->watchpoint_type = old_loc->watchpoint_type;
12299                             }
12300
12301                           /* loc2 is a duplicated location. We need to check
12302                              if it should be inserted in case it will be
12303                              unduplicated.  */
12304                           if (loc2 != old_loc
12305                               && unduplicated_should_be_inserted (loc2))
12306                             {
12307                               swap_insertion (old_loc, loc2);
12308                               keep_in_target = 1;
12309                               break;
12310                             }
12311                         }
12312                     }
12313                 }
12314             }
12315
12316           if (!keep_in_target)
12317             {
12318               if (remove_breakpoint (old_loc, mark_uninserted))
12319                 {
12320                   /* This is just about all we can do.  We could keep
12321                      this location on the global list, and try to
12322                      remove it next time, but there's no particular
12323                      reason why we will succeed next time.
12324                      
12325                      Note that at this point, old_loc->owner is still
12326                      valid, as delete_breakpoint frees the breakpoint
12327                      only after calling us.  */
12328                   printf_filtered (_("warning: Error removing "
12329                                      "breakpoint %d\n"), 
12330                                    old_loc->owner->number);
12331                 }
12332               removed = 1;
12333             }
12334         }
12335
12336       if (!found_object)
12337         {
12338           if (removed && non_stop
12339               && need_moribund_for_location_type (old_loc))
12340             {
12341               /* This location was removed from the target.  In
12342                  non-stop mode, a race condition is possible where
12343                  we've removed a breakpoint, but stop events for that
12344                  breakpoint are already queued and will arrive later.
12345                  We apply an heuristic to be able to distinguish such
12346                  SIGTRAPs from other random SIGTRAPs: we keep this
12347                  breakpoint location for a bit, and will retire it
12348                  after we see some number of events.  The theory here
12349                  is that reporting of events should, "on the average",
12350                  be fair, so after a while we'll see events from all
12351                  threads that have anything of interest, and no longer
12352                  need to keep this breakpoint location around.  We
12353                  don't hold locations forever so to reduce chances of
12354                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12355                  SIGTRAP.
12356
12357                  The heuristic failing can be disastrous on
12358                  decr_pc_after_break targets.
12359
12360                  On decr_pc_after_break targets, like e.g., x86-linux,
12361                  if we fail to recognize a late breakpoint SIGTRAP,
12362                  because events_till_retirement has reached 0 too
12363                  soon, we'll fail to do the PC adjustment, and report
12364                  a random SIGTRAP to the user.  When the user resumes
12365                  the inferior, it will most likely immediately crash
12366                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12367                  corrupted, because of being resumed e.g., in the
12368                  middle of a multi-byte instruction, or skipped a
12369                  one-byte instruction.  This was actually seen happen
12370                  on native x86-linux, and should be less rare on
12371                  targets that do not support new thread events, like
12372                  remote, due to the heuristic depending on
12373                  thread_count.
12374
12375                  Mistaking a random SIGTRAP for a breakpoint trap
12376                  causes similar symptoms (PC adjustment applied when
12377                  it shouldn't), but then again, playing with SIGTRAPs
12378                  behind the debugger's back is asking for trouble.
12379
12380                  Since hardware watchpoint traps are always
12381                  distinguishable from other traps, so we don't need to
12382                  apply keep hardware watchpoint moribund locations
12383                  around.  We simply always ignore hardware watchpoint
12384                  traps we can no longer explain.  */
12385
12386               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12387               old_loc->owner = NULL;
12388
12389               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12390             }
12391           else
12392             {
12393               old_loc->owner = NULL;
12394               decref_bp_location (&old_loc);
12395             }
12396         }
12397     }
12398
12399   /* Rescan breakpoints at the same address and section, marking the
12400      first one as "first" and any others as "duplicates".  This is so
12401      that the bpt instruction is only inserted once.  If we have a
12402      permanent breakpoint at the same place as BPT, make that one the
12403      official one, and the rest as duplicates.  Permanent breakpoints
12404      are sorted first for the same address.
12405
12406      Do the same for hardware watchpoints, but also considering the
12407      watchpoint's type (regular/access/read) and length.  */
12408
12409   bp_loc_first = NULL;
12410   wp_loc_first = NULL;
12411   awp_loc_first = NULL;
12412   rwp_loc_first = NULL;
12413   ALL_BP_LOCATIONS (loc, locp)
12414     {
12415       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12416          non-NULL.  */
12417       struct bp_location **loc_first_p;
12418       b = loc->owner;
12419
12420       if (!unduplicated_should_be_inserted (loc)
12421           || !breakpoint_address_is_meaningful (b)
12422           /* Don't detect duplicate for tracepoint locations because they are
12423            never duplicated.  See the comments in field `duplicate' of
12424            `struct bp_location'.  */
12425           || is_tracepoint (b))
12426         {
12427           /* Clear the condition modification flag.  */
12428           loc->condition_changed = condition_unchanged;
12429           continue;
12430         }
12431
12432       /* Permanent breakpoint should always be inserted.  */
12433       if (loc->permanent && ! loc->inserted)
12434         internal_error (__FILE__, __LINE__,
12435                         _("allegedly permanent breakpoint is not "
12436                         "actually inserted"));
12437
12438       if (b->type == bp_hardware_watchpoint)
12439         loc_first_p = &wp_loc_first;
12440       else if (b->type == bp_read_watchpoint)
12441         loc_first_p = &rwp_loc_first;
12442       else if (b->type == bp_access_watchpoint)
12443         loc_first_p = &awp_loc_first;
12444       else
12445         loc_first_p = &bp_loc_first;
12446
12447       if (*loc_first_p == NULL
12448           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12449           || !breakpoint_locations_match (loc, *loc_first_p))
12450         {
12451           *loc_first_p = loc;
12452           loc->duplicate = 0;
12453
12454           if (is_breakpoint (loc->owner) && loc->condition_changed)
12455             {
12456               loc->needs_update = 1;
12457               /* Clear the condition modification flag.  */
12458               loc->condition_changed = condition_unchanged;
12459             }
12460           continue;
12461         }
12462
12463
12464       /* This and the above ensure the invariant that the first location
12465          is not duplicated, and is the inserted one.
12466          All following are marked as duplicated, and are not inserted.  */
12467       if (loc->inserted)
12468         swap_insertion (loc, *loc_first_p);
12469       loc->duplicate = 1;
12470
12471       /* Clear the condition modification flag.  */
12472       loc->condition_changed = condition_unchanged;
12473
12474       if (loc->inserted && !loc->permanent
12475           && (*loc_first_p)->permanent)
12476         internal_error (__FILE__, __LINE__,
12477                         _("another breakpoint was inserted on top of "
12478                         "a permanent breakpoint"));
12479     }
12480
12481   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12482     {
12483       if (insert_mode != UGLL_DONT_INSERT)
12484         insert_breakpoint_locations ();
12485       else
12486         {
12487           /* Even though the caller told us to not insert new
12488              locations, we may still need to update conditions on the
12489              target's side of breakpoints that were already inserted
12490              if the target is evaluating breakpoint conditions.  We
12491              only update conditions for locations that are marked
12492              "needs_update".  */
12493           update_inserted_breakpoint_locations ();
12494         }
12495     }
12496
12497   if (insert_mode != UGLL_DONT_INSERT)
12498     download_tracepoint_locations ();
12499
12500   do_cleanups (cleanups);
12501 }
12502
12503 void
12504 breakpoint_retire_moribund (void)
12505 {
12506   struct bp_location *loc;
12507   int ix;
12508
12509   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12510     if (--(loc->events_till_retirement) == 0)
12511       {
12512         decref_bp_location (&loc);
12513         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12514         --ix;
12515       }
12516 }
12517
12518 static void
12519 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12520 {
12521
12522   TRY
12523     {
12524       update_global_location_list (insert_mode);
12525     }
12526   CATCH (e, RETURN_MASK_ERROR)
12527     {
12528     }
12529   END_CATCH
12530 }
12531
12532 /* Clear BKP from a BPS.  */
12533
12534 static void
12535 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12536 {
12537   bpstat bs;
12538
12539   for (bs = bps; bs; bs = bs->next)
12540     if (bs->breakpoint_at == bpt)
12541       {
12542         bs->breakpoint_at = NULL;
12543         bs->old_val = NULL;
12544         /* bs->commands will be freed later.  */
12545       }
12546 }
12547
12548 /* Callback for iterate_over_threads.  */
12549 static int
12550 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12551 {
12552   struct breakpoint *bpt = data;
12553
12554   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12555   return 0;
12556 }
12557
12558 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12559    callbacks.  */
12560
12561 static void
12562 say_where (struct breakpoint *b)
12563 {
12564   struct value_print_options opts;
12565
12566   get_user_print_options (&opts);
12567
12568   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12569      single string.  */
12570   if (b->loc == NULL)
12571     {
12572       printf_filtered (_(" (%s) pending."), b->addr_string);
12573     }
12574   else
12575     {
12576       if (opts.addressprint || b->loc->symtab == NULL)
12577         {
12578           printf_filtered (" at ");
12579           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12580                           gdb_stdout);
12581         }
12582       if (b->loc->symtab != NULL)
12583         {
12584           /* If there is a single location, we can print the location
12585              more nicely.  */
12586           if (b->loc->next == NULL)
12587             printf_filtered (": file %s, line %d.",
12588                              symtab_to_filename_for_display (b->loc->symtab),
12589                              b->loc->line_number);
12590           else
12591             /* This is not ideal, but each location may have a
12592                different file name, and this at least reflects the
12593                real situation somewhat.  */
12594             printf_filtered (": %s.", b->addr_string);
12595         }
12596
12597       if (b->loc->next)
12598         {
12599           struct bp_location *loc = b->loc;
12600           int n = 0;
12601           for (; loc; loc = loc->next)
12602             ++n;
12603           printf_filtered (" (%d locations)", n);
12604         }
12605     }
12606 }
12607
12608 /* Default bp_location_ops methods.  */
12609
12610 static void
12611 bp_location_dtor (struct bp_location *self)
12612 {
12613   xfree (self->cond);
12614   if (self->cond_bytecode)
12615     free_agent_expr (self->cond_bytecode);
12616   xfree (self->function_name);
12617
12618   VEC_free (agent_expr_p, self->target_info.conditions);
12619   VEC_free (agent_expr_p, self->target_info.tcommands);
12620 }
12621
12622 static const struct bp_location_ops bp_location_ops =
12623 {
12624   bp_location_dtor
12625 };
12626
12627 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12628    inherit from.  */
12629
12630 static void
12631 base_breakpoint_dtor (struct breakpoint *self)
12632 {
12633   decref_counted_command_line (&self->commands);
12634   xfree (self->cond_string);
12635   xfree (self->extra_string);
12636   xfree (self->addr_string);
12637   xfree (self->filter);
12638   xfree (self->addr_string_range_end);
12639 }
12640
12641 static struct bp_location *
12642 base_breakpoint_allocate_location (struct breakpoint *self)
12643 {
12644   struct bp_location *loc;
12645
12646   loc = XNEW (struct bp_location);
12647   init_bp_location (loc, &bp_location_ops, self);
12648   return loc;
12649 }
12650
12651 static void
12652 base_breakpoint_re_set (struct breakpoint *b)
12653 {
12654   /* Nothing to re-set. */
12655 }
12656
12657 #define internal_error_pure_virtual_called() \
12658   gdb_assert_not_reached ("pure virtual function called")
12659
12660 static int
12661 base_breakpoint_insert_location (struct bp_location *bl)
12662 {
12663   internal_error_pure_virtual_called ();
12664 }
12665
12666 static int
12667 base_breakpoint_remove_location (struct bp_location *bl)
12668 {
12669   internal_error_pure_virtual_called ();
12670 }
12671
12672 static int
12673 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12674                                 struct address_space *aspace,
12675                                 CORE_ADDR bp_addr,
12676                                 const struct target_waitstatus *ws)
12677 {
12678   internal_error_pure_virtual_called ();
12679 }
12680
12681 static void
12682 base_breakpoint_check_status (bpstat bs)
12683 {
12684   /* Always stop.   */
12685 }
12686
12687 /* A "works_in_software_mode" breakpoint_ops method that just internal
12688    errors.  */
12689
12690 static int
12691 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12692 {
12693   internal_error_pure_virtual_called ();
12694 }
12695
12696 /* A "resources_needed" breakpoint_ops method that just internal
12697    errors.  */
12698
12699 static int
12700 base_breakpoint_resources_needed (const struct bp_location *bl)
12701 {
12702   internal_error_pure_virtual_called ();
12703 }
12704
12705 static enum print_stop_action
12706 base_breakpoint_print_it (bpstat bs)
12707 {
12708   internal_error_pure_virtual_called ();
12709 }
12710
12711 static void
12712 base_breakpoint_print_one_detail (const struct breakpoint *self,
12713                                   struct ui_out *uiout)
12714 {
12715   /* nothing */
12716 }
12717
12718 static void
12719 base_breakpoint_print_mention (struct breakpoint *b)
12720 {
12721   internal_error_pure_virtual_called ();
12722 }
12723
12724 static void
12725 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12726 {
12727   internal_error_pure_virtual_called ();
12728 }
12729
12730 static void
12731 base_breakpoint_create_sals_from_address (char **arg,
12732                                           struct linespec_result *canonical,
12733                                           enum bptype type_wanted,
12734                                           char *addr_start,
12735                                           char **copy_arg)
12736 {
12737   internal_error_pure_virtual_called ();
12738 }
12739
12740 static void
12741 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12742                                         struct linespec_result *c,
12743                                         char *cond_string,
12744                                         char *extra_string,
12745                                         enum bptype type_wanted,
12746                                         enum bpdisp disposition,
12747                                         int thread,
12748                                         int task, int ignore_count,
12749                                         const struct breakpoint_ops *o,
12750                                         int from_tty, int enabled,
12751                                         int internal, unsigned flags)
12752 {
12753   internal_error_pure_virtual_called ();
12754 }
12755
12756 static void
12757 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12758                                  struct symtabs_and_lines *sals)
12759 {
12760   internal_error_pure_virtual_called ();
12761 }
12762
12763 /* The default 'explains_signal' method.  */
12764
12765 static int
12766 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12767 {
12768   return 1;
12769 }
12770
12771 /* The default "after_condition_true" method.  */
12772
12773 static void
12774 base_breakpoint_after_condition_true (struct bpstats *bs)
12775 {
12776   /* Nothing to do.   */
12777 }
12778
12779 struct breakpoint_ops base_breakpoint_ops =
12780 {
12781   base_breakpoint_dtor,
12782   base_breakpoint_allocate_location,
12783   base_breakpoint_re_set,
12784   base_breakpoint_insert_location,
12785   base_breakpoint_remove_location,
12786   base_breakpoint_breakpoint_hit,
12787   base_breakpoint_check_status,
12788   base_breakpoint_resources_needed,
12789   base_breakpoint_works_in_software_mode,
12790   base_breakpoint_print_it,
12791   NULL,
12792   base_breakpoint_print_one_detail,
12793   base_breakpoint_print_mention,
12794   base_breakpoint_print_recreate,
12795   base_breakpoint_create_sals_from_address,
12796   base_breakpoint_create_breakpoints_sal,
12797   base_breakpoint_decode_linespec,
12798   base_breakpoint_explains_signal,
12799   base_breakpoint_after_condition_true,
12800 };
12801
12802 /* Default breakpoint_ops methods.  */
12803
12804 static void
12805 bkpt_re_set (struct breakpoint *b)
12806 {
12807   /* FIXME: is this still reachable?  */
12808   if (b->addr_string == NULL)
12809     {
12810       /* Anything without a string can't be re-set.  */
12811       delete_breakpoint (b);
12812       return;
12813     }
12814
12815   breakpoint_re_set_default (b);
12816 }
12817
12818 static int
12819 bkpt_insert_location (struct bp_location *bl)
12820 {
12821   if (bl->loc_type == bp_loc_hardware_breakpoint)
12822     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12823   else
12824     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12825 }
12826
12827 static int
12828 bkpt_remove_location (struct bp_location *bl)
12829 {
12830   if (bl->loc_type == bp_loc_hardware_breakpoint)
12831     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12832   else
12833     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12834 }
12835
12836 static int
12837 bkpt_breakpoint_hit (const struct bp_location *bl,
12838                      struct address_space *aspace, CORE_ADDR bp_addr,
12839                      const struct target_waitstatus *ws)
12840 {
12841   if (ws->kind != TARGET_WAITKIND_STOPPED
12842       || ws->value.sig != GDB_SIGNAL_TRAP)
12843     return 0;
12844
12845   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12846                                  aspace, bp_addr))
12847     return 0;
12848
12849   if (overlay_debugging         /* unmapped overlay section */
12850       && section_is_overlay (bl->section)
12851       && !section_is_mapped (bl->section))
12852     return 0;
12853
12854   return 1;
12855 }
12856
12857 static int
12858 dprintf_breakpoint_hit (const struct bp_location *bl,
12859                         struct address_space *aspace, CORE_ADDR bp_addr,
12860                         const struct target_waitstatus *ws)
12861 {
12862   if (dprintf_style == dprintf_style_agent
12863       && target_can_run_breakpoint_commands ())
12864     {
12865       /* An agent-style dprintf never causes a stop.  If we see a trap
12866          for this address it must be for a breakpoint that happens to
12867          be set at the same address.  */
12868       return 0;
12869     }
12870
12871   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12872 }
12873
12874 static int
12875 bkpt_resources_needed (const struct bp_location *bl)
12876 {
12877   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12878
12879   return 1;
12880 }
12881
12882 static enum print_stop_action
12883 bkpt_print_it (bpstat bs)
12884 {
12885   struct breakpoint *b;
12886   const struct bp_location *bl;
12887   int bp_temp;
12888   struct ui_out *uiout = current_uiout;
12889
12890   gdb_assert (bs->bp_location_at != NULL);
12891
12892   bl = bs->bp_location_at;
12893   b = bs->breakpoint_at;
12894
12895   bp_temp = b->disposition == disp_del;
12896   if (bl->address != bl->requested_address)
12897     breakpoint_adjustment_warning (bl->requested_address,
12898                                    bl->address,
12899                                    b->number, 1);
12900   annotate_breakpoint (b->number);
12901   if (bp_temp)
12902     ui_out_text (uiout, "\nTemporary breakpoint ");
12903   else
12904     ui_out_text (uiout, "\nBreakpoint ");
12905   if (ui_out_is_mi_like_p (uiout))
12906     {
12907       ui_out_field_string (uiout, "reason",
12908                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12909       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12910     }
12911   ui_out_field_int (uiout, "bkptno", b->number);
12912   ui_out_text (uiout, ", ");
12913
12914   return PRINT_SRC_AND_LOC;
12915 }
12916
12917 static void
12918 bkpt_print_mention (struct breakpoint *b)
12919 {
12920   if (ui_out_is_mi_like_p (current_uiout))
12921     return;
12922
12923   switch (b->type)
12924     {
12925     case bp_breakpoint:
12926     case bp_gnu_ifunc_resolver:
12927       if (b->disposition == disp_del)
12928         printf_filtered (_("Temporary breakpoint"));
12929       else
12930         printf_filtered (_("Breakpoint"));
12931       printf_filtered (_(" %d"), b->number);
12932       if (b->type == bp_gnu_ifunc_resolver)
12933         printf_filtered (_(" at gnu-indirect-function resolver"));
12934       break;
12935     case bp_hardware_breakpoint:
12936       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12937       break;
12938     case bp_dprintf:
12939       printf_filtered (_("Dprintf %d"), b->number);
12940       break;
12941     }
12942
12943   say_where (b);
12944 }
12945
12946 static void
12947 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12948 {
12949   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12950     fprintf_unfiltered (fp, "tbreak");
12951   else if (tp->type == bp_breakpoint)
12952     fprintf_unfiltered (fp, "break");
12953   else if (tp->type == bp_hardware_breakpoint
12954            && tp->disposition == disp_del)
12955     fprintf_unfiltered (fp, "thbreak");
12956   else if (tp->type == bp_hardware_breakpoint)
12957     fprintf_unfiltered (fp, "hbreak");
12958   else
12959     internal_error (__FILE__, __LINE__,
12960                     _("unhandled breakpoint type %d"), (int) tp->type);
12961
12962   fprintf_unfiltered (fp, " %s", tp->addr_string);
12963   print_recreate_thread (tp, fp);
12964 }
12965
12966 static void
12967 bkpt_create_sals_from_address (char **arg,
12968                                struct linespec_result *canonical,
12969                                enum bptype type_wanted,
12970                                char *addr_start, char **copy_arg)
12971 {
12972   create_sals_from_address_default (arg, canonical, type_wanted,
12973                                     addr_start, copy_arg);
12974 }
12975
12976 static void
12977 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12978                              struct linespec_result *canonical,
12979                              char *cond_string,
12980                              char *extra_string,
12981                              enum bptype type_wanted,
12982                              enum bpdisp disposition,
12983                              int thread,
12984                              int task, int ignore_count,
12985                              const struct breakpoint_ops *ops,
12986                              int from_tty, int enabled,
12987                              int internal, unsigned flags)
12988 {
12989   create_breakpoints_sal_default (gdbarch, canonical,
12990                                   cond_string, extra_string,
12991                                   type_wanted,
12992                                   disposition, thread, task,
12993                                   ignore_count, ops, from_tty,
12994                                   enabled, internal, flags);
12995 }
12996
12997 static void
12998 bkpt_decode_linespec (struct breakpoint *b, char **s,
12999                       struct symtabs_and_lines *sals)
13000 {
13001   decode_linespec_default (b, s, sals);
13002 }
13003
13004 /* Virtual table for internal breakpoints.  */
13005
13006 static void
13007 internal_bkpt_re_set (struct breakpoint *b)
13008 {
13009   switch (b->type)
13010     {
13011       /* Delete overlay event and longjmp master breakpoints; they
13012          will be reset later by breakpoint_re_set.  */
13013     case bp_overlay_event:
13014     case bp_longjmp_master:
13015     case bp_std_terminate_master:
13016     case bp_exception_master:
13017       delete_breakpoint (b);
13018       break;
13019
13020       /* This breakpoint is special, it's set up when the inferior
13021          starts and we really don't want to touch it.  */
13022     case bp_shlib_event:
13023
13024       /* Like bp_shlib_event, this breakpoint type is special.  Once
13025          it is set up, we do not want to touch it.  */
13026     case bp_thread_event:
13027       break;
13028     }
13029 }
13030
13031 static void
13032 internal_bkpt_check_status (bpstat bs)
13033 {
13034   if (bs->breakpoint_at->type == bp_shlib_event)
13035     {
13036       /* If requested, stop when the dynamic linker notifies GDB of
13037          events.  This allows the user to get control and place
13038          breakpoints in initializer routines for dynamically loaded
13039          objects (among other things).  */
13040       bs->stop = stop_on_solib_events;
13041       bs->print = stop_on_solib_events;
13042     }
13043   else
13044     bs->stop = 0;
13045 }
13046
13047 static enum print_stop_action
13048 internal_bkpt_print_it (bpstat bs)
13049 {
13050   struct breakpoint *b;
13051
13052   b = bs->breakpoint_at;
13053
13054   switch (b->type)
13055     {
13056     case bp_shlib_event:
13057       /* Did we stop because the user set the stop_on_solib_events
13058          variable?  (If so, we report this as a generic, "Stopped due
13059          to shlib event" message.) */
13060       print_solib_event (0);
13061       break;
13062
13063     case bp_thread_event:
13064       /* Not sure how we will get here.
13065          GDB should not stop for these breakpoints.  */
13066       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13067       break;
13068
13069     case bp_overlay_event:
13070       /* By analogy with the thread event, GDB should not stop for these.  */
13071       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13072       break;
13073
13074     case bp_longjmp_master:
13075       /* These should never be enabled.  */
13076       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13077       break;
13078
13079     case bp_std_terminate_master:
13080       /* These should never be enabled.  */
13081       printf_filtered (_("std::terminate Master Breakpoint: "
13082                          "gdb should not stop!\n"));
13083       break;
13084
13085     case bp_exception_master:
13086       /* These should never be enabled.  */
13087       printf_filtered (_("Exception Master Breakpoint: "
13088                          "gdb should not stop!\n"));
13089       break;
13090     }
13091
13092   return PRINT_NOTHING;
13093 }
13094
13095 static void
13096 internal_bkpt_print_mention (struct breakpoint *b)
13097 {
13098   /* Nothing to mention.  These breakpoints are internal.  */
13099 }
13100
13101 /* Virtual table for momentary breakpoints  */
13102
13103 static void
13104 momentary_bkpt_re_set (struct breakpoint *b)
13105 {
13106   /* Keep temporary breakpoints, which can be encountered when we step
13107      over a dlopen call and solib_add is resetting the breakpoints.
13108      Otherwise these should have been blown away via the cleanup chain
13109      or by breakpoint_init_inferior when we rerun the executable.  */
13110 }
13111
13112 static void
13113 momentary_bkpt_check_status (bpstat bs)
13114 {
13115   /* Nothing.  The point of these breakpoints is causing a stop.  */
13116 }
13117
13118 static enum print_stop_action
13119 momentary_bkpt_print_it (bpstat bs)
13120 {
13121   struct ui_out *uiout = current_uiout;
13122
13123   if (ui_out_is_mi_like_p (uiout))
13124     {
13125       struct breakpoint *b = bs->breakpoint_at;
13126
13127       switch (b->type)
13128         {
13129         case bp_finish:
13130           ui_out_field_string
13131             (uiout, "reason",
13132              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13133           break;
13134
13135         case bp_until:
13136           ui_out_field_string
13137             (uiout, "reason",
13138              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13139           break;
13140         }
13141     }
13142
13143   return PRINT_UNKNOWN;
13144 }
13145
13146 static void
13147 momentary_bkpt_print_mention (struct breakpoint *b)
13148 {
13149   /* Nothing to mention.  These breakpoints are internal.  */
13150 }
13151
13152 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13153
13154    It gets cleared already on the removal of the first one of such placed
13155    breakpoints.  This is OK as they get all removed altogether.  */
13156
13157 static void
13158 longjmp_bkpt_dtor (struct breakpoint *self)
13159 {
13160   struct thread_info *tp = find_thread_id (self->thread);
13161
13162   if (tp)
13163     tp->initiating_frame = null_frame_id;
13164
13165   momentary_breakpoint_ops.dtor (self);
13166 }
13167
13168 /* Specific methods for probe breakpoints.  */
13169
13170 static int
13171 bkpt_probe_insert_location (struct bp_location *bl)
13172 {
13173   int v = bkpt_insert_location (bl);
13174
13175   if (v == 0)
13176     {
13177       /* The insertion was successful, now let's set the probe's semaphore
13178          if needed.  */
13179       if (bl->probe.probe->pops->set_semaphore != NULL)
13180         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13181                                               bl->probe.objfile,
13182                                               bl->gdbarch);
13183     }
13184
13185   return v;
13186 }
13187
13188 static int
13189 bkpt_probe_remove_location (struct bp_location *bl)
13190 {
13191   /* Let's clear the semaphore before removing the location.  */
13192   if (bl->probe.probe->pops->clear_semaphore != NULL)
13193     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13194                                             bl->probe.objfile,
13195                                             bl->gdbarch);
13196
13197   return bkpt_remove_location (bl);
13198 }
13199
13200 static void
13201 bkpt_probe_create_sals_from_address (char **arg,
13202                                      struct linespec_result *canonical,
13203                                      enum bptype type_wanted,
13204                                      char *addr_start, char **copy_arg)
13205 {
13206   struct linespec_sals lsal;
13207
13208   lsal.sals = parse_probes (arg, canonical);
13209
13210   *copy_arg = xstrdup (canonical->addr_string);
13211   lsal.canonical = xstrdup (*copy_arg);
13212
13213   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13214 }
13215
13216 static void
13217 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13218                             struct symtabs_and_lines *sals)
13219 {
13220   *sals = parse_probes (s, NULL);
13221   if (!sals->sals)
13222     error (_("probe not found"));
13223 }
13224
13225 /* The breakpoint_ops structure to be used in tracepoints.  */
13226
13227 static void
13228 tracepoint_re_set (struct breakpoint *b)
13229 {
13230   breakpoint_re_set_default (b);
13231 }
13232
13233 static int
13234 tracepoint_breakpoint_hit (const struct bp_location *bl,
13235                            struct address_space *aspace, CORE_ADDR bp_addr,
13236                            const struct target_waitstatus *ws)
13237 {
13238   /* By definition, the inferior does not report stops at
13239      tracepoints.  */
13240   return 0;
13241 }
13242
13243 static void
13244 tracepoint_print_one_detail (const struct breakpoint *self,
13245                              struct ui_out *uiout)
13246 {
13247   struct tracepoint *tp = (struct tracepoint *) self;
13248   if (tp->static_trace_marker_id)
13249     {
13250       gdb_assert (self->type == bp_static_tracepoint);
13251
13252       ui_out_text (uiout, "\tmarker id is ");
13253       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13254                            tp->static_trace_marker_id);
13255       ui_out_text (uiout, "\n");
13256     }
13257 }
13258
13259 static void
13260 tracepoint_print_mention (struct breakpoint *b)
13261 {
13262   if (ui_out_is_mi_like_p (current_uiout))
13263     return;
13264
13265   switch (b->type)
13266     {
13267     case bp_tracepoint:
13268       printf_filtered (_("Tracepoint"));
13269       printf_filtered (_(" %d"), b->number);
13270       break;
13271     case bp_fast_tracepoint:
13272       printf_filtered (_("Fast tracepoint"));
13273       printf_filtered (_(" %d"), b->number);
13274       break;
13275     case bp_static_tracepoint:
13276       printf_filtered (_("Static tracepoint"));
13277       printf_filtered (_(" %d"), b->number);
13278       break;
13279     default:
13280       internal_error (__FILE__, __LINE__,
13281                       _("unhandled tracepoint type %d"), (int) b->type);
13282     }
13283
13284   say_where (b);
13285 }
13286
13287 static void
13288 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13289 {
13290   struct tracepoint *tp = (struct tracepoint *) self;
13291
13292   if (self->type == bp_fast_tracepoint)
13293     fprintf_unfiltered (fp, "ftrace");
13294   if (self->type == bp_static_tracepoint)
13295     fprintf_unfiltered (fp, "strace");
13296   else if (self->type == bp_tracepoint)
13297     fprintf_unfiltered (fp, "trace");
13298   else
13299     internal_error (__FILE__, __LINE__,
13300                     _("unhandled tracepoint type %d"), (int) self->type);
13301
13302   fprintf_unfiltered (fp, " %s", self->addr_string);
13303   print_recreate_thread (self, fp);
13304
13305   if (tp->pass_count)
13306     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13307 }
13308
13309 static void
13310 tracepoint_create_sals_from_address (char **arg,
13311                                      struct linespec_result *canonical,
13312                                      enum bptype type_wanted,
13313                                      char *addr_start, char **copy_arg)
13314 {
13315   create_sals_from_address_default (arg, canonical, type_wanted,
13316                                     addr_start, copy_arg);
13317 }
13318
13319 static void
13320 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13321                                    struct linespec_result *canonical,
13322                                    char *cond_string,
13323                                    char *extra_string,
13324                                    enum bptype type_wanted,
13325                                    enum bpdisp disposition,
13326                                    int thread,
13327                                    int task, int ignore_count,
13328                                    const struct breakpoint_ops *ops,
13329                                    int from_tty, int enabled,
13330                                    int internal, unsigned flags)
13331 {
13332   create_breakpoints_sal_default (gdbarch, canonical,
13333                                   cond_string, extra_string,
13334                                   type_wanted,
13335                                   disposition, thread, task,
13336                                   ignore_count, ops, from_tty,
13337                                   enabled, internal, flags);
13338 }
13339
13340 static void
13341 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13342                             struct symtabs_and_lines *sals)
13343 {
13344   decode_linespec_default (b, s, sals);
13345 }
13346
13347 struct breakpoint_ops tracepoint_breakpoint_ops;
13348
13349 /* The breakpoint_ops structure to be use on tracepoints placed in a
13350    static probe.  */
13351
13352 static void
13353 tracepoint_probe_create_sals_from_address (char **arg,
13354                                            struct linespec_result *canonical,
13355                                            enum bptype type_wanted,
13356                                            char *addr_start, char **copy_arg)
13357 {
13358   /* We use the same method for breakpoint on probes.  */
13359   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13360                                        addr_start, copy_arg);
13361 }
13362
13363 static void
13364 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13365                                   struct symtabs_and_lines *sals)
13366 {
13367   /* We use the same method for breakpoint on probes.  */
13368   bkpt_probe_decode_linespec (b, s, sals);
13369 }
13370
13371 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13372
13373 /* Dprintf breakpoint_ops methods.  */
13374
13375 static void
13376 dprintf_re_set (struct breakpoint *b)
13377 {
13378   breakpoint_re_set_default (b);
13379
13380   /* This breakpoint could have been pending, and be resolved now, and
13381      if so, we should now have the extra string.  If we don't, the
13382      dprintf was malformed when created, but we couldn't tell because
13383      we can't extract the extra string until the location is
13384      resolved.  */
13385   if (b->loc != NULL && b->extra_string == NULL)
13386     error (_("Format string required"));
13387
13388   /* 1 - connect to target 1, that can run breakpoint commands.
13389      2 - create a dprintf, which resolves fine.
13390      3 - disconnect from target 1
13391      4 - connect to target 2, that can NOT run breakpoint commands.
13392
13393      After steps #3/#4, you'll want the dprintf command list to
13394      be updated, because target 1 and 2 may well return different
13395      answers for target_can_run_breakpoint_commands().
13396      Given absence of finer grained resetting, we get to do
13397      it all the time.  */
13398   if (b->extra_string != NULL)
13399     update_dprintf_command_list (b);
13400 }
13401
13402 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13403
13404 static void
13405 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13406 {
13407   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13408                       tp->extra_string);
13409   print_recreate_thread (tp, fp);
13410 }
13411
13412 /* Implement the "after_condition_true" breakpoint_ops method for
13413    dprintf.
13414
13415    dprintf's are implemented with regular commands in their command
13416    list, but we run the commands here instead of before presenting the
13417    stop to the user, as dprintf's don't actually cause a stop.  This
13418    also makes it so that the commands of multiple dprintfs at the same
13419    address are all handled.  */
13420
13421 static void
13422 dprintf_after_condition_true (struct bpstats *bs)
13423 {
13424   struct cleanup *old_chain;
13425   struct bpstats tmp_bs = { NULL };
13426   struct bpstats *tmp_bs_p = &tmp_bs;
13427
13428   /* dprintf's never cause a stop.  This wasn't set in the
13429      check_status hook instead because that would make the dprintf's
13430      condition not be evaluated.  */
13431   bs->stop = 0;
13432
13433   /* Run the command list here.  Take ownership of it instead of
13434      copying.  We never want these commands to run later in
13435      bpstat_do_actions, if a breakpoint that causes a stop happens to
13436      be set at same address as this dprintf, or even if running the
13437      commands here throws.  */
13438   tmp_bs.commands = bs->commands;
13439   bs->commands = NULL;
13440   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13441
13442   bpstat_do_actions_1 (&tmp_bs_p);
13443
13444   /* 'tmp_bs.commands' will usually be NULL by now, but
13445      bpstat_do_actions_1 may return early without processing the whole
13446      list.  */
13447   do_cleanups (old_chain);
13448 }
13449
13450 /* The breakpoint_ops structure to be used on static tracepoints with
13451    markers (`-m').  */
13452
13453 static void
13454 strace_marker_create_sals_from_address (char **arg,
13455                                         struct linespec_result *canonical,
13456                                         enum bptype type_wanted,
13457                                         char *addr_start, char **copy_arg)
13458 {
13459   struct linespec_sals lsal;
13460
13461   lsal.sals = decode_static_tracepoint_spec (arg);
13462
13463   *copy_arg = savestring (addr_start, *arg - addr_start);
13464
13465   canonical->addr_string = xstrdup (*copy_arg);
13466   lsal.canonical = xstrdup (*copy_arg);
13467   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13468 }
13469
13470 static void
13471 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13472                                       struct linespec_result *canonical,
13473                                       char *cond_string,
13474                                       char *extra_string,
13475                                       enum bptype type_wanted,
13476                                       enum bpdisp disposition,
13477                                       int thread,
13478                                       int task, int ignore_count,
13479                                       const struct breakpoint_ops *ops,
13480                                       int from_tty, int enabled,
13481                                       int internal, unsigned flags)
13482 {
13483   int i;
13484   struct linespec_sals *lsal = VEC_index (linespec_sals,
13485                                           canonical->sals, 0);
13486
13487   /* If the user is creating a static tracepoint by marker id
13488      (strace -m MARKER_ID), then store the sals index, so that
13489      breakpoint_re_set can try to match up which of the newly
13490      found markers corresponds to this one, and, don't try to
13491      expand multiple locations for each sal, given than SALS
13492      already should contain all sals for MARKER_ID.  */
13493
13494   for (i = 0; i < lsal->sals.nelts; ++i)
13495     {
13496       struct symtabs_and_lines expanded;
13497       struct tracepoint *tp;
13498       struct cleanup *old_chain;
13499       char *addr_string;
13500
13501       expanded.nelts = 1;
13502       expanded.sals = &lsal->sals.sals[i];
13503
13504       addr_string = xstrdup (canonical->addr_string);
13505       old_chain = make_cleanup (xfree, addr_string);
13506
13507       tp = XCNEW (struct tracepoint);
13508       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13509                            addr_string, NULL,
13510                            cond_string, extra_string,
13511                            type_wanted, disposition,
13512                            thread, task, ignore_count, ops,
13513                            from_tty, enabled, internal, flags,
13514                            canonical->special_display);
13515       /* Given that its possible to have multiple markers with
13516          the same string id, if the user is creating a static
13517          tracepoint by marker id ("strace -m MARKER_ID"), then
13518          store the sals index, so that breakpoint_re_set can
13519          try to match up which of the newly found markers
13520          corresponds to this one  */
13521       tp->static_trace_marker_id_idx = i;
13522
13523       install_breakpoint (internal, &tp->base, 0);
13524
13525       discard_cleanups (old_chain);
13526     }
13527 }
13528
13529 static void
13530 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13531                                struct symtabs_and_lines *sals)
13532 {
13533   struct tracepoint *tp = (struct tracepoint *) b;
13534
13535   *sals = decode_static_tracepoint_spec (s);
13536   if (sals->nelts > tp->static_trace_marker_id_idx)
13537     {
13538       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13539       sals->nelts = 1;
13540     }
13541   else
13542     error (_("marker %s not found"), tp->static_trace_marker_id);
13543 }
13544
13545 static struct breakpoint_ops strace_marker_breakpoint_ops;
13546
13547 static int
13548 strace_marker_p (struct breakpoint *b)
13549 {
13550   return b->ops == &strace_marker_breakpoint_ops;
13551 }
13552
13553 /* Delete a breakpoint and clean up all traces of it in the data
13554    structures.  */
13555
13556 void
13557 delete_breakpoint (struct breakpoint *bpt)
13558 {
13559   struct breakpoint *b;
13560
13561   gdb_assert (bpt != NULL);
13562
13563   /* Has this bp already been deleted?  This can happen because
13564      multiple lists can hold pointers to bp's.  bpstat lists are
13565      especial culprits.
13566
13567      One example of this happening is a watchpoint's scope bp.  When
13568      the scope bp triggers, we notice that the watchpoint is out of
13569      scope, and delete it.  We also delete its scope bp.  But the
13570      scope bp is marked "auto-deleting", and is already on a bpstat.
13571      That bpstat is then checked for auto-deleting bp's, which are
13572      deleted.
13573
13574      A real solution to this problem might involve reference counts in
13575      bp's, and/or giving them pointers back to their referencing
13576      bpstat's, and teaching delete_breakpoint to only free a bp's
13577      storage when no more references were extent.  A cheaper bandaid
13578      was chosen.  */
13579   if (bpt->type == bp_none)
13580     return;
13581
13582   /* At least avoid this stale reference until the reference counting
13583      of breakpoints gets resolved.  */
13584   if (bpt->related_breakpoint != bpt)
13585     {
13586       struct breakpoint *related;
13587       struct watchpoint *w;
13588
13589       if (bpt->type == bp_watchpoint_scope)
13590         w = (struct watchpoint *) bpt->related_breakpoint;
13591       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13592         w = (struct watchpoint *) bpt;
13593       else
13594         w = NULL;
13595       if (w != NULL)
13596         watchpoint_del_at_next_stop (w);
13597
13598       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13599       for (related = bpt; related->related_breakpoint != bpt;
13600            related = related->related_breakpoint);
13601       related->related_breakpoint = bpt->related_breakpoint;
13602       bpt->related_breakpoint = bpt;
13603     }
13604
13605   /* watch_command_1 creates a watchpoint but only sets its number if
13606      update_watchpoint succeeds in creating its bp_locations.  If there's
13607      a problem in that process, we'll be asked to delete the half-created
13608      watchpoint.  In that case, don't announce the deletion.  */
13609   if (bpt->number)
13610     observer_notify_breakpoint_deleted (bpt);
13611
13612   if (breakpoint_chain == bpt)
13613     breakpoint_chain = bpt->next;
13614
13615   ALL_BREAKPOINTS (b)
13616     if (b->next == bpt)
13617     {
13618       b->next = bpt->next;
13619       break;
13620     }
13621
13622   /* Be sure no bpstat's are pointing at the breakpoint after it's
13623      been freed.  */
13624   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13625      in all threads for now.  Note that we cannot just remove bpstats
13626      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13627      commands are associated with the bpstat; if we remove it here,
13628      then the later call to bpstat_do_actions (&stop_bpstat); in
13629      event-top.c won't do anything, and temporary breakpoints with
13630      commands won't work.  */
13631
13632   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13633
13634   /* Now that breakpoint is removed from breakpoint list, update the
13635      global location list.  This will remove locations that used to
13636      belong to this breakpoint.  Do this before freeing the breakpoint
13637      itself, since remove_breakpoint looks at location's owner.  It
13638      might be better design to have location completely
13639      self-contained, but it's not the case now.  */
13640   update_global_location_list (UGLL_DONT_INSERT);
13641
13642   bpt->ops->dtor (bpt);
13643   /* On the chance that someone will soon try again to delete this
13644      same bp, we mark it as deleted before freeing its storage.  */
13645   bpt->type = bp_none;
13646   xfree (bpt);
13647 }
13648
13649 static void
13650 do_delete_breakpoint_cleanup (void *b)
13651 {
13652   delete_breakpoint (b);
13653 }
13654
13655 struct cleanup *
13656 make_cleanup_delete_breakpoint (struct breakpoint *b)
13657 {
13658   return make_cleanup (do_delete_breakpoint_cleanup, b);
13659 }
13660
13661 /* Iterator function to call a user-provided callback function once
13662    for each of B and its related breakpoints.  */
13663
13664 static void
13665 iterate_over_related_breakpoints (struct breakpoint *b,
13666                                   void (*function) (struct breakpoint *,
13667                                                     void *),
13668                                   void *data)
13669 {
13670   struct breakpoint *related;
13671
13672   related = b;
13673   do
13674     {
13675       struct breakpoint *next;
13676
13677       /* FUNCTION may delete RELATED.  */
13678       next = related->related_breakpoint;
13679
13680       if (next == related)
13681         {
13682           /* RELATED is the last ring entry.  */
13683           function (related, data);
13684
13685           /* FUNCTION may have deleted it, so we'd never reach back to
13686              B.  There's nothing left to do anyway, so just break
13687              out.  */
13688           break;
13689         }
13690       else
13691         function (related, data);
13692
13693       related = next;
13694     }
13695   while (related != b);
13696 }
13697
13698 static void
13699 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13700 {
13701   delete_breakpoint (b);
13702 }
13703
13704 /* A callback for map_breakpoint_numbers that calls
13705    delete_breakpoint.  */
13706
13707 static void
13708 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13709 {
13710   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13711 }
13712
13713 void
13714 delete_command (char *arg, int from_tty)
13715 {
13716   struct breakpoint *b, *b_tmp;
13717
13718   dont_repeat ();
13719
13720   if (arg == 0)
13721     {
13722       int breaks_to_delete = 0;
13723
13724       /* Delete all breakpoints if no argument.  Do not delete
13725          internal breakpoints, these have to be deleted with an
13726          explicit breakpoint number argument.  */
13727       ALL_BREAKPOINTS (b)
13728         if (user_breakpoint_p (b))
13729           {
13730             breaks_to_delete = 1;
13731             break;
13732           }
13733
13734       /* Ask user only if there are some breakpoints to delete.  */
13735       if (!from_tty
13736           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13737         {
13738           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13739             if (user_breakpoint_p (b))
13740               delete_breakpoint (b);
13741         }
13742     }
13743   else
13744     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13745 }
13746
13747 static int
13748 all_locations_are_pending (struct bp_location *loc)
13749 {
13750   for (; loc; loc = loc->next)
13751     if (!loc->shlib_disabled
13752         && !loc->pspace->executing_startup)
13753       return 0;
13754   return 1;
13755 }
13756
13757 /* Subroutine of update_breakpoint_locations to simplify it.
13758    Return non-zero if multiple fns in list LOC have the same name.
13759    Null names are ignored.  */
13760
13761 static int
13762 ambiguous_names_p (struct bp_location *loc)
13763 {
13764   struct bp_location *l;
13765   htab_t htab = htab_create_alloc (13, htab_hash_string,
13766                                    (int (*) (const void *, 
13767                                              const void *)) streq,
13768                                    NULL, xcalloc, xfree);
13769
13770   for (l = loc; l != NULL; l = l->next)
13771     {
13772       const char **slot;
13773       const char *name = l->function_name;
13774
13775       /* Allow for some names to be NULL, ignore them.  */
13776       if (name == NULL)
13777         continue;
13778
13779       slot = (const char **) htab_find_slot (htab, (const void *) name,
13780                                              INSERT);
13781       /* NOTE: We can assume slot != NULL here because xcalloc never
13782          returns NULL.  */
13783       if (*slot != NULL)
13784         {
13785           htab_delete (htab);
13786           return 1;
13787         }
13788       *slot = name;
13789     }
13790
13791   htab_delete (htab);
13792   return 0;
13793 }
13794
13795 /* When symbols change, it probably means the sources changed as well,
13796    and it might mean the static tracepoint markers are no longer at
13797    the same address or line numbers they used to be at last we
13798    checked.  Losing your static tracepoints whenever you rebuild is
13799    undesirable.  This function tries to resync/rematch gdb static
13800    tracepoints with the markers on the target, for static tracepoints
13801    that have not been set by marker id.  Static tracepoint that have
13802    been set by marker id are reset by marker id in breakpoint_re_set.
13803    The heuristic is:
13804
13805    1) For a tracepoint set at a specific address, look for a marker at
13806    the old PC.  If one is found there, assume to be the same marker.
13807    If the name / string id of the marker found is different from the
13808    previous known name, assume that means the user renamed the marker
13809    in the sources, and output a warning.
13810
13811    2) For a tracepoint set at a given line number, look for a marker
13812    at the new address of the old line number.  If one is found there,
13813    assume to be the same marker.  If the name / string id of the
13814    marker found is different from the previous known name, assume that
13815    means the user renamed the marker in the sources, and output a
13816    warning.
13817
13818    3) If a marker is no longer found at the same address or line, it
13819    may mean the marker no longer exists.  But it may also just mean
13820    the code changed a bit.  Maybe the user added a few lines of code
13821    that made the marker move up or down (in line number terms).  Ask
13822    the target for info about the marker with the string id as we knew
13823    it.  If found, update line number and address in the matching
13824    static tracepoint.  This will get confused if there's more than one
13825    marker with the same ID (possible in UST, although unadvised
13826    precisely because it confuses tools).  */
13827
13828 static struct symtab_and_line
13829 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13830 {
13831   struct tracepoint *tp = (struct tracepoint *) b;
13832   struct static_tracepoint_marker marker;
13833   CORE_ADDR pc;
13834
13835   pc = sal.pc;
13836   if (sal.line)
13837     find_line_pc (sal.symtab, sal.line, &pc);
13838
13839   if (target_static_tracepoint_marker_at (pc, &marker))
13840     {
13841       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13842         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13843                  b->number,
13844                  tp->static_trace_marker_id, marker.str_id);
13845
13846       xfree (tp->static_trace_marker_id);
13847       tp->static_trace_marker_id = xstrdup (marker.str_id);
13848       release_static_tracepoint_marker (&marker);
13849
13850       return sal;
13851     }
13852
13853   /* Old marker wasn't found on target at lineno.  Try looking it up
13854      by string ID.  */
13855   if (!sal.explicit_pc
13856       && sal.line != 0
13857       && sal.symtab != NULL
13858       && tp->static_trace_marker_id != NULL)
13859     {
13860       VEC(static_tracepoint_marker_p) *markers;
13861
13862       markers
13863         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13864
13865       if (!VEC_empty(static_tracepoint_marker_p, markers))
13866         {
13867           struct symtab_and_line sal2;
13868           struct symbol *sym;
13869           struct static_tracepoint_marker *tpmarker;
13870           struct ui_out *uiout = current_uiout;
13871
13872           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13873
13874           xfree (tp->static_trace_marker_id);
13875           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13876
13877           warning (_("marker for static tracepoint %d (%s) not "
13878                      "found at previous line number"),
13879                    b->number, tp->static_trace_marker_id);
13880
13881           init_sal (&sal2);
13882
13883           sal2.pc = tpmarker->address;
13884
13885           sal2 = find_pc_line (tpmarker->address, 0);
13886           sym = find_pc_sect_function (tpmarker->address, NULL);
13887           ui_out_text (uiout, "Now in ");
13888           if (sym)
13889             {
13890               ui_out_field_string (uiout, "func",
13891                                    SYMBOL_PRINT_NAME (sym));
13892               ui_out_text (uiout, " at ");
13893             }
13894           ui_out_field_string (uiout, "file",
13895                                symtab_to_filename_for_display (sal2.symtab));
13896           ui_out_text (uiout, ":");
13897
13898           if (ui_out_is_mi_like_p (uiout))
13899             {
13900               const char *fullname = symtab_to_fullname (sal2.symtab);
13901
13902               ui_out_field_string (uiout, "fullname", fullname);
13903             }
13904
13905           ui_out_field_int (uiout, "line", sal2.line);
13906           ui_out_text (uiout, "\n");
13907
13908           b->loc->line_number = sal2.line;
13909           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13910
13911           xfree (b->addr_string);
13912           b->addr_string = xstrprintf ("%s:%d",
13913                                    symtab_to_filename_for_display (sal2.symtab),
13914                                        b->loc->line_number);
13915
13916           /* Might be nice to check if function changed, and warn if
13917              so.  */
13918
13919           release_static_tracepoint_marker (tpmarker);
13920         }
13921     }
13922   return sal;
13923 }
13924
13925 /* Returns 1 iff locations A and B are sufficiently same that
13926    we don't need to report breakpoint as changed.  */
13927
13928 static int
13929 locations_are_equal (struct bp_location *a, struct bp_location *b)
13930 {
13931   while (a && b)
13932     {
13933       if (a->address != b->address)
13934         return 0;
13935
13936       if (a->shlib_disabled != b->shlib_disabled)
13937         return 0;
13938
13939       if (a->enabled != b->enabled)
13940         return 0;
13941
13942       a = a->next;
13943       b = b->next;
13944     }
13945
13946   if ((a == NULL) != (b == NULL))
13947     return 0;
13948
13949   return 1;
13950 }
13951
13952 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13953    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13954    a ranged breakpoint.  */
13955
13956 void
13957 update_breakpoint_locations (struct breakpoint *b,
13958                              struct symtabs_and_lines sals,
13959                              struct symtabs_and_lines sals_end)
13960 {
13961   int i;
13962   struct bp_location *existing_locations = b->loc;
13963
13964   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13965     {
13966       /* Ranged breakpoints have only one start location and one end
13967          location.  */
13968       b->enable_state = bp_disabled;
13969       update_global_location_list (UGLL_MAY_INSERT);
13970       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13971                            "multiple locations found\n"),
13972                          b->number);
13973       return;
13974     }
13975
13976   /* If there's no new locations, and all existing locations are
13977      pending, don't do anything.  This optimizes the common case where
13978      all locations are in the same shared library, that was unloaded.
13979      We'd like to retain the location, so that when the library is
13980      loaded again, we don't loose the enabled/disabled status of the
13981      individual locations.  */
13982   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13983     return;
13984
13985   b->loc = NULL;
13986
13987   for (i = 0; i < sals.nelts; ++i)
13988     {
13989       struct bp_location *new_loc;
13990
13991       switch_to_program_space_and_thread (sals.sals[i].pspace);
13992
13993       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13994
13995       /* Reparse conditions, they might contain references to the
13996          old symtab.  */
13997       if (b->cond_string != NULL)
13998         {
13999           const char *s;
14000
14001           s = b->cond_string;
14002           TRY
14003             {
14004               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14005                                            block_for_pc (sals.sals[i].pc), 
14006                                            0);
14007             }
14008           CATCH (e, RETURN_MASK_ERROR)
14009             {
14010               warning (_("failed to reevaluate condition "
14011                          "for breakpoint %d: %s"), 
14012                        b->number, e.message);
14013               new_loc->enabled = 0;
14014             }
14015           END_CATCH
14016         }
14017
14018       if (sals_end.nelts)
14019         {
14020           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14021
14022           new_loc->length = end - sals.sals[0].pc + 1;
14023         }
14024     }
14025
14026   /* If possible, carry over 'disable' status from existing
14027      breakpoints.  */
14028   {
14029     struct bp_location *e = existing_locations;
14030     /* If there are multiple breakpoints with the same function name,
14031        e.g. for inline functions, comparing function names won't work.
14032        Instead compare pc addresses; this is just a heuristic as things
14033        may have moved, but in practice it gives the correct answer
14034        often enough until a better solution is found.  */
14035     int have_ambiguous_names = ambiguous_names_p (b->loc);
14036
14037     for (; e; e = e->next)
14038       {
14039         if (!e->enabled && e->function_name)
14040           {
14041             struct bp_location *l = b->loc;
14042             if (have_ambiguous_names)
14043               {
14044                 for (; l; l = l->next)
14045                   if (breakpoint_locations_match (e, l))
14046                     {
14047                       l->enabled = 0;
14048                       break;
14049                     }
14050               }
14051             else
14052               {
14053                 for (; l; l = l->next)
14054                   if (l->function_name
14055                       && strcmp (e->function_name, l->function_name) == 0)
14056                     {
14057                       l->enabled = 0;
14058                       break;
14059                     }
14060               }
14061           }
14062       }
14063   }
14064
14065   if (!locations_are_equal (existing_locations, b->loc))
14066     observer_notify_breakpoint_modified (b);
14067
14068   update_global_location_list (UGLL_MAY_INSERT);
14069 }
14070
14071 /* Find the SaL locations corresponding to the given ADDR_STRING.
14072    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14073
14074 static struct symtabs_and_lines
14075 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14076 {
14077   char *s;
14078   struct symtabs_and_lines sals = {0};
14079   struct gdb_exception exception = exception_none;
14080
14081   gdb_assert (b->ops != NULL);
14082   s = addr_string;
14083
14084   TRY
14085     {
14086       b->ops->decode_linespec (b, &s, &sals);
14087     }
14088   CATCH (e, RETURN_MASK_ERROR)
14089     {
14090       int not_found_and_ok = 0;
14091
14092       exception = e;
14093
14094       /* For pending breakpoints, it's expected that parsing will
14095          fail until the right shared library is loaded.  User has
14096          already told to create pending breakpoints and don't need
14097          extra messages.  If breakpoint is in bp_shlib_disabled
14098          state, then user already saw the message about that
14099          breakpoint being disabled, and don't want to see more
14100          errors.  */
14101       if (e.error == NOT_FOUND_ERROR
14102           && (b->condition_not_parsed 
14103               || (b->loc && b->loc->shlib_disabled)
14104               || (b->loc && b->loc->pspace->executing_startup)
14105               || b->enable_state == bp_disabled))
14106         not_found_and_ok = 1;
14107
14108       if (!not_found_and_ok)
14109         {
14110           /* We surely don't want to warn about the same breakpoint
14111              10 times.  One solution, implemented here, is disable
14112              the breakpoint on error.  Another solution would be to
14113              have separate 'warning emitted' flag.  Since this
14114              happens only when a binary has changed, I don't know
14115              which approach is better.  */
14116           b->enable_state = bp_disabled;
14117           throw_exception (e);
14118         }
14119     }
14120   END_CATCH
14121
14122   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14123     {
14124       int i;
14125
14126       for (i = 0; i < sals.nelts; ++i)
14127         resolve_sal_pc (&sals.sals[i]);
14128       if (b->condition_not_parsed && s && s[0])
14129         {
14130           char *cond_string, *extra_string;
14131           int thread, task;
14132
14133           find_condition_and_thread (s, sals.sals[0].pc,
14134                                      &cond_string, &thread, &task,
14135                                      &extra_string);
14136           if (cond_string)
14137             b->cond_string = cond_string;
14138           b->thread = thread;
14139           b->task = task;
14140           if (extra_string)
14141             b->extra_string = extra_string;
14142           b->condition_not_parsed = 0;
14143         }
14144
14145       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14146         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14147
14148       *found = 1;
14149     }
14150   else
14151     *found = 0;
14152
14153   return sals;
14154 }
14155
14156 /* The default re_set method, for typical hardware or software
14157    breakpoints.  Reevaluate the breakpoint and recreate its
14158    locations.  */
14159
14160 static void
14161 breakpoint_re_set_default (struct breakpoint *b)
14162 {
14163   int found;
14164   struct symtabs_and_lines sals, sals_end;
14165   struct symtabs_and_lines expanded = {0};
14166   struct symtabs_and_lines expanded_end = {0};
14167
14168   sals = addr_string_to_sals (b, b->addr_string, &found);
14169   if (found)
14170     {
14171       make_cleanup (xfree, sals.sals);
14172       expanded = sals;
14173     }
14174
14175   if (b->addr_string_range_end)
14176     {
14177       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14178       if (found)
14179         {
14180           make_cleanup (xfree, sals_end.sals);
14181           expanded_end = sals_end;
14182         }
14183     }
14184
14185   update_breakpoint_locations (b, expanded, expanded_end);
14186 }
14187
14188 /* Default method for creating SALs from an address string.  It basically
14189    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14190
14191 static void
14192 create_sals_from_address_default (char **arg,
14193                                   struct linespec_result *canonical,
14194                                   enum bptype type_wanted,
14195                                   char *addr_start, char **copy_arg)
14196 {
14197   parse_breakpoint_sals (arg, canonical);
14198 }
14199
14200 /* Call create_breakpoints_sal for the given arguments.  This is the default
14201    function for the `create_breakpoints_sal' method of
14202    breakpoint_ops.  */
14203
14204 static void
14205 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14206                                 struct linespec_result *canonical,
14207                                 char *cond_string,
14208                                 char *extra_string,
14209                                 enum bptype type_wanted,
14210                                 enum bpdisp disposition,
14211                                 int thread,
14212                                 int task, int ignore_count,
14213                                 const struct breakpoint_ops *ops,
14214                                 int from_tty, int enabled,
14215                                 int internal, unsigned flags)
14216 {
14217   create_breakpoints_sal (gdbarch, canonical, cond_string,
14218                           extra_string,
14219                           type_wanted, disposition,
14220                           thread, task, ignore_count, ops, from_tty,
14221                           enabled, internal, flags);
14222 }
14223
14224 /* Decode the line represented by S by calling decode_line_full.  This is the
14225    default function for the `decode_linespec' method of breakpoint_ops.  */
14226
14227 static void
14228 decode_linespec_default (struct breakpoint *b, char **s,
14229                          struct symtabs_and_lines *sals)
14230 {
14231   struct linespec_result canonical;
14232
14233   init_linespec_result (&canonical);
14234   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14235                     (struct symtab *) NULL, 0,
14236                     &canonical, multiple_symbols_all,
14237                     b->filter);
14238
14239   /* We should get 0 or 1 resulting SALs.  */
14240   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14241
14242   if (VEC_length (linespec_sals, canonical.sals) > 0)
14243     {
14244       struct linespec_sals *lsal;
14245
14246       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14247       *sals = lsal->sals;
14248       /* Arrange it so the destructor does not free the
14249          contents.  */
14250       lsal->sals.sals = NULL;
14251     }
14252
14253   destroy_linespec_result (&canonical);
14254 }
14255
14256 /* Prepare the global context for a re-set of breakpoint B.  */
14257
14258 static struct cleanup *
14259 prepare_re_set_context (struct breakpoint *b)
14260 {
14261   struct cleanup *cleanups;
14262
14263   input_radix = b->input_radix;
14264   cleanups = save_current_space_and_thread ();
14265   if (b->pspace != NULL)
14266     switch_to_program_space_and_thread (b->pspace);
14267   set_language (b->language);
14268
14269   return cleanups;
14270 }
14271
14272 /* Reset a breakpoint given it's struct breakpoint * BINT.
14273    The value we return ends up being the return value from catch_errors.
14274    Unused in this case.  */
14275
14276 static int
14277 breakpoint_re_set_one (void *bint)
14278 {
14279   /* Get past catch_errs.  */
14280   struct breakpoint *b = (struct breakpoint *) bint;
14281   struct cleanup *cleanups;
14282
14283   cleanups = prepare_re_set_context (b);
14284   b->ops->re_set (b);
14285   do_cleanups (cleanups);
14286   return 0;
14287 }
14288
14289 /* Re-set all breakpoints after symbols have been re-loaded.  */
14290 void
14291 breakpoint_re_set (void)
14292 {
14293   struct breakpoint *b, *b_tmp;
14294   enum language save_language;
14295   int save_input_radix;
14296   struct cleanup *old_chain;
14297
14298   save_language = current_language->la_language;
14299   save_input_radix = input_radix;
14300   old_chain = save_current_program_space ();
14301
14302   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14303   {
14304     /* Format possible error msg.  */
14305     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14306                                 b->number);
14307     struct cleanup *cleanups = make_cleanup (xfree, message);
14308     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14309     do_cleanups (cleanups);
14310   }
14311   set_language (save_language);
14312   input_radix = save_input_radix;
14313
14314   jit_breakpoint_re_set ();
14315
14316   do_cleanups (old_chain);
14317
14318   create_overlay_event_breakpoint ();
14319   create_longjmp_master_breakpoint ();
14320   create_std_terminate_master_breakpoint ();
14321   create_exception_master_breakpoint ();
14322 }
14323 \f
14324 /* Reset the thread number of this breakpoint:
14325
14326    - If the breakpoint is for all threads, leave it as-is.
14327    - Else, reset it to the current thread for inferior_ptid.  */
14328 void
14329 breakpoint_re_set_thread (struct breakpoint *b)
14330 {
14331   if (b->thread != -1)
14332     {
14333       if (in_thread_list (inferior_ptid))
14334         b->thread = pid_to_thread_id (inferior_ptid);
14335
14336       /* We're being called after following a fork.  The new fork is
14337          selected as current, and unless this was a vfork will have a
14338          different program space from the original thread.  Reset that
14339          as well.  */
14340       b->loc->pspace = current_program_space;
14341     }
14342 }
14343
14344 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14345    If from_tty is nonzero, it prints a message to that effect,
14346    which ends with a period (no newline).  */
14347
14348 void
14349 set_ignore_count (int bptnum, int count, int from_tty)
14350 {
14351   struct breakpoint *b;
14352
14353   if (count < 0)
14354     count = 0;
14355
14356   ALL_BREAKPOINTS (b)
14357     if (b->number == bptnum)
14358     {
14359       if (is_tracepoint (b))
14360         {
14361           if (from_tty && count != 0)
14362             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14363                              bptnum);
14364           return;
14365         }
14366       
14367       b->ignore_count = count;
14368       if (from_tty)
14369         {
14370           if (count == 0)
14371             printf_filtered (_("Will stop next time "
14372                                "breakpoint %d is reached."),
14373                              bptnum);
14374           else if (count == 1)
14375             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14376                              bptnum);
14377           else
14378             printf_filtered (_("Will ignore next %d "
14379                                "crossings of breakpoint %d."),
14380                              count, bptnum);
14381         }
14382       observer_notify_breakpoint_modified (b);
14383       return;
14384     }
14385
14386   error (_("No breakpoint number %d."), bptnum);
14387 }
14388
14389 /* Command to set ignore-count of breakpoint N to COUNT.  */
14390
14391 static void
14392 ignore_command (char *args, int from_tty)
14393 {
14394   char *p = args;
14395   int num;
14396
14397   if (p == 0)
14398     error_no_arg (_("a breakpoint number"));
14399
14400   num = get_number (&p);
14401   if (num == 0)
14402     error (_("bad breakpoint number: '%s'"), args);
14403   if (*p == 0)
14404     error (_("Second argument (specified ignore-count) is missing."));
14405
14406   set_ignore_count (num,
14407                     longest_to_int (value_as_long (parse_and_eval (p))),
14408                     from_tty);
14409   if (from_tty)
14410     printf_filtered ("\n");
14411 }
14412 \f
14413 /* Call FUNCTION on each of the breakpoints
14414    whose numbers are given in ARGS.  */
14415
14416 static void
14417 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14418                                                       void *),
14419                         void *data)
14420 {
14421   int num;
14422   struct breakpoint *b, *tmp;
14423   int match;
14424   struct get_number_or_range_state state;
14425
14426   if (args == 0 || *args == '\0')
14427     error_no_arg (_("one or more breakpoint numbers"));
14428
14429   init_number_or_range (&state, args);
14430
14431   while (!state.finished)
14432     {
14433       const char *p = state.string;
14434
14435       match = 0;
14436
14437       num = get_number_or_range (&state);
14438       if (num == 0)
14439         {
14440           warning (_("bad breakpoint number at or near '%s'"), p);
14441         }
14442       else
14443         {
14444           ALL_BREAKPOINTS_SAFE (b, tmp)
14445             if (b->number == num)
14446               {
14447                 match = 1;
14448                 function (b, data);
14449                 break;
14450               }
14451           if (match == 0)
14452             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14453         }
14454     }
14455 }
14456
14457 static struct bp_location *
14458 find_location_by_number (char *number)
14459 {
14460   char *dot = strchr (number, '.');
14461   char *p1;
14462   int bp_num;
14463   int loc_num;
14464   struct breakpoint *b;
14465   struct bp_location *loc;  
14466
14467   *dot = '\0';
14468
14469   p1 = number;
14470   bp_num = get_number (&p1);
14471   if (bp_num == 0)
14472     error (_("Bad breakpoint number '%s'"), number);
14473
14474   ALL_BREAKPOINTS (b)
14475     if (b->number == bp_num)
14476       {
14477         break;
14478       }
14479
14480   if (!b || b->number != bp_num)
14481     error (_("Bad breakpoint number '%s'"), number);
14482   
14483   p1 = dot+1;
14484   loc_num = get_number (&p1);
14485   if (loc_num == 0)
14486     error (_("Bad breakpoint location number '%s'"), number);
14487
14488   --loc_num;
14489   loc = b->loc;
14490   for (;loc_num && loc; --loc_num, loc = loc->next)
14491     ;
14492   if (!loc)
14493     error (_("Bad breakpoint location number '%s'"), dot+1);
14494     
14495   return loc;  
14496 }
14497
14498
14499 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14500    If from_tty is nonzero, it prints a message to that effect,
14501    which ends with a period (no newline).  */
14502
14503 void
14504 disable_breakpoint (struct breakpoint *bpt)
14505 {
14506   /* Never disable a watchpoint scope breakpoint; we want to
14507      hit them when we leave scope so we can delete both the
14508      watchpoint and its scope breakpoint at that time.  */
14509   if (bpt->type == bp_watchpoint_scope)
14510     return;
14511
14512   bpt->enable_state = bp_disabled;
14513
14514   /* Mark breakpoint locations modified.  */
14515   mark_breakpoint_modified (bpt);
14516
14517   if (target_supports_enable_disable_tracepoint ()
14518       && current_trace_status ()->running && is_tracepoint (bpt))
14519     {
14520       struct bp_location *location;
14521      
14522       for (location = bpt->loc; location; location = location->next)
14523         target_disable_tracepoint (location);
14524     }
14525
14526   update_global_location_list (UGLL_DONT_INSERT);
14527
14528   observer_notify_breakpoint_modified (bpt);
14529 }
14530
14531 /* A callback for iterate_over_related_breakpoints.  */
14532
14533 static void
14534 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14535 {
14536   disable_breakpoint (b);
14537 }
14538
14539 /* A callback for map_breakpoint_numbers that calls
14540    disable_breakpoint.  */
14541
14542 static void
14543 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14544 {
14545   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14546 }
14547
14548 static void
14549 disable_command (char *args, int from_tty)
14550 {
14551   if (args == 0)
14552     {
14553       struct breakpoint *bpt;
14554
14555       ALL_BREAKPOINTS (bpt)
14556         if (user_breakpoint_p (bpt))
14557           disable_breakpoint (bpt);
14558     }
14559   else
14560     {
14561       char *num = extract_arg (&args);
14562
14563       while (num)
14564         {
14565           if (strchr (num, '.'))
14566             {
14567               struct bp_location *loc = find_location_by_number (num);
14568
14569               if (loc)
14570                 {
14571                   if (loc->enabled)
14572                     {
14573                       loc->enabled = 0;
14574                       mark_breakpoint_location_modified (loc);
14575                     }
14576                   if (target_supports_enable_disable_tracepoint ()
14577                       && current_trace_status ()->running && loc->owner
14578                       && is_tracepoint (loc->owner))
14579                     target_disable_tracepoint (loc);
14580                 }
14581               update_global_location_list (UGLL_DONT_INSERT);
14582             }
14583           else
14584             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14585           num = extract_arg (&args);
14586         }
14587     }
14588 }
14589
14590 static void
14591 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14592                         int count)
14593 {
14594   int target_resources_ok;
14595
14596   if (bpt->type == bp_hardware_breakpoint)
14597     {
14598       int i;
14599       i = hw_breakpoint_used_count ();
14600       target_resources_ok = 
14601         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14602                                             i + 1, 0);
14603       if (target_resources_ok == 0)
14604         error (_("No hardware breakpoint support in the target."));
14605       else if (target_resources_ok < 0)
14606         error (_("Hardware breakpoints used exceeds limit."));
14607     }
14608
14609   if (is_watchpoint (bpt))
14610     {
14611       /* Initialize it just to avoid a GCC false warning.  */
14612       enum enable_state orig_enable_state = 0;
14613
14614       TRY
14615         {
14616           struct watchpoint *w = (struct watchpoint *) bpt;
14617
14618           orig_enable_state = bpt->enable_state;
14619           bpt->enable_state = bp_enabled;
14620           update_watchpoint (w, 1 /* reparse */);
14621         }
14622       CATCH (e, RETURN_MASK_ALL)
14623         {
14624           bpt->enable_state = orig_enable_state;
14625           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14626                              bpt->number);
14627           return;
14628         }
14629       END_CATCH
14630     }
14631
14632   bpt->enable_state = bp_enabled;
14633
14634   /* Mark breakpoint locations modified.  */
14635   mark_breakpoint_modified (bpt);
14636
14637   if (target_supports_enable_disable_tracepoint ()
14638       && current_trace_status ()->running && is_tracepoint (bpt))
14639     {
14640       struct bp_location *location;
14641
14642       for (location = bpt->loc; location; location = location->next)
14643         target_enable_tracepoint (location);
14644     }
14645
14646   bpt->disposition = disposition;
14647   bpt->enable_count = count;
14648   update_global_location_list (UGLL_MAY_INSERT);
14649
14650   observer_notify_breakpoint_modified (bpt);
14651 }
14652
14653
14654 void
14655 enable_breakpoint (struct breakpoint *bpt)
14656 {
14657   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14658 }
14659
14660 static void
14661 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14662 {
14663   enable_breakpoint (bpt);
14664 }
14665
14666 /* A callback for map_breakpoint_numbers that calls
14667    enable_breakpoint.  */
14668
14669 static void
14670 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14671 {
14672   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14673 }
14674
14675 /* The enable command enables the specified breakpoints (or all defined
14676    breakpoints) so they once again become (or continue to be) effective
14677    in stopping the inferior.  */
14678
14679 static void
14680 enable_command (char *args, int from_tty)
14681 {
14682   if (args == 0)
14683     {
14684       struct breakpoint *bpt;
14685
14686       ALL_BREAKPOINTS (bpt)
14687         if (user_breakpoint_p (bpt))
14688           enable_breakpoint (bpt);
14689     }
14690   else
14691     {
14692       char *num = extract_arg (&args);
14693
14694       while (num)
14695         {
14696           if (strchr (num, '.'))
14697             {
14698               struct bp_location *loc = find_location_by_number (num);
14699
14700               if (loc)
14701                 {
14702                   if (!loc->enabled)
14703                     {
14704                       loc->enabled = 1;
14705                       mark_breakpoint_location_modified (loc);
14706                     }
14707                   if (target_supports_enable_disable_tracepoint ()
14708                       && current_trace_status ()->running && loc->owner
14709                       && is_tracepoint (loc->owner))
14710                     target_enable_tracepoint (loc);
14711                 }
14712               update_global_location_list (UGLL_MAY_INSERT);
14713             }
14714           else
14715             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14716           num = extract_arg (&args);
14717         }
14718     }
14719 }
14720
14721 /* This struct packages up disposition data for application to multiple
14722    breakpoints.  */
14723
14724 struct disp_data
14725 {
14726   enum bpdisp disp;
14727   int count;
14728 };
14729
14730 static void
14731 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14732 {
14733   struct disp_data disp_data = *(struct disp_data *) arg;
14734
14735   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14736 }
14737
14738 static void
14739 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14740 {
14741   struct disp_data disp = { disp_disable, 1 };
14742
14743   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14744 }
14745
14746 static void
14747 enable_once_command (char *args, int from_tty)
14748 {
14749   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14750 }
14751
14752 static void
14753 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14754 {
14755   struct disp_data disp = { disp_disable, *(int *) countptr };
14756
14757   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14758 }
14759
14760 static void
14761 enable_count_command (char *args, int from_tty)
14762 {
14763   int count;
14764
14765   if (args == NULL)
14766     error_no_arg (_("hit count"));
14767
14768   count = get_number (&args);
14769
14770   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14771 }
14772
14773 static void
14774 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14775 {
14776   struct disp_data disp = { disp_del, 1 };
14777
14778   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14779 }
14780
14781 static void
14782 enable_delete_command (char *args, int from_tty)
14783 {
14784   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14785 }
14786 \f
14787 static void
14788 set_breakpoint_cmd (char *args, int from_tty)
14789 {
14790 }
14791
14792 static void
14793 show_breakpoint_cmd (char *args, int from_tty)
14794 {
14795 }
14796
14797 /* Invalidate last known value of any hardware watchpoint if
14798    the memory which that value represents has been written to by
14799    GDB itself.  */
14800
14801 static void
14802 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14803                                       CORE_ADDR addr, ssize_t len,
14804                                       const bfd_byte *data)
14805 {
14806   struct breakpoint *bp;
14807
14808   ALL_BREAKPOINTS (bp)
14809     if (bp->enable_state == bp_enabled
14810         && bp->type == bp_hardware_watchpoint)
14811       {
14812         struct watchpoint *wp = (struct watchpoint *) bp;
14813
14814         if (wp->val_valid && wp->val)
14815           {
14816             struct bp_location *loc;
14817
14818             for (loc = bp->loc; loc != NULL; loc = loc->next)
14819               if (loc->loc_type == bp_loc_hardware_watchpoint
14820                   && loc->address + loc->length > addr
14821                   && addr + len > loc->address)
14822                 {
14823                   value_free (wp->val);
14824                   wp->val = NULL;
14825                   wp->val_valid = 0;
14826                 }
14827           }
14828       }
14829 }
14830
14831 /* Create and insert a breakpoint for software single step.  */
14832
14833 void
14834 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14835                                struct address_space *aspace, 
14836                                CORE_ADDR next_pc)
14837 {
14838   struct thread_info *tp = inferior_thread ();
14839   struct symtab_and_line sal;
14840   CORE_ADDR pc = next_pc;
14841
14842   if (tp->control.single_step_breakpoints == NULL)
14843     {
14844       tp->control.single_step_breakpoints
14845         = new_single_step_breakpoint (tp->num, gdbarch);
14846     }
14847
14848   sal = find_pc_line (pc, 0);
14849   sal.pc = pc;
14850   sal.section = find_pc_overlay (pc);
14851   sal.explicit_pc = 1;
14852   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14853
14854   update_global_location_list (UGLL_INSERT);
14855 }
14856
14857 /* See breakpoint.h.  */
14858
14859 int
14860 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14861                                        struct address_space *aspace,
14862                                        CORE_ADDR pc)
14863 {
14864   struct bp_location *loc;
14865
14866   for (loc = bp->loc; loc != NULL; loc = loc->next)
14867     if (loc->inserted
14868         && breakpoint_location_address_match (loc, aspace, pc))
14869       return 1;
14870
14871   return 0;
14872 }
14873
14874 /* Check whether a software single-step breakpoint is inserted at
14875    PC.  */
14876
14877 int
14878 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
14879                                         CORE_ADDR pc)
14880 {
14881   struct breakpoint *bpt;
14882
14883   ALL_BREAKPOINTS (bpt)
14884     {
14885       if (bpt->type == bp_single_step
14886           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14887         return 1;
14888     }
14889   return 0;
14890 }
14891
14892 /* Tracepoint-specific operations.  */
14893
14894 /* Set tracepoint count to NUM.  */
14895 static void
14896 set_tracepoint_count (int num)
14897 {
14898   tracepoint_count = num;
14899   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14900 }
14901
14902 static void
14903 trace_command (char *arg, int from_tty)
14904 {
14905   struct breakpoint_ops *ops;
14906   const char *arg_cp = arg;
14907
14908   if (arg && probe_linespec_to_ops (&arg_cp))
14909     ops = &tracepoint_probe_breakpoint_ops;
14910   else
14911     ops = &tracepoint_breakpoint_ops;
14912
14913   create_breakpoint (get_current_arch (),
14914                      arg,
14915                      NULL, 0, NULL, 1 /* parse arg */,
14916                      0 /* tempflag */,
14917                      bp_tracepoint /* type_wanted */,
14918                      0 /* Ignore count */,
14919                      pending_break_support,
14920                      ops,
14921                      from_tty,
14922                      1 /* enabled */,
14923                      0 /* internal */, 0);
14924 }
14925
14926 static void
14927 ftrace_command (char *arg, int from_tty)
14928 {
14929   create_breakpoint (get_current_arch (),
14930                      arg,
14931                      NULL, 0, NULL, 1 /* parse arg */,
14932                      0 /* tempflag */,
14933                      bp_fast_tracepoint /* type_wanted */,
14934                      0 /* Ignore count */,
14935                      pending_break_support,
14936                      &tracepoint_breakpoint_ops,
14937                      from_tty,
14938                      1 /* enabled */,
14939                      0 /* internal */, 0);
14940 }
14941
14942 /* strace command implementation.  Creates a static tracepoint.  */
14943
14944 static void
14945 strace_command (char *arg, int from_tty)
14946 {
14947   struct breakpoint_ops *ops;
14948
14949   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14950      or with a normal static tracepoint.  */
14951   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14952     ops = &strace_marker_breakpoint_ops;
14953   else
14954     ops = &tracepoint_breakpoint_ops;
14955
14956   create_breakpoint (get_current_arch (),
14957                      arg,
14958                      NULL, 0, NULL, 1 /* parse arg */,
14959                      0 /* tempflag */,
14960                      bp_static_tracepoint /* type_wanted */,
14961                      0 /* Ignore count */,
14962                      pending_break_support,
14963                      ops,
14964                      from_tty,
14965                      1 /* enabled */,
14966                      0 /* internal */, 0);
14967 }
14968
14969 /* Set up a fake reader function that gets command lines from a linked
14970    list that was acquired during tracepoint uploading.  */
14971
14972 static struct uploaded_tp *this_utp;
14973 static int next_cmd;
14974
14975 static char *
14976 read_uploaded_action (void)
14977 {
14978   char *rslt;
14979
14980   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14981
14982   next_cmd++;
14983
14984   return rslt;
14985 }
14986
14987 /* Given information about a tracepoint as recorded on a target (which
14988    can be either a live system or a trace file), attempt to create an
14989    equivalent GDB tracepoint.  This is not a reliable process, since
14990    the target does not necessarily have all the information used when
14991    the tracepoint was originally defined.  */
14992   
14993 struct tracepoint *
14994 create_tracepoint_from_upload (struct uploaded_tp *utp)
14995 {
14996   char *addr_str, small_buf[100];
14997   struct tracepoint *tp;
14998
14999   if (utp->at_string)
15000     addr_str = utp->at_string;
15001   else
15002     {
15003       /* In the absence of a source location, fall back to raw
15004          address.  Since there is no way to confirm that the address
15005          means the same thing as when the trace was started, warn the
15006          user.  */
15007       warning (_("Uploaded tracepoint %d has no "
15008                  "source location, using raw address"),
15009                utp->number);
15010       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15011       addr_str = small_buf;
15012     }
15013
15014   /* There's not much we can do with a sequence of bytecodes.  */
15015   if (utp->cond && !utp->cond_string)
15016     warning (_("Uploaded tracepoint %d condition "
15017                "has no source form, ignoring it"),
15018              utp->number);
15019
15020   if (!create_breakpoint (get_current_arch (),
15021                           addr_str,
15022                           utp->cond_string, -1, NULL,
15023                           0 /* parse cond/thread */,
15024                           0 /* tempflag */,
15025                           utp->type /* type_wanted */,
15026                           0 /* Ignore count */,
15027                           pending_break_support,
15028                           &tracepoint_breakpoint_ops,
15029                           0 /* from_tty */,
15030                           utp->enabled /* enabled */,
15031                           0 /* internal */,
15032                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15033     return NULL;
15034
15035   /* Get the tracepoint we just created.  */
15036   tp = get_tracepoint (tracepoint_count);
15037   gdb_assert (tp != NULL);
15038
15039   if (utp->pass > 0)
15040     {
15041       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15042                  tp->base.number);
15043
15044       trace_pass_command (small_buf, 0);
15045     }
15046
15047   /* If we have uploaded versions of the original commands, set up a
15048      special-purpose "reader" function and call the usual command line
15049      reader, then pass the result to the breakpoint command-setting
15050      function.  */
15051   if (!VEC_empty (char_ptr, utp->cmd_strings))
15052     {
15053       struct command_line *cmd_list;
15054
15055       this_utp = utp;
15056       next_cmd = 0;
15057
15058       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15059
15060       breakpoint_set_commands (&tp->base, cmd_list);
15061     }
15062   else if (!VEC_empty (char_ptr, utp->actions)
15063            || !VEC_empty (char_ptr, utp->step_actions))
15064     warning (_("Uploaded tracepoint %d actions "
15065                "have no source form, ignoring them"),
15066              utp->number);
15067
15068   /* Copy any status information that might be available.  */
15069   tp->base.hit_count = utp->hit_count;
15070   tp->traceframe_usage = utp->traceframe_usage;
15071
15072   return tp;
15073 }
15074   
15075 /* Print information on tracepoint number TPNUM_EXP, or all if
15076    omitted.  */
15077
15078 static void
15079 tracepoints_info (char *args, int from_tty)
15080 {
15081   struct ui_out *uiout = current_uiout;
15082   int num_printed;
15083
15084   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15085
15086   if (num_printed == 0)
15087     {
15088       if (args == NULL || *args == '\0')
15089         ui_out_message (uiout, 0, "No tracepoints.\n");
15090       else
15091         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15092     }
15093
15094   default_collect_info ();
15095 }
15096
15097 /* The 'enable trace' command enables tracepoints.
15098    Not supported by all targets.  */
15099 static void
15100 enable_trace_command (char *args, int from_tty)
15101 {
15102   enable_command (args, from_tty);
15103 }
15104
15105 /* The 'disable trace' command disables tracepoints.
15106    Not supported by all targets.  */
15107 static void
15108 disable_trace_command (char *args, int from_tty)
15109 {
15110   disable_command (args, from_tty);
15111 }
15112
15113 /* Remove a tracepoint (or all if no argument).  */
15114 static void
15115 delete_trace_command (char *arg, int from_tty)
15116 {
15117   struct breakpoint *b, *b_tmp;
15118
15119   dont_repeat ();
15120
15121   if (arg == 0)
15122     {
15123       int breaks_to_delete = 0;
15124
15125       /* Delete all breakpoints if no argument.
15126          Do not delete internal or call-dummy breakpoints, these
15127          have to be deleted with an explicit breakpoint number 
15128          argument.  */
15129       ALL_TRACEPOINTS (b)
15130         if (is_tracepoint (b) && user_breakpoint_p (b))
15131           {
15132             breaks_to_delete = 1;
15133             break;
15134           }
15135
15136       /* Ask user only if there are some breakpoints to delete.  */
15137       if (!from_tty
15138           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15139         {
15140           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15141             if (is_tracepoint (b) && user_breakpoint_p (b))
15142               delete_breakpoint (b);
15143         }
15144     }
15145   else
15146     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15147 }
15148
15149 /* Helper function for trace_pass_command.  */
15150
15151 static void
15152 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15153 {
15154   tp->pass_count = count;
15155   observer_notify_breakpoint_modified (&tp->base);
15156   if (from_tty)
15157     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15158                      tp->base.number, count);
15159 }
15160
15161 /* Set passcount for tracepoint.
15162
15163    First command argument is passcount, second is tracepoint number.
15164    If tracepoint number omitted, apply to most recently defined.
15165    Also accepts special argument "all".  */
15166
15167 static void
15168 trace_pass_command (char *args, int from_tty)
15169 {
15170   struct tracepoint *t1;
15171   unsigned int count;
15172
15173   if (args == 0 || *args == 0)
15174     error (_("passcount command requires an "
15175              "argument (count + optional TP num)"));
15176
15177   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15178
15179   args = skip_spaces (args);
15180   if (*args && strncasecmp (args, "all", 3) == 0)
15181     {
15182       struct breakpoint *b;
15183
15184       args += 3;                        /* Skip special argument "all".  */
15185       if (*args)
15186         error (_("Junk at end of arguments."));
15187
15188       ALL_TRACEPOINTS (b)
15189       {
15190         t1 = (struct tracepoint *) b;
15191         trace_pass_set_count (t1, count, from_tty);
15192       }
15193     }
15194   else if (*args == '\0')
15195     {
15196       t1 = get_tracepoint_by_number (&args, NULL);
15197       if (t1)
15198         trace_pass_set_count (t1, count, from_tty);
15199     }
15200   else
15201     {
15202       struct get_number_or_range_state state;
15203
15204       init_number_or_range (&state, args);
15205       while (!state.finished)
15206         {
15207           t1 = get_tracepoint_by_number (&args, &state);
15208           if (t1)
15209             trace_pass_set_count (t1, count, from_tty);
15210         }
15211     }
15212 }
15213
15214 struct tracepoint *
15215 get_tracepoint (int num)
15216 {
15217   struct breakpoint *t;
15218
15219   ALL_TRACEPOINTS (t)
15220     if (t->number == num)
15221       return (struct tracepoint *) t;
15222
15223   return NULL;
15224 }
15225
15226 /* Find the tracepoint with the given target-side number (which may be
15227    different from the tracepoint number after disconnecting and
15228    reconnecting).  */
15229
15230 struct tracepoint *
15231 get_tracepoint_by_number_on_target (int num)
15232 {
15233   struct breakpoint *b;
15234
15235   ALL_TRACEPOINTS (b)
15236     {
15237       struct tracepoint *t = (struct tracepoint *) b;
15238
15239       if (t->number_on_target == num)
15240         return t;
15241     }
15242
15243   return NULL;
15244 }
15245
15246 /* Utility: parse a tracepoint number and look it up in the list.
15247    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15248    If the argument is missing, the most recent tracepoint
15249    (tracepoint_count) is returned.  */
15250
15251 struct tracepoint *
15252 get_tracepoint_by_number (char **arg,
15253                           struct get_number_or_range_state *state)
15254 {
15255   struct breakpoint *t;
15256   int tpnum;
15257   char *instring = arg == NULL ? NULL : *arg;
15258
15259   if (state)
15260     {
15261       gdb_assert (!state->finished);
15262       tpnum = get_number_or_range (state);
15263     }
15264   else if (arg == NULL || *arg == NULL || ! **arg)
15265     tpnum = tracepoint_count;
15266   else
15267     tpnum = get_number (arg);
15268
15269   if (tpnum <= 0)
15270     {
15271       if (instring && *instring)
15272         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15273                          instring);
15274       else
15275         printf_filtered (_("No previous tracepoint\n"));
15276       return NULL;
15277     }
15278
15279   ALL_TRACEPOINTS (t)
15280     if (t->number == tpnum)
15281     {
15282       return (struct tracepoint *) t;
15283     }
15284
15285   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15286   return NULL;
15287 }
15288
15289 void
15290 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15291 {
15292   if (b->thread != -1)
15293     fprintf_unfiltered (fp, " thread %d", b->thread);
15294
15295   if (b->task != 0)
15296     fprintf_unfiltered (fp, " task %d", b->task);
15297
15298   fprintf_unfiltered (fp, "\n");
15299 }
15300
15301 /* Save information on user settable breakpoints (watchpoints, etc) to
15302    a new script file named FILENAME.  If FILTER is non-NULL, call it
15303    on each breakpoint and only include the ones for which it returns
15304    non-zero.  */
15305
15306 static void
15307 save_breakpoints (char *filename, int from_tty,
15308                   int (*filter) (const struct breakpoint *))
15309 {
15310   struct breakpoint *tp;
15311   int any = 0;
15312   struct cleanup *cleanup;
15313   struct ui_file *fp;
15314   int extra_trace_bits = 0;
15315
15316   if (filename == 0 || *filename == 0)
15317     error (_("Argument required (file name in which to save)"));
15318
15319   /* See if we have anything to save.  */
15320   ALL_BREAKPOINTS (tp)
15321   {
15322     /* Skip internal and momentary breakpoints.  */
15323     if (!user_breakpoint_p (tp))
15324       continue;
15325
15326     /* If we have a filter, only save the breakpoints it accepts.  */
15327     if (filter && !filter (tp))
15328       continue;
15329
15330     any = 1;
15331
15332     if (is_tracepoint (tp))
15333       {
15334         extra_trace_bits = 1;
15335
15336         /* We can stop searching.  */
15337         break;
15338       }
15339   }
15340
15341   if (!any)
15342     {
15343       warning (_("Nothing to save."));
15344       return;
15345     }
15346
15347   filename = tilde_expand (filename);
15348   cleanup = make_cleanup (xfree, filename);
15349   fp = gdb_fopen (filename, "w");
15350   if (!fp)
15351     error (_("Unable to open file '%s' for saving (%s)"),
15352            filename, safe_strerror (errno));
15353   make_cleanup_ui_file_delete (fp);
15354
15355   if (extra_trace_bits)
15356     save_trace_state_variables (fp);
15357
15358   ALL_BREAKPOINTS (tp)
15359   {
15360     /* Skip internal and momentary breakpoints.  */
15361     if (!user_breakpoint_p (tp))
15362       continue;
15363
15364     /* If we have a filter, only save the breakpoints it accepts.  */
15365     if (filter && !filter (tp))
15366       continue;
15367
15368     tp->ops->print_recreate (tp, fp);
15369
15370     /* Note, we can't rely on tp->number for anything, as we can't
15371        assume the recreated breakpoint numbers will match.  Use $bpnum
15372        instead.  */
15373
15374     if (tp->cond_string)
15375       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15376
15377     if (tp->ignore_count)
15378       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15379
15380     if (tp->type != bp_dprintf && tp->commands)
15381       {
15382         struct gdb_exception exception;
15383
15384         fprintf_unfiltered (fp, "  commands\n");
15385         
15386         ui_out_redirect (current_uiout, fp);
15387         TRY
15388           {
15389             print_command_lines (current_uiout, tp->commands->commands, 2);
15390           }
15391         CATCH (ex, RETURN_MASK_ALL)
15392           {
15393             ui_out_redirect (current_uiout, NULL);
15394             throw_exception (ex);
15395           }
15396         END_CATCH
15397
15398         ui_out_redirect (current_uiout, NULL);
15399         fprintf_unfiltered (fp, "  end\n");
15400       }
15401
15402     if (tp->enable_state == bp_disabled)
15403       fprintf_unfiltered (fp, "disable $bpnum\n");
15404
15405     /* If this is a multi-location breakpoint, check if the locations
15406        should be individually disabled.  Watchpoint locations are
15407        special, and not user visible.  */
15408     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15409       {
15410         struct bp_location *loc;
15411         int n = 1;
15412
15413         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15414           if (!loc->enabled)
15415             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15416       }
15417   }
15418
15419   if (extra_trace_bits && *default_collect)
15420     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15421
15422   if (from_tty)
15423     printf_filtered (_("Saved to file '%s'.\n"), filename);
15424   do_cleanups (cleanup);
15425 }
15426
15427 /* The `save breakpoints' command.  */
15428
15429 static void
15430 save_breakpoints_command (char *args, int from_tty)
15431 {
15432   save_breakpoints (args, from_tty, NULL);
15433 }
15434
15435 /* The `save tracepoints' command.  */
15436
15437 static void
15438 save_tracepoints_command (char *args, int from_tty)
15439 {
15440   save_breakpoints (args, from_tty, is_tracepoint);
15441 }
15442
15443 /* Create a vector of all tracepoints.  */
15444
15445 VEC(breakpoint_p) *
15446 all_tracepoints (void)
15447 {
15448   VEC(breakpoint_p) *tp_vec = 0;
15449   struct breakpoint *tp;
15450
15451   ALL_TRACEPOINTS (tp)
15452   {
15453     VEC_safe_push (breakpoint_p, tp_vec, tp);
15454   }
15455
15456   return tp_vec;
15457 }
15458
15459 \f
15460 /* This help string is used for the break, hbreak, tbreak and thbreak
15461    commands.  It is defined as a macro to prevent duplication.
15462    COMMAND should be a string constant containing the name of the
15463    command.  */
15464 #define BREAK_ARGS_HELP(command) \
15465 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15466 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15467 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15468 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15469 `-probe-dtrace' (for a DTrace probe).\n\
15470 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15471 If a line number is specified, break at start of code for that line.\n\
15472 If a function is specified, break at start of code for that function.\n\
15473 If an address is specified, break at that exact address.\n\
15474 With no LOCATION, uses current execution address of the selected\n\
15475 stack frame.  This is useful for breaking on return to a stack frame.\n\
15476 \n\
15477 THREADNUM is the number from \"info threads\".\n\
15478 CONDITION is a boolean expression.\n\
15479 \n\
15480 Multiple breakpoints at one place are permitted, and useful if their\n\
15481 conditions are different.\n\
15482 \n\
15483 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15484
15485 /* List of subcommands for "catch".  */
15486 static struct cmd_list_element *catch_cmdlist;
15487
15488 /* List of subcommands for "tcatch".  */
15489 static struct cmd_list_element *tcatch_cmdlist;
15490
15491 void
15492 add_catch_command (char *name, char *docstring,
15493                    cmd_sfunc_ftype *sfunc,
15494                    completer_ftype *completer,
15495                    void *user_data_catch,
15496                    void *user_data_tcatch)
15497 {
15498   struct cmd_list_element *command;
15499
15500   command = add_cmd (name, class_breakpoint, NULL, docstring,
15501                      &catch_cmdlist);
15502   set_cmd_sfunc (command, sfunc);
15503   set_cmd_context (command, user_data_catch);
15504   set_cmd_completer (command, completer);
15505
15506   command = add_cmd (name, class_breakpoint, NULL, docstring,
15507                      &tcatch_cmdlist);
15508   set_cmd_sfunc (command, sfunc);
15509   set_cmd_context (command, user_data_tcatch);
15510   set_cmd_completer (command, completer);
15511 }
15512
15513 static void
15514 save_command (char *arg, int from_tty)
15515 {
15516   printf_unfiltered (_("\"save\" must be followed by "
15517                        "the name of a save subcommand.\n"));
15518   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15519 }
15520
15521 struct breakpoint *
15522 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15523                           void *data)
15524 {
15525   struct breakpoint *b, *b_tmp;
15526
15527   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15528     {
15529       if ((*callback) (b, data))
15530         return b;
15531     }
15532
15533   return NULL;
15534 }
15535
15536 /* Zero if any of the breakpoint's locations could be a location where
15537    functions have been inlined, nonzero otherwise.  */
15538
15539 static int
15540 is_non_inline_function (struct breakpoint *b)
15541 {
15542   /* The shared library event breakpoint is set on the address of a
15543      non-inline function.  */
15544   if (b->type == bp_shlib_event)
15545     return 1;
15546
15547   return 0;
15548 }
15549
15550 /* Nonzero if the specified PC cannot be a location where functions
15551    have been inlined.  */
15552
15553 int
15554 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15555                            const struct target_waitstatus *ws)
15556 {
15557   struct breakpoint *b;
15558   struct bp_location *bl;
15559
15560   ALL_BREAKPOINTS (b)
15561     {
15562       if (!is_non_inline_function (b))
15563         continue;
15564
15565       for (bl = b->loc; bl != NULL; bl = bl->next)
15566         {
15567           if (!bl->shlib_disabled
15568               && bpstat_check_location (bl, aspace, pc, ws))
15569             return 1;
15570         }
15571     }
15572
15573   return 0;
15574 }
15575
15576 /* Remove any references to OBJFILE which is going to be freed.  */
15577
15578 void
15579 breakpoint_free_objfile (struct objfile *objfile)
15580 {
15581   struct bp_location **locp, *loc;
15582
15583   ALL_BP_LOCATIONS (loc, locp)
15584     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15585       loc->symtab = NULL;
15586 }
15587
15588 void
15589 initialize_breakpoint_ops (void)
15590 {
15591   static int initialized = 0;
15592
15593   struct breakpoint_ops *ops;
15594
15595   if (initialized)
15596     return;
15597   initialized = 1;
15598
15599   /* The breakpoint_ops structure to be inherit by all kinds of
15600      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15601      internal and momentary breakpoints, etc.).  */
15602   ops = &bkpt_base_breakpoint_ops;
15603   *ops = base_breakpoint_ops;
15604   ops->re_set = bkpt_re_set;
15605   ops->insert_location = bkpt_insert_location;
15606   ops->remove_location = bkpt_remove_location;
15607   ops->breakpoint_hit = bkpt_breakpoint_hit;
15608   ops->create_sals_from_address = bkpt_create_sals_from_address;
15609   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15610   ops->decode_linespec = bkpt_decode_linespec;
15611
15612   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15613   ops = &bkpt_breakpoint_ops;
15614   *ops = bkpt_base_breakpoint_ops;
15615   ops->re_set = bkpt_re_set;
15616   ops->resources_needed = bkpt_resources_needed;
15617   ops->print_it = bkpt_print_it;
15618   ops->print_mention = bkpt_print_mention;
15619   ops->print_recreate = bkpt_print_recreate;
15620
15621   /* Ranged breakpoints.  */
15622   ops = &ranged_breakpoint_ops;
15623   *ops = bkpt_breakpoint_ops;
15624   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15625   ops->resources_needed = resources_needed_ranged_breakpoint;
15626   ops->print_it = print_it_ranged_breakpoint;
15627   ops->print_one = print_one_ranged_breakpoint;
15628   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15629   ops->print_mention = print_mention_ranged_breakpoint;
15630   ops->print_recreate = print_recreate_ranged_breakpoint;
15631
15632   /* Internal breakpoints.  */
15633   ops = &internal_breakpoint_ops;
15634   *ops = bkpt_base_breakpoint_ops;
15635   ops->re_set = internal_bkpt_re_set;
15636   ops->check_status = internal_bkpt_check_status;
15637   ops->print_it = internal_bkpt_print_it;
15638   ops->print_mention = internal_bkpt_print_mention;
15639
15640   /* Momentary breakpoints.  */
15641   ops = &momentary_breakpoint_ops;
15642   *ops = bkpt_base_breakpoint_ops;
15643   ops->re_set = momentary_bkpt_re_set;
15644   ops->check_status = momentary_bkpt_check_status;
15645   ops->print_it = momentary_bkpt_print_it;
15646   ops->print_mention = momentary_bkpt_print_mention;
15647
15648   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15649   ops = &longjmp_breakpoint_ops;
15650   *ops = momentary_breakpoint_ops;
15651   ops->dtor = longjmp_bkpt_dtor;
15652
15653   /* Probe breakpoints.  */
15654   ops = &bkpt_probe_breakpoint_ops;
15655   *ops = bkpt_breakpoint_ops;
15656   ops->insert_location = bkpt_probe_insert_location;
15657   ops->remove_location = bkpt_probe_remove_location;
15658   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15659   ops->decode_linespec = bkpt_probe_decode_linespec;
15660
15661   /* Watchpoints.  */
15662   ops = &watchpoint_breakpoint_ops;
15663   *ops = base_breakpoint_ops;
15664   ops->dtor = dtor_watchpoint;
15665   ops->re_set = re_set_watchpoint;
15666   ops->insert_location = insert_watchpoint;
15667   ops->remove_location = remove_watchpoint;
15668   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15669   ops->check_status = check_status_watchpoint;
15670   ops->resources_needed = resources_needed_watchpoint;
15671   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15672   ops->print_it = print_it_watchpoint;
15673   ops->print_mention = print_mention_watchpoint;
15674   ops->print_recreate = print_recreate_watchpoint;
15675   ops->explains_signal = explains_signal_watchpoint;
15676
15677   /* Masked watchpoints.  */
15678   ops = &masked_watchpoint_breakpoint_ops;
15679   *ops = watchpoint_breakpoint_ops;
15680   ops->insert_location = insert_masked_watchpoint;
15681   ops->remove_location = remove_masked_watchpoint;
15682   ops->resources_needed = resources_needed_masked_watchpoint;
15683   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15684   ops->print_it = print_it_masked_watchpoint;
15685   ops->print_one_detail = print_one_detail_masked_watchpoint;
15686   ops->print_mention = print_mention_masked_watchpoint;
15687   ops->print_recreate = print_recreate_masked_watchpoint;
15688
15689   /* Tracepoints.  */
15690   ops = &tracepoint_breakpoint_ops;
15691   *ops = base_breakpoint_ops;
15692   ops->re_set = tracepoint_re_set;
15693   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15694   ops->print_one_detail = tracepoint_print_one_detail;
15695   ops->print_mention = tracepoint_print_mention;
15696   ops->print_recreate = tracepoint_print_recreate;
15697   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15698   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15699   ops->decode_linespec = tracepoint_decode_linespec;
15700
15701   /* Probe tracepoints.  */
15702   ops = &tracepoint_probe_breakpoint_ops;
15703   *ops = tracepoint_breakpoint_ops;
15704   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15705   ops->decode_linespec = tracepoint_probe_decode_linespec;
15706
15707   /* Static tracepoints with marker (`-m').  */
15708   ops = &strace_marker_breakpoint_ops;
15709   *ops = tracepoint_breakpoint_ops;
15710   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15711   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15712   ops->decode_linespec = strace_marker_decode_linespec;
15713
15714   /* Fork catchpoints.  */
15715   ops = &catch_fork_breakpoint_ops;
15716   *ops = base_breakpoint_ops;
15717   ops->insert_location = insert_catch_fork;
15718   ops->remove_location = remove_catch_fork;
15719   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15720   ops->print_it = print_it_catch_fork;
15721   ops->print_one = print_one_catch_fork;
15722   ops->print_mention = print_mention_catch_fork;
15723   ops->print_recreate = print_recreate_catch_fork;
15724
15725   /* Vfork catchpoints.  */
15726   ops = &catch_vfork_breakpoint_ops;
15727   *ops = base_breakpoint_ops;
15728   ops->insert_location = insert_catch_vfork;
15729   ops->remove_location = remove_catch_vfork;
15730   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15731   ops->print_it = print_it_catch_vfork;
15732   ops->print_one = print_one_catch_vfork;
15733   ops->print_mention = print_mention_catch_vfork;
15734   ops->print_recreate = print_recreate_catch_vfork;
15735
15736   /* Exec catchpoints.  */
15737   ops = &catch_exec_breakpoint_ops;
15738   *ops = base_breakpoint_ops;
15739   ops->dtor = dtor_catch_exec;
15740   ops->insert_location = insert_catch_exec;
15741   ops->remove_location = remove_catch_exec;
15742   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15743   ops->print_it = print_it_catch_exec;
15744   ops->print_one = print_one_catch_exec;
15745   ops->print_mention = print_mention_catch_exec;
15746   ops->print_recreate = print_recreate_catch_exec;
15747
15748   /* Solib-related catchpoints.  */
15749   ops = &catch_solib_breakpoint_ops;
15750   *ops = base_breakpoint_ops;
15751   ops->dtor = dtor_catch_solib;
15752   ops->insert_location = insert_catch_solib;
15753   ops->remove_location = remove_catch_solib;
15754   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15755   ops->check_status = check_status_catch_solib;
15756   ops->print_it = print_it_catch_solib;
15757   ops->print_one = print_one_catch_solib;
15758   ops->print_mention = print_mention_catch_solib;
15759   ops->print_recreate = print_recreate_catch_solib;
15760
15761   ops = &dprintf_breakpoint_ops;
15762   *ops = bkpt_base_breakpoint_ops;
15763   ops->re_set = dprintf_re_set;
15764   ops->resources_needed = bkpt_resources_needed;
15765   ops->print_it = bkpt_print_it;
15766   ops->print_mention = bkpt_print_mention;
15767   ops->print_recreate = dprintf_print_recreate;
15768   ops->after_condition_true = dprintf_after_condition_true;
15769   ops->breakpoint_hit = dprintf_breakpoint_hit;
15770 }
15771
15772 /* Chain containing all defined "enable breakpoint" subcommands.  */
15773
15774 static struct cmd_list_element *enablebreaklist = NULL;
15775
15776 void
15777 _initialize_breakpoint (void)
15778 {
15779   struct cmd_list_element *c;
15780
15781   initialize_breakpoint_ops ();
15782
15783   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15784   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15785   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15786
15787   breakpoint_objfile_key
15788     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15789
15790   breakpoint_chain = 0;
15791   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15792      before a breakpoint is set.  */
15793   breakpoint_count = 0;
15794
15795   tracepoint_count = 0;
15796
15797   add_com ("ignore", class_breakpoint, ignore_command, _("\
15798 Set ignore-count of breakpoint number N to COUNT.\n\
15799 Usage is `ignore N COUNT'."));
15800
15801   add_com ("commands", class_breakpoint, commands_command, _("\
15802 Set commands to be executed when a breakpoint is hit.\n\
15803 Give breakpoint number as argument after \"commands\".\n\
15804 With no argument, the targeted breakpoint is the last one set.\n\
15805 The commands themselves follow starting on the next line.\n\
15806 Type a line containing \"end\" to indicate the end of them.\n\
15807 Give \"silent\" as the first line to make the breakpoint silent;\n\
15808 then no output is printed when it is hit, except what the commands print."));
15809
15810   c = add_com ("condition", class_breakpoint, condition_command, _("\
15811 Specify breakpoint number N to break only if COND is true.\n\
15812 Usage is `condition N COND', where N is an integer and COND is an\n\
15813 expression to be evaluated whenever breakpoint N is reached."));
15814   set_cmd_completer (c, condition_completer);
15815
15816   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15817 Set a temporary breakpoint.\n\
15818 Like \"break\" except the breakpoint is only temporary,\n\
15819 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15820 by using \"enable delete\" on the breakpoint number.\n\
15821 \n"
15822 BREAK_ARGS_HELP ("tbreak")));
15823   set_cmd_completer (c, location_completer);
15824
15825   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15826 Set a hardware assisted breakpoint.\n\
15827 Like \"break\" except the breakpoint requires hardware support,\n\
15828 some target hardware may not have this support.\n\
15829 \n"
15830 BREAK_ARGS_HELP ("hbreak")));
15831   set_cmd_completer (c, location_completer);
15832
15833   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15834 Set a temporary hardware assisted breakpoint.\n\
15835 Like \"hbreak\" except the breakpoint is only temporary,\n\
15836 so it will be deleted when hit.\n\
15837 \n"
15838 BREAK_ARGS_HELP ("thbreak")));
15839   set_cmd_completer (c, location_completer);
15840
15841   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15842 Enable some breakpoints.\n\
15843 Give breakpoint numbers (separated by spaces) as arguments.\n\
15844 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15845 This is used to cancel the effect of the \"disable\" command.\n\
15846 With a subcommand you can enable temporarily."),
15847                   &enablelist, "enable ", 1, &cmdlist);
15848
15849   add_com_alias ("en", "enable", class_breakpoint, 1);
15850
15851   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15852 Enable some breakpoints.\n\
15853 Give breakpoint numbers (separated by spaces) as arguments.\n\
15854 This is used to cancel the effect of the \"disable\" command.\n\
15855 May be abbreviated to simply \"enable\".\n"),
15856                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15857
15858   add_cmd ("once", no_class, enable_once_command, _("\
15859 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15860 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15861            &enablebreaklist);
15862
15863   add_cmd ("delete", no_class, enable_delete_command, _("\
15864 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15865 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15866            &enablebreaklist);
15867
15868   add_cmd ("count", no_class, enable_count_command, _("\
15869 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15870 If a breakpoint is hit while enabled in this fashion,\n\
15871 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15872            &enablebreaklist);
15873
15874   add_cmd ("delete", no_class, enable_delete_command, _("\
15875 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15876 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15877            &enablelist);
15878
15879   add_cmd ("once", no_class, enable_once_command, _("\
15880 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15881 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15882            &enablelist);
15883
15884   add_cmd ("count", no_class, enable_count_command, _("\
15885 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15886 If a breakpoint is hit while enabled in this fashion,\n\
15887 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15888            &enablelist);
15889
15890   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15891 Disable some breakpoints.\n\
15892 Arguments are breakpoint numbers with spaces in between.\n\
15893 To disable all breakpoints, give no argument.\n\
15894 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15895                   &disablelist, "disable ", 1, &cmdlist);
15896   add_com_alias ("dis", "disable", class_breakpoint, 1);
15897   add_com_alias ("disa", "disable", class_breakpoint, 1);
15898
15899   add_cmd ("breakpoints", class_alias, disable_command, _("\
15900 Disable some breakpoints.\n\
15901 Arguments are breakpoint numbers with spaces in between.\n\
15902 To disable all breakpoints, give no argument.\n\
15903 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15904 This command may be abbreviated \"disable\"."),
15905            &disablelist);
15906
15907   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15908 Delete some breakpoints or auto-display expressions.\n\
15909 Arguments are breakpoint numbers with spaces in between.\n\
15910 To delete all breakpoints, give no argument.\n\
15911 \n\
15912 Also a prefix command for deletion of other GDB objects.\n\
15913 The \"unset\" command is also an alias for \"delete\"."),
15914                   &deletelist, "delete ", 1, &cmdlist);
15915   add_com_alias ("d", "delete", class_breakpoint, 1);
15916   add_com_alias ("del", "delete", class_breakpoint, 1);
15917
15918   add_cmd ("breakpoints", class_alias, delete_command, _("\
15919 Delete some breakpoints or auto-display expressions.\n\
15920 Arguments are breakpoint numbers with spaces in between.\n\
15921 To delete all breakpoints, give no argument.\n\
15922 This command may be abbreviated \"delete\"."),
15923            &deletelist);
15924
15925   add_com ("clear", class_breakpoint, clear_command, _("\
15926 Clear breakpoint at specified line or function.\n\
15927 Argument may be line number, function name, or \"*\" and an address.\n\
15928 If line number is specified, all breakpoints in that line are cleared.\n\
15929 If function is specified, breakpoints at beginning of function are cleared.\n\
15930 If an address is specified, breakpoints at that address are cleared.\n\
15931 \n\
15932 With no argument, clears all breakpoints in the line that the selected frame\n\
15933 is executing in.\n\
15934 \n\
15935 See also the \"delete\" command which clears breakpoints by number."));
15936   add_com_alias ("cl", "clear", class_breakpoint, 1);
15937
15938   c = add_com ("break", class_breakpoint, break_command, _("\
15939 Set breakpoint at specified line or function.\n"
15940 BREAK_ARGS_HELP ("break")));
15941   set_cmd_completer (c, location_completer);
15942
15943   add_com_alias ("b", "break", class_run, 1);
15944   add_com_alias ("br", "break", class_run, 1);
15945   add_com_alias ("bre", "break", class_run, 1);
15946   add_com_alias ("brea", "break", class_run, 1);
15947
15948   if (dbx_commands)
15949     {
15950       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15951 Break in function/address or break at a line in the current file."),
15952                              &stoplist, "stop ", 1, &cmdlist);
15953       add_cmd ("in", class_breakpoint, stopin_command,
15954                _("Break in function or address."), &stoplist);
15955       add_cmd ("at", class_breakpoint, stopat_command,
15956                _("Break at a line in the current file."), &stoplist);
15957       add_com ("status", class_info, breakpoints_info, _("\
15958 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15959 The \"Type\" column indicates one of:\n\
15960 \tbreakpoint     - normal breakpoint\n\
15961 \twatchpoint     - watchpoint\n\
15962 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15963 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15964 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15965 address and file/line number respectively.\n\
15966 \n\
15967 Convenience variable \"$_\" and default examine address for \"x\"\n\
15968 are set to the address of the last breakpoint listed unless the command\n\
15969 is prefixed with \"server \".\n\n\
15970 Convenience variable \"$bpnum\" contains the number of the last\n\
15971 breakpoint set."));
15972     }
15973
15974   add_info ("breakpoints", breakpoints_info, _("\
15975 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15976 The \"Type\" column indicates one of:\n\
15977 \tbreakpoint     - normal breakpoint\n\
15978 \twatchpoint     - watchpoint\n\
15979 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15980 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15981 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15982 address and file/line number respectively.\n\
15983 \n\
15984 Convenience variable \"$_\" and default examine address for \"x\"\n\
15985 are set to the address of the last breakpoint listed unless the command\n\
15986 is prefixed with \"server \".\n\n\
15987 Convenience variable \"$bpnum\" contains the number of the last\n\
15988 breakpoint set."));
15989
15990   add_info_alias ("b", "breakpoints", 1);
15991
15992   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15993 Status of all breakpoints, or breakpoint number NUMBER.\n\
15994 The \"Type\" column indicates one of:\n\
15995 \tbreakpoint     - normal breakpoint\n\
15996 \twatchpoint     - watchpoint\n\
15997 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15998 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15999 \tuntil          - internal breakpoint used by the \"until\" command\n\
16000 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16001 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16002 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16003 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16004 address and file/line number respectively.\n\
16005 \n\
16006 Convenience variable \"$_\" and default examine address for \"x\"\n\
16007 are set to the address of the last breakpoint listed unless the command\n\
16008 is prefixed with \"server \".\n\n\
16009 Convenience variable \"$bpnum\" contains the number of the last\n\
16010 breakpoint set."),
16011            &maintenanceinfolist);
16012
16013   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16014 Set catchpoints to catch events."),
16015                   &catch_cmdlist, "catch ",
16016                   0/*allow-unknown*/, &cmdlist);
16017
16018   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16019 Set temporary catchpoints to catch events."),
16020                   &tcatch_cmdlist, "tcatch ",
16021                   0/*allow-unknown*/, &cmdlist);
16022
16023   add_catch_command ("fork", _("Catch calls to fork."),
16024                      catch_fork_command_1,
16025                      NULL,
16026                      (void *) (uintptr_t) catch_fork_permanent,
16027                      (void *) (uintptr_t) catch_fork_temporary);
16028   add_catch_command ("vfork", _("Catch calls to vfork."),
16029                      catch_fork_command_1,
16030                      NULL,
16031                      (void *) (uintptr_t) catch_vfork_permanent,
16032                      (void *) (uintptr_t) catch_vfork_temporary);
16033   add_catch_command ("exec", _("Catch calls to exec."),
16034                      catch_exec_command_1,
16035                      NULL,
16036                      CATCH_PERMANENT,
16037                      CATCH_TEMPORARY);
16038   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16039 Usage: catch load [REGEX]\n\
16040 If REGEX is given, only stop for libraries matching the regular expression."),
16041                      catch_load_command_1,
16042                      NULL,
16043                      CATCH_PERMANENT,
16044                      CATCH_TEMPORARY);
16045   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16046 Usage: catch unload [REGEX]\n\
16047 If REGEX is given, only stop for libraries matching the regular expression."),
16048                      catch_unload_command_1,
16049                      NULL,
16050                      CATCH_PERMANENT,
16051                      CATCH_TEMPORARY);
16052
16053   c = add_com ("watch", class_breakpoint, watch_command, _("\
16054 Set a watchpoint for an expression.\n\
16055 Usage: watch [-l|-location] EXPRESSION\n\
16056 A watchpoint stops execution of your program whenever the value of\n\
16057 an expression changes.\n\
16058 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16059 the memory to which it refers."));
16060   set_cmd_completer (c, expression_completer);
16061
16062   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16063 Set a read watchpoint for an expression.\n\
16064 Usage: rwatch [-l|-location] EXPRESSION\n\
16065 A watchpoint stops execution of your program whenever the value of\n\
16066 an expression is read.\n\
16067 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16068 the memory to which it refers."));
16069   set_cmd_completer (c, expression_completer);
16070
16071   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16072 Set a watchpoint for an expression.\n\
16073 Usage: awatch [-l|-location] EXPRESSION\n\
16074 A watchpoint stops execution of your program whenever the value of\n\
16075 an expression is either read or written.\n\
16076 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16077 the memory to which it refers."));
16078   set_cmd_completer (c, expression_completer);
16079
16080   add_info ("watchpoints", watchpoints_info, _("\
16081 Status of specified watchpoints (all watchpoints if no argument)."));
16082
16083   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16084      respond to changes - contrary to the description.  */
16085   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16086                             &can_use_hw_watchpoints, _("\
16087 Set debugger's willingness to use watchpoint hardware."), _("\
16088 Show debugger's willingness to use watchpoint hardware."), _("\
16089 If zero, gdb will not use hardware for new watchpoints, even if\n\
16090 such is available.  (However, any hardware watchpoints that were\n\
16091 created before setting this to nonzero, will continue to use watchpoint\n\
16092 hardware.)"),
16093                             NULL,
16094                             show_can_use_hw_watchpoints,
16095                             &setlist, &showlist);
16096
16097   can_use_hw_watchpoints = 1;
16098
16099   /* Tracepoint manipulation commands.  */
16100
16101   c = add_com ("trace", class_breakpoint, trace_command, _("\
16102 Set a tracepoint at specified line or function.\n\
16103 \n"
16104 BREAK_ARGS_HELP ("trace") "\n\
16105 Do \"help tracepoints\" for info on other tracepoint commands."));
16106   set_cmd_completer (c, location_completer);
16107
16108   add_com_alias ("tp", "trace", class_alias, 0);
16109   add_com_alias ("tr", "trace", class_alias, 1);
16110   add_com_alias ("tra", "trace", class_alias, 1);
16111   add_com_alias ("trac", "trace", class_alias, 1);
16112
16113   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16114 Set a fast tracepoint at specified line or function.\n\
16115 \n"
16116 BREAK_ARGS_HELP ("ftrace") "\n\
16117 Do \"help tracepoints\" for info on other tracepoint commands."));
16118   set_cmd_completer (c, location_completer);
16119
16120   c = add_com ("strace", class_breakpoint, strace_command, _("\
16121 Set a static tracepoint at specified line, function or marker.\n\
16122 \n\
16123 strace [LOCATION] [if CONDITION]\n\
16124 LOCATION may be a line number, function name, \"*\" and an address,\n\
16125 or -m MARKER_ID.\n\
16126 If a line number is specified, probe the marker at start of code\n\
16127 for that line.  If a function is specified, probe the marker at start\n\
16128 of code for that function.  If an address is specified, probe the marker\n\
16129 at that exact address.  If a marker id is specified, probe the marker\n\
16130 with that name.  With no LOCATION, uses current execution address of\n\
16131 the selected stack frame.\n\
16132 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16133 This collects arbitrary user data passed in the probe point call to the\n\
16134 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16135 by printing the $_sdata variable like any other convenience variable.\n\
16136 \n\
16137 CONDITION is a boolean expression.\n\
16138 \n\
16139 Multiple tracepoints at one place are permitted, and useful if their\n\
16140 conditions are different.\n\
16141 \n\
16142 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16143 Do \"help tracepoints\" for info on other tracepoint commands."));
16144   set_cmd_completer (c, location_completer);
16145
16146   add_info ("tracepoints", tracepoints_info, _("\
16147 Status of specified tracepoints (all tracepoints if no argument).\n\
16148 Convenience variable \"$tpnum\" contains the number of the\n\
16149 last tracepoint set."));
16150
16151   add_info_alias ("tp", "tracepoints", 1);
16152
16153   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16154 Delete specified tracepoints.\n\
16155 Arguments are tracepoint numbers, separated by spaces.\n\
16156 No argument means delete all tracepoints."),
16157            &deletelist);
16158   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16159
16160   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16161 Disable specified tracepoints.\n\
16162 Arguments are tracepoint numbers, separated by spaces.\n\
16163 No argument means disable all tracepoints."),
16164            &disablelist);
16165   deprecate_cmd (c, "disable");
16166
16167   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16168 Enable specified tracepoints.\n\
16169 Arguments are tracepoint numbers, separated by spaces.\n\
16170 No argument means enable all tracepoints."),
16171            &enablelist);
16172   deprecate_cmd (c, "enable");
16173
16174   add_com ("passcount", class_trace, trace_pass_command, _("\
16175 Set the passcount for a tracepoint.\n\
16176 The trace will end when the tracepoint has been passed 'count' times.\n\
16177 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16178 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16179
16180   add_prefix_cmd ("save", class_breakpoint, save_command,
16181                   _("Save breakpoint definitions as a script."),
16182                   &save_cmdlist, "save ",
16183                   0/*allow-unknown*/, &cmdlist);
16184
16185   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16186 Save current breakpoint definitions as a script.\n\
16187 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16188 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16189 session to restore them."),
16190                &save_cmdlist);
16191   set_cmd_completer (c, filename_completer);
16192
16193   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16194 Save current tracepoint definitions as a script.\n\
16195 Use the 'source' command in another debug session to restore them."),
16196                &save_cmdlist);
16197   set_cmd_completer (c, filename_completer);
16198
16199   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16200   deprecate_cmd (c, "save tracepoints");
16201
16202   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16203 Breakpoint specific settings\n\
16204 Configure various breakpoint-specific variables such as\n\
16205 pending breakpoint behavior"),
16206                   &breakpoint_set_cmdlist, "set breakpoint ",
16207                   0/*allow-unknown*/, &setlist);
16208   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16209 Breakpoint specific settings\n\
16210 Configure various breakpoint-specific variables such as\n\
16211 pending breakpoint behavior"),
16212                   &breakpoint_show_cmdlist, "show breakpoint ",
16213                   0/*allow-unknown*/, &showlist);
16214
16215   add_setshow_auto_boolean_cmd ("pending", no_class,
16216                                 &pending_break_support, _("\
16217 Set debugger's behavior regarding pending breakpoints."), _("\
16218 Show debugger's behavior regarding pending breakpoints."), _("\
16219 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16220 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16221 an error.  If auto, an unrecognized breakpoint location results in a\n\
16222 user-query to see if a pending breakpoint should be created."),
16223                                 NULL,
16224                                 show_pending_break_support,
16225                                 &breakpoint_set_cmdlist,
16226                                 &breakpoint_show_cmdlist);
16227
16228   pending_break_support = AUTO_BOOLEAN_AUTO;
16229
16230   add_setshow_boolean_cmd ("auto-hw", no_class,
16231                            &automatic_hardware_breakpoints, _("\
16232 Set automatic usage of hardware breakpoints."), _("\
16233 Show automatic usage of hardware breakpoints."), _("\
16234 If set, the debugger will automatically use hardware breakpoints for\n\
16235 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16236 a warning will be emitted for such breakpoints."),
16237                            NULL,
16238                            show_automatic_hardware_breakpoints,
16239                            &breakpoint_set_cmdlist,
16240                            &breakpoint_show_cmdlist);
16241
16242   add_setshow_boolean_cmd ("always-inserted", class_support,
16243                            &always_inserted_mode, _("\
16244 Set mode for inserting breakpoints."), _("\
16245 Show mode for inserting breakpoints."), _("\
16246 When this mode is on, breakpoints are inserted immediately as soon as\n\
16247 they're created, kept inserted even when execution stops, and removed\n\
16248 only when the user deletes them.  When this mode is off (the default),\n\
16249 breakpoints are inserted only when execution continues, and removed\n\
16250 when execution stops."),
16251                                 NULL,
16252                                 &show_always_inserted_mode,
16253                                 &breakpoint_set_cmdlist,
16254                                 &breakpoint_show_cmdlist);
16255
16256   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16257                         condition_evaluation_enums,
16258                         &condition_evaluation_mode_1, _("\
16259 Set mode of breakpoint condition evaluation."), _("\
16260 Show mode of breakpoint condition evaluation."), _("\
16261 When this is set to \"host\", breakpoint conditions will be\n\
16262 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16263 breakpoint conditions will be downloaded to the target (if the target\n\
16264 supports such feature) and conditions will be evaluated on the target's side.\n\
16265 If this is set to \"auto\" (default), this will be automatically set to\n\
16266 \"target\" if it supports condition evaluation, otherwise it will\n\
16267 be set to \"gdb\""),
16268                            &set_condition_evaluation_mode,
16269                            &show_condition_evaluation_mode,
16270                            &breakpoint_set_cmdlist,
16271                            &breakpoint_show_cmdlist);
16272
16273   add_com ("break-range", class_breakpoint, break_range_command, _("\
16274 Set a breakpoint for an address range.\n\
16275 break-range START-LOCATION, END-LOCATION\n\
16276 where START-LOCATION and END-LOCATION can be one of the following:\n\
16277   LINENUM, for that line in the current file,\n\
16278   FILE:LINENUM, for that line in that file,\n\
16279   +OFFSET, for that number of lines after the current line\n\
16280            or the start of the range\n\
16281   FUNCTION, for the first line in that function,\n\
16282   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16283   *ADDRESS, for the instruction at that address.\n\
16284 \n\
16285 The breakpoint will stop execution of the inferior whenever it executes\n\
16286 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16287 range (including START-LOCATION and END-LOCATION)."));
16288
16289   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16290 Set a dynamic printf at specified line or function.\n\
16291 dprintf location,format string,arg1,arg2,...\n\
16292 location may be a line number, function name, or \"*\" and an address.\n\
16293 If a line number is specified, break at start of code for that line.\n\
16294 If a function is specified, break at start of code for that function."));
16295   set_cmd_completer (c, location_completer);
16296
16297   add_setshow_enum_cmd ("dprintf-style", class_support,
16298                         dprintf_style_enums, &dprintf_style, _("\
16299 Set the style of usage for dynamic printf."), _("\
16300 Show the style of usage for dynamic printf."), _("\
16301 This setting chooses how GDB will do a dynamic printf.\n\
16302 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16303 console, as with the \"printf\" command.\n\
16304 If the value is \"call\", the print is done by calling a function in your\n\
16305 program; by default printf(), but you can choose a different function or\n\
16306 output stream by setting dprintf-function and dprintf-channel."),
16307                         update_dprintf_commands, NULL,
16308                         &setlist, &showlist);
16309
16310   dprintf_function = xstrdup ("printf");
16311   add_setshow_string_cmd ("dprintf-function", class_support,
16312                           &dprintf_function, _("\
16313 Set the function to use for dynamic printf"), _("\
16314 Show the function to use for dynamic printf"), NULL,
16315                           update_dprintf_commands, NULL,
16316                           &setlist, &showlist);
16317
16318   dprintf_channel = xstrdup ("");
16319   add_setshow_string_cmd ("dprintf-channel", class_support,
16320                           &dprintf_channel, _("\
16321 Set the channel to use for dynamic printf"), _("\
16322 Show the channel to use for dynamic printf"), NULL,
16323                           update_dprintf_commands, NULL,
16324                           &setlist, &showlist);
16325
16326   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16327                            &disconnected_dprintf, _("\
16328 Set whether dprintf continues after GDB disconnects."), _("\
16329 Show whether dprintf continues after GDB disconnects."), _("\
16330 Use this to let dprintf commands continue to hit and produce output\n\
16331 even if GDB disconnects or detaches from the target."),
16332                            NULL,
16333                            NULL,
16334                            &setlist, &showlist);
16335
16336   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16337 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16338 (target agent only) This is useful for formatted output in user-defined commands."));
16339
16340   automatic_hardware_breakpoints = 1;
16341
16342   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16343   observer_attach_thread_exit (remove_threaded_breakpoints);
16344 }